From 7e0b4501030aa268da323c1eaa69c8a2b29ee6a3 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Thu, 24 Apr 2025 15:22:41 -0600 Subject: Added scripts to generate tex files from markdown --- book/generate_module_tex.sh | 27 ++++ book/generate_tex_files.sh | 32 ++++ tutorials/module_1/1_array.md | 169 --------------------- tutorials/module_1/1_basics_of_python.md | 160 ------------------- tutorials/module_1/1_classes_and_objects.md | 47 ------ tutorials/module_1/1_computational_expense.md | 2 - tutorials/module_1/1_computing_fundamentals.md | 15 -- tutorials/module_1/1_control_structures.md | 127 ---------------- tutorials/module_1/1_functions.md | 67 -------- .../module_1/1_fundamentals_of_programming.md | 15 -- tutorials/module_1/1_installing_anaconda.md | 59 ------- tutorials/module_1/1_intro_to_anaconda.md | 79 ---------- tutorials/module_1/1_intro_to_programming.md | 15 -- tutorials/module_1/1_jupyter_lab_notebook.md | 105 ------------- tutorials/module_1/1_open_source_software.md | 43 ------ tutorials/module_1/1_spyder_getting_started.md | 41 ----- tutorials/module_1/array.md | 169 +++++++++++++++++++++ tutorials/module_1/basics_of_python.md | 160 +++++++++++++++++++ tutorials/module_1/classes_and_objects.md | 47 ++++++ tutorials/module_1/computational_expense.md | 2 + tutorials/module_1/computing_fundamentals.md | 15 ++ tutorials/module_1/control_structures.md | 127 ++++++++++++++++ tutorials/module_1/functions.md | 67 ++++++++ tutorials/module_1/fundamentals_of_programming.md | 15 ++ tutorials/module_1/installing_anaconda.md | 59 +++++++ tutorials/module_1/intro_to_anaconda.md | 79 ++++++++++ tutorials/module_1/intro_to_programming.md | 15 ++ tutorials/module_1/jupyter_lab_notebook.md | 105 +++++++++++++ tutorials/module_1/open_source_software.md | 43 ++++++ tutorials/module_1/spyder_getting_started.md | 41 +++++ .../module_2/2_01_intro_to_numerical_methods.md | 41 ----- tutorials/module_2/2_ai_assisted_programming.md | 38 ----- tutorials/module_2/2_debugging_code.md | 88 ----------- tutorials/module_2/2_problem_solving_strategies.md | 64 -------- tutorials/module_2/2_version_control.md | 112 -------------- tutorials/module_2/ai_assisted_programming.md | 38 +++++ tutorials/module_2/debugging_code.md | 88 +++++++++++ tutorials/module_2/intro_to_numerical_methods.md | 41 +++++ tutorials/module_2/problem_solving_strategies.md | 64 ++++++++ tutorials/module_2/version_control.md | 112 ++++++++++++++ 40 files changed, 1346 insertions(+), 1287 deletions(-) create mode 100755 book/generate_module_tex.sh create mode 100755 book/generate_tex_files.sh delete mode 100644 tutorials/module_1/1_array.md delete mode 100644 tutorials/module_1/1_basics_of_python.md delete mode 100644 tutorials/module_1/1_classes_and_objects.md delete mode 100644 tutorials/module_1/1_computational_expense.md delete mode 100644 tutorials/module_1/1_computing_fundamentals.md delete mode 100644 tutorials/module_1/1_control_structures.md delete mode 100644 tutorials/module_1/1_functions.md delete mode 100644 tutorials/module_1/1_fundamentals_of_programming.md delete mode 100644 tutorials/module_1/1_installing_anaconda.md delete mode 100644 tutorials/module_1/1_intro_to_anaconda.md delete mode 100644 tutorials/module_1/1_intro_to_programming.md delete mode 100644 tutorials/module_1/1_jupyter_lab_notebook.md delete mode 100644 tutorials/module_1/1_open_source_software.md delete mode 100644 tutorials/module_1/1_spyder_getting_started.md create mode 100644 tutorials/module_1/array.md create mode 100644 tutorials/module_1/basics_of_python.md create mode 100644 tutorials/module_1/classes_and_objects.md create mode 100644 tutorials/module_1/computational_expense.md create mode 100644 tutorials/module_1/computing_fundamentals.md create mode 100644 tutorials/module_1/control_structures.md create mode 100644 tutorials/module_1/functions.md create mode 100644 tutorials/module_1/fundamentals_of_programming.md create mode 100644 tutorials/module_1/installing_anaconda.md create mode 100644 tutorials/module_1/intro_to_anaconda.md create mode 100644 tutorials/module_1/intro_to_programming.md create mode 100644 tutorials/module_1/jupyter_lab_notebook.md create mode 100644 tutorials/module_1/open_source_software.md create mode 100644 tutorials/module_1/spyder_getting_started.md delete mode 100644 tutorials/module_2/2_01_intro_to_numerical_methods.md delete mode 100644 tutorials/module_2/2_ai_assisted_programming.md delete mode 100644 tutorials/module_2/2_debugging_code.md delete mode 100644 tutorials/module_2/2_problem_solving_strategies.md delete mode 100644 tutorials/module_2/2_version_control.md create mode 100644 tutorials/module_2/ai_assisted_programming.md create mode 100644 tutorials/module_2/debugging_code.md create mode 100644 tutorials/module_2/intro_to_numerical_methods.md create mode 100644 tutorials/module_2/problem_solving_strategies.md create mode 100644 tutorials/module_2/version_control.md diff --git a/book/generate_module_tex.sh b/book/generate_module_tex.sh new file mode 100755 index 0000000..4d3c449 --- /dev/null +++ b/book/generate_module_tex.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +book_dir="." + +# Loop through all module directories (module1, module2, etc.) +for module_path in "$book_dir"/module*/; do + [ -d "$module_path" ] || continue + + module_name=$(basename "$module_path") # e.g. module2 + module_number="${module_name//[!0-9]/}" # extract number: 2 + output_file="$module_path/$module_name.tex" + + echo "Generating $output_file" + + # Start writing the .tex file + { + echo "\\chapter{Module $module_number}" + for texfile in "$module_path"/*.tex; do + tex_base=$(basename "$texfile" .tex) + + # Skip the module.tex itself + [[ "$tex_base" == "$module_name" ]] && continue + + echo "\\input{$module_name/$tex_base}" + done + } > "$output_file" +done diff --git a/book/generate_tex_files.sh b/book/generate_tex_files.sh new file mode 100755 index 0000000..87238f4 --- /dev/null +++ b/book/generate_tex_files.sh @@ -0,0 +1,32 @@ +#!/bin/bash + +markdown_dir="../tutorials" +book_dir="." + +# Enable recursive globbing with ** +shopt -s globstar + +# Loop through markdown files in source directory +for filepath in "$markdown_dir"/module_*/**/*.md; do + [ -e "$filepath" ] || continue + + # Get module name and clean it (remove underscore) + module_base=$(basename "$(dirname "$filepath")") # module_# + module_clean="${module_base//_/}" # module# + + # Get filename without extension + filename="${filepath##*/}" # file.md + filename_no_ext="${filename%.md}" # file + + # Make sure output directory exists + output_dir="$book_dir/$module_clean" + mkdir -p "$output_dir" + + # Define output .tex file path + output_file="$output_dir/$filename_no_ext.tex" + + # Convert markdown to LaTeX + pandoc -f markdown -t latex "$filepath" -o "$output_file" + + echo "Converted $filepath -> $output_file" +done diff --git a/tutorials/module_1/1_array.md b/tutorials/module_1/1_array.md deleted file mode 100644 index c8f2452..0000000 --- a/tutorials/module_1/1_array.md +++ /dev/null @@ -1,169 +0,0 @@ -# Arrays - -In computer programming, an array is a structure for storing and retrieving data. We often talk about an array as if it were a grid in space, with each cell storing one element of the data. For instance, if each element of the data were a number, we might visualize a “one-dimensional” array like a list: - -| 1 | 5 | 2 | 0 | -| --- | --- | --- | --- | - -A two-dimensional array would be like a table: - -| 1 | 5 | 2 | 0 | -| --- | --- | --- | --- | -| 8 | 3 | 6 | 1 | -| 1 | 7 | 2 | 9 | - -A three-dimensional array would be like a set of tables, perhaps stacked as though they were printed on separate pages. If we visualize the position of each element as a position in space. Then we can represent the value of the element as a property. In other words, if we were to analyze the stress concentration of an aluminum block, the property would be stress. - -- From [Numpy documentation](https://numpy.org/doc/2.2/user/absolute_beginners.html) -![Mathworks 3-D array](https://www.mathworks.com/help/examples/matlab/win64/nddemo_02.gif) - -If the load on this block changes over time, then we may want to add a 4th dimension i.e. additional sets of 3-D arrays for each time increment. As you can see - the more dimensions we add, the more complicated of a problem we have to solve. It is possible to increase the number of dimensions to the n-th order. This course we will not be going beyond dimensional analysis. - ---- -# Numpy - the python's array library - -In this tutorial we will be introducing arrays and we will be using the numpy library. Arrays, lists, vectors, matrices, sets - You might've heard of them before, they all store data. In programming, an array is a variable that can hold more than one value at a time. We will be using the Numpy python library to create arrays. Since we already have installed Numpy previously, we can start using the package. - -Before importing our first package, let's as ourselves *what is a package?* A package can be thought of as pre-written python code that we can re-use. This means the for every script that we write in python we need to tell it to use a certain package. We call this importing a package. - -## Importing Numpy -When using packages in python, we need to let it know what package we will be using. This is called importing. To import numpy we need to declare it a the start of a script as follows: -```python -import numpy as np -``` -- `import` - calls for a library to use, in our case it is Numpy. -- `as` - gives the library an alias in your script. It's common convention in Python programming to make the code shorter and more readable. We will be using *np* as it's a standard using in many projects. - ---- -# Creating arrays -Now that we have imported the library we can create a one dimensional array or *vector* with three elements. -```python -x = np.array([1,2,3]) -``` - - -To create a *matrix* we can nest the arrays to create a two dimensional array. This is done as follows. - -```python -matrix = np.array([[1,2,3], - [4,5,6], - [7,8,9]]) -``` - -*Note: for every array we nest, we get a new dimension in our data structure.* - -## Numpy array creation functions -Numpy comes with some built-in function that we can use to create arrays quickly. Here are a couple of functions that are commonly used in python. -### np.arange -The `np.arange()` function returns an array with evenly spaced values within a specified range. It is similar to the built-in `range()` function in Python but returns a Numpy array instead of a list. The parameters for this function are the start value (inclusive), the stop value (exclusive), and the step size. If the step size is not provided, it defaults to 1. - -```python ->>> np.arange(4) -array([0. , 1., 2., 3. ]) -``` - -In this example, `np.arange(4)` generates an array starting from 0 and ending before 4, with a step size of 1. - -### np.linspace -The `np.linspace()` function returns an array of evenly spaced values over a specified range. Unlike `np.arange()`, which uses a step size to define the spacing between elements, `np.linspace()` uses the number of values you want to generate and calculates the spacing automatically. It accepts three parameters: the start value, the stop value, and the number of samples. - -```python ->>> np.linspace(1., 4., 6) -array([1. , 1.6, 2.2, 2.8, 3.4, 4. ]) -``` - -In this example, `np.linspace(1., 4., 6)` generates 6 evenly spaced values between 1. and 4., including both endpoints. - -Try this and see what happens: - -```python -x = np.linspace(0,100,101) -y = np.sin(x) -``` - -### Other useful functions -- `np.zeros()` -- `np.ones()` -- `np.eye()` - -## Working with Arrays -Now that we have been introduced to some ways to create arrays using the Numpy functions let's start using them. -### Indexing -Indexing in Python allows you to access specific elements within an array based on their position. This means you can directly retrieve and manipulate individual items as needed. - -Python uses **zero-based indexing**, meaning the first element is at position **0** rather than **1**. This approach is common in many programming languages. For example, in a list with five elements, the first element is at index `0`, followed by elements at indices `1`, `2`, `3`, and `4`. - -Here's an example of data from a rocket test stand where thrust was recorded as a function of time. - -```python -thrust_lbf = np.array(0.603355, 2.019083, 2.808092, 4.054973, 1.136618, 0.943668) - ->>> thrust_lbs[3] -``` - -Due to the nature of zero-based indexing. If we want to call the value `4.054973` that will be the 3rd index. -### Operations on arrays -- Arithmetic operations (`+`, `-`, `*`, `/`, `**`) -- `np.add()`, `np.subtract()`, `np.multiply()`, `np.divide()` -- `np.dot()` for dot product -- `np.matmul()` for matrix multiplication -- `np.linalg.inv()`, `np.linalg.det()` for linear algebra -#### Statistics -- `np.mean()`, `np.median()`, `np.std()`, `np.var()` -- `np.min()`, `np.max()`, `np.argmin()`, `np.argmax()` -- Summation along axes: `np.sum(arr, axis=0)` -#### Combining arrays -- Concatenation: `np.concatenate((arr1, arr2), axis=0)` -- Stacking: `np.vstack()`, `np.hstack()` -- Splitting: `np.split()` - -# Exercise -Let's solve a statics problem given the following problem - -A simply supported bridge of length L=20L = 20L=20 m is subjected to three point loads: - -- $P1=10P_1 = 10P1​=10 kN$ at $x=5x = 5x=5 m$ -- $P2=15P_2 = 15P2​=15 kN$ at $x=10x = 10x=10 m$ -- $P3=20P_3 = 20P3​=20 kN$ at $x=15x = 15x=15 m$ - -The bridge is supported by two reaction forces at points AAA (left support) and BBB (right support). We assume the bridge is in static equilibrium, meaning the sum of forces and sum of moments about any point must be zero. - -#### Equilibrium Equations: - -1. **Sum of Forces in the Vertical Direction**: - $RA+RB−P1−P2−P3=0R_A + R_B - P_1 - P_2 - P_3 = 0RA​+RB​−P1​−P2​−P3​=0$ -2. **Sum of Moments About Point A**: - $5P1+10P2+15P3−20RB=05 P_1 + 10 P_2 + 15 P_3 - 20 R_B = 05P1​+10P2​+15P3​−20RB​=0$ -3. **Sum of Moments About Point B**: - $20RA−15P3−10P2−5P1=020 R_A - 15 P_3 - 10 P_2 - 5 P_1 = 020RA​−15P3​−10P2​−5P1​=0$ - -#### System of Equations: - -{RA+RB−10−15−20=05(10)+10(15)+15(20)−20RB=020RA−5(10)−10(15)−15(20)=0\begin{cases} R_A + R_B - 10 - 15 - 20 = 0 \\ 5(10) + 10(15) + 15(20) - 20 R_B = 0 \\ 20 R_A - 5(10) - 10(15) - 15(20) = 0 \end{cases}⎩ - - -## Solution -```python -import numpy as np - -# Define the coefficient matrix A -A = np.array([ - [1, 1], - [0, -20], - [20, 0] -]) - -# Define the right-hand side vector b -b = np.array([ - 45, - 5*10 + 10*15 + 15*20, - 5*10 + 10*15 + 15*20 -]) - -# Solve the system of equations Ax = b -x = np.linalg.lstsq(A, b, rcond=None)[0] # Using least squares to handle potential overdetermination - -# Display the results -print(f"Reaction force at A (R_A): {x[0]:.2f} kN") -print(f"Reaction force at B (R_B): {x[1]:.2f} kN") -``` \ No newline at end of file diff --git a/tutorials/module_1/1_basics_of_python.md b/tutorials/module_1/1_basics_of_python.md deleted file mode 100644 index 48952c6..0000000 --- a/tutorials/module_1/1_basics_of_python.md +++ /dev/null @@ -1,160 +0,0 @@ -# Basics of Python - -This page contains important fundamental concepts used in Python such as syntax, operators, order or precedence and more. - -[Syntax](1_05_basics_of_python#Syntax) -[Operators](1_05_basics_of_python#Operators) -[Order of operation](1_05_basics_of_python#Order%20of%20Operation) -[Data types](1_05_basics_of_python#data%20types) -[Variables](1_05_basics_of_python#Variables) - ---- -## Syntax -### Indentations and blocks -In python *indentations* or the space at the start of each line, signifies a block of code. This becomes important when we start working with function and loops. We will talk more about this in the controls structures tutorial. -### Comments -Comments can be added to your code using the hash operator (#). Any text behind the comment operator till the end of the line will be rendered as a comment. -If you have an entire block of text or code that needs to be commented out, the triple quotation marks (""") can be used. Once used all the code after it will be considered a comment until the comment is ended with the triple quotation marks.f - ---- -## Operators -In python, operators are special symbols or keywords that perform operations on values or variables. This section covers some of the most common operator that you will see in this course. -### Arithmetic operators -| Operator | Name | -| --- | --- | -| + | Addition | -| - | Subtraction | -| * | Multiplication | -| / | Division | -| % | Modulus | -| ** | Exponentiation | -| // | Floor division | - - -### Comparison operators -Used in conditional statements such as `if` statements or `while` loops. Note that in the computer world a double equal sign (`==`) means *is equal to*, where as the single equal sign assigns the variable or defines the variable to be something. - -| Operator | Name | -| --- | --- | -| == | Equal | -| != | Not equal | -| > | Greater than | -| < | Less than | -| >= | Greater than or equal to | -| <= | Less than or equal to | - -### Logical operators -| Operator | Descrription | -| --- | --- | -| and | Returns True if both statemetns are true | -| or | Returns True if one of the statements is true | -| not | Reerse the result, returns False if the result is true | - -### Identity operators -| Operator | Description | -| --- | --- | -| is | Returns True if both variables are the same object | -| is not | Returns True if both variables are not the same object | - ---- -## Order of Operation -Similarly to the order or precedence in mathematics, different computer languages have their own set of rules. Here is a comprehensive table of the order of operation that python follows. - -| Operator | Description | -| ------------------------------------------------------- | ----------------------------------------------------- | -| `()` | Parentheses | -| `**` | Exponentiation | -| `+x` `-x` `~x` | Unary plus, unary minus, and bitwise NOT | -| `*` `/` `//` `%` | Multiplication, Division, floor division, and modulus | -| `+` `-` | Addition and subtraction | -| `<<` `>>` | Bitwise left and right shifts | -| & | Bitwise AND | -| ^ | Bitwise XOR | -| \| | Bitwise OR | -| `==` `!=` `>` `>=` `<` `<=` `is` `is not` `in` `not in` | Comparision, identity and membership operators | -| `not` | logical NOT | -| `and` | AND | -| `or` | OR | - ---- -## Data types -Data types are different ways a computer stores data. Other data types use fewer bits than others allowing you to better utilize your computer memory. This is important for engineers because -The most common data types that an engineer encounters in python are numeric types. -- `int` - integer -- `float` - a decimal number -- `complex` - imaginary number - -The comprehensive table below show all built-in data types available in python. - -| Category | Data Type | -| -------- | ---------------------------- | -| Text | int, float, complex | -| Sequance | list, tuple, range | -| Mapping | dict | -| Set | set, frozenset | -| Boolean | bytes, bytearray, memoryview | -| Binary | bytes, bytearray, memoryview | -| None | NoneType | - ---- -## Variables - -A **variable** in Python is a name that stores a value, allowing you to use and manipulate data efficiently. - -#### Declaring and Assigning Variables - -It is common in low-level computer languages to declare the datatype if the variable. In python, the datatype is set whilst you assign it. We assign values to variables using a single `=`. - -```python -x = 10 # Integer -y = 3.14 # Float -name = "Joe" # String -is_valid = True # Boolean -``` - -You can assign multiple variables at once: - -```python -a, b, c = 1, 2, 3 -``` - -Similarly we can assign the same value to multiple variables: - -```python -x = y = z = 100 -``` -##### Rules - -- Must start with a letter or `_` -- Cannot start with a number -- Can only contain letters, numbers, and `_` -- Case-sensitive (`Name` and `name` are different) - -#### Updating Variables - -You can change a variable’s value at any time. - -```python -x = 5 -x = x + 10 # Now x is 15 -``` - -Or shorthand: - -```python -x += 10 # Same as x = x + 10 -``` - -#### Variable Types & Type Checking - -Use `type()` to check a variable’s type. - -```python -x = 10 -print(type(x)) # Output: - -y = "Hello" -print(type(y)) # Output: -``` - - diff --git a/tutorials/module_1/1_classes_and_objects.md b/tutorials/module_1/1_classes_and_objects.md deleted file mode 100644 index ec85633..0000000 --- a/tutorials/module_1/1_classes_and_objects.md +++ /dev/null @@ -1,47 +0,0 @@ -# Modular Programming - -## 1. Introduction - -- A. What is Object-Oriented Programming? -- B. Why use OOP? (vs. procedural) -- C. Real-world analogies (e.g., modeling components like pumps, motors, or vehicles) - ---- -## 2. Core OOP Concepts -- A. **Classes and Objects** - - Definitions - - Syntax in Python -- B. **Attributes and Methods** - - Instance variables - - Functions inside classes -- C. **Encapsulation** - - Public vs private variables - - Using `__init__` and `self` -- D. **Inheritance** - - Parent and child classes - - Reuse and extension of code -- E. **Polymorphism** _(brief overview)_ - - Method overriding - - Flexibility in interfaces - ---- -## 3. Python OOP Syntax and Examples -- A. Define a simple class (e.g., `Spring`) -- B. Instantiate objects and use methods -- C. Show `__init__`, `__str__`, custom methods -- D. Add a derived class (e.g., `DampedSpring` inherits from `Spring`) - ---- -## 4. Engineering Applications of OOP -- A. Modeling a mechanical system using classes - - Example: Mass-Spring-Damper system -- B. Creating reusable components (e.g., `Material`, `Beam`, `Force`) -- C. Organizing simulation code with OOP - ---- -## 5. Hands-On Coding Activity -- A. Write a class for a basic physical component (e.g., `Motor`) -- B. Add behavior (e.g., `calculate_torque`) -- C. Extend with inheritance (e.g., `ServoMotor`) -- D. Bonus: Integrate two objects to simulate interaction - diff --git a/tutorials/module_1/1_computational_expense.md b/tutorials/module_1/1_computational_expense.md deleted file mode 100644 index c9631e1..0000000 --- a/tutorials/module_1/1_computational_expense.md +++ /dev/null @@ -1,2 +0,0 @@ -# Computational Expense - diff --git a/tutorials/module_1/1_computing_fundamentals.md b/tutorials/module_1/1_computing_fundamentals.md deleted file mode 100644 index 1fef338..0000000 --- a/tutorials/module_1/1_computing_fundamentals.md +++ /dev/null @@ -1,15 +0,0 @@ -# Computing Fundamentals - -## Using computers as a tool for engineers - -## How do computers work? -Globe analogy: Hardware, Kernel, Shell, Application, Software. - -## Interfaces - -### Text editor for Scripting - - - -### Command window -Command window, terminal, console, command prompt you might've heard of theses terms before. They all essentially mean the same thing. The command window is used to control your system. diff --git a/tutorials/module_1/1_control_structures.md b/tutorials/module_1/1_control_structures.md deleted file mode 100644 index 15e97eb..0000000 --- a/tutorials/module_1/1_control_structures.md +++ /dev/null @@ -1,127 +0,0 @@ -# Control Structures -Control structures allow us to control the flow of execution in a Python program. The two main types are **conditional statements (`if` statements)** and **loops (`for` and `while` loops)**. - -## Conditional Statements - -Conditional statements allow a program to execute different blocks of code depending on whether a given condition is `True` or `False`. These conditions are typically comparisons, such as checking if one number is greater than another. - -### The `if` Statement - -The simplest form of a conditional statement is the `if` statement. If the condition evaluates to `True`, the indented block of code runs. Otherwise, the program moves on without executing the statement. - -For example, consider a situation where we need to determine if a person is an adult based on their age. If the age is 18 or greater, we print a message saying they are an adult. - -### The `if-else` Statement - -Sometimes, we need to specify what should happen if the condition is `False`. The `else` clause allows us to handle this case. Instead of just skipping over the block, the program can execute an alternative action. - -For instance, if a person is younger than 18, they are considered a minor. If the condition of being an adult is not met, the program will print a message indicating that the person is a minor. - -### The `if-elif-else` Statement - -When dealing with multiple conditions, the `if-elif-else` structure is useful. The program evaluates conditions in order, executing the first one that is `True`. If none of the conditions are met, the `else` block runs. - -For example, in a grading system, different score ranges correspond to different letter grades. If a student's score is 90 or higher, they receive an "A". If it's between 80 and 89, they get a "B", and so on. If none of the conditions match, they receive an "F". - -### Nested `if` Statements - -Sometimes, we need to check conditions within other conditions. This is known as **nesting**. For example, if we first determine that a person is an adult, we can then check if they are a student. Based on that information, we print different messages. - - -```python -# Getting user input for the student's score -score = int(input("Enter the student's score (0-100): ")) - -if 0 <= score <= 100: - if score >= 90: - grade = "A" - elif score >= 80: - grade = "B" - elif score >= 70: - grade = "C" - elif score >= 60: - grade = "D" - else: - grade = "F" # Score below 60 is a failing grade - - - if grade == "F": - print("The student has failed.") - retake_eligible = input("Is the student eligible for a retest? (yes/no): ").strip().lower() - - if retake_eligible == "yes": - print("The student is eligible for a retest.") - else: - print("The student has failed the course and must retake it next semester.") - - -``` - ---- - -## Loops in Python - -Loops allow a program to execute a block of code multiple times. This is especially useful for tasks such as processing lists of data, performing repetitive calculations, or automating tasks. - -### The `for` Loop - -A `for` loop iterates over a sequence, such as a list, tuple, string, or a range of numbers. Each iteration assigns the next value in the sequence to a loop variable, which can then be used inside the loop. - -For instance, if we have a list of fruits and want to print each fruit's name, a `for` loop can iterate over the list and display each item. - -Another useful feature of `for` loops is the `range()` function, which generates a sequence of numbers. This is commonly used when we need to repeat an action a specific number of times. For example, iterating from 0 to 4 allows us to print a message five times. - -Additionally, the `enumerate()` function can be used to loop through a list while keeping track of the index of each item. This is useful when both the position and the value in a sequence are needed. - -```python -fruits = ["apple", "banana", "cherry"] -for x in fruits: -  print(x) -``` - -```python -for x in range(6): -  print(x) -else: -  print("Finally finished!") -``` -### The `while` Loop - -Unlike `for` loops, which iterate over a sequence, `while` loops continue running as long as a specified condition remains `True`. This is useful when the number of iterations is not known in advance. - -For example, a countdown timer can be implemented using a `while` loop. The loop will continue decreasing the count until it reaches zero. - -It's important to be careful with `while` loops to avoid infinite loops, which occur when the condition never becomes `False`. To prevent this, ensure that the condition will eventually change during the execution of the loop. - -A `while` loop can also be used to wait for a certain event to occur. For example, in interactive programs, a `while True` loop can keep running until the user provides a valid input, at which point we break out of the loop. - -```python -i = 1 -while i < 6: -  print(i) -  i += 1 -``` - ---- - -## Loop Control Statements - -Python provides special statements to control the behavior of loops. These can be used to break out of a loop, skip certain iterations, or simply include a placeholder for future code. - -### The `break` Statement - -The `break` statement is used to exit a loop before it has iterated through all its elements. When the `break` statement is encountered, the loop stops immediately, and the program continues executing the next statement outside the loop. - -For instance, if we are searching for a specific value in a list, we can use a `break` statement to stop the loop as soon as we find the item, instead of continuing unnecessary iterations. - -### The `continue` Statement - -The `continue` statement is used to skip the current iteration and proceed to the next one. Instead of exiting the loop entirely, it simply moves on to the next cycle. - -For example, if we are iterating over numbers and want to skip processing number 2, we can use `continue`. The loop will ignore that iteration and proceed with the next number. - -### The `pass` Statement - -The `pass` statement is a placeholder that does nothing. It is useful when a block of code is syntactically required but no action needs to be performed yet. - -For example, in a loop where a condition has not yet been implemented, using `pass` ensures that the code remains valid while avoiding errors. diff --git a/tutorials/module_1/1_functions.md b/tutorials/module_1/1_functions.md deleted file mode 100644 index 8235fe3..0000000 --- a/tutorials/module_1/1_functions.md +++ /dev/null @@ -1,67 +0,0 @@ -# Functions - -Like a traditional mathematical functions, python functions can take an input, process it, and give an output. In python, the input variables are referred to as *arguments*. Functions are blocks of code that is run every time it's called. This allows us to re-use code. - -Functions are defined by using the def keyword. Reminder: it is important to keep track of indentations as it signifies the end of the function when the indentation returns back to the same level. - -## Defining Functions -### Simple function -A simple function with no input variable can be useful if you need to re-use code multiple times without having to re-write it. - -```python - def function_name(): - print("This is from a function") -``` - -### Defining a function with one input -We can pass variables through to the function to be processed as follows: - -```python - def function(x): - print(x + " is best") -``` - -Note input variables can be of any data type (integer, float, string, etc.). -### Returning values from a function -If we want to calculate a value and pass it back to the script for further use, we can use the `return` keyword. Let's define a linear function that takes two inputs, `x` and `b`, computes the corresponding `y` value, and returns it so it can be used elsewhere in the code. - -```python - def function(x, b): - y = 3*x+b - return y -``` - -For multiple output variables we can add -## Calling functions -Now that we've covered defining functions we want to call the function in order to execute the block inside the function. To do this, we simply re-call the function name as follows. - -```python -function(2,-1) -``` - -Note that when running this code, nothing happens. This is because we haven't told the computer what to do with the output. Hence, if we wish to store the output then we need to use the assign operator `=`. - -```python -output = function(2,-1) - -print(output) -``` - -In case you want to return multiple output variable from a single function we will have... - -## Summary - -```python -def function_name(argument1, argument2, argument3) - output1 = argument1 * argument2 - argument3 - output2 = argument2 + argument3 - return output1, output2 - -[solution1, solution2] = function_name(1,2,3) -``` - - -- `def` - defines a function. All the code that is indented underneath is considered inside the function block. -- `function_name` - this is used to call the function block. -- `argument1` (optional) - input variable. This is data that can be pass to the function. It is possible to have multiple variables separated by a comma. As well as can be omitted if the function should just give you an output such as. -- `return` (optional) - if you wish to return something to your script, the return keyword is used. The keyword can be followed by an output variable or a constant. For multiple output variables, separate them by a comma. \ No newline at end of file diff --git a/tutorials/module_1/1_fundamentals_of_programming.md b/tutorials/module_1/1_fundamentals_of_programming.md deleted file mode 100644 index 617d2c3..0000000 --- a/tutorials/module_1/1_fundamentals_of_programming.md +++ /dev/null @@ -1,15 +0,0 @@ -# Fundamentals of programming -## Orientation of common interfaces -In this section we will cover the use and purpose of some common interfaces that you'll be using in this course. - -### Command window, terminal, console, command prompt. -This is a text based interface that allows the users to interact with the computer. It is used to execute commands, run scripts or programs. - - -### Text Editor / Script -Your text editor is the program used to write a script which can be re-run every time you call it from the command window. This can be a built-in text editor such as Spyder and MATLAB provide or an external on such a notepad++. - - - - Globe analogy: Hardware, Kernel, shell, Application software. - - Scripting \ No newline at end of file diff --git a/tutorials/module_1/1_installing_anaconda.md b/tutorials/module_1/1_installing_anaconda.md deleted file mode 100644 index baa4d71..0000000 --- a/tutorials/module_1/1_installing_anaconda.md +++ /dev/null @@ -1,59 +0,0 @@ -# Installing Anaconda - -This tutorial will cover the steps on how to install Anaconda. - -*Note for Advanced users: For those who wish to have a lightweight installation, can install miniconda or miniForge, however for this course we will show you how to use Anaconda Navigator. If you've never used the programs before then using Anaconda is recommended.* - -### What is Anaconda? -Anaconda Distribution is a popular open-source Python distribution specifically designed for scientific computing, data science, machine learning, and artificial intelligence applications. It simplifies the set up and use of Python for data science, machine learning, and scientific computing. It comes with all the important tools you need, like NumPy, Pandas, and JupyterLab, so you don’t have to install everything separately. The Conda package manager helps you install and update software without worrying about breaking other programs. It also lets you create separate environments, so different projects don’t interfere with each other. Additionally, Anaconda includes programs like JupyterLab for interactive coding, and Spyer a MATLAB-like IDE. - ---- -## Instructions -1. Find the latest version of Navigator from the official Anaconda Inc. website: [Download Anaconda](https://www.anaconda.com/download) - -2. Press the *Download Now* button. - -3. Press the *Skip registration* button below the submit button, otherwise submit your email address to subscribe to the Anaconda email list. - -4. Under Anaconda Installers press *Download* or find the appropriate version for your operating system below. - -Proceed to next section for your respective operating system. - -### Windows - -5. Once the download is complete, double click the executable (.exe) file to start the installer. Proceed with the installation instructions. - -![Welcome screen](figures/installingAnaconda_windows_installer_01_welcome.png) - -![Terms and conditions](figures/installingAnaconda_windows_installer_02_terms.png) - - -6. Select the *Just Me* recommended option. - -![Install for](figures/installingAnaconda_windows_installer_03_for.png) - - -7. You can leave the destination folder as is, just make sure you have a minimum of ~5 GB available storage space. Press *Next* to proceed. - -![Installation destination](figures/installingAnaconda_windows_installer_04_destination.png) - - -8. It is recommended to register Anaconda3 as the default python version if you already have an instance of python installed. Otherwise, you can leave the checkboxes as defaults. - -![Avanced Options](figures/installingAnaconda_windows_installer_05_advanced.png) - -![Installing](figures/installingAnaconda_windows_installer_06_installing.png) - -![Installing 2](figures/installingAnaconda_windows_installer_07_installing2.png) - -![Complete](figures/installingAnaconda_windows_installer_08_installing_complete.png) - -![Cloud](figures/installingAnaconda_windows_installer_09_cloud.png) - -![Finish](figures/installingAnaconda_windows_installer_10_finish.png) - - -9. You made it! Anaconda is now installed, you are ready for launch. Assuming that you didn't add Anaconda to PATH environment variable you will need to start navigator from the start menu. - -### Mac/Linux -Anaconda provides installation documentation for Mac and Linux users, please refer to the [documentation page](https://docs.anaconda.com/anaconda/install/). diff --git a/tutorials/module_1/1_intro_to_anaconda.md b/tutorials/module_1/1_intro_to_anaconda.md deleted file mode 100644 index 84c6516..0000000 --- a/tutorials/module_1/1_intro_to_anaconda.md +++ /dev/null @@ -1,79 +0,0 @@ -# Introduction to Anaconda Navigator - -Anaconda Navigator is a program that we will be using in this course to manage Python environments, libraries and launch programs to help us write our python code. - -The Anaconda website nicely describes *Navigator* as: -
-

