0% found this document useful (0 votes)
2 views65 pages

Lecture 02

The document provides an introduction to optimization using Python, covering installation of Anaconda and Gurobi, as well as Python basics such as data types, variables, and control structures. It also discusses the use of Python for linear algebra and file input/output operations, emphasizing the importance of code readability and the use of libraries like numpy. Additionally, it includes examples and resources for further learning about Python programming.

Uploaded by

sushantgoyal3525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views65 pages

Lecture 02

The document provides an introduction to optimization using Python, covering installation of Anaconda and Gurobi, as well as Python basics such as data types, variables, and control structures. It also discusses the use of Python for linear algebra and file input/output operations, emphasizing the importance of code readability and the use of libraries like numpy. Additionally, it includes examples and resources for further learning about Python programming.

Uploaded by

sushantgoyal3525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

DBA3701/DSC3214

Introduction to Optimization
Lecture 2
Run! Python, Run!

I just feel like


running……
Python!
Run! Python, Run!
• Installation

‣ Anaconda

✓ Python, Jupyter, Spyder

‣ Gurobi
Anaconda (for Python) and Gurobi

• Anaconda
– It includes over 330 Python and R packages
– It includes Integrated Development Environment (Spyder) and
the leading web interactive notebook for data science (Jupyter).
• Gurobi
– A commercial optimization solver for linear
programming (LP), quadratic programming (QP), quadratically
constrained programming (QCP), mixed integer linear
programming (MILP), mixed-integer quadratic programming
(MIQP), and mixed-integer quadratically constrained
programming (MIQCP).
Back to LOP Example:

• A furniture company makes tables and chairs


• Production require wood, finishing labor and
carpentry labor.
Desk Table Chair Avail.
Revenue 60 30 20
Wood 8 6 1 48
Finish Hrs 4 2 1.5 20
Carpentry Hrs 2 1.5 0.5 8
LOP Example:
Gurobi Python API
Python Basics
• Python is an interpreted high-level programming language for
general-purpose programming.
Python Basics
• Python is an interpreted high-level programming language for
general-purpose programming.

• Python has a design philosophy that emphasizes code readability,


notably using significant whitespace.
Good Code Readability
• Being “Pythonic”

BABY, FOR EACH DAY IN


A WEEK, I MISS YOU! WOW SWEETY, YOU SOUND SO PYTHONIC!
Good Code Readability
• Being “Pythonic”

‣ Meaningful names

‣ Comments

‣ Meaningful variable names


Python Basics
• Python is an interpreted high-level programming language for
general-purpose programming.

• Python has a design philosophy that emphasizes code readability,


notably using significant whitespace.

• It has a large and comprehensive standard library.


Python Basics
• Python is an interpreted high-level programming language for
general-purpose programming.

• Python has a design philosophy that emphasizes code readability,


notably using significant whitespace.

• It has a large and comprehensive standard library.

• More tutorials can be found here:


– https://docs.python.org/3.6/tutorial/index.html
– https://www.tutorialspoint.com/python3/index.htm
– http://cs231n.github.io/python-numpy-tutorial/
Variables and Basic Types
Basic Types
• Numbers
– int (integers), e.g., -10
– float (floating point real values), e.g., -10.0, 32.3+e18

• Booleans: Bool, true or false

• Strings
– A contiguous set of characters represented in the quotation
marks. e.g., “Hello World!”
Basic Arithmetic
• More examples on basic arithmetic operations
Boolean Variables
• Evaluated to True or False
• Combine Boolean expression using and, or
• Flip Boolean value using not
• Membership: use in, not in
Boolean Expression

• The Boolean Type Expressions

‣ Status: True or False

‣ Comparison operators

Operators Remarks Example


== Equal x == y
!= Not equal x != y
>= Greater than or equal to x >= y
<= Smaller than or equal to x <= y
> Greater than x > y
< Smaller than x < y
Strings
Type Conversion

• Data Type Conversion

‣ Enable manipulating data differently

‣ Use type name as the conversion function

HOW ABOUT MULTIPLYING THE DATA TYPE


INPUT CONVERSION!!
NUMBER BY TEN?
Type Conversion

• Data Type Conversion

‣ Enable manipulating data differently

‣ Use type name as the conversion function

HOW ABOUT MULTIPLYING THE DATA TYPE


INPUT CONVERSION!!
NUMBER BY TEN?
Type Conversion

• Data Type Conversion

‣ Enable manipulating data differently

‣ Use type name as the conversion function


DATA TYPE CONVERSION!!
Type Conversion

• Data Type Conversion

BEFORE TYPE
CONVERSION
Type Conversion

• Data Type Conversion

BEFORE TYPE
CONVERSION

AFTER TYPE
CONVERSION
Compound Types
• List
– e.g., [‘abcd’, 786, 2.23, ‘john’, 70.2]

• Tuple
– e.g., (‘abcd’, 786, 2.23, ‘john’, 70.2)

• Dictionary
– e.g., {‘cat’: ‘cute’, ‘dog’: ‘furry’}

• Set
– e.g., {‘cat’, ‘dog’}
List
• A list is the Python equivalent of an array, but is resizeable and can
contain elements of different types.
• Note that the first index is 0

For more, see


https://docs.python.org/3.6/tutorial/datastructures.html#more-on-lists
Python Lists
• List Methods

‣ append, extend

1 2 3 4
the_list
0 1 2 3
Python Lists
• List Methods

‣ append, extend

1 2 3 4 5 Append one item “5”


the_list
0 1 2 3 4 to the end of the list
Python Lists
• List Methods

‣ append, extend

1 2 3 4 5 6 7 8 9 Extend the list by adding


the_list
0 1 2 3 4 5 6 7 8 [6, 7, 8, 9] to the end
Tuple
• A tuple is in many ways similar to a list.
• But it is immutable ordered list of values.
Slicing and Indexing
• Slicing: Python provides concise syntax to access sublists.
• Range: the range type represents an immutable sequence of
numbers

For more, see


https://docs.python.org/3.6/library/stdtypes.html?highlight=range#range
Slicing and Indexing
• Indexing and Slicing

‣ Slicing expression

[start:stop:step]

Arguments Remarks Default Values


start The first index of the slice 0
stop The index before which the slice stops Length of the string
step The step length of the slice 1
Python Dictionary
• A dictionary stores unordered (key, value) pairs.
• Search and Insert elements fast.
• key is immutable.
• More than one entry per key is not allowed.

For more, see


https://www.tutorialspoint.com/python3/python_dictionary.htm
Python Dictionaries
• Create and Access Dictionaries

An “elegant” and efficient solution via Python dictionaries:

keys to
access values
Set
• A set is an unordered collection of distinct elements (same as the
corresponding concepts in math)
Conditional Statement
• Test if a Boolean expression is True or False and run
different code in each case
• Can split the code into more than two cases
For Loops

• More examples
While Loops

• You can also use while to loop

For more, see


https://www.tutorialspoint.com/python3/python_loops.htm
List Comprehension
• To transform one type of data into another easily.
• Instead of using loops, we can write

• You can add conditional control


Functions
Passing by Reference
• All parameters (arguments) in Python are passed by reference. It
means if you change what a parameter refers to within a function,
the change also reflects back in the calling function.
Passing by Reference
• All parameters (arguments) in Python are passed by reference. It
means if you change what a parameter refers to within a function,
the change also reflects back in the calling function.
More Examples of Function from Modules

• math

• random
Vector, Matrix, and Array
• For Linear Algebra use, you need to install and import numpy
module.

• Slicing and transpose


• Basic vector and matrix operation
• Basic Linear Algebra

To learn numpy, you are encouraged to read the tutorial:


http://cs231n.github.io/python-numpy-tutorial/
https://docs.scipy.org/doc/numpy/user/quickstart.html
Basic Initialization
Special Initialization
Slicing and Transpose
Vector and Matrix Multiplication
• n-dim vectors are NOT 1xn or nx1 matrices and can be
either column or row vectors
Basic Linear Algebra
• Matrix Inverse

• Solve linear systems


Basic Linear Algebra
• Get determinant, eigenvalues and eigenvectors
File Input/Output
• First, open a file by open()
• Then, read the file:
– For small file, we can use read() to read the file in a batch
– For large file, we can use read(size)
– readline() read a line each time
• Finally, use close() to close the file
File Input/Output
• Using the with keyword when dealing with file objects is
highly suggested.
File Input/Output
• Add contents at the end of the file. Notice the argument is a ‘a+’.

If you want to rewrite the file from the beginning, use ‘w’ or ‘r+’. For
more details, see
https://www.tutorialspoint.com/python3/python_files_io.htm
https://docs.python.org/3.6/tutorial/inputoutput.html
File Input/Output
• Read CSV file

• Write CSV file


File Input/Output
• Read CSV data as Dictionary

You might also like