markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Basic Functions![](http://)**Hint** Be sure to `return` values from your function definitions. The assert statements will call your function(s) for you.
# Run this cell in order to generate some numbers to use in our functions after this. import random positive_even_number = random.randrange(2, 101, 2) negative_even_number = random.randrange(-100, -1, 2) positive_odd_number = random.randrange(1, 100, 2) negative_odd_number = random.randrange(-101, 0, 2) print("We now have some random numbers available for future exercises.") print("The random positive even number is", positive_even_number) print("The random positive odd nubmer is", positive_odd_number) print("The random negative even number", negative_even_number) print("The random negative odd number", negative_odd_number) # Example function defintion: # Write a say_hello function that adds the string "Hello, " to the beginning and "!" to the end of any given input. def say_hello(name): return "Hello, " + name + "!" assert say_hello("Jane") == "Hello, Jane!", "Double check the inputs and data types" assert say_hello("Pat") == "Hello, Pat!", "Double check the inputs and data types" assert say_hello("Astrud") == "Hello, Astrud!", "Double check the inputs and data types" print("The example function definition ran appropriately") # Another example function definition: # This plus_two function takes in a variable and adds 2 to it. def plus_two(number): return number + 2 assert plus_two(3) == 5 assert plus_two(0) == 2 assert plus_two(-2) == 0 print("The plus_two assertions executed appropriately... The second function definition example executed appropriately.") # Exercise 11 # Write a function definition for a function named add_one that takes in a number and returns that number plus one. def add_one(x): new = x + 1 return new assert add_one(2) == 3, "Ensure that the function is defined, named properly, and returns the correct value" assert add_one(0) == 1, "Zero plus one is one." assert add_one(positive_even_number) == positive_even_number + 1, "Ensure that the function is defined, named properly, and returns the correct value" assert add_one(negative_odd_number) == negative_odd_number + 1, "Ensure that the function is defined, named properly, and returns the correct value" print("Exercise 11 is correct.") # Exercise 12 # Write a function definition named is_positive that takes in a number and returns True or False if that number is positive. def is_positive(x): return x > 0 assert is_positive(positive_odd_number) == True, "Ensure that the function is defined, named properly, and returns the correct value" assert is_positive(positive_even_number) == True, "Ensure that the function is defined, named properly, and returns the correct value" assert is_positive(negative_odd_number) == False, "Ensure that the function is defined, named properly, and returns the correct value" assert is_positive(negative_even_number) == False, "Ensure that the function is defined, named properly, and returns the correct value" print("Exercise 12 is correct.") # Exercise 13 # Write a function definition named is_negative that takes in a number and returns True or False if that number is negative. def is_negative(x): return x < 0 assert is_negative(positive_odd_number) == False, "Ensure that the function is defined, named properly, and returns the correct value" assert is_negative(positive_even_number) == False, "Ensure that the function is defined, named properly, and returns the correct value" assert is_negative(negative_odd_number) == True, "Ensure that the function is defined, named properly, and returns the correct value" assert is_negative(negative_even_number) == True, "Ensure that the function is defined, named properly, and returns the correct value" print("Exercise 13 is correct.") # Exercise 14 # Write a function definition named is_odd that takes in a number and returns True or False if that number is odd. def is_odd(x): return x % 2 != 0 assert is_odd(positive_odd_number) == True, "Ensure that the function is defined, named properly, and returns the correct value" assert is_odd(positive_even_number) == False, "Ensure that the function is defined, named properly, and returns the correct value" assert is_odd(negative_odd_number) == True, "Ensure that the function is defined, named properly, and returns the correct value" assert is_odd(negative_even_number) == False, "Ensure that the function is defined, named properly, and returns the correct value" print("Exercise 14 is correct.") # Exercise 15 # Write a function definition named is_even that takes in a number and returns True or False if that number is even. def is_even(x): return x % 2 == 0 assert is_even(2) == True, "Ensure that the function is defined, named properly, and returns the correct value" assert is_even(positive_odd_number) == False, "Ensure that the function is defined, named properly, and returns the correct value" assert is_even(positive_even_number) == True, "Ensure that the function is defined, named properly, and returns the correct value" assert is_even(negative_odd_number) == False, "Ensure that the function is defined, named properly, and returns the correct value" assert is_even(negative_even_number) == True, "Ensure that the function is defined, named properly, and returns the correct value" print("Exercise 15 is correct.") # Exercise 16 # Write a function definition named identity that takes in any argument and returns that argument's value. Don't overthink this one! def identity(x): return x assert identity(fruits) == fruits, "Ensure that the function is defined, named properly, and returns the correct value" assert identity(vegetables) == vegetables, "Ensure that the function is defined, named properly, and returns the correct value" assert identity(positive_odd_number) == positive_odd_number, "Ensure that the function is defined, named properly, and returns the correct value" assert identity(positive_even_number) == positive_even_number, "Ensure that the function is defined, named properly, and returns the correct value" assert identity(negative_odd_number) == negative_odd_number, "Ensure that the function is defined, named properly, and returns the correct value" assert identity(negative_even_number) == negative_even_number, "Ensure that the function is defined, named properly, and returns the correct value" print("Exercise 16 is correct.") # Exercise 17 # Write a function definition named is_positive_odd that takes in a number and returns True or False if the value is both greater than zero and odd def is_positive_odd(x): return (x > 0) and (x % 2 != 0) assert is_positive_odd(3) == True, "Double check your syntax and logic" assert is_positive_odd(positive_odd_number) == True, "Double check your syntax and logic" assert is_positive_odd(positive_even_number) == False, "Double check your syntax and logic" assert is_positive_odd(negative_odd_number) == False, "Double check your syntax and logic" assert is_positive_odd(negative_even_number) == False, "Double check your syntax and logic" print("Exercise 17 is correct.") # Exercise 18 # Write a function definition named is_positive_even that takes in a number and returns True or False if the value is both greater than zero and even def is_positive_even(x): return (x > 0) and (x % 2 == 0) assert is_positive_even(4) == True, "Double check your syntax and logic" assert is_positive_even(positive_odd_number) == False, "Double check your syntax and logic" assert is_positive_even(positive_even_number) == True, "Double check your syntax and logic" assert is_positive_even(negative_odd_number) == False, "Double check your syntax and logic" assert is_positive_even(negative_even_number) == False, "Double check your syntax and logic" print("Exercise 18 is correct.") # Exercise 19 # Write a function definition named is_negative_odd that takes in a number and returns True or False if the value is both less than zero and odd. def is_negative_odd(x): return (x < 0) and (x % 2 != 0) assert is_negative_odd(-3) == True, "Double check your syntax and logic" assert is_negative_odd(positive_odd_number) == False, "Double check your syntax and logic" assert is_negative_odd(positive_even_number) == False, "Double check your syntax and logic" assert is_negative_odd(negative_odd_number) == True, "Double check your syntax and logic" assert is_negative_odd(negative_even_number) == False, "Double check your syntax and logic" print("Exercise 19 is correct.") # Exercise 20 # Write a function definition named is_negative_even that takes in a number and returns True or False if the value is both less than zero and even. def is_negative_even(x): return (x < 0) and (x % 2 == 0) assert is_negative_even(-4) == True, "Double check your syntax and logic" assert is_negative_even(positive_odd_number) == False, "Double check your syntax and logic" assert is_negative_even(positive_even_number) == False, "Double check your syntax and logic" assert is_negative_even(negative_odd_number) == False, "Double check your syntax and logic" assert is_negative_even(negative_even_number) == True, "Double check your syntax and logic" print("Exercise 20 is correct.") # Exercise 21 # Write a function definition named half that takes in a number and returns half the provided number. def half(x): return x/2 assert half(4) == 2 assert half(5) == 2.5 assert half(positive_odd_number) == positive_odd_number / 2 assert half(positive_even_number) == positive_even_number / 2 assert half(negative_odd_number) == negative_odd_number / 2 assert half(negative_even_number) == negative_even_number / 2 print("Exercise 21 is correct.") # Exercise 22 # Write a function definition named double that takes in a number and returns double the provided number. def double(x): return x * 2 assert double(4) == 8 assert double(5) == 10 assert double(positive_odd_number) == positive_odd_number * 2 assert double(positive_even_number) == positive_even_number * 2 assert double(negative_odd_number) == negative_odd_number * 2 assert double(negative_even_number) == negative_even_number * 2 print("Exercise 22 is correct.") # Exercise 23 # Write a function definition named triple that takes in a number and returns triple the provided number. def triple(x): return x * 3 assert triple(4) == 12 assert triple(5) == 15 assert triple(positive_odd_number) == positive_odd_number * 3 assert triple(positive_even_number) == positive_even_number * 3 assert triple(negative_odd_number) == negative_odd_number * 3 assert triple(negative_even_number) == negative_even_number * 3 print("Exercise 23 is correct.") # Exercise 24 # Write a function definition named reverse_sign that takes in a number and returns the provided number but with the sign reversed. def reverse_sign(x): return x * (-1) assert reverse_sign(4) == -4 assert reverse_sign(-5) == 5 assert reverse_sign(positive_odd_number) == positive_odd_number * -1 assert reverse_sign(positive_even_number) == positive_even_number * -1 assert reverse_sign(negative_odd_number) == negative_odd_number * -1 assert reverse_sign(negative_even_number) == negative_even_number * -1 print("Exercise 24 is correct.") # Exercise 25 # Write a function definition named absolute_value that takes in a number and returns the absolute value of the provided number import numpy as np def absolute_value(x): return abs(x) assert absolute_value(4) == 4 assert absolute_value(-5) == 5 assert absolute_value(positive_odd_number) == positive_odd_number assert absolute_value(positive_even_number) == positive_even_number assert absolute_value(negative_odd_number) == negative_odd_number * -1 assert absolute_value(negative_even_number) == negative_even_number * -1 print("Exercise 25 is correct.") # Exercise 26 # Write a function definition named is_multiple_of_three that takes in a number and returns True or False if the number is evenly divisible by 3. def is_multiple_of_three(x): return x % 3 == 0 assert is_multiple_of_three(3) == True assert is_multiple_of_three(15) == True assert is_multiple_of_three(9) == True assert is_multiple_of_three(4) == False assert is_multiple_of_three(10) == False print("Exercise 26 is correct.") # Exercise 27 # Write a function definition named is_multiple_of_five that takes in a number and returns True or False if the number is evenly divisible by 5. def is_multiple_of_five(x): return x % 5 == 0 assert is_multiple_of_five(3) == False assert is_multiple_of_five(15) == True assert is_multiple_of_five(9) == False assert is_multiple_of_five(4) == False assert is_multiple_of_five(10) == True print("Exercise 27 is correct.") # Exercise 28 # Write a function definition named is_multiple_of_both_three_and_five that takes in a number and returns True or False if the number is evenly divisible by both 3 and 5. def is_multiple_of_both_three_and_five(x): return x % 5 == 0 and x % 3 == 0 assert is_multiple_of_both_three_and_five(15) == True assert is_multiple_of_both_three_and_five(45) == True assert is_multiple_of_both_three_and_five(3) == False assert is_multiple_of_both_three_and_five(9) == False assert is_multiple_of_both_three_and_five(4) == False print("Exercise 28 is correct.") # Exercise 29 # Write a function definition named square that takes in a number and returns the number times itself. def square(x): return x ** 2 assert square(3) == 9 assert square(2) == 4 assert square(9) == 81 assert square(positive_odd_number) == positive_odd_number * positive_odd_number print("Exercise 29 is correct.") # Exercise 30 # Write a function definition named add that takes in two numbers and returns the sum. def add(x,y): return x + y assert add(3, 2) == 5 assert add(10, -2) == 8 assert add(5, 7) == 12 print("Exercise 30 is correct.") # Exercise 31 # Write a function definition named cube that takes in a number and returns the number times itself, times itself. def cube(x): return x ** 3 assert cube(3) == 27 assert cube(2) == 8 assert cube(5) == 125 assert cube(positive_odd_number) == positive_odd_number * positive_odd_number * positive_odd_number print("Exercise 31 is correct.") # Exercise 32 # Write a function definition named square_root that takes in a number and returns the square root of the provided number def square_root(x): return np.sqrt(x) assert square_root(4) == 2.0 assert square_root(64) == 8.0 assert square_root(81) == 9.0 print("Exercise 32 is correct.") # Exercise 33 # Write a function definition named subtract that takes in two numbers and returns the first minus the second argument. def subtract(x,y): return x - y assert subtract(8, 6) == 2 assert subtract(27, 4) == 23 assert subtract(12, 2) == 10 print("Exercise 33 is correct.") # Exercise 34 # Write a function definition named multiply that takes in two numbers and returns the first times the second argument. def multiply(x,y): return x * y assert multiply(2, 1) == 2 assert multiply(3, 5) == 15 assert multiply(5, 2) == 10 print("Exercise 34 is correct.") # Exercise 35 # Write a function definition named divide that takes in two numbers and returns the first argument divided by the second argument. def divide(x,y): return x/y assert divide(27, 9) == 3 assert divide(15, 3) == 5 assert divide(5, 2) == 2.5 assert divide(10, 2) == 5 print("Exercise 35 is correct.") # Exercise 36 # Write a function definition named quotient that takes in two numbers and returns only the quotient from dividing the first argument by the second argument. def quotient(x,y): return x // y assert quotient(27, 9) == 3 assert quotient(5, 2) == 2 assert quotient(10, 3) == 3 print("Exercise 36 is correct.") # Exercise 37 # Write a function definition named remainder that takes in two numbers and returns the remainder of first argument divided by the second argument. def remainder(x,y): return x % y assert remainder(3, 3) == 0 assert remainder(5, 2) == 1 assert remainder(7, 5) == 2 print("Exercise 37 is correct.") # Exercise 38 # Write a function definition named sum_of_squares that takes in two numbers, squares each number, then returns the sum of both squares. def sum_of_squares(x,y): return (x ** 2) + (y ** 2) assert sum_of_squares(3, 2) == 13 assert sum_of_squares(5, 2) == 29 assert sum_of_squares(2, 4) == 20 print("Exercise 38 is correct.") # Exercise 39 # Write a function definition named times_two_plus_three that takes in a number, multiplies it by two, adds 3 and returns the result. def times_two_plus_three(x): return x * 2 + 3 assert times_two_plus_three(0) == 3 assert times_two_plus_three(1) == 5 assert times_two_plus_three(2) == 7 assert times_two_plus_three(3) == 9 assert times_two_plus_three(5) == 13 print("Exercise 39 is correct.") # Exercise 40 # Write a function definition named area_of_rectangle that takes in two numbers and returns the product. def area_of_rectangle(x,y): return x * y assert area_of_rectangle(1, 3) == 3 assert area_of_rectangle(5, 2) == 10 assert area_of_rectangle(2, 7) == 14 assert area_of_rectangle(5.3, 10.3) == 54.59 print("Exercise 40 is correct.") import math # Exercise 41 # Write a function definition named area_of_circle that takes in a number representing a circle's radius and returns the area of the circl def area_of_circle(radius): return math.pi * radius ** 2 assert area_of_circle(3) == 28.274333882308138 assert area_of_circle(5) == 78.53981633974483 assert area_of_circle(7) == 153.93804002589985 print("Exercise 41 is correct.") import math # Exercise 42 # Write a function definition named circumference that takes in a number representing a circle's radius and returns the circumference. def circumference(radius): return math.pi * 2 * radius assert circumference(3) == 18.84955592153876 assert circumference(5) == 31.41592653589793 assert circumference(7) == 43.982297150257104 print("Exercise 42 is correct.")
Exercise 42 is correct.
MIT
101_exercises.ipynb
barbmarques/python-exercises
Functions working with stringsIf you need some guidance working with the next few problems, recommend reading through [this example code](https://gist.github.com/ryanorsinger/f758599c886549e7615ec43488ae514c)
# Exercise 43 # Write a function definition named is_vowel that takes in value and returns True if the value is a, e, i, o, u in upper or lower case. def is_vowel(x): return x.lower() in "aeiou" assert is_vowel("a") == True assert is_vowel("U") == True assert is_vowel("banana") == False assert is_vowel("Q") == False assert is_vowel("y") == False print("Exercise 43 is correct.") # Exercise 44 # Write a function definition named has_vowels that takes in value and returns True if the string contains any vowels. def has_vowels(x): for i in x: if i.lower() in "aeiou": return True else: return False assert has_vowels("banana") == True assert has_vowels("ubuntu") == True assert has_vowels("QQQQ") == False assert has_vowels("wyrd") == False print("Exercise 44 is correct.") # Exercise 45 # Write a function definition named count_vowels that takes in value and returns the count of the number of vowels in a sequence. def count_vowels(letters): count = 0 for i in letters: if i in 'aeiou': count += 1 return count assert count_vowels("banana") == 3 assert count_vowels("ubuntu") == 3 assert count_vowels("mango") == 2 assert count_vowels("QQQQ") == 0 assert count_vowels("wyrd") == 0 print("Exercise 45 is correct.") # Exercise 46 # Write a function definition named remove_vowels that takes in string and returns the string without any vowels def remove_vowels(astring): for x in astring: if x.lower() in 'aeiou': astring = astring.replace(x,'') return astring assert remove_vowels("banana") == "bnn" assert remove_vowels("ubuntu") == "bnt" assert remove_vowels("mango") == "mng" assert remove_vowels("QQQQ") == "QQQQ" print("Exercise 46 is correct.") # Exercise 47 # Write a function definition named starts_with_vowel that takes in string and True if the string starts with a vowel def starts_with_vowel(word): if word[0] in 'aeiou': return True else: return False assert starts_with_vowel("ubuntu") == True assert starts_with_vowel("banana") == False assert starts_with_vowel("mango") == False print("Exercise 47 is correct.") # Exercise 48 # Write a function definition named ends_with_vowel that takes in string and True if the string ends with a vowel def ends_with_vowel(word): if word[-1] in 'aeiou': return True else: return False assert ends_with_vowel("ubuntu") == True assert ends_with_vowel("banana") == True assert ends_with_vowel("mango") == True assert ends_with_vowel("spinach") == False print("Exercise 48 is correct.") # Exercise 49 # Write a function definition named starts_and_ends_with_vowel that takes in string and returns True if the string starts and ends with a vowel def starts_and_ends_with_vowel(word): if word[0] in 'aeiou' and word[-1] in 'aeiou': return True else: return False assert starts_and_ends_with_vowel("ubuntu") == True assert starts_and_ends_with_vowel("banana") == False assert starts_and_ends_with_vowel("mango") == False print("Exercise 49 is correct.")
Exercise 49 is correct.
MIT
101_exercises.ipynb
barbmarques/python-exercises
Accessing List Elements
# Exercise 50 # Write a function definition named first that takes in sequence and returns the first value of that sequence. def first(x): return x[0] assert first("ubuntu") == "u" assert first([1, 2, 3]) == 1 assert first(["python", "is", "awesome"]) == "python" print("Exercise 50 is correct.") # Exercise 51 # Write a function definition named second that takes in sequence and returns the second value of that sequence. def second(x): return x[1] assert second("ubuntu") == "b" assert second([1, 2, 3]) == 2 assert second(["python", "is", "awesome"]) == "is" print("Exercise 51 is correct.") # Exercise 52 # Write a function definition named third that takes in sequence and returns the third value of that sequence. def third(x): return x[2] assert third("ubuntu") == "u" assert third([1, 2, 3]) == 3 assert third(["python", "is", "awesome"]) == "awesome" print("Exercise 52 is correct.") # Exercise 53 # Write a function definition named forth that takes in sequence and returns the forth value of that sequence. def forth(x): return x[3] assert forth("ubuntu") == "n" assert forth([1, 2, 3, 4]) == 4 assert forth(["python", "is", "awesome", "right?"]) == "right?" print("Exercise 53 is correct.") # Exercise 54 # Write a function definition named last that takes in sequence and returns the last value of that sequence. def last(x): return x[-1] assert last("ubuntu") == "u" assert last([1, 2, 3, 4]) == 4 assert last(["python", "is", "awesome"]) == "awesome" assert last(["kiwi", "mango", "guava"]) == "guava" print("Exercise 54 is correct.") # Exercise 55 # Write a function definition named second_to_last that takes in sequence and returns the second to last value of that sequence. def second_to_last(x): return x[-2] assert second_to_last("ubuntu") == "t" assert second_to_last([1, 2, 3, 4]) == 3 assert second_to_last(["python", "is", "awesome"]) == "is" assert second_to_last(["kiwi", "mango", "guava"]) == "mango" print("Exercise 55 is correct.") # Exercise 56 # Write a function definition named third_to_last that takes in sequence and returns the third to last value of that sequence. def third_to_last(x): return x[-3] assert third_to_last("ubuntu") == "n" assert third_to_last([1, 2, 3, 4]) == 2 assert third_to_last(["python", "is", "awesome"]) == "python" assert third_to_last(["strawberry", "kiwi", "mango", "guava"]) == "kiwi" print("Exercise 56 is correct.") # Exercise 57 # Write a function definition named first_and_second that takes in sequence and returns the first and second value of that sequence as a list def first_and_second(x): return x[:2] assert first_and_second([1, 2, 3, 4]) == [1, 2] assert first_and_second(["python", "is", "awesome"]) == ["python", "is"] assert first_and_second(["strawberry", "kiwi", "mango", "guava"]) == ["strawberry", "kiwi"] print("Exercise 57 is correct.") # Exercise 58 # Write a function definition named first_and_last that takes in sequence and returns the first and last value of that sequence as a list def first_and_last(x): return [x[0], x[-1]] assert first_and_last([1, 2, 3, 4]) == [1, 4] assert first_and_last(["python", "is", "awesome"]) == ["python", "awesome"] assert first_and_last(["strawberry", "kiwi", "mango", "guava"]) == ["strawberry", "guava"] print("Exercise 58 is correct.") # Exercise 59 # Write a function definition named first_to_last that takes in sequence and returns the sequence with the first value moved to the end of the sequence. def first_to_last(b): x = b[0] b.append(x) b.pop(0) return b assert first_to_last([1, 2, 3, 4]) == [2, 3, 4, 1] assert first_to_last(["python", "is", "awesome"]) == ["is", "awesome", "python"] assert first_to_last(["strawberry", "kiwi", "mango", "guava"]) == ["kiwi", "mango", "guava", "strawberry"] print("Exercise 59 is correct.")
Exercise 59 is correct.
MIT
101_exercises.ipynb
barbmarques/python-exercises
Functions to describe data
# Exercise 60 # Write a function definition named sum_all that takes in sequence of numbers and returns all the numbers added together. def sum_all(numbers): return sum(numbers) assert sum_all([1, 2, 3, 4]) == 10 assert sum_all([3, 3, 3]) == 9 assert sum_all([0, 5, 6]) == 11 print("Exercise 60 is correct.") # Exercise 61 # Write a function definition named mean that takes in sequence of numbers and returns the average value import numpy as np def mean(x): return np.mean(x) assert mean([1, 2, 3, 4]) == 2.5 assert mean([3, 3, 3]) == 3 assert mean([1, 5, 6]) == 4 print("Exercise 61 is correct.") # Exercise 62 # Write a function definition named median that takes in sequence of numbers and returns the average value def median(x): return np.median(x) assert median([1, 2, 3, 4, 5]) == 3.0 assert median([1, 2, 3]) == 2.0 assert median([1, 5, 6]) == 5.0 assert median([1, 2, 5, 6]) == 3.5 print("Exercise 62 is correct.") # Exercise 63 # Write a function definition named mode that takes in sequence of numbers and returns the most commonly occuring value import statistics as stat def mode(x): return stat.mode(x) assert mode([1, 2, 2, 3, 4]) == 2 assert mode([1, 1, 2, 3]) == 1 assert mode([2, 2, 3, 3, 3]) == 3 print("Exercise 63 is correct.") # Exercise 64 # Write a function definition named product_of_all that takes in sequence of numbers and returns the product of multiplying all the numbers together def product_of_all(x): return np.prod(x) assert product_of_all([1, 2, 3]) == 6 assert product_of_all([3, 4, 5]) == 60 assert product_of_all([2, 2, 3, 0]) == 0 print("Exercise 64 is correct.")
Exercise 64 is correct.
MIT
101_exercises.ipynb
barbmarques/python-exercises
Applying functions to lists
# Run this cell in order to use the following list of numbers for the next exercises numbers = [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5] # Exercise 65 # Write a function definition named get_highest_number that takes in sequence of numbers and returns the largest number. def get_highest_number(x): return max(x) assert get_highest_number([1, 2, 3]) == 3 assert get_highest_number([12, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5]) == 12 assert get_highest_number([-5, -3, 1]) == 1 print("Exercise 65 is correct.") # Exercise 66 # Write a function definition named get_smallest_number that takes in sequence of numbers and returns the smallest number. def get_smallest_number(x): return min(x) assert get_smallest_number([1, 3, 2]) == 1 assert get_smallest_number([5, -5, -4, -3, -2, -1, 1, 2, 3, 4]) == -5 assert get_smallest_number([-4, -3, 1, -10]) == -10 print("Exercise 66 is correct.") # Exercise 67 # Write a function definition named only_odd_numbers that takes in sequence of numbers and returns the odd numbers in a list. def only_odd_numbers(num_list): return [x for x in num_list if x % 2 != 0] assert only_odd_numbers([1, 2, 3]) == [1, 3] assert only_odd_numbers([-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]) == [-5, -3, -1, 1, 3, 5] assert only_odd_numbers([-4, -3, 1]) == [-3, 1] print("Exercise 67 is correct.") # Exercise 68 # Write a function definition named only_even_numbers that takes in sequence of numbers and returns the even numbers in a list. def only_even_numbers(num_list): return [x for x in num_list if x % 2 == 0] assert only_even_numbers([1, 2, 3]) == [2] assert only_even_numbers([-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]) == [-4, -2, 2, 4] assert only_even_numbers([-4, -3, 1]) == [-4] print("Exercise 68 is correct.") # Exercise 69 # Write a function definition named only_positive_numbers that takes in sequence of numbers and returns the positive numbers in a list. def only_positive_numbers(num_list): return [x for x in num_list if x > 0] assert only_positive_numbers([1, 2, 3]) == [1, 2, 3] assert only_positive_numbers([-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] assert only_positive_numbers([-4, -3, 1]) == [1] print("Exercise 69 is correct.") # Exercise 70 # Write a function definition named only_negative_numbers that takes in sequence of numbers and returns the negative numbers in a list. def only_negative_numbers(num_list): return [x for x in num_list if x < 0] assert only_negative_numbers([1, 2, 3]) == [] assert only_negative_numbers([-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]) == [-5, -4, -3, -2, -1] assert only_negative_numbers([-4, -3, 1]) == [-4, -3] print("Exercise 70 is correct.") # Exercise 71 # Write a function definition named has_evens that takes in sequence of numbers and returns True if there are any even numbers in the sequence def has_evens(num_list): for x in num_list: if x % 2 == 0: return True break return False assert has_evens([1, 2, 3]) == True assert has_evens([2, 5, 6]) == True assert has_evens([3, 3, 3]) == False assert has_evens([]) == False print("Exercise 71 is correct.") # Exercise 72 # Write a function definition named count_evens that takes in sequence of numbers and returns the number of even numbers def count_evens(num_list): return(len([x for x in num_list if x % 2 == 0])) assert count_evens([1, 2, 3]) == 1 assert count_evens([2, 5, 6]) == 2 assert count_evens([3, 3, 3]) == 0 assert count_evens([5, 6, 7, 8] ) == 2 print("Exercise 72 is correct.") # Exercise 73 # Write a function definition named has_odds that takes in sequence of numbers and returns True if there are any odd numbers in the sequence def has_odds(num_list): for x in num_list: if x % 2 != 0: return True break return False assert has_odds([1, 2, 3]) == True assert has_odds([2, 5, 6]) == True assert has_odds([3, 3, 3]) == True assert has_odds([2, 4, 6]) == False print("Exercise 73 is correct.") # Exercise 74 # Write a function definition named count_odds that takes in sequence of numbers and returns True if there are any odd numbers in the sequence def count_odds(num_list): return(len([x for x in num_list if x % 2 != 0])) assert count_odds([1, 2, 3]) == 2 assert count_odds([2, 5, 6]) == 1 assert count_odds([3, 3, 3]) == 3 assert count_odds([2, 4, 6]) == 0 print("Exercise 74 is correct.") # Exercise 75 # Write a function definition named count_negatives that takes in sequence of numbers and returns a count of the number of negative numbers def count_negatives(num_list): return(len([x for x in num_list if x < 0])) assert count_negatives([1, -2, 3]) == 1 assert count_negatives([2, -5, -6]) == 2 assert count_negatives([3, 3, 3]) == 0 print("Exercise 75 is correct.") # Exercise 76 # Write a function definition named count_positives that takes in sequence of numbers and returns a count of the number of positive numbers def count_positives(num_list): return(len([x for x in num_list if x > 0])) assert count_positives([1, -2, 3]) == 2 assert count_positives([2, -5, -6]) == 1 assert count_positives([3, 3, 3]) == 3 assert count_positives([-2, -1, -5]) == 0 print("Exercise 76 is correct.") # Exercise 77 # Write a function definition named only_positive_evens that takes in sequence of numbers and returns a list containing all the positive evens from the sequence def only_positive_evens(num_list): return [x for x in num_list if x > 0 and x % 2 == 0] assert only_positive_evens([1, -2, 3]) == [] assert only_positive_evens([2, -5, -6]) == [2] assert only_positive_evens([3, 3, 4, 6]) == [4, 6] assert only_positive_evens([2, 3, 4, -1, -5]) == [2, 4] print("Exercise 77 is correct.") # Exercise 78 # Write a function definition named only_positive_odds that takes in sequence of numbers and returns a list containing all the positive odd numbers from the sequence def only_positive_odds(num_list): return [x for x in num_list if x > 0 and x % 2 != 0] assert only_positive_odds([1, -2, 3]) == [1, 3] assert only_positive_odds([2, -5, -6]) == [] assert only_positive_odds([3, 3, 4, 6]) == [3, 3] assert only_positive_odds([2, 3, 4, -1, -5]) == [3] print("Exercise 78 is correct.") # Exercise 79 # Write a function definition named only_negative_evens that takes in sequence of numbers and returns a list containing all the negative even numbers from the sequence def only_negative_evens(num_list): return [x for x in num_list if x < 0 and x % 2 == 0] assert only_negative_evens([1, -2, 3]) == [-2] assert only_negative_evens([2, -5, -6]) == [-6] assert only_negative_evens([3, 3, 4, 6]) == [] assert only_negative_evens([-2, 3, 4, -1, -4]) == [-2, -4] print("Exercise 79 is correct.") # Exercise 80 # Write a function definition named only_negative_odds that takes in sequence of numbers and returns a list containing all the negative odd numbers from the sequence def only_negative_odds(num_list): return [x for x in num_list if x < 0 and x % 2 != 0] assert only_negative_odds([1, -2, 3]) == [] assert only_negative_odds([2, -5, -6]) == [-5] assert only_negative_odds([3, 3, 4, 6]) == [] assert only_negative_odds([2, -3, 4, -1, -4]) == [-3, -1] print("Exercise 80 is correct.") # Exercise 81 # Write a function definition named shortest_string that takes in a list of strings and returns the shortest string in the list. def shortest_string(my_list): return(min((word for word in my_list), key=len)) assert shortest_string(["kiwi", "mango", "strawberry"]) == "kiwi" assert shortest_string(["hello", "everybody"]) == "hello" assert shortest_string(["mary", "had", "a", "little", "lamb"]) == "a" print("Exercise 81 is correct.") # Exercise 82 # Write a function definition named longest_string that takes in sequence of strings and returns the longest string in the list. def longest_string(my_list): return(max((word for word in my_list), key=len)) assert longest_string(["kiwi", "mango", "strawberry"]) == "strawberry" assert longest_string(["hello", "everybody"]) == "everybody" assert longest_string(["mary", "had", "a", "little", "lamb"]) == "little" print("Exercise 82 is correct.")
Exercise 82 is correct.
MIT
101_exercises.ipynb
barbmarques/python-exercises
Working with sets**Hint** Take a look at the `set` function in Python, the `set` data type, and built-in `set` methods.
# Example set function usage print(set("kiwi")) print(set([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])) # Exercise 83 # Write a function definition named get_unique_values that takes in a list and returns a set with only the unique values from that list. def get_unique_values(x): return set(x) assert get_unique_values(["ant", "ant", "mosquito", "mosquito", "ladybug"]) == {"ant", "mosquito", "ladybug"} assert get_unique_values(["b", "a", "n", "a", "n", "a", "s"]) == {"b", "a", "n", "s"} assert get_unique_values(["mary", "had", "a", "little", "lamb", "little", "lamb", "little", "lamb"]) == {"mary", "had", "a", "little", "lamb"} print("Exercise 83 is correct.") # Exercise 84 # Write a function definition named get_unique_values_from_two_lists that takes two lists and returns a single set with only the unique values def get_unique_values_from_two_lists(x,y): return set(x).union(set(y)) assert get_unique_values_from_two_lists([5, 1, 2, 3], [3, 4, 5, 5]) == {1, 2, 3, 4, 5} assert get_unique_values_from_two_lists([1, 1], [2, 2, 3]) == {1, 2, 3} assert get_unique_values_from_two_lists(["tomato", "mango", "kiwi"], ["eggplant", "tomato", "broccoli"]) == {"tomato", "mango", "kiwi", "eggplant", "broccoli"} print("Exercise 84 is correct.") # Exercise 85 # Write a function definition named get_values_in_common that takes two lists and returns a single set with the values that each list has in common def get_values_in_common(x,y): return set(x).intersection(set(y)) assert get_values_in_common([5, 1, 2, 3], [3, 4, 5, 5]) == {3, 5} assert get_values_in_common([1, 2], [2, 2, 3]) == {2} assert get_values_in_common(["tomato", "mango", "kiwi"], ["eggplant", "tomato", "broccoli"]) == {"tomato"} print("Exercise 85 is correct.") # Exercise 86 # Write a function definition named get_values_not_in_common that takes two lists and returns a single set with the values that each list does not have in common def get_values_not_in_common(x,y): return (set(x)-set(y)).union(set(y)-set(x)) assert get_values_not_in_common([5, 1, 2, 3], [3, 4, 5, 5]) == {1, 2, 4} assert get_values_not_in_common([1, 1], [2, 2, 3]) == {1, 2, 3} assert get_values_not_in_common(["tomato", "mango", "kiwi"], ["eggplant", "tomato", "broccoli"]) == {"mango", "kiwi", "eggplant", "broccoli"} print("Exercise 86 is correct.")
Exercise 86 is correct.
MIT
101_exercises.ipynb
barbmarques/python-exercises
Working with Dictionaries
# Run this cell in order to have these two dictionary variables defined. tukey_paper = { "title": "The Future of Data Analysis", "author": "John W. Tukey", "link": "https://projecteuclid.org/euclid.aoms/1177704711", "year_published": 1962 } thomas_paper = { "title": "A mathematical model of glutathione metabolism", "author": "Rachel Thomas", "link": "https://www.ncbi.nlm.nih.gov/pubmed/18442411", "year_published": 2008 } # Exercise 87 # Write a function named get_paper_title that takes in a dictionary and returns the title property def get_paper_title(my_dictionary): return my_dictionary.get("title") assert get_paper_title(tukey_paper) == "The Future of Data Analysis" assert get_paper_title(thomas_paper) == "A mathematical model of glutathione metabolism" print("Exercise 87 is correct.") # Exercise 88 # Write a function named get_year_published that takes in a dictionary and returns the value behind the "year_published" key. def get_year_published(my_dictionary): return my_dictionary.get("year_published") assert get_year_published(tukey_paper) == 1962 assert get_year_published(thomas_paper) == 2008 print("Exercise 88 is correct.") # Run this code to create data for the next two questions book = { "title": "Genetic Algorithms and Machine Learning for Programmers", "price": 36.99, "author": "Frances Buontempo" } # Exercise 89 # Write a function named get_price that takes in a dictionary and returns the price def get_price(x): return x.get("price") assert get_price(book) == 36.99 print("Exercise 89 is complete.") # Exercise 90 # Write a function named get_book_author that takes in a dictionary (the above declared book variable) and returns the author's name def get_book_author(x): return x.get("author") assert get_book_author(book) == "Frances Buontempo" print("Exercise 90 is complete.")
Exercise 90 is complete.
MIT
101_exercises.ipynb
barbmarques/python-exercises
Working with Lists of Dictionaries**Hint** If you need an example of lists of dictionaries, see [https://gist.github.com/ryanorsinger/fce8154028a924c1073eac24c7c3f409](https://gist.github.com/ryanorsinger/fce8154028a924c1073eac24c7c3f409)
# Run this cell in order to have some setup data for the next exercises books = [ { "title": "Genetic Algorithms and Machine Learning for Programmers", "price": 36.99, "author": "Frances Buontempo" }, { "title": "The Visual Display of Quantitative Information", "price": 38.00, "author": "Edward Tufte" }, { "title": "Practical Object-Oriented Design", "author": "Sandi Metz", "price": 30.47 }, { "title": "Weapons of Math Destruction", "author": "Cathy O'Neil", "price": 17.44 } ] # Exercise 91 # Write a function named get_number_of_books that takes in a list of objects and returns the number of dictionaries in that list. def get_number_of_books(x): return len(x) assert get_number_of_books(books) == 4 print("Exercise 91 is complete.") # Exercise 92 # Write a function named total_of_book_prices that takes in a list of dictionaries and returns the sum total of all the book prices added together def total_of_book_prices(mylist): return sum(x["price"] for x in books) assert total_of_book_prices(books) == 122.9 print("Exercise 92 is complete.") # Exercise 93 # Write a function named get_average_book_price that takes in a list of dictionaries and returns the average book price. import numpy as np def get_average_book_price(x): return np.mean([i["price"] for i in books]) assert get_average_book_price(books) == 30.725 print("Exercise 93 is complete.") # Exercise 94 # Write a function called highest_price_book that takes in the above defined list of dictionaries "books" and returns the dictionary containing the title, price, and author of the book with the highest priced book. # Hint: Much like sometimes start functions with a variable set to zero, you may want to create a dictionary with the price set to zero to compare to each dictionary's price in the list def highest_price_book(x): return dict(max(books, key = "price")) # def myfunc(somedict): # x = list(somedict.values()) # for i in x: # data = dict_from_otherfunc(i) # mylist = [float(max(data.values()))] # mydict = dict(zip([i], mylist)) # return mydict assert highest_price_book(books) == { "title": "The Visual Display of Quantitative Information", "price": 38.00, "author": "Edward Tufte"} print("Exercise 94 is complete") # Exercise 95 # Write a function called lowest_priced_book that takes in the above defined list of dictionaries "books" and returns the dictionary containing the title, price, and author of the book with the lowest priced book. # Hint: Much like sometimes start functions with a variable set to zero or float('inf'), you may want to create a dictionary with the price set to float('inf') to compare to each dictionary in the list assert lowest_price_book(books) == { "title": "Weapons of Math Destruction", "author": "Cathy O'Neil", "price": 17.44 } print("Exercise 95 is complete.") shopping_cart = { "tax": .08, "items": [ { "title": "orange juice", "price": 3.99, "quantity": 1 }, { "title": "rice", "price": 1.99, "quantity": 3 }, { "title": "beans", "price": 0.99, "quantity": 3 }, { "title": "chili sauce", "price": 2.99, "quantity": 1 }, { "title": "chocolate", "price": 0.75, "quantity": 9 } ] } # Exercise 96 # Write a function named get_tax_rate that takes in the above shopping cart as input and returns the tax rate. # Hint: How do you access a key's value on a dictionary? The tax rate is one key of the entire shopping_cart dictionary. def get_tax_rate(x): return shopping_cart.get("tax") assert get_tax_rate(shopping_cart) == .08 print("Exercise 96 is complete") # Exercise 97 # Write a function named number_of_item_types that takes in the shopping cart as input and returns the number of unique item types in the shopping cart. # We're not yet using the quantity of each item, but rather focusing on determining how many different types of items are in the cart. def number_of_item_types(x): return len('items') assert number_of_item_types(shopping_cart) == 5 print("Exercise 97 is complete.") # Exercise 98 # Write a function named total_number_of_items that takes in the shopping cart as input and returns the total number all item quantities. # This should return the sum of all of the quantities from each item type def total_number_of_items(s): return sum("quantity"() for x in s) assert total_number_of_items(shopping_cart) == 17 print("Exercise 98 is complete.") # Exercise 99 # Write a function named get_average_item_price that takes in the shopping cart as an input and returns the average of all the item prices. # Hint - This should determine the total price divided by the number of types of items. This does not account for each item type's quantity. assert get_average_item_price(shopping_cart) == 2.1420000000000003 print("Exercise 99 is complete.") # Exercise 100 # Write a function named get_average_spent_per_item that takes in the shopping cart and returns the average of summing each item's quanties times that item's price. # Hint: You may need to set an initial total price and total total quantity to zero, then sum up and divide that total price by the total quantity assert get_average_spent_per_item(shopping_cart) == 1.333529411764706 print("Exercise 100 is complete.") # Exercise 101 # Write a function named most_spent_on_item that takes in the shopping cart as input and returns the dictionary associated with the item that has the highest price*quantity. # Be sure to do this as programmatically as possible. # Hint: Similarly to how we sometimes begin a function with setting a variable to zero, we need a starting place: # Hint: Consider creating a variable that is a dictionary with the keys "price" and "quantity" both set to 0. You can then compare each item's price and quantity total to the one from "most" assert most_spent_on_item(shopping_cart) == { "title": "chocolate", "price": 0.75, "quantity": 9 } print("Exercise 101 is complete.")
_____no_output_____
MIT
101_exercises.ipynb
barbmarques/python-exercises
Data Analysis for Inverse Observation Data Assimilation of Kolmogorov FlowThis notebook analyzes the paper's data and reproduces the plots.
import os os.environ["CUDA_VISIBLE_DEVICES"]="0" # system integration faster on GPU import warnings warnings.filterwarnings('ignore') from functools import partial import numpy as np import scipy import jax import jax.numpy as jnp from jax import random, jit import argparse from datetime import datetime import xarray as xr import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from cycler import cycler %matplotlib inline from dynamical_system import KolmogorovFlow from util import jnp_to_aa_tuple, aa_tuple_to_jnp from jax_cfd.data import xarray_utils as xru from util import jnp_to_aa_tuple, aa_tuple_to_jnp from analysis_util import ( compute_vorticity, integrate_kolmogorov_xr, compute_l1_error_kolmogorov, adjust_row_labels, plot_colors, load_da_results, ) # create figure directory ! mkdir -p figures
_____no_output_____
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Copy data from Google cloudThis requires [gsutil](https://cloud.google.com/storage/docs/gsutil).
!gsutil cp -r gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/ /tmp
Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/kolmogorov_baselineinit_hybridopt.nc... Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/kolmogorov_baselineinit_obsopt.nc... Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/kolmogorov_invobsinit_hybridopt.nc... Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/kolmogorov_invobsinit_obsopt.nc... - [4 files][ 43.7 MiB/ 43.7 MiB] ==> NOTE: You are performing a sequence of gsutil operations that may run significantly faster if you instead use gsutil -m cp ... Please see the -m section under "gsutil help options" for further information about when gsutil -m can be advantageous. Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/lorenz96_baselineinit_hybridopt.nc... Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/lorenz96_baselineinit_obsopt.nc... Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/lorenz96_invobsinit_hybridopt.nc... Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/lorenz96_invobsinit_obsopt.nc... | [8 files][ 47.0 MiB/ 47.0 MiB] Operation completed over 8 objects/47.0 MiB.
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Load data
path = '/tmp/invobs-da-results' filenames = [ 'kolmogorov_baselineinit_obsopt.nc', 'kolmogorov_baselineinit_hybridopt.nc', 'kolmogorov_invobsinit_obsopt.nc', 'kolmogorov_invobsinit_hybridopt.nc', ] retained_variables = [ 'f_vals', 'eval_vals', 'X0_ground_truth', 'X0_opt', 'X0_init', ] retained_attrs = [ 'observe_every', 'grid_size', 'num_time_steps', 'num_warmup_steps', 'num_inner_steps', 'viscosity', 'peak_wavenumber', 'offset_x', 'offset_y', ] full_filenames = [os.path.join(path, filename) for filename in filenames] ds = load_da_results(full_filenames, retained_variables, retained_attrs)
_____no_output_____
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Instantiate dynamical system
kolmogorov_flow = KolmogorovFlow( grid_size=ds.attrs['grid_size'], num_inner_steps=ds.attrs['num_inner_steps'], viscosity=ds.attrs['viscosity'], observe_every=ds.attrs['observe_every'], wavenumber=ds.attrs['peak_wavenumber'], )
_____no_output_____
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Data assimilation initialization samplesComparison of initialization schemes.
da_init = xr.concat( [ ds['X0_init'].sel(init=['invobs', 'baseline']), ds['X0_ground_truth'].sel(init='baseline'), ], dim='init', ) \ .assign_coords(init=['invobs', 'baseline', 'ground_truth']) \ .sel(opt_space='observation') vort_init = compute_vorticity(da_init, kolmogorov_flow.grid) # create subsampled ground truth vort_gt_subsampled_jnp = jax.vmap(jnp.kron, in_axes=(0, None))( vort_init.sel(init='ground_truth').data[...,::16,::16], jnp.ones((16,16)), ) vort_gt_subsampled = vort_init.sel(init='ground_truth').copy() vort_gt_subsampled.data = np.asarray(vort_gt_subsampled_jnp) vort_gt_subsampled = vort_gt_subsampled.assign_coords(init='ground_truth_sub') vort = xr.concat([vort_gt_subsampled, vort_init], dim='init') vort = vort.rename({'init': 'data_type'}) sns.set(font_scale=2.4) plt.rc('font', **{'family': 'Times New Roman'}) g = vort.sel( n=3, data_type=['ground_truth', 'ground_truth_sub', 'baseline', 'invobs'], ) \ .plot.imshow( x='x', y='y', col='data_type', col_wrap=2, size=5, add_colorbar=False, cmap=sns.cm.icefire, vmin=-8, vmax=8, ) col_labels = [ 'ground truth', 'observed ground truth', 'interpolation init', 'inverse init', ] [ax.set_title(t) for ax, t in zip(g.axes.ravel(), col_labels)] g.set_axis_labels('', '') [ax.set_aspect('equal') for ax in g.axes.ravel()] [ax.set_yticks([]) for ax in g.axes.ravel()] [ax.set_xticks([]) for ax in g.axes.ravel()] plt.subplots_adjust(wspace=-0.2) # plot subsamling grid sub_grid_points = np.linspace(0, 2*np.pi, num=4) one_pixel_size = 2*np.pi / 64 sub_grid_points[0] += one_pixel_size sub_grid_points[-1] -= one_pixel_size g.axes.ravel()[0].plot( np.repeat(sub_grid_points, 4), np.tile(sub_grid_points, 4), 's', color=plot_colors['y'], markersize=8, markeredgecolor='k', ) plt.savefig( 'figures/da_init_kolmogorov.pdf', bbox_inches='tight', pad_inches=0.1, )
_____no_output_____
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Optimization curvesPlot value of observation space objective function during optimization normalized by the first-step value of the observation space objective function.
sns.set(font_scale=1.5) sns.set_style('white') to_plot = ds['eval_vals'].sel(n=[6, 9]) to_plot_relative_mean = ( to_plot / to_plot.sel(opt_step=0, opt_space='observation') ) to_plot_relative_mean = to_plot_relative_mean.sel( init=['invobs', 'baseline'], opt_space=['hybrid', 'observation'], ) df_opt_curves = ( to_plot_relative_mean .to_dataframe('observation objective') .reset_index() ) sns.set(font_scale=2.5) sns.set_style('ticks') plt.rc( 'axes', prop_cycle=(cycler('color', [plot_colors['r'], plot_colors['b']])), ) plt.rc('font', **{'family': 'Times New Roman'}) g = sns.relplot( data=df_opt_curves, x='opt_step', y='observation objective', col='init', row='n', hue='opt_space', style='opt_space', kind='line', lw=4, legend=True, height=5.8, ) sns.despine() g.set(yscale='log', xlabel='optimization step') g.set_titles('') g.axes[0,0].set_title('inverse init') g.axes[0,1].set_title('interpolation init') g._margin_titles = True [ax.axvline(x=100, color='k', ls='--') for ax in g.axes.flat] # place legend in first facet plot g.axes[0,0].legend(frameon=False, labels=['hybrid opt', 'observation opt']) g._legend.remove() plt.savefig( 'figures/opt_curves_kolmogorov.pdf', bbox_inches='tight', pad_inches=0.1, )
_____no_output_____
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Forecast quality
X0_da = ds[['X0_ground_truth', 'X0_init', 'X0_opt']].to_array('data_type') \ .assign_coords({'data_type': ['gt', 'init', 'opt']}) X_da = integrate_kolmogorov_xr(kolmogorov_flow, X0_da, 20) vorticity = compute_vorticity(X_da, kolmogorov_flow.grid) relative_scale = 14533 # average L1 norm over independent samples l1_error = compute_l1_error_kolmogorov(vorticity, 'gt', scale=relative_scale) delta_t = ds.attrs['num_inner_steps'] * kolmogorov_flow.dt l1_error_stacked = ( l1_error .mean(dim='n') .sel(data_type='opt', drop=True) .assign_coords( { 't': delta_t * np.arange(l1_error.sizes['t']), 'init': [s.split('_')[0] for s in l1_error.init.values], }, ) .stack(opt_method=['init', 'opt_space']) ) tuple_labels = l1_error_stacked.opt_method.values concat_labels = [ a + ' init' + ' / ' + b + ' opt' for a,b in tuple_labels] l1_error_stacked = l1_error_stacked.assign_coords({'opt_method': concat_labels}) # select to have a custom sort of the optimization methods l1_error_stacked = l1_error_stacked.sel( opt_method=[ 'invobs init / observation opt', 'invobs init / hybrid opt', 'baseline init / observation opt', 'baseline init / hybrid opt', ] ) plt.figure(figsize=(10, 7.5)) sns.set(font_scale=2.2) sns.set_style('ticks') plt.rc('font', **{'family': 'Times New Roman'}) plt.rc( 'axes', prop_cycle=( cycler( 'color', [plot_colors['r']]*2 + [plot_colors['b']]*2, ) + cycler( 'linestyle', ['-', 'dotted']*2, ) + cycler( 'marker', ['o', 'o', 'v', 'v'], ) ), ) time_steps = l1_error_stacked.coords['t'].values ax = plt.subplot(1,1,1) for opt_method in l1_error_stacked.opt_method.values: ax.plot( time_steps, l1_error_stacked.sel(opt_method=opt_method).values, markersize=13, markeredgecolor='white', lw=4, label=opt_method, ) sns.despine() plt.xlabel('time') plt.ylabel('mean relative $L_1$ error') plt.ylim(0, 1.1) plt.axvline(x=9.5 * delta_t, ymax=0.6, color='k', ls='--') plt.title('') handles, labels = ax.get_legend_handles_labels() line_ordering = [2, 3, 1, 0] # legend ordering according to appearance in plot reordered_handles = [handles[i] for i in line_ordering] reordered_labels = [labels[i] for i in line_ordering] ax.legend(reordered_handles, reordered_labels, frameon=False) plt.savefig( 'figures/da_kolmogorov_invobs.pdf', bbox_inches='tight', pad_inches=0.1, )
_____no_output_____
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Summary statsCompare forecast performance on the first forecast state relative to baseline init and optimization method.
summary_stats = l1_error.sel(data_type='opt', t=11).mean(dim='n') / l1_error.sel(data_type='opt', t=11, init='baseline', opt_space='observation').mean(dim='n') print( summary_stats.sel(opt_space='observation', init='baseline').values, summary_stats.sel(opt_space='hybrid', init='baseline').values, summary_stats.sel(opt_space='observation', init='invobs').values, summary_stats.sel(opt_space='hybrid', init='invobs').values, )
1.0 0.8789517 0.19961545 0.22848208
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Significance test between trajectoriesPerform a Z-test to evaluate significance level between optimization methods for the two initialization schemes. Inverse observation initialization
time_step = 11 # beginning of forecast window num_samples = l1_error.sizes['n'] l1_error_inv = l1_error.sel(init='invobs', data_type='opt') diff_l1_error = ( l1_error_inv.sel(opt_space='observation') - l1_error_inv.sel(opt_space='hybrid') ) m = diff_l1_error.sel(t=time_step).mean(dim='n') s = diff_l1_error.sel(t=time_step).std(dim='n') Z = m / (s / np.sqrt(num_samples)) p = scipy.stats.norm.sf(np.abs(Z)) print('Z-value', Z.values) print('p-value', p)
Z-value -5.658017083581407 p-value 7.656594807321588e-09
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Baseline initialization
time_step = 11 # beginning of forecast window num_samples = l1_error.sizes['n'] l1_error_inv = l1_error.sel(init='baseline', data_type='opt') diff_l1_error = ( l1_error_inv.sel(opt_space='observation') - l1_error_inv.sel(opt_space='hybrid') ) m = diff_l1_error.sel(t=time_step).mean(dim='n') s = diff_l1_error.sel(t=time_step).std(dim='n') Z = m / (s / np.sqrt(num_samples)) p = scipy.stats.norm.sf(np.abs(Z)) print('Z-value', Z.values) print('p-value', p)
Z-value 6.508546551414507 p-value 3.7940697809822585e-11
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Assimilated trajectories
gt = vorticity.sel(data_type='gt', opt_space='observation', init='baseline') baseline = vorticity.sel( data_type='opt', opt_space='observation', init='baseline', ) invobs = vorticity.sel(data_type='opt', opt_space='hybrid', init='invobs') forecast_comparison = ( xr.concat([invobs, baseline, gt], dim='da_method') .assign_coords( da_method=['invobs', 'baseline', 'gt'], t=kolmogorov_flow.dt * np.arange(gt.sizes['t']), ) .sel(da_method=['gt', 'invobs', 'baseline']) ) sns.set(font_scale=3) plt.rc('font', **{'family': 'Times New Roman'}) snapshot_selection = np.asarray([0, 10, 18]) g = ( forecast_comparison .isel(n=1, t=snapshot_selection) .plot.imshow( x='x', y='y', row='t', col='da_method', size=5, add_colorbar=False, cmap=sns.cm.icefire, vmin=-8, vmax=8, ) ) col_labels = ['ground truth', 'proposed', 'baseline'] [ax.set_title(t) for ax, t in zip(g.axes.ravel(), col_labels)] row_labels = [ 'initial state, t=0', 'start forecast, t=1.75', 'end forecast, t=3.15', ] adjust_row_labels(g, row_labels) g.set_axis_labels('', '') [ax.set_aspect('equal') for ax in g.axes.ravel()] [ax.set_yticks([]) for ax in g.axes.ravel()] [ax.set_xticks([]) for ax in g.axes.ravel()] plt.subplots_adjust(hspace=-0.3, wspace=0.) plt.tight_layout() # add highlight patches rectangle_coords = [ [ (3.5, 1.8), ], [ (0.1, 4.7), ], ] def generate_rectangle(rx, ry): rectangle = plt.Rectangle( (rx, ry), 1.5, 1.5, lw=4, ec=plot_colors['y'], fill=False, ) return rectangle for row, row_coords in enumerate(rectangle_coords): row += 1 for rx, ry in row_coords: ps = [generate_rectangle(rx, ry) for _ in range(3)] [g.axes[row,i].add_patch(p) for i, p in zip(range(3), ps)] plt.savefig( 'figures/forecast_results_kolmogorov.pdf', bbox_inches='tight', pad_inches=0.1, )
_____no_output_____
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Summary figure
sns.set(font_scale=3) plt.rc('font', **{'family': 'Times New Roman'}) g = forecast_comparison.isel(n=1, t=11) \ .plot.imshow( x='x', y='y', col='da_method', size=5, add_colorbar=False, cmap=sns.cm.icefire, vmin=-8, vmax=8, ) col_labels = ['ground truth', 'proposed', 'baseline'] g.set_titles('') g.set_axis_labels('', '') [ax.set_xlabel(label) for ax, label in zip(g.axes.ravel(), col_labels)] [ax.set_aspect('equal') for ax in g.axes.ravel()] [ax.set_yticks([]) for ax in g.axes.ravel()] [ax.set_xticks([]) for ax in g.axes.ravel()] plt.tight_layout() # add highlight patches rectangle_coords = [ (1.0, 1.0), (1, 4.7), (3.5, 1.8), ] for rx, ry in rectangle_coords: ps = [generate_rectangle(rx, ry) for _ in range(3)] [g.axes[0,i].add_patch(p) for i, p in zip(range(3), ps)] plt.savefig('figures/result_summary.pdf', bbox_inches='tight', pad_inches=0.1)
_____no_output_____
Apache-2.0
Analysis_KolmogorovFlow.ipynb
googleinterns/invobs-data-assimilation
Индивидуальное задание: Изобразить эмблему Бэтмена для его призыва к спасению города от противников бабы Нины Задача: Существуют хейтеры бабы Нины и перед Бэтменом была поставлена задача спасти её от них Решение: V = 1 Бэтмен, p хейтеры = 100 штук P = pV P = 100 * 1 = 100 штук Q = V : P Q = 1 : 100= 0,01 H Ответ: Q = 0,01 H. Именно такой процент сил надо применить Бэтмену,чтобы спасти бабу Нину от хейтеров
%load_ext autoreload %autoreload 2 import jupyter_lesson %matplotlib inline jupyter_lesson.plot_batman() import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt fig, ax = plt.subplots() Path = mpath.Path path_data = [ (Path.MOVETO, (1.58, -2.57)), (Path.CURVE4, (0.35, -1.1)), (Path.CURVE4, (-1.75, 2.0)), (Path.CURVE4, (0.375, 2.0)), (Path.LINETO, (0.85, 1.15)), (Path.CURVE4, (2.2, 3.2)), (Path.CURVE4, (3, 0.05)), (Path.CURVE4, (2.0, -0.5)), (Path.CLOSEPOLY, (1.58, -2.57)), ] codes, verts = zip(*path_data) path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5) ax.add_patch(patch) # plot control points and connecting lines x, y = zip(*path.vertices) line, = ax.plot(x, y, 'go-') ax.grid() ax.axis('equal') plt.show()
_____no_output_____
MIT
ind.ipynb
A1zak/cross6
Definitions of Python:1. Primitive types, basic operations2. Composed types: lists, tuples, dictionaries3. Everything is an object4. Control structures: blocks, branching, loops Primitive typesThe basic types build into Python include:* `int`: variable length integers,* `float`: double precision floating point numbers, * `complex`: composed of two floats for *real* and *imag* part, * `str`: unicode character strings,* `bool`: boolean which can be only True or False* `None`: actually `NoneType` but there is only one, equivalent of *NULL* or *nil* Some examples of each:
##### -1234567890 # an integer 2.0 # a floating point number 6.02e23 # a floating point number with scientific notation complex(1, 5) # a complex True or False # the two possible boolean values 'This is a string' "It's another string" print("""Triple quotes (also with '''), allow strings to break over multiple lines. Alternatively \n is a newline character (\t for tab, \\ is a single backslash)""") print(complex(1, 5))
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Primary operations| Symbol | Task Performed ||----|---|| + | Addition || - | Subtraction || * | Multiplication || / | Floating point division || // | Floor division || % | Modulus or rest || ** or pow(a, b) | Power || abs(a) | absolute value || round(a) | Banker's rounding |Some examples:
#divisions print(3 / 2, 3 // 2) print(3. / 2, 3. // 2) #operation with complex print((5. + 4.0j - 3.5) * 2.1)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Relational Operators | Symbol | Task Performed ||---|---|| == | True if it is equal || != | True if not equal to || < | less than || > | greater than || <= | less than or equal to || >= | greater than or equal to ||&nbsp;|| not | negate a `bool` value || is | True if both are the same || and | True if both are True || or | True if any are are True || ^ | True if one or the other but not both are True ||&nbsp;|| ^ | bitwise xor operator in `int` || & | bitwise and operator in `int` || \| | bitwise or operator in `int` || >> | right shift bitwise operation on `int`|| << | left shift bitwise operation on `int` || | |Note the difference between: * `==` equality test * `=` assignment
# grouping comparison print(1 >= 0.5 and (2 > 3 or 5 % 2 == 1))
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Strings* Basic operations on strings: `+` or `*`* Formating using `%s` or `.format`* Slicing using the [start: stop: step]
s = "a is equal to" a = 5 print(s+str(a)) print(s, a) #/!\ s+a # String muliplied by int works ! "*--*" * 5
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
String formating
# %s will convert anything to an int. %i, %d, %f works like in C or spec. print("a is equal to %s" % a) print("%s %05i" % (s,a)) #new style formating '{2} {1} {2} {0}'.format('a','b','c') '{0:.2} {1:.1%}'.format(0.3698, 9.6/100)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
String access and slicing* Access a single element with `[index]`* Extract a sub part of a string using `[start:stop:step]` → **slicing**.* Works the same on lists, tuples, arrays, ...
letters = "abcdefghijklmnopqrstuvwxyz" print(letters) len(letters) # remind you that python is 0-based indexing print(letters[0], letters[4], letters[25]) #/!\ letters[56] #slicing from beginging letters[0:4] #from the end letters[-5:] # two by two using a stepsize of 2 letters[::2] # inverted using a stepsize of -1: letters[-1::-1] #strings are not mutable ! letters[2] = "d" #ask for help ! help(str)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Useful string methods```pythonmy_str = 'toto'```* `len(my_str)`: returns the length of the string* `my_str.find('to')`, `my_str.index('to')`: returns the starting index. Find returns ``-1`` if not found, index fails.* `my_str.replace(str1, str2)`: replaces `str1` with `str2` in string* `my_str.split()` splits the string in a list of words* `my_str.startswith(sub)`, `my_str.endswith(sub)`: returns `True` if the string `my_str` starts with `sub`-string* `my_str.isalnum()`, `my_str.isalpha()`, `my_str.isdigit()`: returns `True` if the chain is alphanumeric, only letter or only numbers* `my_str.strip()`, `my_str.rstrip()`, `lstrip()`: removes spaces at the extremities of the string (R and L variant for Right/Left)* `my_str.upper()`, `my_str.lower()`, `my_str.swapcase()`: converts to all upper-case, all lowercase, swap case Composed types* Lists* Tuples* Dictionaries ListLists are defined using square brackets `[]` or the `list(iter)` and can contain any type of objects. They are mutable.
print([1, 2, 3]) digits = list(range(10)) print(digits) print(list(letters)) print(digits + list(letters)) #but digits + letters # lists can contain anything a = ['my string', True, 5+7] print(len(a)) a.append(3.141592) print(a, len(a)) list(range(5, 12, 2))
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Useful methods for lists```pythonlst = [1, 2, 3, 'a', 'b', 'c']```* `lst.append(a)`: adds *a* at the end of lst* `lst.insert(idx, a)`: inserts one element at a given index* `lst.index(a)`: finds first index containing a value* `lst.count(a)`: counts the number of occurences of *a* in the list * `lst.pop(idx)`: removes and returns one element by index* `lst.remove(obj)`: removes an element by value* `lst.sort()` and `lst.reverse()`: sorts and reverses the list **in place** (no return value, the original list is changed)**Warning**: this deletes the list: `lst = lst.sort()`
lst = ['eggs', 'sausages'] print(len(lst)) lst.append("spam") print(lst, len(lst)) lst.insert(0, "spam") print(lst) print(lst.index("spam"), lst.index("sausages")) #but: lst.index(5) lst.count("spam") print(lst.pop(), lst.pop(2)) # lists are mutable: print(lst) lst[0] = 1 print(lst) lst.remove("eggs") print(lst) # but not twice: lst.remove("eggs") # and always: help(list)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Tuple* Tuples are defined by the `tuple(iter)` or by a ``,`` separated list in parenthesis ``()`` * Tuples are like lists, but not mutable !
mytuple = ('spam', 'eggs', 5, 3.141592, 'sausages') print(mytuple[0], mytuple[-1]) # /!\ tuples are not mutable mytuple[3] = "ham" # Single element tuple: mind the comma t = 5, print(t)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
List comprehension and generatorsVery *pythonic* and convenient way of creating lists or tuples from an iterator: ` [ f(i) for i in iterable if condition(i) ]`The content of the `[]` is called a *generator*.A *generator* generates elements on demand, which is *fast* and *low-memory usage*. It is the base of the asynchronous programming used in Python3 (out of scope).It is an alternative to functional programming based on `lambda`, `map` & `filter`:* less *pythonic*, harder to read, and not faster* `lambda`, `map` and `filter` are reserved keywords, they should not be used as variable names, especially not **lambda**.
[2*x+1 for x in range(5)] tuple(x**(1/2.) for x in range(5)) (x**(1/2.) for x in range(5)) [x for x in range(10) if x**3 - 15*x**2 + 71*x == 105] print([l.upper() for l in letters])
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Mapping Types: DictionariesDictionaries associate a key to a value using curly braces `{key1: value1, key2:value2}`: * Keys must be *hashable*, i.e. any object that is unmutable, also known as *hash table* in other languages* Dictionaries were not ordered before Python 3.7 (`OrderedDict` are)
help(dict) periodic_table = { "H": 1, "He": 2, "Li": 3, "Be": 4, "B": 5, "C": 6, "N": 7, "O": 8, "F": 9, "Ne": 10, } print(periodic_table) print(periodic_table['He']) print(periodic_table.keys()) print(periodic_table.values()) #search for a key in a dict: 'F' in periodic_table len(periodic_table) print(periodic_table) periodic_table["Z"] # With a fallback value: periodic_table.get("Z", "unknown element") other = periodic_table.copy() k1 = other.pop('Li') print(periodic_table) print(other)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
In Python, everything is object* In Python everything is object (inherits from ``object``)* Names are just labels, references, attached to an object* Memory is freed when the number of references drops to 0- `dir(obj)`: lists the attributes of an object- `help(obj)`: prints the help of the object- `type(obj)`: gets the type of an object- `id(obj)`: gets the memory adress of an object
a = object() print(dir(a)) print(type(True), type(a), id(a)) b = 5 c = 5 print(id(b), id(c), id(b) == id(c), b is c) # == vs `is` a, b = 5, 5.0 print(a == b) print(type(a), type(b)) # int are unique print(a, bin(a), a is 0b0101) print(a == 5.0, a is 5.0) print(1 is None, None is None)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Warning: in Python, everything is object ...
list1 = [3, 2, 1] print("list1=", list1) list2 = list1 list2[1] = 10 print("list2=", list2) # Did you expect ? print("list1= ", list1)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
![a=1](img/Python_memory_1.png "a=1") ![list1](img/Python_memory_2.png "list11") ![list1](img/Python_memory_3.png "list2") ![mutate](img/Python_memory_4.png "Mutate list2") ![a=1](img/Python_memory_5.png "a=1") ![copy](img/Python_memory_6.png "copy")
print("indeed: id(list1)=", id(list1)," and id(list2):", id(list2), "so list2 is list1:", list2 is list1) #How to avoid this: make copies of mutable objects: list1 = [3, 2, 1] print("list1=", list1) list3 = list1 [:] # copy the content ! list3[1] = 10 print("As expected: list3= ", list3) print("And now: list1= ", list1)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
**Warning:** This is very error prone when manipulating **any** mutable objects.
# Generic solution: use the copy module import copy list3 = copy.copy(list1) # same, more explicit print(id(list1) == id(list3))
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Control structures: blocks Code structurePython uses a colon `:` at the end of the line and 4 white-spaces indentationto establish code block structure.Many other programming languages use braces { }, not python. ``` Block 1 ... Header making new block: Block 2 ... Header making new block: Block 3 ... Block 2 (continuation) ... Block 1 continuation ...```- Clearly indicates the beginning of a block.- Coding style is mostly uniform. Use **4 spaces**, never ****.- Code structure is much more readable and clearer. Branching - Condition branchings are made with `if elif else` statements- Can have many ``elif``'s (not recommended)- Can be nested (too much nesting is bad for readability)Example for solving a second order polynomial root:
a = -1 b = 2 c = 1 q2 = b * b - 4.0 * a * c print("Determinant is ", q2) import math if q2 < 0: print("No real solution") elif q2 > 0: x1 = (-b + math.sqrt(q2)) / (2.0 * a) x2 = (-b - math.sqrt(q2)) / (2.0 * a) print("Two solutions %.2f and %.2f" % (x1, x2)) else: x = -b / (2.0 * a) print("One solution: %.2f" % x)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
For loop- iterate over a sequence (list, tuple, char in string, keys in dict, any iterator)- no indexes, uses directly the object in the sequence- when the index is really needed, use `enumerate`- One can use multiple sequences in parallel using `zip`
ingredients = ["spam", "eggs", "ham", "spam", "sausages"] for food in ingredients: print("I like %s" % food) for idx, food in enumerate(ingredients[-1::-1]): print("%s is number %d in my top 5 of foods" % (food, len(ingredients)- idx)) subjects = ["Roses", "Violets", "Sugar"] verbs = ["are", "are", "is"] adjectives = ["red,", "blue,", "sweet."] for s, v, a in zip(subjects, verbs, adjectives): print("%s %s %s" % (s, v, a))
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
While loop- Iterate while a condition is fulfilled- Make sure the condition becomes unfulfilled, else it could result in infinite loops ...
a, b = 175, 3650 stop = False possible_divisor = max(a, b) // 2 while possible_divisor >= 1 and not stop: if a % possible_divisor == 0 and b % possible_divisor == 0: print("Found greatest common divisor: %d" % possible_divisor) stop = True possible_divisor = possible_divisor - 1 while True: print("I will print this forever") # Now you are ready to interrupt the kernel ! #go in the menu and click kernel-> interrput
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Useful commands in loops- `continue`: go directly to the next iteration of the most inner loop- `break`: quit the most inner loop- `pass`: a block cannot be empty; ``pass`` is a command that does nothing- `else`: block executed after the normal exit of the loop.
for i in range(10): if not i % 7 == 0: print("%d is *not* a multiple of 7" % i) continue print("%d is a multiple of 7" % i) n = 112 # divide n by 2 until this does no longer return an integer while True: if n % 2 != 0: print("%d is not a multiple of 2" % n) break print("%d is a multiple of 2" % n) n = n // 2
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
Exercise: Fibonacci series- Fibonacci: - Each element is the sum of the previous two elements - The first two elements are 0 and 1- Calculate all elements in this series up to 1000, put them in a list, then print the list.``[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]``prepend the cell with `%%timeit` to measure the execution time
# One possible solution res = [0, 1] next_el = 1 while next_el < 1000: res.append(next_el) next_el = res[-2] + res[-1] print(res)
_____no_output_____
CC-BY-4.0
python/python/1_Definitions.ipynb
t20100/silx-training
RNNs for Timeseries Analysis Timeseries Bruno Gonçalves www.data4sci.com @bgoncalves, @data4sci
import pandas as pd from pandas.plotting import autocorrelation_plot import numpy as np np.random.seed(123) from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt import watermark %load_ext watermark %matplotlib inline %watermark -n -v -m -p numpy,matplotlib,pandas,sklearn
Wed Sep 25 2019 CPython 3.7.3 IPython 6.2.1 numpy 1.16.2 matplotlib 3.1.0 pandas 0.24.2 sklearn 0.20.3 compiler : Clang 4.0.1 (tags/RELEASE_401/final) system : Darwin release : 18.7.0 machine : x86_64 processor : i386 CPU cores : 8 interpreter: 64bit
MIT
Timeseries.ipynb
k-rajmani2k/RNN
Load the datasetGDP data from the Federal Reserve Bank [website](https://fred.stlouisfed.org/series/GDP)
series = pd.read_csv('data/GDP.csv', header=0, parse_dates=[0], index_col=0) plt.plot(series) plt.xlabel('Date') plt.ylabel('GDP (B$)'); plt.gcf().set_size_inches(11,8) series['GDP'].pct_change().plot() plt.gca().plot([series.index.min(), series.index.max()], [0, 0], 'r-') plt.xlabel('Date') plt.ylabel('GDP QoQ Growth'); plt.gcf().set_size_inches(11,8)
_____no_output_____
MIT
Timeseries.ipynb
k-rajmani2k/RNN
Autocorrelation function
autocorrelation_plot(series, label='DJIA') autocorrelation_plot(series.pct_change().dropna(), ax=plt.gca(), label='DoD') plt.gcf().set_size_inches(11,8) values = series.pct_change().dropna().values.reshape(-1, 1) X = values[:-1] y = values[1:] plt.plot(X.flatten(), y, '*') plt.xlabel('x_t') plt.ylabel('x_t+1') lm = LinearRegression() lm.fit(X, y) y_pred = lm.predict(X)
_____no_output_____
MIT
Timeseries.ipynb
k-rajmani2k/RNN
Fit comparison
plt.plot(series.index[2:], series.values[2:], ) plt.plot(series.index[2:], (1+y_pred).cumprod()*series.values[0]) plt.xlabel('Date') plt.ylabel('GDP (B$)') plt.gcf().set_size_inches(11, 8)
_____no_output_____
MIT
Timeseries.ipynb
k-rajmani2k/RNN
Now without looking into the future
n_points = len(series) train_points = int(2/3*n_points)+1 X_train = X[:train_points] y_train = y[:train_points] X_test = X[train_points:] y_test = y[train_points:] lm.fit(X_train, y_train) y_train_pred = lm.predict(X_train) y_test_pred = lm.predict(X_test) plt.plot(series.index[:train_points], y_train, label='data') plt.plot(series.index[:train_points], y_train_pred, label='fit') plt.plot(series.index[:train_points], y_train_pred*0+y_train_pred[0], label='reference') plt.xlabel('Date') plt.ylabel('DJIA DoD') plt.legend() plt.gcf().set_size_inches(11, 8)
_____no_output_____
MIT
Timeseries.ipynb
k-rajmani2k/RNN
Comparison plot
plt.plot(series.index[:train_points], (1+y_train).cumprod()*series.values[0], label='train') plt.plot(series.index[train_points+2:], (1+y_test).cumprod()*series.values[train_points], label='test') plt.plot(series.index[:train_points], (1+y_train_pred).cumprod()*series.values[0], label='train_pred') plt.plot(series.index[train_points+2:], (1+y_test_pred).cumprod()*series.values[train_points], label='test_pred') plt.xlabel('Date') plt.ylabel('DJIA') plt.legend() plt.gcf().set_size_inches(11,8)
_____no_output_____
MIT
Timeseries.ipynb
k-rajmani2k/RNN
Parallel simulations using mpi4py
import os,sys Nthread = 1 os.environ["OMP_NUM_THREADS"] = str(Nthread) # export OMP_NUM_THREADS=1 os.environ["OPENBLAS_NUM_THREADS"] = str(Nthread) # export OPENBLAS_NUM_THREADS=1 os.environ["MKL_NUM_THREADS"] = str(Nthread) # export MKL_NUM_THREADS=1 os.environ["VECLIB_MAXIMUM_THREADS"] = str(Nthread) # export VECLIB_MAXIMUM_THREADS=1 os.environ["NUMEXPR_NUM_THREADS"] = str(Nthread) # export NUMEXPR_NUM_THREADS=1 from palik_silicon import silicon from Photodetector import * import autograd.numpy as np from autograd import grad import nlopt import numpy as npf from mpi4py import MPI # import use_autograd # use_autograd.use = 1 import rcwa import materials, cons from mpi_nlopt import nlopt_opt,b_filter,f_symmetry from fft_funs import get_conv import pickle comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() def fun_mpi(dof,fun,N): '''mpi parallization for fun(dof,ctrl), ctrl is the numbering of ctrl's frequency calculation N calculations in total returns the sum: sum_{ctrl=1 toN} fun(dof,ctrl) ''' dof = comm.bcast(dof) Nloop = int(np.ceil(1.0*N/size)) # number of calculations for each node val_i=[] g_i=[] val=[] g=[] for i in range(0,Nloop): ctrl = i*size+rank #print(ctrl) if(ctrl < N): color,wvlen, wvlen_index = wavelengths_tuple[ctrl]; funi = lambda dof: fun(dof,wvlen,theta,phi, color, wvlen_index) grad_fun = grad(funi) val = funi(dof) gval = grad_fun(dof) # include indexing for now, in case one is interested val_i.append([ctrl,val]) g_i.append([ctrl,gval]) # gather the solution val_i = comm.gather(val_i) g_i = comm.gather(g_i) # summation if rank == 0: val_i = [x for x in val_i if x] g_i = [x for x in g_i if x] val_i = npf.concatenate(npf.array(val_i)) g_i = npf.concatenate(npf.array(g_i)) # sindex = val_i[:,0].argsort() val = np.sum(val_i[:,1]) g = np.sum(g_i[:,1]) val = comm.bcast(val) g = comm.bcast(g) return val,g
_____no_output_____
MIT
notebooks/parallel_simulations.ipynb
zhaonat/py-maxwell-fd3d
Playing TextWorld generated games with OpenAI GymThis tutorial shows how to play a text-based adventure game **generated by TextWorld** using OpenAI's Gym API. Generate a new TextWorld game
!tw-make custom --world-size 2 --quest-length 3 --nb-objects 10 --output tw_games/game.ulx -f -v --seed 1234
Global seed: 1234 Game generated: tw_games/game.ulx Welcome to another fast paced game of TextWorld! Here is your task for today. First, it would be great if you could try to go east. With that accomplished, take the shoe that's in the attic. With the shoe, place the shoe on the shelf. Alright, thanks!
MIT
notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb
zhaozj89/TextWorld
Register the game with GymIn order to call to `gym.make`, we need to create a valid `env_id` for our game.
import textworld.gym env_id = textworld.gym.register_game('tw_games/game.ulx')
_____no_output_____
MIT
notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb
zhaozj89/TextWorld
Make the gym environmentWith our `env_id` we are ready to use gym to start the new environment.
import gym env = gym.make(env_id)
_____no_output_____
MIT
notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb
zhaozj89/TextWorld
Start the gameLike for other Gym environments, we start a new game by calling the `env.reset` method. It returns the initial observation text string as well as a dictionary for additional informations (more on that later).
obs, infos = env.reset() print(obs)
________ ________ __ __ ________ | \| \| \ | \| \ \$$$$$$$$| $$$$$$$$| $$ | $$ \$$$$$$$$ | $$ | $$__ \$$\/ $$ | $$ | $$ | $$ \ >$$ $$ | $$ | $$ | $$$$$ / $$$$\ | $$ | $$ | $$_____ | $$ \$$\ | $$ | $$ | $$ \| $$ | $$ | $$ \$$ \$$$$$$$$ \$$ \$$ \$$ __ __ ______ _______ __ _______ | \ _ | \ / \ | \ | \ | \ | $$ / \ | $$| $$$$$$\| $$$$$$$\| $$ | $$$$$$$\ | $$/ $\| $$| $$ | $$| $$__| $$| $$ | $$ | $$ | $$ $$$\ $$| $$ | $$| $$ $$| $$ | $$ | $$ | $$ $$\$$\$$| $$ | $$| $$$$$$$\| $$ | $$ | $$ | $$$$ \$$$$| $$__/ $$| $$ | $$| $$_____ | $$__/ $$ | $$$ \$$$ \$$ $$| $$ | $$| $$ \| $$ $$ \$$ \$$ \$$$$$$ \$$ \$$ \$$$$$$$$ \$$$$$$$ Welcome to another fast paced game of TextWorld! Here is your task for today. First, it would be great if you could try to go east. With that accomplished, take the shoe that's in the attic. With the shoe, place the shoe on the shelf. Alright, thanks! -= Scullery =- You've just shown up in a scullery. You make out a Canadian style box. If you haven't noticed it already, there seems to be something there by the wall, it's a board. The board appears to be empty. What, you think everything in TextWorld should have stuff on it? You bend down to tie your shoe. When you stand up, you notice a bowl. But there isn't a thing on it. This always happens! You don't like doors? Why not try going east, that entranceway is unguarded.
MIT
notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb
zhaozj89/TextWorld
Interact with the gameThe `env.step` method is used to send text command to the game. This method returns the observation for the new state, the current game score, whether the game is done, and dictionary for additional informations (more on that later).
obs, score, done, infos = env.step("open box") print(obs)
You have to unlock the Canadian style box with the Canadian style key first.
MIT
notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb
zhaozj89/TextWorld
Make a simple play loopWe now have everything we need in order to interactively play a text-based game.
try: done = False obs, _ = env.reset() print(obs) nb_moves = 0 while not done: command = input("> ") obs, score, done, _ = env.step(command) print(obs) nb_moves += 1 except KeyboardInterrupt: pass # Press the stop button in the toolbar to quit the game. print("Played {} steps, scoring {} points.".format(nb_moves, score))
________ ________ __ __ ________ | \| \| \ | \| \ \$$$$$$$$| $$$$$$$$| $$ | $$ \$$$$$$$$ | $$ | $$__ \$$\/ $$ | $$ | $$ | $$ \ >$$ $$ | $$ | $$ | $$$$$ / $$$$\ | $$ | $$ | $$_____ | $$ \$$\ | $$ | $$ | $$ \| $$ | $$ | $$ \$$ \$$$$$$$$ \$$ \$$ \$$ __ __ ______ _______ __ _______ | \ _ | \ / \ | \ | \ | \ | $$ / \ | $$| $$$$$$\| $$$$$$$\| $$ | $$$$$$$\ | $$/ $\| $$| $$ | $$| $$__| $$| $$ | $$ | $$ | $$ $$$\ $$| $$ | $$| $$ $$| $$ | $$ | $$ | $$ $$\$$\$$| $$ | $$| $$$$$$$\| $$ | $$ | $$ | $$$$ \$$$$| $$__/ $$| $$ | $$| $$_____ | $$__/ $$ | $$$ \$$$ \$$ $$| $$ | $$| $$ \| $$ $$ \$$ \$$ \$$$$$$ \$$ \$$ \$$$$$$$$ \$$$$$$$ Welcome to another fast paced game of TextWorld! Here is your task for today. First, it would be great if you could try to go east. With that accomplished, take the shoe that's in the attic. With the shoe, place the shoe on the shelf. Alright, thanks! -= Scullery =- You've just shown up in a scullery. You make out a Canadian style box. If you haven't noticed it already, there seems to be something there by the wall, it's a board. The board appears to be empty. What, you think everything in TextWorld should have stuff on it? You bend down to tie your shoe. When you stand up, you notice a bowl. But there isn't a thing on it. This always happens! You don't like doors? Why not try going east, that entranceway is unguarded. > help Available commands: look: describe the current room goal: print the goal of this game inventory: print player's inventory go <dir>: move the player north, east, south or west examine ...: examine something more closely eat ...: eat edible food open ...: open a door or a container close ...: close a door or a container drop ...: drop an object on the floor take ...: take an object that is on the floor put ... on ...: place an object on a supporter take ... from ...: take an object from a container or a supporter insert ... into ...: place an object into a container lock ... with ...: lock a door or a container with a key unlock ... with ...: unlock a door or a container with a key Played 1 steps, scoring 0 points.
MIT
notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb
zhaozj89/TextWorld
Request additional information_*Only available for games generated with TextWorld._To ease the learning process of AI agents, TextWorld offers control over what information should be available alongside the game's narrative (i.e. the observation).Let's request the list of __admissible__ commands (i.e. commands that are guaranteed to be understood by the game interpreter) for every game state. We will also request the list of entity names that can be interacted with. For the complete list of information that can be requested, see the [documentation](https://textworld.readthedocs.io/en/latest/_modules/textworld/envs/wrappers/filter.html?highlight=envinfos)).
import textworld request_infos = textworld.EnvInfos(admissible_commands=True, entities=True) # Requesting additional information should be done when registering the game. env_id = textworld.gym.register_game('tw_games/game.ulx', request_infos) env = gym.make(env_id) obs, infos = env.reset() print("Entities: {}".format(infos["entities"])) print("Admissible commands:\n {}".format("\n ".join(infos["admissible_commands"])))
Entities: ['safe', 'Canadian style box', 'shoe', 'cane', 'shelf', 'workbench', 'board', 'bowl', 'Canadian style key', 'book', 'fork', 'pair of pants', 'north', 'south', 'east', 'west'] Admissible commands: drop Canadian style key drop book drop fork examine Canadian style box examine Canadian style key examine board examine book examine bowl examine fork go east inventory look put Canadian style key on board put Canadian style key on bowl put book on board put book on bowl put fork on board put fork on bowl unlock Canadian style box with Canadian style key
MIT
notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb
zhaozj89/TextWorld
* Problem 2 - Even Fibonacci numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. Let's break the trouble in more steps, at least meanwhile:* Find the fibonacci term;* Check if this term is even;* If the term is even, append this in one list;* Set the interval of the list;* Find the sum of all members of this list. * At first, we must remember the Fibonacci algorithm:a(n) = a(n-2) + a(n-1)Therefore, we must to apply it.
if __name__ == "__main__": assert fibonacci(10) == 89 """Let's start with the 10th fibonacci term""" def fibonacci(n): return 89 if __name__ == "__main__": assert fibonacci(10) == 89 #assert fibonacci(9) == 55 def fibonacci(n): if n == 9: return 55 return 89 if __name__ == "__main__": assert fibonacci(10) == 89 assert fibonacci(9) == 55
_____no_output_____
MIT
2-Even Fibonacci numbers(right).ipynb
vss-py/TDD-ProjectEuler
But if I do this way, I probabilly having a problem to apply the fibonacci algorithm,so, let's begin with the ascending order
def fibonacci(n): return 1 if __name__ == '__main__': assert fibonacci(1) == 1 def fibonacci(n): return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 def fibonacci(n): if n == 2: return 2 return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 def fibonacci(n): if n == 2: return n#refactoring return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 #assert fibonacci(3) == 3 def fibonacci(n): if n == 2: return n return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 """Let's use the fact the 3 is the sum of the 2 and 1, that is, the two first numbers in the growing order""" def fibonacci(n): if n > 2: n = (n-2) + (n-1) return n if n == 2: return n return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 """Now, we can check the 4th and any other terms""" def fibonacci(n): if n > 2: n = (n-2) + (n-1) return n if n == 2: return n return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 fibonacci(5)
_____no_output_____
MIT
2-Even Fibonacci numbers(right).ipynb
vss-py/TDD-ProjectEuler
What the code is doing is: n = (5 - 2) + (5 - 1).Therefore we must to apply a repetition.
def fibonacci(n): a = 1 b = 2 c = 0 i = 0 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 2: return n return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 fibonacci(5) """It is happening because I set i == 1, but the condition is applied when n > 2, therefore I should to set i == 2""" def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 2: return n return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 2: return n return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 """The first step is done"""
_____no_output_____
MIT
2-Even Fibonacci numbers(right).ipynb
vss-py/TDD-ProjectEuler
* Now, I must to find the list (the second step)As I am using the TDD, I can do this without a problem.
def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 2: return n return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 assert fibonacci_list(1) == [1] def fibonacci_list(l): lista = [] i = 1 while i < l: a = fibonacci(i) lista.append(a) i = i + 1 return lista def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 2: return n return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 assert fibonacci_list(1) == [1] #Let's check fibonacci_list(1) def fibonacci_list(l): lista = [] i = 0 while i < l: a = fibonacci(i) lista.append(a) i = i + 1 return lista def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 2: return n return 1 if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 assert fibonacci_list(1) == [1] assert fibonacci_list(2) == [1, 2] """Now I can do the test with the first ten terms""" fibonacci_list(6) """I must to avoid this repetition of the first term""" fibonacci_list(6)
_____no_output_____
MIT
2-Even Fibonacci numbers(right).ipynb
vss-py/TDD-ProjectEuler
The repetition of the first term occurs because I don't set what the function should to do if n < 2.
def fibonacci_list(l): lista = [] i = 1 while i < l: a = fibonacci(i) lista.append(a) i = i + 1 return lista def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 1 or n == 2: return n if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 assert fibonacci_list(1) == [1] assert fibonacci_list(2) == [1, 2] print(fibonacci_list(0)) print(fibonacci_list(1)) print(fibonacci_list(2)) fibonacci_list(5) def fibonacci_list(l): lista = [] i = 1 while i < l: a = fibonacci(i) lista.append(a) i = i + 1 return lista def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 1 or n == 2: return n if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 assert fibonacci_list(1) == [] assert fibonacci_list(2) == [1] assert fibonacci_list(3) == [1, 2]
_____no_output_____
MIT
2-Even Fibonacci numbers(right).ipynb
vss-py/TDD-ProjectEuler
Now, I must to apply the condition that I miss. To append in the list only the even terms.
def fibonacci_list(l): lista = [] i = 1 while i < l: a = fibonacci(i) if a % 2 == 0: lista.append(a) i = i + 1 else: i = i + 1 return lista def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 1 or n == 2: return n if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 assert fibonacci_list(1) == [] assert fibonacci_list(2) == [2] #assert fibonacci_list(3) == [1, 2] fibonacci_list(10) fibonacci_list(3) """As 0 is a order of the first term, the first even term is showed in the 3tr member""" def fibonacci_list(l): lista = [] i = 1 while i < l: a = fibonacci(i) if a % 2 == 0: lista.append(a) i = i + 1 else: i = i + 1 return lista def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 1 or n == 2: return n if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 assert fibonacci_list(1) == [] assert fibonacci_list(3) == [2]
_____no_output_____
MIT
2-Even Fibonacci numbers(right).ipynb
vss-py/TDD-ProjectEuler
Now, for the next step, I must to set a interval condition. In the statement, the condition is "the values not exced 4 milions".
def fibonacci_list_interval(m): lista = [] i = 1 while True: a = fibonacci(i) if a > m: print('The last term is: ' + str(a)) break if a % 2 == 0: lista.append(a) i = i + 1 else: i = i + 1 return lista def fibonacci_list(l): lista = [] i = 1 while i < l: a = fibonacci(i) if a % 2 == 0: lista.append(a) i = i + 1 else: i = i + 1 return lista def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 1 or n == 2: return n if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 assert fibonacci_list(1) == [] assert fibonacci_list(3) == [2] fibonacci_list_interval(50) fibonacci_list_interval(4000000)
The last term is: 5702887
MIT
2-Even Fibonacci numbers(right).ipynb
vss-py/TDD-ProjectEuler
I don't know how can I make first a test in this case, but how the code was developed, I see no one problem to do this way. Whatever, the new function is just the previous function with same changes. To return the sum of even numbers of the fibonacci list, I must to do only this:
def fibonacci_list_interval(m): lista = [] i = 1 while True: a = fibonacci(i) if a > m: print('The last term is: ' + str(a)) break if a % 2 == 0: lista.append(a) i = i + 1 else: i = i + 1 return sum(lista) def fibonacci_list(l): lista = [] i = 1 while i < l: a = fibonacci(i) if a % 2 == 0: lista.append(a) i = i + 1 else: i = i + 1 return lista def fibonacci(n): a = 1 b = 2 c = 0 i = 2 if n > 2: while i < n: c = a + b a = b b = c i = i + 1 return c if n == 1 or n == 2: return n if __name__ == '__main__': assert fibonacci(1) == 1 assert fibonacci(2) == 2 assert fibonacci(3) == 3 assert fibonacci(4) == 5 assert fibonacci(5) == 8 assert fibonacci(6) == 13 assert fibonacci(7) == 21 assert fibonacci(8) == 34 assert fibonacci(9) == 55 assert fibonacci(10) == 89 assert fibonacci_list(1) == [] assert fibonacci_list(3) == [2] fibonacci_list_interval(4000000)
The last term is: 5702887
MIT
2-Even Fibonacci numbers(right).ipynb
vss-py/TDD-ProjectEuler
Chapter 3 - Regression Models Segment 2 - Multiple linear regression
import numpy as np import pandas as pd import matplotlib.pyplot as plt from pylab import rcParams import sklearn from sklearn.linear_model import LinearRegression from sklearn.preprocessing import scale %matplotlib inline rcParams['figure.figsize'] = 5, 4 import seaborn as sb sb.set_style('whitegrid') from collections import Counter
_____no_output_____
MIT
modules/module_12/part3/03_02_begin/03_02_begin.ipynb
ryanjmccall/sb_ml_eng_capstone
(Multiple) linear regression on the enrollment data
address = 'C:/Users/Lillian/Desktop/ExerciseFiles/Data/enrollment_forecast.csv' enroll = pd.read_csv(address) enroll.columns = ['year', 'roll', 'unem', 'hgrad', 'inc'] enroll.head() sb.pairplot(enroll) print(enroll.corr()) enroll_data = enroll[['unem', 'hgrad']].values enroll_target = enroll[['roll']].values enroll_data_names = ['unem', 'hgrad'] X, y = scale(enroll_data), enroll_target
_____no_output_____
MIT
modules/module_12/part3/03_02_begin/03_02_begin.ipynb
ryanjmccall/sb_ml_eng_capstone
Checking for missing values
missing_values = X==np.NAN X[missing_values == True] LinReg = LinearRegression(normalize=True) LinReg.fit(X, y) print(LinReg.score(X, y))
0.8488812666133723
MIT
modules/module_12/part3/03_02_begin/03_02_begin.ipynb
ryanjmccall/sb_ml_eng_capstone
Discrete Models Task 1) Data Preparation Installing 'tslearn' - only run if not installed previously (if necessary, for more information see documentation of the package at https://tslearn.readthedocs.io/en/latest/index.html?highlight=install
##!pip install tslearn
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Importing packages
import datetime import pandas as pd from pandas import Series from pandas import DataFrame from pandas import concat import numpy as np import time, datetime import matplotlib.pyplot as plt import sys from tslearn.generators import random_walks from tslearn.preprocessing import TimeSeriesScalerMeanVariance from tslearn.piecewise import PiecewiseAggregateApproximation from tslearn.piecewise import SymbolicAggregateApproximation, OneD_SymbolicAggregateApproximation import string from collections import Counter from nltk import ngrams import itertools import random from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm from sklearn.metrics import confusion_matrix import seaborn as sns from sklearn.datasets import make_classification from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import roc_curve from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import fbeta_score from sklearn.preprocessing import MinMaxScaler from sklearn import preprocessing
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Reading the data, converting the time to timestamp and indexing the date to use it as a time series
#Data Paths DATA_PATH = sys.path[0]+"\\data\\" filename_train1="BATADAL_dataset03.csv" filename_train2="BATADAL_dataset04.csv" filename_test="BATADAL_test_dataset.csv" #Reading the data dftrain1 = pd.read_csv(DATA_PATH + filename_train1) dftrain2 = pd.read_csv(DATA_PATH + filename_train2) dftest = pd.read_csv(DATA_PATH + filename_test) # Modify string date to timestamp dftrain1.DATETIME = dftrain1.DATETIME.apply(lambda s: pd.to_datetime(s,format='%d/%m/%y %H')) dftrain2.DATETIME = dftrain2.DATETIME.apply(lambda s: pd.to_datetime(s,format='%d/%m/%y %H')) dftest.DATETIME = dftest.DATETIME.apply(lambda s: pd.to_datetime(s,format='%d/%m/%y %H')) # Choosing 0 if not an anomaly and 1 if anomaly #dftrain2[' ATT_FLAG']=dftrain2[' ATT_FLAG'].apply(lambda x: 0 if x==-999 else x) # Indexing dftrain1 = dftrain1.set_index('DATETIME') dftrain2 = dftrain2.set_index('DATETIME') dftest = dftest.set_index('DATETIME') #dftrain1.shift(1)
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Scaling the data to normal distribution with mean zero and standard deviation
#Obs: some values will be converted to float dftrain1_original=dftrain1 dftrain2_original=dftrain2 dftest_original=dftest #Dftrain1 dftrain1.iloc[:,range(0,31)]=preprocessing.scale(dftrain1.iloc[:,range(0,31)]) #Dftrain2 dftrain2.iloc[:,range(0,31)]=preprocessing.scale(dftrain2.iloc[:,range(0,31)]) #Dftest dftest.iloc[:,range(0,31)]=preprocessing.scale(dftest.iloc[:,range(0,31)])
C:\Users\pvbia\Anaconda3\lib\site-packages\ipykernel_launcher.py:6: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by the scale function. C:\Users\pvbia\Anaconda3\lib\site-packages\ipykernel_launcher.py:10: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by the scale function. # Remove the CWD from sys.path while we load stuff.
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Labeling the attacks on dftrain2 according to the information below For L_T713/09/2016 23 - 16/09/2016 00 |26/09/2016 11 - 27/09/2016 10 For F_PU10 and F_PU1126/09/2016 11 - 27/09/2016 10 For L_T109/10/2016 9 - 11/10/2016 20 |29/10/2016 19 - 02/11/2016 16 |14/12/2016 15 - 19/12/2016 04 For F_PU1 and F_PU229/10/2016 19 - 02/11/2016 16 |14/12/2016 15 - 19/12/2016 04 For L_T426/11/2016 17 - 29/11/2016 04
#L_T7 dftrain2_L_T7=dftrain2.loc[:,[' L_T7',' ATT_FLAG']] dftrain2_L_T7.loc[:,' ATT_FLAG']=0 dftrain2_L_T7.loc['2016-09-13 23':'2016-09-16 00',' ATT_FLAG']=1 dftrain2_L_T7.loc['2016-09-26 11':'2016-09-27 10',' ATT_FLAG']=1 #F_PU10 and F_PU11 dftrain2_F_PU10=dftrain2.loc[:,[' F_PU10',' ATT_FLAG']] dftrain2_F_PU10.loc[:,' ATT_FLAG']=0 dftrain2_F_PU10.loc['2016-09-26 11':'2016-09-27 10',' ATT_FLAG']=1 dftrain2_F_PU11=dftrain2.loc[:,[' F_PU11',' ATT_FLAG']] dftrain2_F_PU11.loc[:,' ATT_FLAG']=0 dftrain2_F_PU11.loc['2016-09-26 11':'2016-09-27 10',' ATT_FLAG']=1 #L_T1 dftrain2_L_T1=dftrain2.loc[:,[' L_T1',' ATT_FLAG']] dftrain2_L_T1.loc[:,' ATT_FLAG']=0 dftrain2_L_T1.loc['2016-10-09 09':'2016-10-11 20',' ATT_FLAG']=1 dftrain2_L_T1.loc['2016-10-29 19':'2016-11-02 16',' ATT_FLAG']=1 dftrain2_L_T1.loc['2016-12-14 15':'2016-12-19 04',' ATT_FLAG']=1 #F_PU1 and F_PU2 dftrain2_F_PU1=dftrain2.loc[:,[' F_PU1',' ATT_FLAG']] dftrain2_F_PU1.loc[:,' ATT_FLAG']=0 dftrain2_F_PU1.loc['2016-10-29 19':'2016-11-02 16',' ATT_FLAG']=1 dftrain2_F_PU1.loc['2016-12-14 15':'2016-12-19 04',' ATT_FLAG']=1 dftrain2_F_PU2=dftrain2.loc[:,[' F_PU2',' ATT_FLAG']] dftrain2_F_PU2.loc[:,' ATT_FLAG']=0 dftrain2_F_PU2.loc['2016-10-29 19':'2016-11-02 16',' ATT_FLAG']=1 dftrain2_F_PU2.loc['2016-12-14 15':'2016-12-19 04',' ATT_FLAG']=1 #L_T4 dftrain2_L_T4=dftrain2.loc[:,[' L_T4',' ATT_FLAG']] dftrain2_L_T4.loc[:,' ATT_FLAG']=0 dftrain2_L_T4.loc['2016-11-26 17':'2016-11-29 04',' ATT_FLAG']=1 #dftrain2[' ATT_FLAG']=dftrain2[' ATT_FLAG'].apply(lambda x: 0 if x==-999 else x)
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Labling the attacks on dftest according to the batadal dataset
###Labling zero in the test set for all anomalies dftest[" ATT_FLAG"]=0 ###Creating one dataset for each dimension #Attack 1 dftest_L_T3=dftest.loc[:,['L_T3',' ATT_FLAG']] dftest_P_U4=dftest.loc[:,['F_PU4', ' ATT_FLAG']] dftest_P_U5=dftest.loc[:,['F_PU5', ' ATT_FLAG']] #Attack 2 dftest_L_T2=dftest.loc[:,['L_T2', ' ATT_FLAG']] #Attack 3 dftest_P_U3=dftest.loc[:,['F_PU3', ' ATT_FLAG']] #Attack 4 dftest_P_U3=dftest.loc[:,['F_PU3', ' ATT_FLAG']] #Attack 5 dftest_L_T2=dftest.loc[:,['L_T2', ' ATT_FLAG']] dftest_V2=dftest.loc[:,['F_V2', ' ATT_FLAG']] dftest_P_J14=dftest.loc[:,['P_J14', ' ATT_FLAG']] dftest_P_J422=dftest.loc[:,['P_J422', ' ATT_FLAG']] #Attack 6 dftest_L_T7=dftest.loc[:,['L_T7', ' ATT_FLAG']] dftest_P_U10=dftest.loc[:,['F_PU10', ' ATT_FLAG']] dftest_P_U11=dftest.loc[:,['F_PU11', ' ATT_FLAG']] dftest_P_J14=dftest.loc[:,['P_J14', ' ATT_FLAG']] dftest_P_J422=dftest.loc[:,['P_J422', ' ATT_FLAG']] #Attack 7 dftest_L_T4=dftest.loc[:,['L_T4', ' ATT_FLAG']] dftest_L_T6=dftest.loc[:,['L_T6', ' ATT_FLAG']] ###Adding one for anomalies #Attack 1 dftest_L_T3.loc['2017-01-16 09':'2017-01-19 06', ' ATT_FLAG']=1 dftest_P_U4.loc['2017-01-16 09':'2017-01-19 06', ' ATT_FLAG']=1 dftest_P_U5.loc['2017-01-16 09':'2017-01-19 06', ' ATT_FLAG']=1 #Attack 2 dftest_L_T2.loc['2017-01-30 08':'2017-02-02 00', ' ATT_FLAG']=1 #Attack 3 dftest_P_U3.loc['2017-02-09 03':'2017-02-10 09', ' ATT_FLAG']=1 #Attack 4 dftest_P_U3.loc['2017-02-12 01':'2017-02-13 07', ' ATT_FLAG']=1 #Attack 5 dftest_L_T2.loc['2017-02-24 05':'2017-02-28 08', ' ATT_FLAG']=1 dftest_V2.loc['2017-02-24 05':'2017-02-28 08', ' ATT_FLAG']=1 dftest_P_J14.loc['2017-02-24 05':'2017-02-28 08', ' ATT_FLAG']=1 dftest_P_J422.loc['2017-02-24 05':'2017-02-28 08', ' ATT_FLAG']=1 #Attack 6 dftest_L_T7.loc['2017-03-10 14':'2017-03-13 21', ' ATT_FLAG']=1 dftest_P_U10.loc['2017-03-10 14':'2017-03-13 21', ' ATT_FLAG']=1 dftest_P_U11.loc['2017-03-10 14':'2017-03-13 21', ' ATT_FLAG']=1 dftest_P_J14.loc['2017-03-10 14':'2017-03-13 21', ' ATT_FLAG']=1 dftest_P_J422.loc['2017-03-10 14':'2017-03-13 21', ' ATT_FLAG']=1 #Attack 7 dftest_L_T4.loc['2017-03-25 20':'2017-03-27 01', ' ATT_FLAG']=1 dftest_L_T6.loc['2017-03-25 20':'2017-03-27 01', ' ATT_FLAG']=1
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Labling all the attacks in one dataset to compute performance
dftest.loc['2017-01-16 09':'2017-01-19 06',' ATT_FLAG']=1 dftest.loc['2017-01-30 08':'2017-02-02 00',' ATT_FLAG']=1 dftest.loc['2017-02-09 03':'2017-02-10 09',' ATT_FLAG']=1 dftest.loc['2017-02-12 01':'2017-02-13 07',' ATT_FLAG']=1 dftest.loc['2017-02-24 05':'2017-02-28 08',' ATT_FLAG']=1 dftest.loc['2017-03-10 14':'2017-03-13 21',' ATT_FLAG']=1 dftest.loc['2017-03-25 20':'2017-03-27 01',' ATT_FLAG']=1
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Adding the anomaly type column to be used in the detection
dftest["anomalytype"]=0
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Attack 1
plt.plot(dftest_L_T3.loc['2017-01-16 09':'2017-01-19 06', 'L_T3'],color="red") plt.plot(dftest_L_T3.loc['2017-01-12 09':'2017-01-16 09', 'L_T3'],color="blue") plt.plot(dftest_L_T3.loc['2017-01-19 06':'2017-01-23 06', 'L_T3'],color="blue") plt.plot(dftest_P_U4.loc['2017-01-16 09':'2017-01-19 06', 'F_PU4'],color="red") plt.plot(dftest_P_U4.loc['2017-01-12 09':'2017-01-16 09', 'F_PU4'],color="blue") plt.plot(dftest_P_U4.loc['2017-01-19 06':'2017-01-23 06', 'F_PU4'],color="blue") plt.plot(dftest_P_U5.loc['2017-01-16 09':'2017-01-19 06', 'F_PU5'],color="red") plt.plot(dftest_P_U5.loc['2017-01-12 09':'2017-01-16 09', 'F_PU5'],color="blue") plt.plot(dftest_P_U5.loc['2017-01-19 06':'2017-01-23 06', 'F_PU5'],color="blue")
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Thus attack 1 generated a contextual anomaly in L_T3
dftest.loc['2017-01-16 09':'2017-01-19 06', 'anomalytype']="contextual"
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Attack 2
plt.plot(dftest_L_T2.loc['2017-01-30 08':'2017-02-02 00', 'L_T2'],color="red") plt.plot(dftest_L_T2.loc['2017-01-26 08':'2017-01-30 08', 'L_T2'],color="blue") plt.plot(dftest_L_T2.loc['2017-02-02 00':'2017-02-06 00', 'L_T2'],color="blue")
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Thus attack 2 generated a collective anomaly in L_T2
dftest.loc['2017-01-30 08':'2017-02-02 00', 'anomalytype']="collective"
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Attack 3
plt.plot(dftest_P_U3.loc['2017-02-09 02':'2017-02-10 09', 'F_PU3'],color="red") plt.plot(dftest_P_U3.loc['2017-02-05 03':'2017-02-09 02', 'F_PU3'],color="blue") plt.plot(dftest_P_U3.loc['2017-02-10 09':'2017-02-14 09', 'F_PU3'],color="blue")
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Thus attack 3 generated a collective anomaly in F_PU3
dftest.loc['2017-02-09 02':'2017-02-10 09', 'anomalytype']="collective"
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Attack 4
plt.plot(dftest_P_U3.loc['2017-02-12 00':'2017-02-13 07', 'F_PU3'],color="red") plt.plot(dftest_P_U3.loc['2017-02-08 01':'2017-02-12 00', 'F_PU3'],color="blue") plt.plot(dftest_P_U3.loc['2017-02-13 07':'2017-02-17 07', 'F_PU3'],color="blue")
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Thus attack 4 generated a collective anomaly in F_PU3
dftest.loc['2017-02-12 00':'2017-02-13 07', 'anomalytype']="collective"
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Attack 5
plt.plot(dftest_L_T2.loc['2017-02-24 05':'2017-02-28 08', 'L_T2'],color="red") plt.plot(dftest_L_T2.loc['2017-02-20 05':'2017-02-24 05', 'L_T2'],color="blue") plt.plot(dftest_L_T2.loc['2017-02-28 08':'2017-03-03 08', 'L_T2'],color="blue") plt.plot(dftest_V2.loc['2017-02-24 05':'2017-02-28 08', 'F_V2'],color="red") plt.plot(dftest_V2.loc['2017-02-20 05':'2017-02-24 05', 'F_V2'],color="blue") plt.plot(dftest_V2.loc['2017-02-28 08':'2017-03-03 08', 'F_V2'],color="blue") plt.plot(dftest_P_J14.loc['2017-02-24 05':'2017-02-28 08', 'P_J14'],color="red") plt.plot(dftest_P_J14.loc['2017-02-20 05':'2017-02-24 05', 'P_J14'],color="blue") plt.plot(dftest_P_J14.loc['2017-02-28 08':'2017-03-03 08', 'P_J14'],color="blue") plt.plot(dftest_P_J422.loc['2017-02-24 05':'2017-02-28 08', 'P_J422'],color="red") plt.plot(dftest_P_J422.loc['2017-02-20 05':'2017-02-24 05', 'P_J422'],color="blue") plt.plot(dftest_P_J422.loc['2017-02-28 08':'2017-03-03 08', 'P_J422'],color="blue")
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Thus attack 5 generated a collective anomaly in L_T2, F_V2, P_J14 and P_J422
dftest.loc['2017-02-24 05':'2017-02-28 08', 'anomalytype']="collective"
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Attack 6
plt.plot(dftest_L_T7.loc['2017-03-10 14':'2017-03-13 21', 'L_T7'],color="red") plt.plot(dftest_L_T7.loc['2017-03-06 14':'2017-03-10 14', 'L_T7'],color="blue") plt.plot(dftest_L_T7.loc['2017-03-13 21':'2017-03-17 21', 'L_T7'],color="blue") plt.plot(dftest_P_U10.loc['2017-03-10 14':'2017-03-13 21', 'F_PU10'],color="red") plt.plot(dftest_P_U10.loc['2017-03-06 14':'2017-03-10 14', 'F_PU10'],color="blue") plt.plot(dftest_P_U10.loc['2017-03-13 21':'2017-03-17 21', 'F_PU10'],color="blue") plt.plot(dftest_P_U11.loc['2017-03-10 14':'2017-03-13 21', 'F_PU11'],color="red") plt.plot(dftest_P_U11.loc['2017-03-06 14':'2017-03-10 14', 'F_PU11'],color="blue") plt.plot(dftest_P_U11.loc['2017-03-13 21':'2017-03-17 21', 'F_PU11'],color="blue") plt.plot(dftest_P_J14.loc['2017-03-10 14':'2017-03-13 21', 'P_J14'],color="red") plt.plot(dftest_P_J14.loc['2017-03-06 14':'2017-03-10 14', 'P_J14'],color="blue") plt.plot(dftest_P_J14.loc['2017-03-13 21':'2017-03-17 21', 'P_J14'],color="blue") plt.plot(dftest_P_J422.loc['2017-03-10 14':'2017-03-13 21', 'P_J422'],color="red") plt.plot(dftest_P_J422.loc['2017-03-06 14':'2017-03-10 14', 'P_J422'],color="blue") plt.plot(dftest_P_J422.loc['2017-03-13 21':'2017-03-17 21', 'P_J422'],color="blue")
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Attack 6 generated collective anomalies
dftest.loc['2017-03-10 14':'2017-03-13 21', 'anomalytype']="collective"
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Attack 7
plt.plot(dftest_L_T4.loc['2017-03-25 20':'2017-03-27 01', 'L_T4'],color="red") plt.plot(dftest_L_T4.loc['2017-03-21 20':'2017-03-25 20', 'L_T4'],color="blue") plt.plot(dftest_L_T4.loc['2017-03-27 01':'2017-03-31 01', 'L_T4'],color="blue") plt.plot(dftest_L_T6.loc['2017-03-25 20':'2017-03-27 01', 'L_T6'],color="red") plt.plot(dftest_L_T6.loc['2017-03-21 20':'2017-03-25 20', 'L_T6'],color="blue") plt.plot(dftest_L_T6.loc['2017-03-27 01':'2017-03-31 01', 'L_T6'],color="blue")
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Thus attack 6 generated a collective anomaly in L_T4 and L_T6
dftest.loc['2017-03-25 20':'2017-03-27 01', 'anomalytype']="collective"
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
2) Discretization Creating a dataset to test the sax
dataset_scale=dftrain1['L_T7']
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Creating the Symbolic Aggregate Approximation (SAX) function and testing in the above mentioned dataset
### Creting a function that creates the sax def tosax(n_paa_segments,n_sax_symbols,dataset_scale): #Creating the SAX using 'n_paa_segments' as number of segments and 'n_sax_symbols' as number of symbols sax = SymbolicAggregateApproximation(n_segments=n_paa_segments, alphabet_size_avg=n_sax_symbols) # Compute sax time series corresponding (by sax.inverse_transform) to the fitted PAA representation (done by sax.fit_transform) return sax.inverse_transform(sax.fit_transform(dataset_scale)) ### Running the function to test it for a given column of the dataset n_sax_symbols = 5 n_paa_segments=int(len(dataset_scale)/4) sax_dataset_inv=tosax(n_paa_segments,n_sax_symbols,dataset_scale)
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Plotting the scaled time series, PAA and SAX representations for the sake of validation of the code
#Plotting - only 100 first values to test the code isworking as expected # Plotting the scaled data set plt.subplot(2, 2, 2) # First, raw time series plt.plot(dataset_scale.ravel()[0:300], "b-") plt.title("Original Time Series") #Plotting the SAX plt.subplot(2, 2, 1) # Then SAX plt.plot(sax_dataset_inv[0].ravel()[0:300], "b-") plt.title("SAX, %d symbols" % n_sax_symbols) plt.tight_layout() plt.show()
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
3) N-Grams Representations Creating a function that returns its n-gram representation.
#'a' will be used just to test the functions below. a=sax_dataset_inv[0].ravel()
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
We need function(s) to convert numeric values generated from the sax to a string to perform N-grams as a it was a NLP problem. For this purpose two functions were created: the first just put all the values of a list in a string and the second convert numerical values of the sax to letters
# First function convert a list of numeric values to a string def convert(list): # Converting integer list to string list s = [str(i) for i in list] # Join list items using join() res = ("".join(s)) return(res) # Second function to convert a sax numeric representation into strings def saxtostring(sax): #Creating a list with all unique elements setsax=set(sax) L=[] for i in setsax: L.append(i) L=sorted(L) #Creating a dictinary with the elements that need to be converted D={} for i in range(0,len(L)): D[L[i]]=string.ascii_lowercase[i] #Converting the numerical values to strings output=[] for i in range(0,len(sax)): output.append(D[sax[i]]) return output #To test b=saxtostring(a)
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Now to generate Ngrams we need a function that gather from the data the possible grams and their possible next values.
#Function that creates the Ngrams representation by creating a dictionary that has as keys the representations and as values #the number elements generated after the n-gram def tongrams(tokens,n): #Creates a dictionary with the Ngrams representation and the next element (that is to be predicted by the ngrams) D = {} #Loop needs to go up to len(tokens)-n-1 to not get out of bounds for i in range(0,len(tokens)-n-1): #If new key, we add this key to the dictionary if convert(tokens[i:(i+n)]) not in D.keys(): D[convert(tokens[i:(i+n)])] = [convert(tokens[i+n+1])] #If existing key, append new value else: D[convert(tokens[i:(i+n)])].append(tokens[i+n+1]) return D #To test g=tongrams(b,3)
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Now we create a Markov Chain that calculates the prior and the posterior given the dictionary generated by the previous function.
#Function that calcualte the likelihood given a ngram def tomarkovchain(ngram): #Create dictionary to be filled with the probability of conditional events (likelihood) l_probs=dict() #Create the dictionaries to be filled with the counting for each gram c1=dict() #Loop through keys to calculate the likelihood for each key for key in ngram.keys(): #Create the variable to be filled with tally of the number of times that a value repeat for each key counts = dict() for i in ngram[key]: counts[i] = counts.get(i, 0) + 1 #Create the dictionary to be filled with the probability of the conditional events (likelihood) l=dict() #Calculate the probability by dividing the count to the sum of values for j in counts.keys(): l[j]=counts[j]/sum(counts.values()) #Assign to each key the dictionary with the probabilities l_probs[key]=l #Assign to each key the dictionary with the counting c1[key]=counts # Return the likelihood,the prior and the counting return [l_probs,c1] #To test m=tomarkovchain(g) #Smoothing the prior #This function return the smoothed probability def smooth_ngram_prob(markovchain_model,n_sax_symbols,input_gram,output_gram): #Calculating denominators ngrams_number=len(random.choice(list(markovchain_model[0].keys()))) #Smoothing if input_gram in markovchain_model[1].keys(): total_values_for_the_key=sum(markovchain_model[1][input_gram].values()) #The Probability is calculated by adding 1 observation for all possible grams (total of n_sax_symbols**ngrams_number ) smoothed=(markovchain_model[1][input_gram].get(output_gram,0)+1)/(total_values_for_the_key+n_sax_symbols) else: #There is no observation of this gram smoothed=0 return smoothed #To test smooth_ngram_prob(m,5,"aae","a")
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Lastly, we create a function that loop through the dataframe and return the index that are below a certain threshold
def prediction(markovchain_model,n_sax_symbols,string_sax, threshold): #Calculating number of ngrams used n=len(random.choice(list(markovchain_model[0].keys()))) #Calculationg the number of times a observation should be reproduced so the data set has the same size as the original #Creating the list to store the values L=[] #And a list to store the probabilities P=[] #looping for i in range(0,len(string_sax)): if (i<=(n+1)): L.append(0) P.append(0) else: P.append(smooth_ngram_prob(markovchain_model,n_sax_symbols,convert(string_sax[i:(i+n)]),string_sax[i])) if smooth_ngram_prob(markovchain_model,n_sax_symbols,convert(string_sax[i:(i+n)]),string_sax[i])<threshold: L.append(1) else: L.append(0) return [L,P] pred_test=prediction(m,5,b, 0.01)[0]
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
And a function that merge the predictions into the original dataframe considering the possible rounding differences that may lead to difference in length when creating SAX
def smartmerge(df,predictions): df=pd.Series.to_frame(df) if len(predictions)==len(df): df.insert(1, "predictions", predictions) df.reset_index(inplace=True) if len(predictions)>len(df): predictions=predictions[:-(len(predictions)-len(df))] df.insert(1, "predictions", predictions) df.reset_index(inplace=True) if len(predictions)<len(df): for i in range(0,(len(df)-len(predictions))): predictions.append(0) df.insert(1, "predictions", predictions) #To help to plot latter #df['color'] = df['predictions'].apply(lambda x: "blue" if x==0 else "red") return df
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
4) Predictions Attacks Using N-grams _In this subchapter we are going to try to predict the attacks on the training dataset 2_ Creating functions that aid the prediction Creating a function that make predicitons and calculate performance indicators.
def model_to_predict(trainset,testset,results,n_sax_symbols,n_paa_segments,n_grams,threshold): ###Generating the model for the train set### #Sax sax_train=tosax(n_paa_segments,n_sax_symbols,trainset).ravel() #Sax to string sax_string_train=saxtostring(sax_train) #Ngrams ngrams=tongrams(sax_string_train,n_grams) #Markov Chain m=tomarkovchain(ngrams) ###Preparing the test set### #Getting the denominator of the paa in a way that the test and train set have the same number of variables in a segment n_paa_segments_test_denominator=len(trainset)/n_paa_segments #Sax sax_test=tosax(int(len(testset)/n_paa_segments_test_denominator),n_sax_symbols,testset).ravel() #Sax to string sax_string_test=saxtostring(sax_test) ###Making predictions pred=prediction(m,n_sax_symbols,sax_string_test, threshold)[0] predictions_df=smartmerge(testset,pred) ###Calculating the performance cm=confusion_matrix(list(results), list(predictions_df['predictions'])) if cm.shape==(3,3): cm=cm[(0,2),1:] #True positive, false positive, false negative and true positive tn, fp, fn, tp = cm.ravel() #Getting the ratios recall=tp/(tp+fn) precision=tp/(tp+fp) accuracy=(tp+tn)/(tp+tn+fn+fp) f1=fbeta_score(list(results), list(predictions_df['predictions']),beta=0.5) #Probability vector probab=prediction(m,n_sax_symbols,sax_string_test, threshold)[1] performance={"recall":recall,"precision":precision,"Accuracy":accuracy,"F1":f1} return [cm,performance,probab, predictions_df] #Testing sax=7 paa=int(len(dftrain1["L_T1"])/2) n=5 t=0.1 MODEL=model_to_predict(dftrain1["L_T1"],dftrain2_L_T1[" L_T1"],dftrain2_L_T1[' ATT_FLAG'],sax,paa,n,t) MODEL[1]
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Creating a function that plot the confusion matrix in a nice format!
def ploting_cm(cm): #Plot ax= plt.subplot() sns.heatmap(cm, annot=True,fmt='g', ax = ax); #annot=True to annotate cells # labels, title and ticks ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); ax.set_title('Confusion Matrix'); ax.xaxis.set_ticklabels(['normal', 'anomaly']); ax.yaxis.set_ticklabels(['normal', 'anomaly'])
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Creating a function that loop over the parameters and select the best set of parameters based the F-score
def parameterselection(trainset,testset,results): #Genereting one first model to have a starting value for the loop with selected parameters parameters={"sax":5,"paa":1,"ngram":3,"threshold":0.10} best_MODEL=model_to_predict(trainset,testset,results,5,int(len(trainset)/1),3,0.1) #Looping for sax in range(4,8,1): for paa in range(1,5,1): for n in range(2,6,1): for t in [0.01,0.02,0.03,0.04,0.05,0.1]: MODEL=model_to_predict(trainset,testset,results,sax,int(len(dftrain1)/paa),n,t) #Selecting using F1-Score that has at least 1 true positive if (MODEL[1]["F1"]>best_MODEL[1]["F1"]) and (MODEL[0].ravel()[3]>1): best_MODEL=MODEL parameters={"sax":sax,"paa":paa,"ngram":n,"threshold":t} return [best_MODEL,parameters]
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics