Materials+ML Workshop Day 1¶

logo

Background Survey¶

background survey

https://forms.gle/FEWqPavJJYC9VzfH7¶

Survey Results: Which department are you from?¶

departments

Survey Results: How familiar are you with computer programming (1-10 scale)?¶

programming survey

Survey Results: How familiar are you with Python (1-10 scale)?¶

python survey

Survey Results: Which programming languages are you most familiar with?¶

languages survey

The Workshop Online Book:¶

https://cburdine.github.io/materials-ml-workshop/¶

Workshop Schedule¶

Session Date Content
Day 0 06/16/2023 (2:30-3:30 PM) Introduction, Setting up your Python Notebook
Day 1 06/19/2023 (2:30-3:30 PM) Python Data Types
Day 2 06/20/2023 (2:30-3:30 PM) Python Functions and Classes
Day 3 06/21/2023 (2:30-3:30 PM) Scientific Computing with Numpy and Scipy
Day 4 06/22/2023 (2:30-3:30 PM) Data Manipulation and Visualization
Day 5 06/23/2023 (2:30-3:30 PM) Materials Science Packages
Day 6 06/26/2023 (2:30-3:30 PM) Introduction to ML, Supervised Learning
Day 7 06/27/2023 (2:30-3:30 PM) Regression Models
Day 8 06/28/2023 (2:30-3:30 PM) Unsupervised Learning
Day 9 06/29/2023 (2:30-3:30 PM) Neural Networks
Day 10 06/30/2023 (2:30-3:30 PM) Advanced Applications in Materials Science

Day 1 Agenda:¶

  • Questions about Day 0 Material
  • Review of Day 0
  • Content for today (Day 1):
    • Boolean variables
    • Python Logic and Flow Control
    • Loops in Python
    • Lists and Tuples
    • Sets and Dictionaries

Questions¶

Review of Day 0:¶

Python types:¶

In [1]:
123  # 'int' (integer) type
Out[1]:
123
In [2]:
1.23e-2 # 'float' (floating point decimal) type
Out[2]:
0.0123
In [3]:
1.2 + 3.4j # 'complex' (complex number type)
Out[3]:
(1.2+3.4j)

Arithmetic in Python:¶

$$ 3 \cdot \left( \frac{20}{5}\right)^{3} - (0.125) \cdot \sqrt[4]{64} $$
In [4]:
(3 * (20 / 5)**3) - (0.125 * 64**(1/4))
Out[4]:
191.64644660940672
  • The string type (str) in Python:
In [5]:
'Hello' # strings are text enclosed in single quotes ('...')
Out[5]:
'Hello'
In [6]:
print(type('Hello')) # prints the type of a python object
<class 'str'>
In [7]:
# The `+` operator concatenates two strings:
'Hello' + 'World'
Out[7]:
'HelloWorld'

Variables in Python:¶

Variables are named Python objects. We assign values to variables using the = operator:

In [8]:
number_1 = 1234
number_2 = 5.67
another_variable = 'some text'
  • Assignment operator (=) behavior:
In [9]:
number_3 = number_1 + number_2
print(number_3)
1239.67
In [10]:
count = 0         # creates a variable called 'count'
count = count + 1 # adds 1 to count
print(count)

count += 1        # also adds 1 to count
print(count)

count -= 1        # decreases count by 1
print(count)
1
2
1

New Content:¶

  • Boolean variables
  • Python Logic and Flow Control
  • Loops in Python
  • Lists and Tuples
  • Sets and Dictionaries

Boolean Variables¶

  • Boolean variables store a logical value (True or False)
  • In Python, Boolean variables are of the bool type
In [11]:
# create some Boolean variables
bool_a = True
bool_b = False
In [12]:
# print out the type of these variables:
print(bool_a, bool_b)
print(type(bool_a), type(bool_b))
True False
<class 'bool'> <class 'bool'>
  • We can perform logical and or, and not operations with bool variables

and and or operations:¶

In [13]:
# behavior of the `and` operator:
print(False and False)
print(False and True)
print(True and False)
print(True and True)
False
False
False
True
In [14]:
# behavior of the `or` operator:
print(False or False)
print(False or True)
print(True or False)
print(True or True)
False
True
True
True

The not operation:¶

In [15]:
# behavior of the `not` operator:
print(not False)
print(not True)
True
False
  • Logic operations with bool variables can be nested in parentheses:
In [16]:
# create boolean variables:
bool_a = True
bool_b = False
bool_c = False

# evaluate nested expression:
print((not bool_a) and ((not bool_b) or bool_c))
False

Comparison Operations:¶

  • The result of comparing two numbers is a bool type.
  • The following comparison operators are supported in Python:
    • Less than ($a < b$): a < b
    • Less than or equal to ($a \le b$): a <= b
    • Greater than ($a > b$): a > b
    • Greater than or equal to ($a \ge b$): a >= b
    • Equal to ($a = b$): a == b
    • Not equal to ($a \neq b$): a != b

Comparison Examples:¶

In [17]:
# create some numerical variables:
x = 0.25
y = -3
z = 20
z_2 = 20.0

# simple comparisons:
print(x < y)
print(y < z)
print(x == y)
print(z >= z_2)
False
True
False
True

if and if/else blocks:¶

  • We can conditionally execute a block of code based on a bool variable or expression.
  • The simplest kind of conditional statement is an if block, which only executes if the condition is True:
In [19]:
# syntax of if statements:
if condition:
    body
  • Example of an if statement: checking if the denominator in division is zero.
In [20]:
numerator = 1.0
denominator = 0.0

# set quotient to a default value:
quotient = 0.0

# perform division if denominator is nonzero:
if denominator != 0:
    quotient = numerator / denominator

# print quotient:
print(quotient)
0.0
  • We can also do the same thing with an if/else block:
In [21]:
numerator = 1.0
denominator = 0.0

# perform division if denominator is nonzero:
if denominator != 0:
    quotient = numerator / denominator
else:
    quotient = 0.0

# print quotient:
print(quotient)
0.0
  • We can chain together multiple blocks in an if/elif/else blocks:
In [22]:
# initialize a numeric value:
value = 100.0

# print out the sign of x:
if value < 0:
    print('Value is negative.')
elif value == 0:
    print('Value is zero.')
else:
    print('Value is positive.')
Value is positive.
  • We can also nest if statements:
In [23]:
# initialize x
x = 0.0

# check if x lies inside [-1,1]
if -1 < x < 1:
    
    # check if x lies at the origin:
    if x == 0:
        print('x lies at the origin')
    
    print('x lies within [-1,1]')
x lies at the origin
x lies within [-1,1]

Exercise: Classifying Chemical Compounds¶

  • Exercise 1 from the "Logic and Flow Control" section

Loops¶

  • Loops are used to repeatedly execute a block of code until a condition is met.
  • Python supports two main kinds of loops: while loops and for loops.
  • The body of a loop is indented (with a single tab)

while loops:¶

  • while loops execute the body as long as a condition is met
In [24]:
# syntax of a while loop:
while condition:
    body
  • while loop example:
In [25]:
# initialize a step counter:
step = 0

# execute the `while` loop:
while step < 5:

    # print step:
    print('step:', step)
    
    # increment step:
    step = step + 1

# print "Done" upon completion of the loop:
print('Done')
step: 0
step: 1
step: 2
step: 3
step: 4
Done

for loops:¶

  • provides a concise way for iterating over a sequence of values
  • To use a range of consecutive integers, Python has the range keyword:
In [27]:
# syntax of a while loop:
for item in sequence:
    body
  • Example: using for loops with the range function
    • range(n) iterates over the sequence 0,1,2,...,n-2,n-1
    • range(m,n) iterates over the sequence m,m+1,...,n-2,n-1
In [28]:
# iterate over i = 1,2,...,4
for i in range(5):
    print('value of i:',i)
value of i: 0
value of i: 1
value of i: 2
value of i: 3
value of i: 4

Exercise: Computing the factorial¶

  • Compute the factorial of an integer $n$:
$$n! = n(n-1)(n-2)...(2)(1)$$

Lists and Tuples in Python¶

  • Lists and tuples are useful for storing a sequence of values
  • Lists are comma-separated values enclosed by square brackets ([...])
  • Tuples are similar, but enclosed by parentheses ((...))
In [29]:
# example of a list:
my_list = [ 1, 2, 3, 4, 5 ]

# example of a tuple:
my_tuple = (1, 2, 3, 4, 5)