a graphical user interface (GUI) that enables you to work with packages and environments without needing to type conda commands in a terminal window.Find the packages you want, install them in an environment, run the packages, and update them – all inside Navigator. -

- -To better understand how Navigator works and interacts with the anaconda ecosystem see the figure below. -![Anaconda Schematic](figures/AnacondaSchematic.png) -As you schematic indicated, Navigator is a tool in the Anaconda toolbox that allows the user to select and configure python environments and libraries. Let's see how we can do this. - ---- -## Getting Started - -Note to windows 10 users: Some installation instances do not allow users to search the start menu for *Navigator*, instead, you'll have to find the program under the *Anaconda (anaconda3)* folder. Expand the folder and click on *Anaconda Navigator* to launch the program. - -![Anaconda Navigator screen](figures/installingAnaconda_windows_launched.png) - -Once Navigator starts, under *Home*, you'll see tiles of programs that come with anaconda. The tab allows you to launch the programs we will be using in this course. Before jumping straight into the programs we will first need to configure our Python instance. - -The *Environment* page allows us to install a variety of libraries and configure our environments for different project, more on this in the next section. - -## Environments -A Python environment can be thought of as a "container" where you can have all the tools, libraries, and dependencies your Python project needs without interfering with other projects. Think of it as a dedicated toolbox for your project. - -Although the base environment comes with many libraries and programs pre-installed, it's recommended to create a dedicated environment for your projects. This protects the base environment from breaking due to complex dependency conflicts. Let us go ahead and create a new environment for us to use Spyder with. - -1. Click on the *Environments* page located on the left hand side. - -![Environment Page](https://mintlify.s3.us-west-1.amazonaws.com/anaconda-29683c67/images/nav-env-labeled.png) - -2. At the bottom of the environments list, click *Create*. - -![Create new environment](https://mintlify.s3.us-west-1.amazonaws.com/anaconda-29683c67/images/nav-getting-started-create.png) - -3. Select the python checkbox. - -4. Select versions of python. At the time of making this tutorial the latest version of Python is 3.xx.x. We will go ahead and use that one. - -5. Choose an appropriate name for your project. We will be creating an environment for the Spyder IDE so we'll call it "Spyder-env". - -6. Click *Create*. - -For more information see [Anaconda Environments](https://docs.anaconda.com/working-with-conda/environments/) and [Managing environment](https://docs.anaconda.com/navigator/tutorials/manage-environments/). - -## Package Management -Now that we have a clean environment configured, let us install some library we will be using for this class. - -1. Navigate to the environment page and select the environment we just created in the previous section. - -![Select environment to manage](https://mintlify.s3.us-west-1.amazonaws.com/anaconda-29683c67/images/nav-pkg-list.png) - -2. Use the search bar in the top right corner to search for the following packages: - -| Library | Usage | -| ---------- | --------------------------------- | -| numpy | Numerical computation | -| scipy | Scientific and techical computing | -| pandas | Data manipulation and analysis | -| matplotlib | Plots and visualizations | -| sympy | Symbolic mathematics | -*Note: The libraries list may change throughout the development of this course* - -3. Check the boxes to install the selected packages to the current environment. - -## Installing Applications -From the *Home* page you can install applications, to the current environment we created in the Environment section above. In this section we will install Spyder IDE, but the process is exactly the same for other applications. - -1. Go to the *Home* page. - -2. Select the desired environment. In our case, we select *Spyder-env*. - -3. From the Home page find the Spyder IDE tile. Click the *Install* button to start the download. - -![Anaconda Home Page](https://mintlify.s3.us-west-1.amazonaws.com/anaconda-29683c67/images/nav-tabs.png) - -4. Once the download is complete, press *Launch* to start the applications. \ No newline at end of file diff --git a/tutorials/module_1/1_intro_to_programming.md b/tutorials/module_1/1_intro_to_programming.md deleted file mode 100644 index 2f12a3a..0000000 --- a/tutorials/module_1/1_intro_to_programming.md +++ /dev/null @@ -1,15 +0,0 @@ -# Introduction to Programming -## The Importance of Programming in Engineering - -Engineering is all about solving problems, designing innovative solutions, and making systems work efficiently. Whether you’re designing cars, airplanes, rockets, or even everyday machines, programming plays a critical role in modern engineering. - -In mechanical engineering, programming helps us **analyze data, model complex systems, automate repetitive tasks, and simulate real-world physics.** For example, instead of spending hours solving equations by hand, engineers can write a program that does it in seconds. This saves time and therefore do more. - -With programming, mechanical engineers can: - -- **Automate calculations:** Quickly solve equations for heat transfer, fluid dynamics, and mechanical stresses. -- **Simulate systems:** Model how a bridge bends under weight or how an engine burns fuel efficiently. -- **Analyze data:** Process thousands of test results to improve designs. -- **Control machines:** Program robots, 3D printers, and CNC's. - -In this course, you’ll see how computing and programming applies to mechanical engineering and how they can make you a better problem solver. By the end, you’ll have the skills and understanding of how to write programs that help you **think like an engineer in the digital age.** diff --git a/tutorials/module_1/1_jupyter_lab_notebook.md b/tutorials/module_1/1_jupyter_lab_notebook.md deleted file mode 100644 index 5fa493a..0000000 --- a/tutorials/module_1/1_jupyter_lab_notebook.md +++ /dev/null @@ -1,105 +0,0 @@ -## Introduction - - -Jupyter Notebooks are often used for data science and scientific computing such as machine learning as the interactive design allow you to experiment easily with your code. For our purpose, we will use Notebooks as it's a useful tool to learn how to code as well as writing reports. - -*Note on the difference between Notebook and Lab: Jupyter Notebook offers a simplified, lightweight notebook authoring experience, where as, JupyterLab offers a feature-rich, tabbed multi-notebook editing environment with additional tools like a customizable interface layout and system console* - - ---- -## Setup and Installation -Installing with Conda using CLI: -- `conda install jupyter` -Jupyter can also be installed using a Anaconda Navigator - - - Launching: - - From terminal: `jupyter notebook` or `jupyter lab` - - From Anaconda Navigator or VSCode - - Navigating the interface: - - Tabs and file browser - - Kernel and terminals - ---- - -## Notebook Basics -- Creating a new notebook (`.ipynb`) -- Types of cells: - - Code - - Markdown - - Raw -- Running a cell: `Shift + Enter` -- Adding/removing cells -- Restarting the kernel -- Saving and auto-checkpoints - ---- - -## Writing and Running Code -- Python syntax: - - `print("Hello, world!")` - - Variables and functions - - Loops and conditionals -- Importing libraries: - - `import numpy as np` - - `import pandas as pd` - - `import matplotlib.pyplot as plt` - ---- - -## Using Markdown -- Headers: `#`, `##`, `###` -- Bullet lists: `- item` -- Numbered lists: `1. item` -- Emphasis: _italic_, **bold**, `monospace` -- LaTeX equations: - - Inline: `$E = mc^2$` - - Block: `$$\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$$` -- Embedding links and images - - - ---- -## Interactive Widgets (optional) - -Install `ipywidgets` from your package manager - -```python -import ipywidgets as widgets -widgets.IntSlider() -``` -Example using interact: - -```python -from ipywidgets import interact -interact(lambda x: x**2, x=5) -``` - - ---- -## Productivity Tips -Here are some keyboard shortcuts to improve your productivity when writing in notebooks. - -| Key | Action | -| --- | ------------------ | -| A | insert cell above | -| B | insert cell below | -| M | switch to Markdown | -| Y | switch to code | - Magic commands: -- `%timeit`, `%matplotlib inline`, `%%bash` -Splitting and merging cells -Auto-save behavior - ---- - -## Exporting and Sharing - - File > Download As: - - Notebook (`.ipynb`) - - HTML - - PDF (requires LaTeX) - - Markdown -- Notebooks can be saved and shared via the following services: - - GitHub - - nbviewer.org - - mybinder.org - - JupyterHub \ No newline at end of file diff --git a/tutorials/module_1/1_open_source_software.md b/tutorials/module_1/1_open_source_software.md deleted file mode 100644 index d82b30a..0000000 --- a/tutorials/module_1/1_open_source_software.md +++ /dev/null @@ -1,43 +0,0 @@ -# Open Source Software - -Open-source software (OSS) is a type of software that allows users to access, modify, and distribute its source code freely. It is built on principles of collaboration, transparency, and community-driven development. - -You've probably heard of the saying "Don't reinventing the wheel". This - -### Key Principles of Open Source Software - -- **Free Distribution:** Anyone can download and use the software without cost. -- **Access to Source Code:** Users can view and modify the code to suit their needs. -- **Community Collaboration:** Developers from around the world contribute to improvements and security fixes. - -### Benefits of Open Source Software - -- **Cost-effectiveness:** Open-source software is free to use, making it accessible to individuals and organizations. -- **Transparency and Security:** Open code allows for peer review, reducing security vulnerabilities. -- **Community Support:** Global developer communities provide assistance, troubleshooting, and improvements. -- **Customization and Flexibility:** Users can modify software to fit their specific requirements. - -### Challenges of Open Source Software - -- **Usability Issues:** Some open-source software may have a steeper learning curve. -- **Compatibility Problems:** Integration with proprietary systems may require additional effort. -- **Support and Documentation:** The quality of documentation and support varies. -- **Sustainability:** Open-source projects often rely on volunteers, which can lead to inconsistent updates. - -### Popular Open Source Projects - -- **Operating Systems:** Linux, Ubuntu -- **Web Browsers:** Mozilla Firefox -- **Programming Languages:** Python, JavaScript -- **Office Suites:** LibreOffice -- **Multimedia Tools:** Audacity, Blender -- **Software Development:** Git, GitHub, Apache - -### How to Contribute to Open Source - -- **Finding Projects:** Platforms like GitHub, GitLab, and SourceForge host many open-source projects. -- **Understanding Licensing:** Common licenses include GPL, MIT, and Apache. -- **Ways to Contribute:** Developers can contribute code, test software, write documentation, translate, or help with design. -- **Best Practices for Contributions:** Using version control (Git), writing clean code, and following community guidelines are essential for successful collaboration. - -## Licensing diff --git a/tutorials/module_1/1_spyder_getting_started.md b/tutorials/module_1/1_spyder_getting_started.md deleted file mode 100644 index ba055d7..0000000 --- a/tutorials/module_1/1_spyder_getting_started.md +++ /dev/null @@ -1,41 +0,0 @@ -# Getting started with Spyder - -In this tutorial we will cover the basics of using the Spyder IDE (Interactive Development Environment). If you've ever worked with MATLAB before, then this will feel familiar. Spyder is a program that allows you to write, run and de-bug code. - -## Launching Spyder -Using Anaconda we will select the environment we created earlier *spyder-dev* and then we can launch spyder from the Home page. - -## Spyder Interface - -![Spyder Interface](https://docs.spyder-ide.org/current/_images/mainwindow_default_1610.png) - -Once you open up Spyder in it's default configuration, you'll see three sections; the editor IPython Console, Help viewer. You can customize the interface to suit your prefference and needs some of which include, rearrange, undock, hide panes. Feel free to set up Spyder as you like. - -### Editor -This pane is used to write your scripts. The - -![Editor key components](https://docs.spyder-ide.org/5/_images/editor-components.png) - -1. The left sidebar shows line numbers and displays any code analysis warnings that exist in the current file. Clicking a line number selects the text on that line, and clicking to the right of it sets a [breakpoint](https://docs.spyder-ide.org/5/panes/debugging.html#debugging-breakpoints). -2. The scrollbars allow vertical and horizontal navigation in a file. -3. The context (right-click) menu displays actions relevant to whatever was clicked. -4. The options menu (“Hamburger” icon at top right) includes useful settings and actions relevant to the Editor. -5. The location bar at the top of the Editor pane shows the full path of the current file. -6. The tab bar displays the names of all opened files. It also has a Browse tabs button (at left) to show every open tab and switch between them—which comes in handy if many are open. - -### IPython Console -This pane allows you to interactively run functions, do math computations, assign and modify variables. - -![IPython Console](https://docs.spyder-ide.org/5/_images/console-standard.png) - -- Automatic code completion -- Real-time function calltips -- Full GUI integration with the enhanced Spyder [Debugger](https://docs.spyder-ide.org/5/panes/debugging.html). -- The [Variable Explorer](https://docs.spyder-ide.org/5/panes/variableexplorer.html), with GUI-based editors for many built-in and third-party Python objects. -- Display of Matplotlib graphics in Spyder’s [Plots](https://docs.spyder-ide.org/5/panes/plots.html) pane, if the Inline backend is selected under Preferences ‣ IPython console ‣ Graphics ‣ Graphics backend, and inline in the console if Mute inline plotting is unchecked under the Plots pane’s options menu. - -### Variable Explorer -This pane shows all the defined variables (objects) stored. This can be used to identify the data type of variables, the size and inspect larger arrays. Double clicking the value cell opens up a window which allowing you to inspect the data in a spreadsheet like view. - -![Variable Explorer](https://docs.spyder-ide.org/5/_images/variable-explorer-standard.png) - diff --git a/tutorials/module_1/array.md b/tutorials/module_1/array.md new file mode 100644 index 0000000..c8f2452 --- /dev/null +++ b/tutorials/module_1/array.md @@ -0,0 +1,169 @@ +# Arrays + +In computer programming, an array is a structure for storing and retrieving data. We often talk about an array as if it were a grid in space, with each cell storing one element of the data. For instance, if each element of the data were a number, we might visualize a “one-dimensional” array like a list: + +| 1 | 5 | 2 | 0 | +| --- | --- | --- | --- | + +A two-dimensional array would be like a table: + +| 1 | 5 | 2 | 0 | +| --- | --- | --- | --- | +| 8 | 3 | 6 | 1 | +| 1 | 7 | 2 | 9 | + +A three-dimensional array would be like a set of tables, perhaps stacked as though they were printed on separate pages. If we visualize the position of each element as a position in space. Then we can represent the value of the element as a property. In other words, if we were to analyze the stress concentration of an aluminum block, the property would be stress. + +- From [Numpy documentation](https://numpy.org/doc/2.2/user/absolute_beginners.html) +![Mathworks 3-D array](https://www.mathworks.com/help/examples/matlab/win64/nddemo_02.gif) + +If the load on this block changes over time, then we may want to add a 4th dimension i.e. additional sets of 3-D arrays for each time increment. As you can see - the more dimensions we add, the more complicated of a problem we have to solve. It is possible to increase the number of dimensions to the n-th order. This course we will not be going beyond dimensional analysis. + +--- +# Numpy - the python's array library + +In this tutorial we will be introducing arrays and we will be using the numpy library. Arrays, lists, vectors, matrices, sets - You might've heard of them before, they all store data. In programming, an array is a variable that can hold more than one value at a time. We will be using the Numpy python library to create arrays. Since we already have installed Numpy previously, we can start using the package. + +Before importing our first package, let's as ourselves *what is a package?* A package can be thought of as pre-written python code that we can re-use. This means the for every script that we write in python we need to tell it to use a certain package. We call this importing a package. + +## Importing Numpy +When using packages in python, we need to let it know what package we will be using. This is called importing. To import numpy we need to declare it a the start of a script as follows: +```python +import numpy as np +``` +- `import` - calls for a library to use, in our case it is Numpy. +- `as` - gives the library an alias in your script. It's common convention in Python programming to make the code shorter and more readable. We will be using *np* as it's a standard using in many projects. + +--- +# Creating arrays +Now that we have imported the library we can create a one dimensional array or *vector* with three elements. +```python +x = np.array([1,2,3]) +``` + + +To create a *matrix* we can nest the arrays to create a two dimensional array. This is done as follows. + +```python +matrix = np.array([[1,2,3], + [4,5,6], + [7,8,9]]) +``` + +*Note: for every array we nest, we get a new dimension in our data structure.* + +## Numpy array creation functions +Numpy comes with some built-in function that we can use to create arrays quickly. Here are a couple of functions that are commonly used in python. +### np.arange +The `np.arange()` function returns an array with evenly spaced values within a specified range. It is similar to the built-in `range()` function in Python but returns a Numpy array instead of a list. The parameters for this function are the start value (inclusive), the stop value (exclusive), and the step size. If the step size is not provided, it defaults to 1. + +```python +>>> np.arange(4) +array([0. , 1., 2., 3. ]) +``` + +In this example, `np.arange(4)` generates an array starting from 0 and ending before 4, with a step size of 1. + +### np.linspace +The `np.linspace()` function returns an array of evenly spaced values over a specified range. Unlike `np.arange()`, which uses a step size to define the spacing between elements, `np.linspace()` uses the number of values you want to generate and calculates the spacing automatically. It accepts three parameters: the start value, the stop value, and the number of samples. + +```python +>>> np.linspace(1., 4., 6) +array([1. , 1.6, 2.2, 2.8, 3.4, 4. ]) +``` + +In this example, `np.linspace(1., 4., 6)` generates 6 evenly spaced values between 1. and 4., including both endpoints. + +Try this and see what happens: + +```python +x = np.linspace(0,100,101) +y = np.sin(x) +``` + +### Other useful functions +- `np.zeros()` +- `np.ones()` +- `np.eye()` + +## Working with Arrays +Now that we have been introduced to some ways to create arrays using the Numpy functions let's start using them. +### Indexing +Indexing in Python allows you to access specific elements within an array based on their position. This means you can directly retrieve and manipulate individual items as needed. + +Python uses **zero-based indexing**, meaning the first element is at position **0** rather than **1**. This approach is common in many programming languages. For example, in a list with five elements, the first element is at index `0`, followed by elements at indices `1`, `2`, `3`, and `4`. + +Here's an example of data from a rocket test stand where thrust was recorded as a function of time. + +```python +thrust_lbf = np.array(0.603355, 2.019083, 2.808092, 4.054973, 1.136618, 0.943668) + +>>> thrust_lbs[3] +``` + +Due to the nature of zero-based indexing. If we want to call the value `4.054973` that will be the 3rd index. +### Operations on arrays +- Arithmetic operations (`+`, `-`, `*`, `/`, `**`) +- `np.add()`, `np.subtract()`, `np.multiply()`, `np.divide()` +- `np.dot()` for dot product +- `np.matmul()` for matrix multiplication +- `np.linalg.inv()`, `np.linalg.det()` for linear algebra +#### Statistics +- `np.mean()`, `np.median()`, `np.std()`, `np.var()` +- `np.min()`, `np.max()`, `np.argmin()`, `np.argmax()` +- Summation along axes: `np.sum(arr, axis=0)` +#### Combining arrays +- Concatenation: `np.concatenate((arr1, arr2), axis=0)` +- Stacking: `np.vstack()`, `np.hstack()` +- Splitting: `np.split()` + +# Exercise +Let's solve a statics problem given the following problem + +A simply supported bridge of length L=20L = 20L=20 m is subjected to three point loads: + +- $P1=10P_1 = 10P1​=10 kN$ at $x=5x = 5x=5 m$ +- $P2=15P_2 = 15P2​=15 kN$ at $x=10x = 10x=10 m$ +- $P3=20P_3 = 20P3​=20 kN$ at $x=15x = 15x=15 m$ + +The bridge is supported by two reaction forces at points AAA (left support) and BBB (right support). We assume the bridge is in static equilibrium, meaning the sum of forces and sum of moments about any point must be zero. + +#### Equilibrium Equations: + +1. **Sum of Forces in the Vertical Direction**: + $RA+RB−P1−P2−P3=0R_A + R_B - P_1 - P_2 - P_3 = 0RA​+RB​−P1​−P2​−P3​=0$ +2. **Sum of Moments About Point A**: + $5P1+10P2+15P3−20RB=05 P_1 + 10 P_2 + 15 P_3 - 20 R_B = 05P1​+10P2​+15P3​−20RB​=0$ +3. **Sum of Moments About Point B**: + $20RA−15P3−10P2−5P1=020 R_A - 15 P_3 - 10 P_2 - 5 P_1 = 020RA​−15P3​−10P2​−5P1​=0$ + +#### System of Equations: + +{RA+RB−10−15−20=05(10)+10(15)+15(20)−20RB=020RA−5(10)−10(15)−15(20)=0\begin{cases} R_A + R_B - 10 - 15 - 20 = 0 \\ 5(10) + 10(15) + 15(20) - 20 R_B = 0 \\ 20 R_A - 5(10) - 10(15) - 15(20) = 0 \end{cases}⎩ + + +## Solution +```python +import numpy as np + +# Define the coefficient matrix A +A = np.array([ + [1, 1], + [0, -20], + [20, 0] +]) + +# Define the right-hand side vector b +b = np.array([ + 45, + 5*10 + 10*15 + 15*20, + 5*10 + 10*15 + 15*20 +]) + +# Solve the system of equations Ax = b +x = np.linalg.lstsq(A, b, rcond=None)[0] # Using least squares to handle potential overdetermination + +# Display the results +print(f"Reaction force at A (R_A): {x[0]:.2f} kN") +print(f"Reaction force at B (R_B): {x[1]:.2f} kN") +``` \ No newline at end of file diff --git a/tutorials/module_1/basics_of_python.md b/tutorials/module_1/basics_of_python.md new file mode 100644 index 0000000..48952c6 --- /dev/null +++ b/tutorials/module_1/basics_of_python.md @@ -0,0 +1,160 @@ +# Basics of Python + +This page contains important fundamental concepts used in Python such as syntax, operators, order or precedence and more. + +[Syntax](1_05_basics_of_python#Syntax) +[Operators](1_05_basics_of_python#Operators) +[Order of operation](1_05_basics_of_python#Order%20of%20Operation) +[Data types](1_05_basics_of_python#data%20types) +[Variables](1_05_basics_of_python#Variables) + +--- +## Syntax +### Indentations and blocks +In python *indentations* or the space at the start of each line, signifies a block of code. This becomes important when we start working with function and loops. We will talk more about this in the controls structures tutorial. +### Comments +Comments can be added to your code using the hash operator (#). Any text behind the comment operator till the end of the line will be rendered as a comment. +If you have an entire block of text or code that needs to be commented out, the triple quotation marks (""") can be used. Once used all the code after it will be considered a comment until the comment is ended with the triple quotation marks.f + +--- +## Operators +In python, operators are special symbols or keywords that perform operations on values or variables. This section covers some of the most common operator that you will see in this course. +### Arithmetic operators +| Operator | Name | +| --- | --- | +| + | Addition | +| - | Subtraction | +| * | Multiplication | +| / | Division | +| % | Modulus | +| ** | Exponentiation | +| // | Floor division | + + +### Comparison operators +Used in conditional statements such as `if` statements or `while` loops. Note that in the computer world a double equal sign (`==`) means *is equal to*, where as the single equal sign assigns the variable or defines the variable to be something. + +| Operator | Name | +| --- | --- | +| == | Equal | +| != | Not equal | +| > | Greater than | +| < | Less than | +| >= | Greater than or equal to | +| <= | Less than or equal to | + +### Logical operators +| Operator | Descrription | +| --- | --- | +| and | Returns True if both statemetns are true | +| or | Returns True if one of the statements is true | +| not | Reerse the result, returns False if the result is true | + +### Identity operators +| Operator | Description | +| --- | --- | +| is | Returns True if both variables are the same object | +| is not | Returns True if both variables are not the same object | + +--- +## Order of Operation +Similarly to the order or precedence in mathematics, different computer languages have their own set of rules. Here is a comprehensive table of the order of operation that python follows. + +| Operator | Description | +| ------------------------------------------------------- | ----------------------------------------------------- | +| `()` | Parentheses | +| `**` | Exponentiation | +| `+x` `-x` `~x` | Unary plus, unary minus, and bitwise NOT | +| `*` `/` `//` `%` | Multiplication, Division, floor division, and modulus | +| `+` `-` | Addition and subtraction | +| `<<` `>>` | Bitwise left and right shifts | +| & | Bitwise AND | +| ^ | Bitwise XOR | +| \| | Bitwise OR | +| `==` `!=` `>` `>=` `<` `<=` `is` `is not` `in` `not in` | Comparision, identity and membership operators | +| `not` | logical NOT | +| `and` | AND | +| `or` | OR | + +--- +## Data types +Data types are different ways a computer stores data. Other data types use fewer bits than others allowing you to better utilize your computer memory. This is important for engineers because +The most common data types that an engineer encounters in python are numeric types. +- `int` - integer +- `float` - a decimal number +- `complex` - imaginary number + +The comprehensive table below show all built-in data types available in python. + +| Category | Data Type | +| -------- | ---------------------------- | +| Text | int, float, complex | +| Sequance | list, tuple, range | +| Mapping | dict | +| Set | set, frozenset | +| Boolean | bytes, bytearray, memoryview | +| Binary | bytes, bytearray, memoryview | +| None | NoneType | + +--- +## Variables + +A **variable** in Python is a name that stores a value, allowing you to use and manipulate data efficiently. + +#### Declaring and Assigning Variables + +It is common in low-level computer languages to declare the datatype if the variable. In python, the datatype is set whilst you assign it. We assign values to variables using a single `=`. + +```python +x = 10 # Integer +y = 3.14 # Float +name = "Joe" # String +is_valid = True # Boolean +``` + +You can assign multiple variables at once: + +```python +a, b, c = 1, 2, 3 +``` + +Similarly we can assign the same value to multiple variables: + +```python +x = y = z = 100 +``` +##### Rules + +- Must start with a letter or `_` +- Cannot start with a number +- Can only contain letters, numbers, and `_` +- Case-sensitive (`Name` and `name` are different) + +#### Updating Variables + +You can change a variable’s value at any time. + +```python +x = 5 +x = x + 10 # Now x is 15 +``` + +Or shorthand: + +```python +x += 10 # Same as x = x + 10 +``` + +#### Variable Types & Type Checking + +Use `type()` to check a variable’s type. + +```python +x = 10 +print(type(x)) # Output: + +y = "Hello" +print(type(y)) # Output: +``` + + diff --git a/tutorials/module_1/classes_and_objects.md b/tutorials/module_1/classes_and_objects.md new file mode 100644 index 0000000..ec85633 --- /dev/null +++ b/tutorials/module_1/classes_and_objects.md @@ -0,0 +1,47 @@ +# Modular Programming + +## 1. Introduction + +- A. What is Object-Oriented Programming? +- B. Why use OOP? (vs. procedural) +- C. Real-world analogies (e.g., modeling components like pumps, motors, or vehicles) + +--- +## 2. Core OOP Concepts +- A. **Classes and Objects** + - Definitions + - Syntax in Python +- B. **Attributes and Methods** + - Instance variables + - Functions inside classes +- C. **Encapsulation** + - Public vs private variables + - Using `__init__` and `self` +- D. **Inheritance** + - Parent and child classes + - Reuse and extension of code +- E. **Polymorphism** _(brief overview)_ + - Method overriding + - Flexibility in interfaces + +--- +## 3. Python OOP Syntax and Examples +- A. Define a simple class (e.g., `Spring`) +- B. Instantiate objects and use methods +- C. Show `__init__`, `__str__`, custom methods +- D. Add a derived class (e.g., `DampedSpring` inherits from `Spring`) + +--- +## 4. Engineering Applications of OOP +- A. Modeling a mechanical system using classes + - Example: Mass-Spring-Damper system +- B. Creating reusable components (e.g., `Material`, `Beam`, `Force`) +- C. Organizing simulation code with OOP + +--- +## 5. Hands-On Coding Activity +- A. Write a class for a basic physical component (e.g., `Motor`) +- B. Add behavior (e.g., `calculate_torque`) +- C. Extend with inheritance (e.g., `ServoMotor`) +- D. Bonus: Integrate two objects to simulate interaction + diff --git a/tutorials/module_1/computational_expense.md b/tutorials/module_1/computational_expense.md new file mode 100644 index 0000000..c9631e1 --- /dev/null +++ b/tutorials/module_1/computational_expense.md @@ -0,0 +1,2 @@ +# Computational Expense + diff --git a/tutorials/module_1/computing_fundamentals.md b/tutorials/module_1/computing_fundamentals.md new file mode 100644 index 0000000..1fef338 --- /dev/null +++ b/tutorials/module_1/computing_fundamentals.md @@ -0,0 +1,15 @@ +# Computing Fundamentals + +## Using computers as a tool for engineers + +## How do computers work? +Globe analogy: Hardware, Kernel, Shell, Application, Software. + +## Interfaces + +### Text editor for Scripting + + + +### Command window +Command window, terminal, console, command prompt you might've heard of theses terms before. They all essentially mean the same thing. The command window is used to control your system. diff --git a/tutorials/module_1/control_structures.md b/tutorials/module_1/control_structures.md new file mode 100644 index 0000000..15e97eb --- /dev/null +++ b/tutorials/module_1/control_structures.md @@ -0,0 +1,127 @@ +# Control Structures +Control structures allow us to control the flow of execution in a Python program. The two main types are **conditional statements (`if` statements)** and **loops (`for` and `while` loops)**. + +## Conditional Statements + +Conditional statements allow a program to execute different blocks of code depending on whether a given condition is `True` or `False`. These conditions are typically comparisons, such as checking if one number is greater than another. + +### The `if` Statement + +The simplest form of a conditional statement is the `if` statement. If the condition evaluates to `True`, the indented block of code runs. Otherwise, the program moves on without executing the statement. + +For example, consider a situation where we need to determine if a person is an adult based on their age. If the age is 18 or greater, we print a message saying they are an adult. + +### The `if-else` Statement + +Sometimes, we need to specify what should happen if the condition is `False`. The `else` clause allows us to handle this case. Instead of just skipping over the block, the program can execute an alternative action. + +For instance, if a person is younger than 18, they are considered a minor. If the condition of being an adult is not met, the program will print a message indicating that the person is a minor. + +### The `if-elif-else` Statement + +When dealing with multiple conditions, the `if-elif-else` structure is useful. The program evaluates conditions in order, executing the first one that is `True`. If none of the conditions are met, the `else` block runs. + +For example, in a grading system, different score ranges correspond to different letter grades. If a student's score is 90 or higher, they receive an "A". If it's between 80 and 89, they get a "B", and so on. If none of the conditions match, they receive an "F". + +### Nested `if` Statements + +Sometimes, we need to check conditions within other conditions. This is known as **nesting**. For example, if we first determine that a person is an adult, we can then check if they are a student. Based on that information, we print different messages. + + +```python +# Getting user input for the student's score +score = int(input("Enter the student's score (0-100): ")) + +if 0 <= score <= 100: + if score >= 90: + grade = "A" + elif score >= 80: + grade = "B" + elif score >= 70: + grade = "C" + elif score >= 60: + grade = "D" + else: + grade = "F" # Score below 60 is a failing grade + + + if grade == "F": + print("The student has failed.") + retake_eligible = input("Is the student eligible for a retest? (yes/no): ").strip().lower() + + if retake_eligible == "yes": + print("The student is eligible for a retest.") + else: + print("The student has failed the course and must retake it next semester.") + + +``` + +--- + +## Loops in Python + +Loops allow a program to execute a block of code multiple times. This is especially useful for tasks such as processing lists of data, performing repetitive calculations, or automating tasks. + +### The `for` Loop + +A `for` loop iterates over a sequence, such as a list, tuple, string, or a range of numbers. Each iteration assigns the next value in the sequence to a loop variable, which can then be used inside the loop. + +For instance, if we have a list of fruits and want to print each fruit's name, a `for` loop can iterate over the list and display each item. + +Another useful feature of `for` loops is the `range()` function, which generates a sequence of numbers. This is commonly used when we need to repeat an action a specific number of times. For example, iterating from 0 to 4 allows us to print a message five times. + +Additionally, the `enumerate()` function can be used to loop through a list while keeping track of the index of each item. This is useful when both the position and the value in a sequence are needed. + +```python +fruits = ["apple", "banana", "cherry"] +for x in fruits: +  print(x) +``` + +```python +for x in range(6): +  print(x) +else: +  print("Finally finished!") +``` +### The `while` Loop + +Unlike `for` loops, which iterate over a sequence, `while` loops continue running as long as a specified condition remains `True`. This is useful when the number of iterations is not known in advance. + +For example, a countdown timer can be implemented using a `while` loop. The loop will continue decreasing the count until it reaches zero. + +It's important to be careful with `while` loops to avoid infinite loops, which occur when the condition never becomes `False`. To prevent this, ensure that the condition will eventually change during the execution of the loop. + +A `while` loop can also be used to wait for a certain event to occur. For example, in interactive programs, a `while True` loop can keep running until the user provides a valid input, at which point we break out of the loop. + +```python +i = 1 +while i < 6: +  print(i) +  i += 1 +``` + +--- + +## Loop Control Statements + +Python provides special statements to control the behavior of loops. These can be used to break out of a loop, skip certain iterations, or simply include a placeholder for future code. + +### The `break` Statement + +The `break` statement is used to exit a loop before it has iterated through all its elements. When the `break` statement is encountered, the loop stops immediately, and the program continues executing the next statement outside the loop. + +For instance, if we are searching for a specific value in a list, we can use a `break` statement to stop the loop as soon as we find the item, instead of continuing unnecessary iterations. + +### The `continue` Statement + +The `continue` statement is used to skip the current iteration and proceed to the next one. Instead of exiting the loop entirely, it simply moves on to the next cycle. + +For example, if we are iterating over numbers and want to skip processing number 2, we can use `continue`. The loop will ignore that iteration and proceed with the next number. + +### The `pass` Statement + +The `pass` statement is a placeholder that does nothing. It is useful when a block of code is syntactically required but no action needs to be performed yet. + +For example, in a loop where a condition has not yet been implemented, using `pass` ensures that the code remains valid while avoiding errors. diff --git a/tutorials/module_1/functions.md b/tutorials/module_1/functions.md new file mode 100644 index 0000000..8235fe3 --- /dev/null +++ b/tutorials/module_1/functions.md @@ -0,0 +1,67 @@ +# Functions + +Like a traditional mathematical functions, python functions can take an input, process it, and give an output. In python, the input variables are referred to as *arguments*. Functions are blocks of code that is run every time it's called. This allows us to re-use code. + +Functions are defined by using the def keyword. Reminder: it is important to keep track of indentations as it signifies the end of the function when the indentation returns back to the same level. + +## Defining Functions +### Simple function +A simple function with no input variable can be useful if you need to re-use code multiple times without having to re-write it. + +```python + def function_name(): + print("This is from a function") +``` + +### Defining a function with one input +We can pass variables through to the function to be processed as follows: + +```python + def function(x): + print(x + " is best") +``` + +Note input variables can be of any data type (integer, float, string, etc.). +### Returning values from a function +If we want to calculate a value and pass it back to the script for further use, we can use the `return` keyword. Let's define a linear function that takes two inputs, `x` and `b`, computes the corresponding `y` value, and returns it so it can be used elsewhere in the code. + +```python + def function(x, b): + y = 3*x+b + return y +``` + +For multiple output variables we can add +## Calling functions +Now that we've covered defining functions we want to call the function in order to execute the block inside the function. To do this, we simply re-call the function name as follows. + +```python +function(2,-1) +``` + +Note that when running this code, nothing happens. This is because we haven't told the computer what to do with the output. Hence, if we wish to store the output then we need to use the assign operator `=`. + +```python +output = function(2,-1) + +print(output) +``` + +In case you want to return multiple output variable from a single function we will have... + +## Summary + +```python +def function_name(argument1, argument2, argument3) + output1 = argument1 * argument2 - argument3 + output2 = argument2 + argument3 + return output1, output2 + +[solution1, solution2] = function_name(1,2,3) +``` + + +- `def` - defines a function. All the code that is indented underneath is considered inside the function block. +- `function_name` - this is used to call the function block. +- `argument1` (optional) - input variable. This is data that can be pass to the function. It is possible to have multiple variables separated by a comma. As well as can be omitted if the function should just give you an output such as. +- `return` (optional) - if you wish to return something to your script, the return keyword is used. The keyword can be followed by an output variable or a constant. For multiple output variables, separate them by a comma. \ No newline at end of file diff --git a/tutorials/module_1/fundamentals_of_programming.md b/tutorials/module_1/fundamentals_of_programming.md new file mode 100644 index 0000000..617d2c3 --- /dev/null +++ b/tutorials/module_1/fundamentals_of_programming.md @@ -0,0 +1,15 @@ +# Fundamentals of programming +## Orientation of common interfaces +In this section we will cover the use and purpose of some common interfaces that you'll be using in this course. + +### Command window, terminal, console, command prompt. +This is a text based interface that allows the users to interact with the computer. It is used to execute commands, run scripts or programs. + + +### Text Editor / Script +Your text editor is the program used to write a script which can be re-run every time you call it from the command window. This can be a built-in text editor such as Spyder and MATLAB provide or an external on such a notepad++. + + + + Globe analogy: Hardware, Kernel, shell, Application software. + - Scripting \ No newline at end of file diff --git a/tutorials/module_1/installing_anaconda.md b/tutorials/module_1/installing_anaconda.md new file mode 100644 index 0000000..baa4d71 --- /dev/null +++ b/tutorials/module_1/installing_anaconda.md @@ -0,0 +1,59 @@ +# Installing Anaconda + +This tutorial will cover the steps on how to install Anaconda. + +*Note for Advanced users: For those who wish to have a lightweight installation, can install miniconda or miniForge, however for this course we will show you how to use Anaconda Navigator. If you've never used the programs before then using Anaconda is recommended.* + +### What is Anaconda? +Anaconda Distribution is a popular open-source Python distribution specifically designed for scientific computing, data science, machine learning, and artificial intelligence applications. It simplifies the set up and use of Python for data science, machine learning, and scientific computing. It comes with all the important tools you need, like NumPy, Pandas, and JupyterLab, so you don’t have to install everything separately. The Conda package manager helps you install and update software without worrying about breaking other programs. It also lets you create separate environments, so different projects don’t interfere with each other. Additionally, Anaconda includes programs like JupyterLab for interactive coding, and Spyer a MATLAB-like IDE. + +--- +## Instructions +1. Find the latest version of Navigator from the official Anaconda Inc. website: [Download Anaconda](https://www.anaconda.com/download) + +2. Press the *Download Now* button. + +3. Press the *Skip registration* button below the submit button, otherwise submit your email address to subscribe to the Anaconda email list. + +4. Under Anaconda Installers press *Download* or find the appropriate version for your operating system below. + +Proceed to next section for your respective operating system. + +### Windows + +5. Once the download is complete, double click the executable (.exe) file to start the installer. Proceed with the installation instructions. + +![Welcome screen](figures/installingAnaconda_windows_installer_01_welcome.png) + +![Terms and conditions](figures/installingAnaconda_windows_installer_02_terms.png) + + +6. Select the *Just Me* recommended option. + +![Install for](figures/installingAnaconda_windows_installer_03_for.png) + + +7. You can leave the destination folder as is, just make sure you have a minimum of ~5 GB available storage space. Press *Next* to proceed. + +![Installation destination](figures/installingAnaconda_windows_installer_04_destination.png) + + +8. It is recommended to register Anaconda3 as the default python version if you already have an instance of python installed. Otherwise, you can leave the checkboxes as defaults. + +![Avanced Options](figures/installingAnaconda_windows_installer_05_advanced.png) + +![Installing](figures/installingAnaconda_windows_installer_06_installing.png) + +![Installing 2](figures/installingAnaconda_windows_installer_07_installing2.png) + +![Complete](figures/installingAnaconda_windows_installer_08_installing_complete.png) + +![Cloud](figures/installingAnaconda_windows_installer_09_cloud.png) + +![Finish](figures/installingAnaconda_windows_installer_10_finish.png) + + +9. You made it! Anaconda is now installed, you are ready for launch. Assuming that you didn't add Anaconda to PATH environment variable you will need to start navigator from the start menu. + +### Mac/Linux +Anaconda provides installation documentation for Mac and Linux users, please refer to the [documentation page](https://docs.anaconda.com/anaconda/install/). diff --git a/tutorials/module_1/intro_to_anaconda.md b/tutorials/module_1/intro_to_anaconda.md new file mode 100644 index 0000000..84c6516 --- /dev/null +++ b/tutorials/module_1/intro_to_anaconda.md @@ -0,0 +1,79 @@ +# Introduction to Anaconda Navigator + +Anaconda Navigator is a program that we will be using in this course to manage Python environments, libraries and launch programs to help us write our python code. + +The Anaconda website nicely describes *Navigator* as: +
+

a graphical user interface (GUI) that enables you to work with packages and environments without needing to type conda commands in a terminal window.Find the packages you want, install them in an environment, run the packages, and update them – all inside Navigator. +

+ +To better understand how Navigator works and interacts with the anaconda ecosystem see the figure below. +![Anaconda Schematic](figures/AnacondaSchematic.png) +As you schematic indicated, Navigator is a tool in the Anaconda toolbox that allows the user to select and configure python environments and libraries. Let's see how we can do this. + +--- +## Getting Started + +Note to windows 10 users: Some installation instances do not allow users to search the start menu for *Navigator*, instead, you'll have to find the program under the *Anaconda (anaconda3)* folder. Expand the folder and click on *Anaconda Navigator* to launch the program. + +![Anaconda Navigator screen](figures/installingAnaconda_windows_launched.png) + +Once Navigator starts, under *Home*, you'll see tiles of programs that come with anaconda. The tab allows you to launch the programs we will be using in this course. Before jumping straight into the programs we will first need to configure our Python instance. + +The *Environment* page allows us to install a variety of libraries and configure our environments for different project, more on this in the next section. + +## Environments +A Python environment can be thought of as a "container" where you can have all the tools, libraries, and dependencies your Python project needs without interfering with other projects. Think of it as a dedicated toolbox for your project. + +Although the base environment comes with many libraries and programs pre-installed, it's recommended to create a dedicated environment for your projects. This protects the base environment from breaking due to complex dependency conflicts. Let us go ahead and create a new environment for us to use Spyder with. + +1. Click on the *Environments* page located on the left hand side. + +![Environment Page](https://mintlify.s3.us-west-1.amazonaws.com/anaconda-29683c67/images/nav-env-labeled.png) + +2. At the bottom of the environments list, click *Create*. + +![Create new environment](https://mintlify.s3.us-west-1.amazonaws.com/anaconda-29683c67/images/nav-getting-started-create.png) + +3. Select the python checkbox. + +4. Select versions of python. At the time of making this tutorial the latest version of Python is 3.xx.x. We will go ahead and use that one. + +5. Choose an appropriate name for your project. We will be creating an environment for the Spyder IDE so we'll call it "Spyder-env". + +6. Click *Create*. + +For more information see [Anaconda Environments](https://docs.anaconda.com/working-with-conda/environments/) and [Managing environment](https://docs.anaconda.com/navigator/tutorials/manage-environments/). + +## Package Management +Now that we have a clean environment configured, let us install some library we will be using for this class. + +1. Navigate to the environment page and select the environment we just created in the previous section. + +![Select environment to manage](https://mintlify.s3.us-west-1.amazonaws.com/anaconda-29683c67/images/nav-pkg-list.png) + +2. Use the search bar in the top right corner to search for the following packages: + +| Library | Usage | +| ---------- | --------------------------------- | +| numpy | Numerical computation | +| scipy | Scientific and techical computing | +| pandas | Data manipulation and analysis | +| matplotlib | Plots and visualizations | +| sympy | Symbolic mathematics | +*Note: The libraries list may change throughout the development of this course* + +3. Check the boxes to install the selected packages to the current environment. + +## Installing Applications +From the *Home* page you can install applications, to the current environment we created in the Environment section above. In this section we will install Spyder IDE, but the process is exactly the same for other applications. + +1. Go to the *Home* page. + +2. Select the desired environment. In our case, we select *Spyder-env*. + +3. From the Home page find the Spyder IDE tile. Click the *Install* button to start the download. + +![Anaconda Home Page](https://mintlify.s3.us-west-1.amazonaws.com/anaconda-29683c67/images/nav-tabs.png) + +4. Once the download is complete, press *Launch* to start the applications. \ No newline at end of file diff --git a/tutorials/module_1/intro_to_programming.md b/tutorials/module_1/intro_to_programming.md new file mode 100644 index 0000000..2f12a3a --- /dev/null +++ b/tutorials/module_1/intro_to_programming.md @@ -0,0 +1,15 @@ +# Introduction to Programming +## The Importance of Programming in Engineering + +Engineering is all about solving problems, designing innovative solutions, and making systems work efficiently. Whether you’re designing cars, airplanes, rockets, or even everyday machines, programming plays a critical role in modern engineering. + +In mechanical engineering, programming helps us **analyze data, model complex systems, automate repetitive tasks, and simulate real-world physics.** For example, instead of spending hours solving equations by hand, engineers can write a program that does it in seconds. This saves time and therefore do more. + +With programming, mechanical engineers can: + +- **Automate calculations:** Quickly solve equations for heat transfer, fluid dynamics, and mechanical stresses. +- **Simulate systems:** Model how a bridge bends under weight or how an engine burns fuel efficiently. +- **Analyze data:** Process thousands of test results to improve designs. +- **Control machines:** Program robots, 3D printers, and CNC's. + +In this course, you’ll see how computing and programming applies to mechanical engineering and how they can make you a better problem solver. By the end, you’ll have the skills and understanding of how to write programs that help you **think like an engineer in the digital age.** diff --git a/tutorials/module_1/jupyter_lab_notebook.md b/tutorials/module_1/jupyter_lab_notebook.md new file mode 100644 index 0000000..5fa493a --- /dev/null +++ b/tutorials/module_1/jupyter_lab_notebook.md @@ -0,0 +1,105 @@ +## Introduction + + +Jupyter Notebooks are often used for data science and scientific computing such as machine learning as the interactive design allow you to experiment easily with your code. For our purpose, we will use Notebooks as it's a useful tool to learn how to code as well as writing reports. + +*Note on the difference between Notebook and Lab: Jupyter Notebook offers a simplified, lightweight notebook authoring experience, where as, JupyterLab offers a feature-rich, tabbed multi-notebook editing environment with additional tools like a customizable interface layout and system console* + + +--- +## Setup and Installation +Installing with Conda using CLI: +- `conda install jupyter` +Jupyter can also be installed using a Anaconda Navigator + + - Launching: + - From terminal: `jupyter notebook` or `jupyter lab` + - From Anaconda Navigator or VSCode + - Navigating the interface: + - Tabs and file browser + - Kernel and terminals + +--- + +## Notebook Basics +- Creating a new notebook (`.ipynb`) +- Types of cells: + - Code + - Markdown + - Raw +- Running a cell: `Shift + Enter` +- Adding/removing cells +- Restarting the kernel +- Saving and auto-checkpoints + +--- + +## Writing and Running Code +- Python syntax: + - `print("Hello, world!")` + - Variables and functions + - Loops and conditionals +- Importing libraries: + - `import numpy as np` + - `import pandas as pd` + - `import matplotlib.pyplot as plt` + +--- + +## Using Markdown +- Headers: `#`, `##`, `###` +- Bullet lists: `- item` +- Numbered lists: `1. item` +- Emphasis: _italic_, **bold**, `monospace` +- LaTeX equations: + - Inline: `$E = mc^2$` + - Block: `$$\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$$` +- Embedding links and images + + + +--- +## Interactive Widgets (optional) + +Install `ipywidgets` from your package manager + +```python +import ipywidgets as widgets +widgets.IntSlider() +``` +Example using interact: + +```python +from ipywidgets import interact +interact(lambda x: x**2, x=5) +``` + + +--- +## Productivity Tips +Here are some keyboard shortcuts to improve your productivity when writing in notebooks. + +| Key | Action | +| --- | ------------------ | +| A | insert cell above | +| B | insert cell below | +| M | switch to Markdown | +| Y | switch to code | + Magic commands: +- `%timeit`, `%matplotlib inline`, `%%bash` +Splitting and merging cells +Auto-save behavior + +--- + +## Exporting and Sharing + - File > Download As: + - Notebook (`.ipynb`) + - HTML + - PDF (requires LaTeX) + - Markdown +- Notebooks can be saved and shared via the following services: + - GitHub + - nbviewer.org + - mybinder.org + - JupyterHub \ No newline at end of file diff --git a/tutorials/module_1/open_source_software.md b/tutorials/module_1/open_source_software.md new file mode 100644 index 0000000..d82b30a --- /dev/null +++ b/tutorials/module_1/open_source_software.md @@ -0,0 +1,43 @@ +# Open Source Software + +Open-source software (OSS) is a type of software that allows users to access, modify, and distribute its source code freely. It is built on principles of collaboration, transparency, and community-driven development. + +You've probably heard of the saying "Don't reinventing the wheel". This + +### Key Principles of Open Source Software + +- **Free Distribution:** Anyone can download and use the software without cost. +- **Access to Source Code:** Users can view and modify the code to suit their needs. +- **Community Collaboration:** Developers from around the world contribute to improvements and security fixes. + +### Benefits of Open Source Software + +- **Cost-effectiveness:** Open-source software is free to use, making it accessible to individuals and organizations. +- **Transparency and Security:** Open code allows for peer review, reducing security vulnerabilities. +- **Community Support:** Global developer communities provide assistance, troubleshooting, and improvements. +- **Customization and Flexibility:** Users can modify software to fit their specific requirements. + +### Challenges of Open Source Software + +- **Usability Issues:** Some open-source software may have a steeper learning curve. +- **Compatibility Problems:** Integration with proprietary systems may require additional effort. +- **Support and Documentation:** The quality of documentation and support varies. +- **Sustainability:** Open-source projects often rely on volunteers, which can lead to inconsistent updates. + +### Popular Open Source Projects + +- **Operating Systems:** Linux, Ubuntu +- **Web Browsers:** Mozilla Firefox +- **Programming Languages:** Python, JavaScript +- **Office Suites:** LibreOffice +- **Multimedia Tools:** Audacity, Blender +- **Software Development:** Git, GitHub, Apache + +### How to Contribute to Open Source + +- **Finding Projects:** Platforms like GitHub, GitLab, and SourceForge host many open-source projects. +- **Understanding Licensing:** Common licenses include GPL, MIT, and Apache. +- **Ways to Contribute:** Developers can contribute code, test software, write documentation, translate, or help with design. +- **Best Practices for Contributions:** Using version control (Git), writing clean code, and following community guidelines are essential for successful collaboration. + +## Licensing diff --git a/tutorials/module_1/spyder_getting_started.md b/tutorials/module_1/spyder_getting_started.md new file mode 100644 index 0000000..ba055d7 --- /dev/null +++ b/tutorials/module_1/spyder_getting_started.md @@ -0,0 +1,41 @@ +# Getting started with Spyder + +In this tutorial we will cover the basics of using the Spyder IDE (Interactive Development Environment). If you've ever worked with MATLAB before, then this will feel familiar. Spyder is a program that allows you to write, run and de-bug code. + +## Launching Spyder +Using Anaconda we will select the environment we created earlier *spyder-dev* and then we can launch spyder from the Home page. + +## Spyder Interface + +![Spyder Interface](https://docs.spyder-ide.org/current/_images/mainwindow_default_1610.png) + +Once you open up Spyder in it's default configuration, you'll see three sections; the editor IPython Console, Help viewer. You can customize the interface to suit your prefference and needs some of which include, rearrange, undock, hide panes. Feel free to set up Spyder as you like. + +### Editor +This pane is used to write your scripts. The + +![Editor key components](https://docs.spyder-ide.org/5/_images/editor-components.png) + +1. The left sidebar shows line numbers and displays any code analysis warnings that exist in the current file. Clicking a line number selects the text on that line, and clicking to the right of it sets a [breakpoint](https://docs.spyder-ide.org/5/panes/debugging.html#debugging-breakpoints). +2. The scrollbars allow vertical and horizontal navigation in a file. +3. The context (right-click) menu displays actions relevant to whatever was clicked. +4. The options menu (“Hamburger” icon at top right) includes useful settings and actions relevant to the Editor. +5. The location bar at the top of the Editor pane shows the full path of the current file. +6. The tab bar displays the names of all opened files. It also has a Browse tabs button (at left) to show every open tab and switch between them—which comes in handy if many are open. + +### IPython Console +This pane allows you to interactively run functions, do math computations, assign and modify variables. + +![IPython Console](https://docs.spyder-ide.org/5/_images/console-standard.png) + +- Automatic code completion +- Real-time function calltips +- Full GUI integration with the enhanced Spyder [Debugger](https://docs.spyder-ide.org/5/panes/debugging.html). +- The [Variable Explorer](https://docs.spyder-ide.org/5/panes/variableexplorer.html), with GUI-based editors for many built-in and third-party Python objects. +- Display of Matplotlib graphics in Spyder’s [Plots](https://docs.spyder-ide.org/5/panes/plots.html) pane, if the Inline backend is selected under Preferences ‣ IPython console ‣ Graphics ‣ Graphics backend, and inline in the console if Mute inline plotting is unchecked under the Plots pane’s options menu. + +### Variable Explorer +This pane shows all the defined variables (objects) stored. This can be used to identify the data type of variables, the size and inspect larger arrays. Double clicking the value cell opens up a window which allowing you to inspect the data in a spreadsheet like view. + +![Variable Explorer](https://docs.spyder-ide.org/5/_images/variable-explorer-standard.png) + diff --git a/tutorials/module_2/2_01_intro_to_numerical_methods.md b/tutorials/module_2/2_01_intro_to_numerical_methods.md deleted file mode 100644 index 6791aff..0000000 --- a/tutorials/module_2/2_01_intro_to_numerical_methods.md +++ /dev/null @@ -1,41 +0,0 @@ -# Numerical Methods -Engineering - -## What is a numerical method? -Numerical methods are techniques that transform mathematical problems into forms that can be solved using arithmetic and logical operations. Because digital computers excel at these computations, numerical methods are often referred to as computer mathematics. - - -## Numerical Differentiation -Forwards difference -Backwards difference - -[Read More](https://pythonnumericalmethods.studentorg.berkeley.edu/notebooks/chapter20.00-Numerical-Differentiation.html) - -## Roots and Optimization -Incremental Search -Bisection -Modified Secant -Newton-Raphson - - -## Numerical Integration - -Trapezoidal - -Simpson's Rule - -[Read More](https://pythonnumericalmethods.studentorg.berkeley.edu/notebooks/chapter21.00-Numerical-Integration.html) - - -## Numerical Solutions of Ordinary Differential Equations - -Euler's Method -- Forward -- Backwards - -Runge-Kutta Method - -[Read More](https://pythonnumericalmethods.studentorg.berkeley.edu/notebooks/chapter22.00-ODE-Initial-Value-Problems.html) - - - diff --git a/tutorials/module_2/2_ai_assisted_programming.md b/tutorials/module_2/2_ai_assisted_programming.md deleted file mode 100644 index bccedbd..0000000 --- a/tutorials/module_2/2_ai_assisted_programming.md +++ /dev/null @@ -1,38 +0,0 @@ -# AI Assisted Programming - -## What is it? -Artificial Intelligence (AI) has been around for a long time. However, not until recently did engineers make it easy and "fun" to work with. By now you probably have a pretty good idea of what AI can do. However, you may not have used an AI assistant before. As the name suggests, an AI assistant can help you develop code, speed up your writing with code suggestions and allows you to focus on solving the problem at hand rather. AI is a technology that is constantly improving. As engineers we need to *understand* how we can use AI as a tool to achieve our goals more efficiently. This section cover good practices of how we can implement AI and lists some AI assistant tools that we can use. -## Good vs. Bad uses of AI -Don't try to get AI to do work *for you* but *with you*. You need to understand what you're doing. If you don't understand what the AI is doing, then you're not in control of the work. You're not going to go far until something unexpected happens. - -AI is a great learning tool, research as show that students can benefit from using AI as personal tutor [more](https://hbsp.harvard.edu/inspiring-minds/ai-as-personal-tutor). -## Available tools -Below is a comprehensive list of tools that are available at not cost to you. - -| Name | Features | -| -------------- | -------------------------------------------------- | -| GitHub Copilot | Paid, but free for students. Integrated in GitHub. | -| ChatGPT | Free, optional paid upgrade | -| Grok | Free, optional paid upgrade | -| Gemini | Free, optional paid upgrade | -| GPT4ALL | Free and Open-Source | -| Code GPT | Free and Open-Source | -| Cody | Free and Open-Source | -| DataLab AI | Free | -| Codeium | Free | -| aiXcoder | Free | -Many of the tools above come with similar, if not, the same features. Some of the tools come as chatbots on the web and others are extensions that can be implemented in your favorite IDE. -## VSCode and GitHub Copilot Integration -We will not cover how to use VSCode in this course, however it is a very versatile IDE that comes with many other extension, for example git, github and github copilot integration. There are also other extensions for other IDE's however we will only cover some basic features that the GithHub Copilot extension in VSCode can do. - -Copilot Comes with the following features: -- Get code suggestions as you type -- Ask questions about the code -- Inline chat to generate code. -- Fix and debug code using the chat window -- Generate code documentation - -[VSCode](https://code.visualstudio.com/) -[Copilot extension](https://code.visualstudio.com/docs/copilot/setup-simplified) -## A note on integrity -If you have a non-disclosure-agreement (NDA) with your employer, it may not always be possible to use AI for security and integrity reasons as you may risk exposing confidential information with third party vendors. It is highly recommended to be able to be able to write program independently of an AI assistant. Always think before you share data. \ No newline at end of file diff --git a/tutorials/module_2/2_debugging_code.md b/tutorials/module_2/2_debugging_code.md deleted file mode 100644 index ef8dfce..0000000 --- a/tutorials/module_2/2_debugging_code.md +++ /dev/null @@ -1,88 +0,0 @@ -# Debugging Code - -### 1. Introduction - -Have you ever had a piece of code not work the way you expected? What did you do? You may have , asked a friend or used an AI assistant. In this section, the following concepts are introduced - definition of a bug, common types of bugs and debugging techniques. - -A *software bug* is an unintentional mistake or defect with a program, this comes either from when the programmer makes a mistake in writing the code or the code works in a way which has consequences that were not foreseen by the programmer. Debugging is the act removing the bugs in the software. Debugging is a normal part of programming that even experiences developers spend a lot of time on. - ---- -### 2. Types of Bugs -When writing code you are guaranteed to have bugs in your code. These bugs can be categorized in the following three groups. - -- **Syntax errors** - this type of error occurs when the code fails due to missing colons, missing indentation or a typo in code - some languages like python are case sensitive meaning that the a capital letter are different symbols. -- **Runtime errors** - e.g., dividing by zero or file not found. -- **Logical errors** - this may be the most dangerous that we need to be careful with because this error can occur without any error messages but it gives you the wrong result. - ---- -### 3. Debugging Techniques -**3.1. Print Debugging** -Insert print statements to check values of variables throughout the program. -```python -def add(x, y): - print(f"x = {x}, y = {y}") - return x + y -``` -In the example above the print statement gives us feedback on what the code is doing. The function in this example is obviously very simple, but when we start applying more complex equations or function then checking to see if the input variables are correct can indicate whether there is an issue lies within the `add()` function or if the function is given an incorrect input. - -**3.2. Rubber Duck Debugging** -This is a technique by which you explaining your code line by line in natural language to someone else, yourself or an inanimate object like a rubber duck. This can help you spot your mistake in the code. - -**3.3. Commenting Out Code** -Using comments to temporarily suppress parts of your code help you isolate and find the bug. - -**3.4. IDE Debugging tools** -Depending if you use an IDE, they often come with some sort of debugging tools such as breakpoints, step into/over and variables explorers. - -**3.5. AI Chat** -AI chat bots can help you find typo or fix logic in your code. You may find yourself going through the steps above when using an AI assistant to help you debug the code. However *never* assume that the code AI gives you works the way you intend it to work. - ---- -### 4. Interactive Debugging Activity - -In the examples debug the code and document the following: - - What the bug is - - How you found it (technique used) - - What actions you took to fix the bug -#### Code 1 -```python -def greet(name) - print("Hello, " + Name) -greet("John") -``` -#### Code 2 -```python -import numpy as np - -x = np.linspace(0,5,100) -y = 1/x - -print("Result:", y[0]) -``` -#### Code 3 -```python -def f(x): - return x**2 - 4 # Root at x = ±2 - -def bisection(a, b, tol=1e-5, max_iter=100): - if f(a) * f(b) >= 0: - print("Bisection method fails. f(a) and f(b) should have opposite signs.") - return None - - for i in range(max_iter): - c = (a + b) / 2 - if abs(f(c)) < tol: - return c - elif f(c) * f(b) < 0: # ❌ Logic error is here - a = c - else: - b = c - return (a + b) / 2 -``` - - - ---- -### 5. Reflection -- What was the most challenging bug you found? -- What debugging method did you find most useful? diff --git a/tutorials/module_2/2_problem_solving_strategies.md b/tutorials/module_2/2_problem_solving_strategies.md deleted file mode 100644 index 1a50aec..0000000 --- a/tutorials/module_2/2_problem_solving_strategies.md +++ /dev/null @@ -1,64 +0,0 @@ -# Algorithmic thinking - -## Learning Objectives - -By the end of this lesson, students will be able to: - -- Apply algorithmic thinking to solve engineering problems using computational tools. -- Translate engineering problems into structured programming logic. -- Use software tools to implement, test, and refine engineering solutions. - ---- -## 1. Define the Problem - -Like many other classes we need to frame the problem before working it. So before jumping straight into coding or building models, clearly define the engineering problem. - -- **List knowns and unknowns.** What inputs are given? What outputs are required? -- **Establish system constraints and assumptions.** Identify physical laws, design requirements, and performance limits. -- **Clarify computational objectives.** What are you trying to calculate, simulate, or optimize? - ---- -## 2. Think Algorithmically - -Since we are going to use computers to calculate our solution we first need to break the problem into logical steps that a computer can follow. - -- **Define the inputs and outputs.** What variables will the program take in, and what results will it produce? -- **Break the problem into sub-tasks.** Identify steps such as data input, logic processing and output. -- **Outline the algorithm.** Write pseudocode or flowcharts that describe the computational steps. -- **Identify patterns or formulas.** Can loops, conditionals, or equations be used to automate parts of the solution? - -**Example:** For processing stress-strain data: -1. Import data from a file. -2. Convert force and displacement to stress and strain. -3. Plot the stress-strain curve. -4. Identify the yield point or modulus. - ---- -## 3. Write & Execute the Code - -- **Choose the right tools.** Are there libraries I can use to get to my objective more effectively? -- **Write modular code.** Use functions to separate different tasks (e.g., reading data, computing values, plotting). -- **Check for syntax and logic errors.** Debug line-by-line using print statements or a debugger. - -**Example:** Write a Python script that uses NumPy and Matplotlib to load a CSV file, compute stress and strain, and generate plots. - ---- -## 4. Test and Validate - -- **Assess the feasibility of your results.** Do the values align with expected physical behavior? -- **Compare against established benchmarks.** Validate solutions using experimental data, literature values, or known theoretical limits. -- **Check units and scaling.** Ensure computations are consistent with physical meaning. - -**Example:** If your plot shows stress values in the thousands when you expect hundreds, check unit conversions in your formula. - ---- -## Case Study: Simulating a Spring-Mass System - -**Scenario:** Model the motion of a mass-spring-damper system using a numerical solver. - -1. **Define the Problem:** Set up the differential equation from Newton’s Second Law. -2. **Develop a Strategy:** Discretize time, apply numerical integration (e.g., Euler or Runge-Kutta). -3. **Execute the Code:** Write a Python function that computes motion over time. -4. **Test the Model:** Compare results with analytical solutions for undamped or lightly damped systems. -5. **Refine the Model:** Add adjustable damping and stiffness parameters. -6. **Troubleshoot Issues:** If the model becomes unstable, reduce the time step or use a more accurate integrator. \ No newline at end of file diff --git a/tutorials/module_2/2_version_control.md b/tutorials/module_2/2_version_control.md deleted file mode 100644 index 78b90db..0000000 --- a/tutorials/module_2/2_version_control.md +++ /dev/null @@ -1,112 +0,0 @@ -# Version Control Software - -## What is Version Control -Version control is a system that tracks changes to files, enabling developers to collaborate, manage code history, and revert to previous versions when needed. The most used version control software (VCS) is git. In this course git is the VCS we will be using. - -In the open-source community VCS is the -- Tracks changes and history. -- Enables collaboration among developers. -- Reduces errors by managing code versions. -- Supports branching and merging for parallel development. - -In this section is divided up into two major sections. The first section *Git* will cover the basics of how to create backups of your project. The second section will cover how to use git with GitHub to *collaborate* on projects. - ---- -## Git -Git is a version control program that tracks changes to files and directories using snapshots. It is a distributed version control system, meaning that each developer has a complete copy of the repository on their local computer. Git is the most widely used version control system and is popular among developers for its speed, flexibility, and efficiency. - -### The Three States -Pay attention now — here is the main thing to remember about Git if you want the rest of your learning process to go smoothly. Git has three main states that your files can reside in: modified, staged, and committed: - -- **Modified** means that you have changed the file but have not committed it to your database yet. -- **Staged** means that you have marked a modified file in its current version to go into your next commit snapshot. -- **Committed** means that the data is safely stored in your local database. - -This leads us to the three main sections of a Git project: the working tree, the staging area, and the Git directory. - -![Pro Git: Figure 6.](https://git-scm.com/book/en/v2/images/areas.png) -### Branching -In git, branches allow for parallel workflow on a project. It give contributors the ability to work different features at the same time. Each branch represents an independent line of development, and once a feature or fix is complete, it can be merged back into the main branch. Here is a common branching structure used in many Git projects: -- Main Branch - The main branch (a.k.a. master branch) is the default branch in a Git repository and contains the stable version of the code. -- Development Branch - is created to develop a new feature or fix a bug without affecting the main branch. It isn’t necessarily always stable, but whenever it gets to a stable state, it can be merged into master. -- Topic Branch - A topic branch is a short-lived branch that you create and use for a single particular feature or related work. -![Figure 27. A "Silo" view of progressive-stability branching](https://git-scm.com/book/en/v2/images/lr-branches-2.png) -### Best Practices -- Use descriptive commit messages. -- Commit early and often. -- Keep commits focused on a single change. -- Use feature branches for new features or bug fixes. -- Review and test changes before merging. -- Resolve conflicts promptly. -- Keep the commit history clean and organized. - -### Basic Commands -Here is a list of some git commands to get you started. -#### Starting your repository -- `git init` - Initialize a new Git repository. -- `git clone` - Clone an existing repository. -#### Committing -- `git status` - Check the status of the repository. -- `git add` - Add files to the staging area. -- `git commit` - Commit changes to the repository. -#### Branching -- `git branch` - List, create, or delete branches. -- `git checkout` - Switch between branches. -#### History/Inspection -- `git log` - View the commit history. -#### Collaborative -- `git fetch` - Fetches updates from a remote but does not merge. -- `git merge` - Merge changes from a named commit to the current branch. -- `git pull` - Fetch and merge changes from a remote repository. -- `git push` - Push changes to a remote repository. - -### More on git -Interested in learning more about git? Here's a free book that teaches you everything about git and how to use it at a professional level. Available as both HTML and PDF download: [Git Pro](https://git-scm.com/book/en/v2). - - -## GitHub - The collaborative platform -GitHub is a web-based platform that hosts Git repositories and provides collaboration tools for developers. It allows developers to share code, track issues, and collaborate on projects with other developers. GitHub is widely used for open-source projects, team collaboration, and code hosting. -### GitHub Features -- Remote Repository Hosting - GitHub allows you to host projects and code remotely on their servers. -- Issues - Issues are used to track bugs, feature -- Pull Requests - Internal request system for contributors to request code to be pulled. -### Workflow -Depending on the size of the project and whether the project is closed- or open-source, the workflow of the project will differ. In this section we cover some git workflow models and the model you're going to be using for this course. - - -**Centralized**: The project has only one central hub or *repository*, can accept code and everybody synchronizes their work with it. This model is suitable for small and closed-sourced projects. -![Centralized Workflow](https://git-scm.com/book/en/v2/images/centralized_workflow.png) - - - -**Integration-Manager:** There are multiple public variants of the code original code known as *forks*. The integration manager can decide what features to pull from the forks. This is the model that is similar to the one used on GitHub -![Integration-Manager Workfow](https://git-scm.com/book/en/v2/images/integration-manager.png) - - - -**Dictator and Lieutenants Workflow:** This is similar to the integration-manager model, however due to the size of the project. A rank of integration managers is formed. one example of this is the development of the Linux kernel. -![Dictator and Lieutenants Workflow](https://git-scm.com/book/en/v2/images/benevolent-dictator.png) - - -GitHub is designed around a particular collaboration workflow, centered on Pull Requests. This flow works whether you’re collaborating with a tightly-knit team in a single shared repository, or a globally-distributed company or network of strangers contributing to a project through dozens of forks. It is centered on the Topic Branches workflow covered in Git Branching. - - - -Here’s how it generally works: -1. Fork the project. -2. Create a topic branch from master. -3. Make some commits to improve the project. -4. Push this branch to your GitHub project. -5. Open a Pull Request on GitHub. -6. Discuss, and optionally continue committing. -7. The project owner merges or closes the Pull Request. -8. Sync the updated master back to your fork. - -### Terms -- Pull Request - A *pull request* is a request to merge changes from a feature branch into the main branch or from a forked repository to the original or "upstream" repository. -- Merge - A *merge* combines the changes from one branch into another branch. -- Conflict - A *conflict* occurs when Git cannot automatically merge changes and requires manual intervention. - - -### Code resource - Using GitHub to re-use existing code. -In your engineering career, you will most likely use a computation method that has been come up with before. In such scenarios, open-source diff --git a/tutorials/module_2/ai_assisted_programming.md b/tutorials/module_2/ai_assisted_programming.md new file mode 100644 index 0000000..bccedbd --- /dev/null +++ b/tutorials/module_2/ai_assisted_programming.md @@ -0,0 +1,38 @@ +# AI Assisted Programming + +## What is it? +Artificial Intelligence (AI) has been around for a long time. However, not until recently did engineers make it easy and "fun" to work with. By now you probably have a pretty good idea of what AI can do. However, you may not have used an AI assistant before. As the name suggests, an AI assistant can help you develop code, speed up your writing with code suggestions and allows you to focus on solving the problem at hand rather. AI is a technology that is constantly improving. As engineers we need to *understand* how we can use AI as a tool to achieve our goals more efficiently. This section cover good practices of how we can implement AI and lists some AI assistant tools that we can use. +## Good vs. Bad uses of AI +Don't try to get AI to do work *for you* but *with you*. You need to understand what you're doing. If you don't understand what the AI is doing, then you're not in control of the work. You're not going to go far until something unexpected happens. + +AI is a great learning tool, research as show that students can benefit from using AI as personal tutor [more](https://hbsp.harvard.edu/inspiring-minds/ai-as-personal-tutor). +## Available tools +Below is a comprehensive list of tools that are available at not cost to you. + +| Name | Features | +| -------------- | -------------------------------------------------- | +| GitHub Copilot | Paid, but free for students. Integrated in GitHub. | +| ChatGPT | Free, optional paid upgrade | +| Grok | Free, optional paid upgrade | +| Gemini | Free, optional paid upgrade | +| GPT4ALL | Free and Open-Source | +| Code GPT | Free and Open-Source | +| Cody | Free and Open-Source | +| DataLab AI | Free | +| Codeium | Free | +| aiXcoder | Free | +Many of the tools above come with similar, if not, the same features. Some of the tools come as chatbots on the web and others are extensions that can be implemented in your favorite IDE. +## VSCode and GitHub Copilot Integration +We will not cover how to use VSCode in this course, however it is a very versatile IDE that comes with many other extension, for example git, github and github copilot integration. There are also other extensions for other IDE's however we will only cover some basic features that the GithHub Copilot extension in VSCode can do. + +Copilot Comes with the following features: +- Get code suggestions as you type +- Ask questions about the code +- Inline chat to generate code. +- Fix and debug code using the chat window +- Generate code documentation + +[VSCode](https://code.visualstudio.com/) +[Copilot extension](https://code.visualstudio.com/docs/copilot/setup-simplified) +## A note on integrity +If you have a non-disclosure-agreement (NDA) with your employer, it may not always be possible to use AI for security and integrity reasons as you may risk exposing confidential information with third party vendors. It is highly recommended to be able to be able to write program independently of an AI assistant. Always think before you share data. \ No newline at end of file diff --git a/tutorials/module_2/debugging_code.md b/tutorials/module_2/debugging_code.md new file mode 100644 index 0000000..ef8dfce --- /dev/null +++ b/tutorials/module_2/debugging_code.md @@ -0,0 +1,88 @@ +# Debugging Code + +### 1. Introduction + +Have you ever had a piece of code not work the way you expected? What did you do? You may have , asked a friend or used an AI assistant. In this section, the following concepts are introduced - definition of a bug, common types of bugs and debugging techniques. + +A *software bug* is an unintentional mistake or defect with a program, this comes either from when the programmer makes a mistake in writing the code or the code works in a way which has consequences that were not foreseen by the programmer. Debugging is the act removing the bugs in the software. Debugging is a normal part of programming that even experiences developers spend a lot of time on. + +--- +### 2. Types of Bugs +When writing code you are guaranteed to have bugs in your code. These bugs can be categorized in the following three groups. + +- **Syntax errors** - this type of error occurs when the code fails due to missing colons, missing indentation or a typo in code - some languages like python are case sensitive meaning that the a capital letter are different symbols. +- **Runtime errors** - e.g., dividing by zero or file not found. +- **Logical errors** - this may be the most dangerous that we need to be careful with because this error can occur without any error messages but it gives you the wrong result. + +--- +### 3. Debugging Techniques +**3.1. Print Debugging** +Insert print statements to check values of variables throughout the program. +```python +def add(x, y): + print(f"x = {x}, y = {y}") + return x + y +``` +In the example above the print statement gives us feedback on what the code is doing. The function in this example is obviously very simple, but when we start applying more complex equations or function then checking to see if the input variables are correct can indicate whether there is an issue lies within the `add()` function or if the function is given an incorrect input. + +**3.2. Rubber Duck Debugging** +This is a technique by which you explaining your code line by line in natural language to someone else, yourself or an inanimate object like a rubber duck. This can help you spot your mistake in the code. + +**3.3. Commenting Out Code** +Using comments to temporarily suppress parts of your code help you isolate and find the bug. + +**3.4. IDE Debugging tools** +Depending if you use an IDE, they often come with some sort of debugging tools such as breakpoints, step into/over and variables explorers. + +**3.5. AI Chat** +AI chat bots can help you find typo or fix logic in your code. You may find yourself going through the steps above when using an AI assistant to help you debug the code. However *never* assume that the code AI gives you works the way you intend it to work. + +--- +### 4. Interactive Debugging Activity + +In the examples debug the code and document the following: + - What the bug is + - How you found it (technique used) + - What actions you took to fix the bug +#### Code 1 +```python +def greet(name) + print("Hello, " + Name) +greet("John") +``` +#### Code 2 +```python +import numpy as np + +x = np.linspace(0,5,100) +y = 1/x + +print("Result:", y[0]) +``` +#### Code 3 +```python +def f(x): + return x**2 - 4 # Root at x = ±2 + +def bisection(a, b, tol=1e-5, max_iter=100): + if f(a) * f(b) >= 0: + print("Bisection method fails. f(a) and f(b) should have opposite signs.") + return None + + for i in range(max_iter): + c = (a + b) / 2 + if abs(f(c)) < tol: + return c + elif f(c) * f(b) < 0: # ❌ Logic error is here + a = c + else: + b = c + return (a + b) / 2 +``` + + + +--- +### 5. Reflection +- What was the most challenging bug you found? +- What debugging method did you find most useful? diff --git a/tutorials/module_2/intro_to_numerical_methods.md b/tutorials/module_2/intro_to_numerical_methods.md new file mode 100644 index 0000000..6791aff --- /dev/null +++ b/tutorials/module_2/intro_to_numerical_methods.md @@ -0,0 +1,41 @@ +# Numerical Methods +Engineering + +## What is a numerical method? +Numerical methods are techniques that transform mathematical problems into forms that can be solved using arithmetic and logical operations. Because digital computers excel at these computations, numerical methods are often referred to as computer mathematics. + + +## Numerical Differentiation +Forwards difference +Backwards difference + +[Read More](https://pythonnumericalmethods.studentorg.berkeley.edu/notebooks/chapter20.00-Numerical-Differentiation.html) + +## Roots and Optimization +Incremental Search +Bisection +Modified Secant +Newton-Raphson + + +## Numerical Integration + +Trapezoidal + +Simpson's Rule + +[Read More](https://pythonnumericalmethods.studentorg.berkeley.edu/notebooks/chapter21.00-Numerical-Integration.html) + + +## Numerical Solutions of Ordinary Differential Equations + +Euler's Method +- Forward +- Backwards + +Runge-Kutta Method + +[Read More](https://pythonnumericalmethods.studentorg.berkeley.edu/notebooks/chapter22.00-ODE-Initial-Value-Problems.html) + + + diff --git a/tutorials/module_2/problem_solving_strategies.md b/tutorials/module_2/problem_solving_strategies.md new file mode 100644 index 0000000..1a50aec --- /dev/null +++ b/tutorials/module_2/problem_solving_strategies.md @@ -0,0 +1,64 @@ +# Algorithmic thinking + +## Learning Objectives + +By the end of this lesson, students will be able to: + +- Apply algorithmic thinking to solve engineering problems using computational tools. +- Translate engineering problems into structured programming logic. +- Use software tools to implement, test, and refine engineering solutions. + +--- +## 1. Define the Problem + +Like many other classes we need to frame the problem before working it. So before jumping straight into coding or building models, clearly define the engineering problem. + +- **List knowns and unknowns.** What inputs are given? What outputs are required? +- **Establish system constraints and assumptions.** Identify physical laws, design requirements, and performance limits. +- **Clarify computational objectives.** What are you trying to calculate, simulate, or optimize? + +--- +## 2. Think Algorithmically + +Since we are going to use computers to calculate our solution we first need to break the problem into logical steps that a computer can follow. + +- **Define the inputs and outputs.** What variables will the program take in, and what results will it produce? +- **Break the problem into sub-tasks.** Identify steps such as data input, logic processing and output. +- **Outline the algorithm.** Write pseudocode or flowcharts that describe the computational steps. +- **Identify patterns or formulas.** Can loops, conditionals, or equations be used to automate parts of the solution? + +**Example:** For processing stress-strain data: +1. Import data from a file. +2. Convert force and displacement to stress and strain. +3. Plot the stress-strain curve. +4. Identify the yield point or modulus. + +--- +## 3. Write & Execute the Code + +- **Choose the right tools.** Are there libraries I can use to get to my objective more effectively? +- **Write modular code.** Use functions to separate different tasks (e.g., reading data, computing values, plotting). +- **Check for syntax and logic errors.** Debug line-by-line using print statements or a debugger. + +**Example:** Write a Python script that uses NumPy and Matplotlib to load a CSV file, compute stress and strain, and generate plots. + +--- +## 4. Test and Validate + +- **Assess the feasibility of your results.** Do the values align with expected physical behavior? +- **Compare against established benchmarks.** Validate solutions using experimental data, literature values, or known theoretical limits. +- **Check units and scaling.** Ensure computations are consistent with physical meaning. + +**Example:** If your plot shows stress values in the thousands when you expect hundreds, check unit conversions in your formula. + +--- +## Case Study: Simulating a Spring-Mass System + +**Scenario:** Model the motion of a mass-spring-damper system using a numerical solver. + +1. **Define the Problem:** Set up the differential equation from Newton’s Second Law. +2. **Develop a Strategy:** Discretize time, apply numerical integration (e.g., Euler or Runge-Kutta). +3. **Execute the Code:** Write a Python function that computes motion over time. +4. **Test the Model:** Compare results with analytical solutions for undamped or lightly damped systems. +5. **Refine the Model:** Add adjustable damping and stiffness parameters. +6. **Troubleshoot Issues:** If the model becomes unstable, reduce the time step or use a more accurate integrator. \ No newline at end of file diff --git a/tutorials/module_2/version_control.md b/tutorials/module_2/version_control.md new file mode 100644 index 0000000..78b90db --- /dev/null +++ b/tutorials/module_2/version_control.md @@ -0,0 +1,112 @@ +# Version Control Software + +## What is Version Control +Version control is a system that tracks changes to files, enabling developers to collaborate, manage code history, and revert to previous versions when needed. The most used version control software (VCS) is git. In this course git is the VCS we will be using. + +In the open-source community VCS is the +- Tracks changes and history. +- Enables collaboration among developers. +- Reduces errors by managing code versions. +- Supports branching and merging for parallel development. + +In this section is divided up into two major sections. The first section *Git* will cover the basics of how to create backups of your project. The second section will cover how to use git with GitHub to *collaborate* on projects. + +--- +## Git +Git is a version control program that tracks changes to files and directories using snapshots. It is a distributed version control system, meaning that each developer has a complete copy of the repository on their local computer. Git is the most widely used version control system and is popular among developers for its speed, flexibility, and efficiency. + +### The Three States +Pay attention now — here is the main thing to remember about Git if you want the rest of your learning process to go smoothly. Git has three main states that your files can reside in: modified, staged, and committed: + +- **Modified** means that you have changed the file but have not committed it to your database yet. +- **Staged** means that you have marked a modified file in its current version to go into your next commit snapshot. +- **Committed** means that the data is safely stored in your local database. + +This leads us to the three main sections of a Git project: the working tree, the staging area, and the Git directory. + +![Pro Git: Figure 6.](https://git-scm.com/book/en/v2/images/areas.png) +### Branching +In git, branches allow for parallel workflow on a project. It give contributors the ability to work different features at the same time. Each branch represents an independent line of development, and once a feature or fix is complete, it can be merged back into the main branch. Here is a common branching structure used in many Git projects: +- Main Branch - The main branch (a.k.a. master branch) is the default branch in a Git repository and contains the stable version of the code. +- Development Branch - is created to develop a new feature or fix a bug without affecting the main branch. It isn’t necessarily always stable, but whenever it gets to a stable state, it can be merged into master. +- Topic Branch - A topic branch is a short-lived branch that you create and use for a single particular feature or related work. +![Figure 27. A "Silo" view of progressive-stability branching](https://git-scm.com/book/en/v2/images/lr-branches-2.png) +### Best Practices +- Use descriptive commit messages. +- Commit early and often. +- Keep commits focused on a single change. +- Use feature branches for new features or bug fixes. +- Review and test changes before merging. +- Resolve conflicts promptly. +- Keep the commit history clean and organized. + +### Basic Commands +Here is a list of some git commands to get you started. +#### Starting your repository +- `git init` - Initialize a new Git repository. +- `git clone` - Clone an existing repository. +#### Committing +- `git status` - Check the status of the repository. +- `git add` - Add files to the staging area. +- `git commit` - Commit changes to the repository. +#### Branching +- `git branch` - List, create, or delete branches. +- `git checkout` - Switch between branches. +#### History/Inspection +- `git log` - View the commit history. +#### Collaborative +- `git fetch` - Fetches updates from a remote but does not merge. +- `git merge` - Merge changes from a named commit to the current branch. +- `git pull` - Fetch and merge changes from a remote repository. +- `git push` - Push changes to a remote repository. + +### More on git +Interested in learning more about git? Here's a free book that teaches you everything about git and how to use it at a professional level. Available as both HTML and PDF download: [Git Pro](https://git-scm.com/book/en/v2). + + +## GitHub - The collaborative platform +GitHub is a web-based platform that hosts Git repositories and provides collaboration tools for developers. It allows developers to share code, track issues, and collaborate on projects with other developers. GitHub is widely used for open-source projects, team collaboration, and code hosting. +### GitHub Features +- Remote Repository Hosting - GitHub allows you to host projects and code remotely on their servers. +- Issues - Issues are used to track bugs, feature +- Pull Requests - Internal request system for contributors to request code to be pulled. +### Workflow +Depending on the size of the project and whether the project is closed- or open-source, the workflow of the project will differ. In this section we cover some git workflow models and the model you're going to be using for this course. + + +**Centralized**: The project has only one central hub or *repository*, can accept code and everybody synchronizes their work with it. This model is suitable for small and closed-sourced projects. +![Centralized Workflow](https://git-scm.com/book/en/v2/images/centralized_workflow.png) + + + +**Integration-Manager:** There are multiple public variants of the code original code known as *forks*. The integration manager can decide what features to pull from the forks. This is the model that is similar to the one used on GitHub +![Integration-Manager Workfow](https://git-scm.com/book/en/v2/images/integration-manager.png) + + + +**Dictator and Lieutenants Workflow:** This is similar to the integration-manager model, however due to the size of the project. A rank of integration managers is formed. one example of this is the development of the Linux kernel. +![Dictator and Lieutenants Workflow](https://git-scm.com/book/en/v2/images/benevolent-dictator.png) + + +GitHub is designed around a particular collaboration workflow, centered on Pull Requests. This flow works whether you’re collaborating with a tightly-knit team in a single shared repository, or a globally-distributed company or network of strangers contributing to a project through dozens of forks. It is centered on the Topic Branches workflow covered in Git Branching. + + + +Here’s how it generally works: +1. Fork the project. +2. Create a topic branch from master. +3. Make some commits to improve the project. +4. Push this branch to your GitHub project. +5. Open a Pull Request on GitHub. +6. Discuss, and optionally continue committing. +7. The project owner merges or closes the Pull Request. +8. Sync the updated master back to your fork. + +### Terms +- Pull Request - A *pull request* is a request to merge changes from a feature branch into the main branch or from a forked repository to the original or "upstream" repository. +- Merge - A *merge* combines the changes from one branch into another branch. +- Conflict - A *conflict* occurs when Git cannot automatically merge changes and requires manual intervention. + + +### Code resource - Using GitHub to re-use existing code. +In your engineering career, you will most likely use a computation method that has been come up with before. In such scenarios, open-source -- cgit v1.2.3