Lists and tuples can be constructed from a sequence of values using the list and tuple functions:

In [30]:
# construct list and tuple from a `range`:
range_list = list(range(6))
range_tuple = tuple(range(6))

# print list and tuple:
print(range_list)
print(range_tuple)
[0, 1, 2, 3, 4, 5]
(0, 1, 2, 3, 4, 5)

Indexing:¶

  • We can access elements at index n using the syntax my_list[n]/my_tuple[n]
  • The index of the first element is 0, the second is 1, etc.
  • Negative indexes n start at the end of the list (-1 is the last element)
In [31]:
# initialize list/tuple example:
list_1  = [ 0, 1, 2, 3, 4 ]
tuple_1 = ( 0, 1, 2, 3, 4 )

# access tuples and lists:
print(list_1[0], list_1[1], list_1[2])
print(tuple_1[0], tuple_1[1], tuple_1[2])

# access end of tuple:
print(list_1[-1])
print(tuple_1[-1])
0 1 2
0 1 2
4
4

Lists versus Tuples:¶

  • Lists and tuples differ because Lists are mutable (their elements can be changed)
  • Tuples are immutable (their elements cannot be changed)
In [32]:
my_list = [1,2,3,4]

# modify the second element of my_list:
my_list[1] = 200

# append a value to my_list:
my_list.append(500)

# print the modified list:
print(my_list)
[1, 200, 3, 4, 500]

Sets in Python¶

  • Unlike, lists and tuples, Python sets deal with unordered data
  • Sets are a collection of unique elements (i.e. mathematical sets)
  • To create a set in Python, use curly braces ({...})
In [33]:
# create a set (duplicate elements will be removed):
example_set = {'A', 'B', 'C', 'A', 'F', 'B'}

# print the set:
print(example_set)
{'C', 'A', 'F', 'B'}

Set operations:¶

  • Python sets support the union, intersection, and difference operations:
    • union: values in either set
    • intersection values in both sets
    • difference: values in first set but not in the second set
In [34]:
# Create sets of physicists and chemists:
chemists = { 'Bohr', 'Curie', 'Pauling', 'Berzelius' }
physicists = { 'Planck', 'Bohr', 'Pauli', 'Curie', 'Fermi' }

# print out the result of a set union:
# (i.e. people who are chemists or physicists):
print(chemists.union(physicists))

# print the result of a set intersection:
# (i.e. people who are chemists and physicists):
print(chemists.intersection(physicists))

# print the result of a set difference:
# (i.e. people who are chemists but not physicists):
print(chemists.difference(physicists))
{'Planck', 'Pauli', 'Fermi', 'Curie', 'Bohr', 'Berzelius', 'Pauling'}
{'Curie', 'Bohr'}
{'Berzelius', 'Pauling'}

Python Dictionaries¶

  • Python Dictionaries are an extension of sets that associate values with a unique set of keys
  • The syntax for creating dictionaries is similar to sets, but with a colon (:) separating key-value pairs
In [35]:
# create a dictionary representing a person:
person = {
    'name' : 'John von Neumann',
    'age' : 40,
    'occupation' : 'Mathematician',
    'birthday' : ('March', 15, 1995)
}

# print the dictionary:
print(person)
{'name': 'John von Neumann', 'age': 40, 'occupation': 'Mathematician', 'birthday': ('March', 15, 1995)}
In [36]:
# create a dictionary representing a person:
person = {
    'name' : 'John von Neumann',
    'age' : 40,
    'occupation' : 'Mathematician',
    'birthday' : ('March', 15, 1995)
}

# print the value of the 'name' key:
print(person['name'])

# print the value of the 'birthday' key:
print(person['birthday'])

# update the value of the 'occupation key':
person['occupation'] = 'Physicist'
print(person['occupation'])

# add the new key 'city' with value 'New Jersey':
person['city'] = 'New Jersey'
print(person['city'])
John von Neumann
('March', 15, 1995)
Physicist
New Jersey

Exercise: Scheduling¶

  • Exercise 1 from "Sets and Dictionaries"
  • If time: Exercise 2 from "Sets and Dictionaries"

Recommended reading for tomorrow:¶

  • Python Functions and Classes

If possible, try to do the exercises.

Bring your questions to our next meeting tomorrow!