Exam Revision Flashcards

1
Q

What will this code give you?

%cd /
%pwd
%ls
%ls - lt
- (3)

A

%pwd = given /

%ls - lists all contents of current working directory (from bin@ to cuda-keyring)

%ls-lt (output starting from total 100) - lists all contents of current working directory by working out file size and sorts them by date

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does the ‘%history’ command do in Colab notebooks?

A

The ‘%history’ command in Colab notebooks displays a history of codes and commands written

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the ‘%magic’ command do in Colab notebooks?

A

The ‘%magic’ command in Colab notebooks provides information and documentation about available commands and their functionalities.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

List all the special commands used in Colab notebooks - (7)

A

‘%cd’,
‘%pwd’, ‘
%ls’,
‘%ls -lt’,
‘%history’,
‘%magic’.
&mkdir

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does the ‘%mkdir’ command do

A

It creates a new directory within the current working directory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Quick Exercise
Practice typing commands in the code window below and run them.

Check what your present working directory is and make a note of it (this might be your home directory on the system on which you are working)

Change to another directory to home

Check where your present working directory

Produce a new directory called test

List contents in test

Change current working directory to test

A

%pwd
Output: /content/sample_data

%cd /home (root then place we want to go)

Output: /home

%pwd - check where we are
Output: ‘/home’

%mkdir test
No output

%ls
Output: test/

%cd test
Output: /home/test

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Identify the issue in the following Python code:

print(“Hello World!)

A

The issue in the code is the absence of a closing double quote, resulting in an “unterminated string literal” error - indicating that the provided string is not properly terminated with a closing double quote - syntax error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Explain the purpose of the + operator in the given Python code - (2)

print(“Hello” + “World”).

A

The + operator is used for string concatenation in the provided Python code.

It combines the strings “Hello” and “World” into a single string, “HelloWorld”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the following code snippet do? - (3)

b = 10
print(b)
del(b)
print(b)

A

The code snippet assigns the value 10 to the variable b and prints it.

Then, it deletes the variable b using the del keyword.

Attempting to print b after it has been deleted will result in a NameError because the variable no longer exists.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain the behavior of type(float(3)) in Python.

A

The expression type(float(3)) converts the integer value 3 to a float and then determines its data type using the type() function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Describe the outcome of int(3.25) in Python.

A

The expression int(3.25) converts the floating point number 3.25 to an integer, resulting in the value 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the result of int(3.999) in Python?

A

The expression int(3.999) converts the floating point number 3.999 to an integer, resulting in the value 3, as the conversion truncates the decimal part.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What arithmetic operations can be performed on numbers in Python?

A

Arithmetic operations such as addition (+), subtraction (-), multiplication (*), division (/), integer division (//), exponentiation (**), and remainder (%) can be performed on numbers in Python

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What happens when executing print(3.0 + 3) in Python? - (3)

A

When running print(3.0 + 3), Python adds a floating point number (3.0) and an integer (3).

Python automatically converts the integer to a floating point number before performing the addition.

Forces the numbers to be same data type before performing addition.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Adding float to integer it will make it

A

float

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

If you keep everything the same datatype when doing arithmetic operations in print statement e.g., print(3 + 2) it will remain the

A

same data type - integer in this case

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

If you mix data types when doing arithmetic operations in print statement e.g., print(3.0 + 2) it will

A

typically become floating point values

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the output of print(3.0 * 2) in Python?

A

The output is 6.0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the output of print(3 * 2) in Python?

A

The output is 6.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Explain the behavior of print(3.0 ** 3) in Python.

A

It computes the result of raising 3.0 to the power of 3, which equals 27.0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What does the expression print(9.0 ** 0.5) compute in Python?

A

It computes the square root of 9.0, which equals 3.0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How does the power operator () behave in Python? - (2)

A

The power operator () can be used to compute both “normal” power values, such as squaring, and roots.

For example, raising a number to 1/2 (0.5) computes the square root.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How does division work in Python? - (2)

A

In Python, division is performed using the / operator.

It automatically converts integers to floating-point numbers ‘where necessary’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the result of print(3 / 2) in Python?

A

The expression print(3 / 2) evaluates to 1.5 because it performs floating-point division, resulting in a floating-point number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What does the // operator do in Python?

A

The // operator in Python performs integer division, discarding any fractional part and returning the integer result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the result of print(3//2) in Python?

A

The expression print(3//2) evaluates to 1 because it performs integer division, resulting in an integer quotient - has not rounded it (chopped off decimal part)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What does the % (modulus) operator do in Python?

A

The % operator in Python returns the remainder of the division of the first number by the second number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is the result of print(8 % 3) in Python?

A

The expression print(8 % 3) evaluates to 2 because when 8 is divided by 3, the remainder is 2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

The ‘/’ allows integers to turn into

A

floating point numbers ‘where necessary’ (in other words if answer is not an integer)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

The ‘//’ does not allow

A

integers to turn to floating point numbers ‘where necessary’ (in other words if answer is not an integer)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

When using the integer division operator on floating point numbers, the division will be performed as if numbers were integer but result will be - (2)

A

floating point

e.g., print(3.0//2) in Python outputs the result of dividing 3.0 by 2 using integer division, resulting in 1.0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What happens when you try to add a string and an integer in Python

print(3 + “dlfkjdofd”),? - (2)

A

When you try to add a string and an integer in Python, you get a exception (error) TypeError because Python does not support adding different types together.

In the given example, print(3 + “dlfkjdofd”), Python raises an exception because you cannot concatenate a string and an integer directly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What type of error do you encounter when trying to add a string and an integer in Python?

A

When trying to add a string and an integer in Python, you encounter a TypeError.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What are collections of data in Python?

A

Collections of data in Python are structures designed to store multiple pieces of information.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What are the different types of collections of data in Python? - (3)

A
  1. Lists
  2. Tuples
  3. Dictionaries
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What are lists - (2)?

A

A list is a collection of data that is ordered and changeable.

It allows you to store multiple items in a single variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is the main difference between a list and a dictionary in Python?

A

The main difference between a list and a dictionary in Python is that a list is ordered and accessed by index, while a dictionary is unordered and accessed by key.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

How are elements accessed in a list compared to a dictionary in Python?

A

In a list, elements are accessed by their index position, starting from 0. In a dictionary, elements are accessed by their key.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What are member functions in Python? - (2)

A

Member functions are built-in functions specific to a data structure that allow operations to be performed on that data.

They are called using the syntax: dataStructure.functionName(argument1, …).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is the purpose of the append() member function in Python lists?

A

The append() member function adds a single value to the end of a list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

We can use append() many times to add many

A

elements to a list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What happens when you append a list to another list in Python?

A

When you append a list to another list using the append() member function, the entire second list becomes a single element of the first list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What will be the output of print(my_main_list) after appending my_other_list to it?

my_main_list = [1, 2, 3]
my_other_list = [10, 20]
my_main_list.append(my_other_list)

  • (2)
A

The output of print(my_main_list) will include my_other_list as a single element within my_main_list, preserving its structure

Output: [1, 2, 3, [10, 20]] and 4

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What is the difference between using .append() and .extend() to add elements from one list to another in Python? - (2)

A

When using .append(), the entire second list is added as a single element to the first list.

In contrast, when using .extend(), each element of the second list is added individually to the first list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What does it mean for Python to be a 0-indexed language?

A

In Python, being a 0-indexed language means that the first element in any sequence, including lists, is referred to as the “zeroth” element, and indexing starts from 0 rather than 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

How do you access individual elements of a list in Python?

A

Individual elements of a list in Python are accessed using square brackets [], with the index of the desired element inside the brackets.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What does the code my_new_list[2] = ‘Hello’ do?

my_new_list = [‘ant’, ‘bear’, 10, 20]

print(my_new_list)

my_new_list[2] = ‘Hello’

print(my_new_list)

A

The code my_new_list[2] = ‘Hello’ replaces the third element in the list my_new_list with the string ‘Hello’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

The square bracket indexing syntax in lists can also be used to modify

A

an element in a list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

note that Python wraps

A

indexing around with negative numbers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

How can you access elements from the end of a list in Python? - (2)

A

In Python, you can access elements from the end of a list using positive indices or by using negative indices.

For example, -1 refers to the last element, -2 refers to the second-to-last element, and so on.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What is the output of the code snippet provided?

print(my_new_list[-1]) do? - (2)

my_new_list = [‘ant’, ‘bear’, 10, 20]

print(my_new_list[-1])

print(my_new_list[-2])

A

20
10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What does the indexing notation [start:stop] in Python lists mean? - (2)

A

The indexing notation [start:stop] in Python lists is used to extract multiple elements from a list.

It specifies a range of indices from the start index (inclusive) to the stop index (exclusive), and returns a sublist containing the elements within that range.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

The indexing notation for extracting multiple elements of list uses a

A

colon ‘:’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

The indexing notation for extracting multiple elements of list uses a colon and its pattern is

A

[start:stop]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

as Python is 0-indexed and end-points are exclusive bold text, the element

A

which has the last number will not be included

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

Explain the output of the given code snippet.

my_new_list = [‘ant’, ‘bear’, 10, 20]

Extract 1:3, meaning elements 1 and 2. Print the data and the length
print(my_new_list[1:3])
print(len(my_new_list[1:3]))
print(type(my_new_list[1:3]))

A

The code extracts elements at index 1 and 2 from my_new_list, prints the extracted elements ([‘bear’, 10]), their length (2), and their data type (<class ‘list’>).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Flashcard 3:
Missing start parameter in list slicing

my_new_list = [‘ant’, ‘bear’, 10, 20]

If we miss out the start parameter, the beginning of the list is presumed
print(my_new_list[:2]) # assumes start parameter is 0

Explain the output of the given code snippet – (2)

A

The code slices my_new_list from the beginning up to index 2 (exclusive), effectively extracting elements at index 0 and 1.

It prints [‘ant’, ‘bear’], assuming the start parameter as 0 when not explicitly provided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

Missing stop parameter in list slicing

my_new_list = [‘ant’, ‘bear’, 10, 20]

If we miss out the stop parameter, the end of the list is presumed
print(my_new_list[2:]) # assuming going right at end, 0 , 1, 10, 20

Describe the output of the given code snippet. - (2)

A

The code slices my_new_list from index 2 to the end, effectively extracting elements starting from index 2 to the end of the list.

It prints [10, 20], assuming the stop parameter is at the end of the list when it’s not explicitly provided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Using the same number as start and stop in list slicing - (2)

python
Copy code
my_new_list = [‘ant’, ‘bear’, 10, 20]

If we use the same number as start and stop, we end up with an empty list
print(my_new_list[1:1]) # ‘[]’

What is the output of the given code snippet and why?

A

The code attempts to slice my_new_list from index 1 to index 1, resulting in an empty list [].

This happens because when the start and stop parameters are the same, no elements are included in the slice.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Assigning sliced data to a variable

my_new_list = [‘ant’, ‘bear’, 10, 20]

Extract 0:2, meaning elements 0 and 1. Put in a variable
my_data = my_new_list[0:2]

print(my_data)

What does the given code snippet do? - (2)

A

The code extracts elements at index 0 and 1 from my_new_list and assigns them to a new variable my_data.

It then prints the content of my_data, which would be [‘ant’, ‘bear’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What does step parameter indicate in list slicing? [start:stop:step] - (2)

A

The step parameter in list slicing indicates the increment between each index when extracting elements from a list.

It allows for skipping elements based on the specified step size.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]

Extract every other item starting at index 1 and finishing at index 5
print(animals[1:5:2]) # start at 1 and finish at 5, exclude 5, go in steps of 2

Describe the output of the given code snippet.

A

The code extracts every other item from index 1 to index 5 (exclusive) in the animals list and prints the result: [‘bear’, ‘deer’].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]

We can miss out the start index and get everything from the start of the list
print(animals[:5:2])

What does the code snippet do, and what is its output? - (2)

A

The code slices animals from the beginning (0
-assumed) up to index 5 (exclusive) in steps of 2, effectively extracting every other item from the start of the list.

It prints the result: [‘ant’, ‘cat’, ‘elk’].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]

We can miss out the stop index and get everything to the end of the list
print(animals[1::2])

Question: Explain the output of the given code snippet. - (2)

A

he code slices animals from index 1 to the end of the list in steps of 2, effectively extracting every other item starting from index 1.

It prints the result: [‘bear’, ‘deer’, ‘frog’, ‘horse’].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]

We can even miss out the start and stop indices
print(animals[::2])

What does the code snippet do, and what is its output? - (2)

A

The code slices animals from the beginning to the end of the list in steps of 2, effectively extracting every other item from the list.

It prints the result: [‘ant’, ‘cat’, ‘elk’, ‘goose’].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]

And we can use any step we like, including negative numbers
print(animals[::-1]) # printing animals in reverse order

Describe the output of the given code snippet.

A

The code prints animals list in reverse order by slicing it with a step of -1: [‘horse’, ‘goose’, ‘frog’, ‘elk’, ‘deer’, ‘cat’, ‘bear’, ‘ant’].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

Describe what the given code snippet does - (2)

my_special_number=[‘1’,’5’,’2’,’7’,’9’,’2’,’3’,’8’,’8’]
numbers_requested=my_special_number[0:8:3] # or write it as [0::3] or [::3], same output, or write in reverse do ‘[::-1]’
print(numbers_requested)

A

The code extracts every third number from the list my_special_number, starting with the first number, and prints the result: [‘1’, ‘7’, ‘3’].

my_special_number can be written as as [0::3] or [::3],

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

Some banks ask for a small subset of your ‘special number’ for verification purpose. Change the code below so that it prints out every third number starting with the first one.

my_special_number=[‘1’,’5’,’2’,’7’,’9’,’2’,’3’,’8’,’8’]
numbers_requested=my_special_number[xxxxx]
print(numbers_requested)

A

my_special_number=[‘1’,’5’,’2’,’7’,’9’,’2’,’3’,’8’,’8’]
numbers_requested=my_special_number[0:8:3] # or write it as [0::3] or [::3], same output,
print(numbers_requested)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

What are the two main ways of removing elements of a list? - (2)

A
  1. Pop
  2. Del statement
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

Explain the functionality of the .pop() method when removing items from a list - (2)

A

The .pop() method in Python removes and returns the element at the specified index from a list.

It modifies the original list by removing the element and optionally allows you to storing the removed element in another variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

Describe the purpose of the del statement when removing items from a list - (2)

A

The del statement in Python is used to remove an item or slice from a list by specifying its index.

It directly modifies the original list by deleting the specified item, and it does not return the removed item as .pop() does.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

Describe what the given code snippet does using the .pop() method - (3)

my_list = [10, 20, 30, 40, 50]

print(my_list)

thing_removed = my_list.pop(2) #stores thing deleted which is 30
print(thing_removed) # prints out 30

print(my_list) # prints out list with ‘30’ deleted

A

The code removes the element at index 2 from the list my_list using the .pop() method.

It stores the removed element in the variable thing_removed which is ‘30’ and prints it.

Then, it prints the updated list (my_list) without the removed element ‘[10,20,40,50]’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

Describe what the given code snippet does using the del statement - (2)

my_list = [10, 20, 30, 40, 50]

del my_list[0] #or use del statement to delete first element of list ‘10’

print(my_list) #prints new list with 10 removed

A

The code uses the del statement to remove the element at index 0 from the list my_list, which is ‘10’.

It then prints the updated list of my_list without the removed element: ‘[20,30,40,50]’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

Question: Explain the functionality of the sorted function when sorting a list - (2)

A

The sorted function in Python returns a new list containing the elements of the original list sorted in ascending order.

It does not modify the original list, instead, it creates a new sorted list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

Describe the purpose of the .sort() method when sorting a list.

A

he .sort() method in Python sorts the elements of a list in ascending order in-place, meaning it directly modifies the original list.

It does not return a new list but instead sorts the elements within the original list itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

Describe what the given code snippet does using the sorted function - (3)

my_num_list = [50, 40, 10, 20]
my_sorted_list = sorted(my_num_list)

print(my_sorted_list)
print(my_num_list)

A

The code snippet sorts the list my_num_list using the sorted function and stores the sorted result in the variable my_sorted_list which is [10,20,40,50]

It then prints both the sorted list of [10,20,40,50] and the original list [50,40,10,20]

The original list remains unchanged after sorting.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

Describe what the given code snippet does using the .sort() method - (3)

my_num_list = [50, 40, 10, 20]
my_num_list.sort()
print(my_num_list)

A

The code snippet sorts the list my_num_list in-place using the .sort() method which is [10,20,40,50]

It directly modifies the original list, sorting it in ascending order.

Then, it prints the sorted list which is [10,20,40,50]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

How would you define a tuple? - (2)

A

A tuple is an ordered collection of elements, similar to a list.

However, tuples are immutable, meaning their contents cannot be changed after creation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

What are the similarities and differences between tuples and lists? - (4)

A

Both tuples and lists can store multiple elements and can be indexed and sliced.

However, tuples are immutable meaning you can’t add or remove items to/from a tuple, while lists are mutable.

Tuples are typically used for fixed collections of data, while lists are used for collections that may need to be modified.

Differences between tuples and lists are tuples are defined using ‘()’ whereas lists use ‘[]’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

We can create an empty tule using

A

round brackets ‘()’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

What is the output of the given code snippet? - (4)

a = ()

Printing the type and content of the tuple
print(type(a))
print(a)

A

The output will display the type of the variable a, which is tuple, and an empty tuple ().

<class ‘tuple’>
()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

The problem with creating an empty tuple is that

A

they cannot be changed - this therefore means that it will remain empty forever!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

More commonly, we would create a tuple with

A

existing content:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

What is the output of the given code snippet?

Creating a tuple with existing content
a = (1, 2, 3)

Printing the tuple
print(a)

A

The output will display the tuple (1, 2, 3) containing the numbers 1, 2, and 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

With tuples you can perform tuple operations like - (2)

A

extract items from tuple e.g., my_tuple[1]

and count length of type using len()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q

What is the output of this code below?

Accessing an item in a tuple and getting its length
my_tuple = (5, 10, 15)

print(my_tuple[1]) # Accessing the second item in the tuple
print(len(my_tuple)) # Getting the length of the tuple

A

10
3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

What happens when you attempt to modify an item in a tuple?

A

Modifying an item in a tuple will raise a TypeError exception since tuples are immutable and do not support item assignment.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

What is output of this code?

Attempting to modify an item in a tuple (will raise a TypeError exception)
my_tuple = (5, 10, 15)

my_tuple[0] = 100 # This will raise a TypeError exception

A

TypeError: ‘tuple’ object does not support item assignment

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

if you have a tuple which you need to modify, you can cast it to (turn it into) a list and back again. This does not modify

A

the first tuple, but creates a new one with new content:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

What is output of this code?

my_orig_tuple = (1, 2, 3, 4)

my_tmp_list = list(my_orig_tuple)

my_tmp_list[0] = 100

my_new_tuple = tuple(my_tmp_list)

print(my_orig_tuple)
print(my_new_tuple)

A

(1, 2, 3, 4)
(100, 2, 3, 4)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

What does the provided code snippet do? - (2)

my_orig_tuple = (1, 2, 3, 4)
my_tmp_list = list(my_orig_tuple)
my_tmp_list[0] = 100
my_new_tuple = tuple(my_tmp_list)
print(my_orig_tuple)
print(my_new_tuple)

A

The code snippet converts the original tuple my_orig_tuple into a list my_tmp_list, modifies the first element of the list to 100, and then converts the modified list back into a tuple my_new_tuple.

It finally prints both the original and modified tuples.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
92
Q

What is the purpose of loops in programming?

A

Loops in programming are used to automate repetitive tasks, making coding more efficient and reducing manual effort

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

Examples of using lops to repeat simple operations that would be useful like

A

making lots of stimuli for an experiment or analyzing lots of different datasets.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

Explain general structure of for loop - (4)

A

LOOPVARIABLE (which can be named whatever you want) will be set to the first item in LIST_OF_THINGS_TO_ITERATE_OVER.

The code which is indented (just a comment in this case) will then run.

Once all of the code which is indented has been run, the loop will go back to the top, LOOPVARIABLE will be set to the second item in LIST_OF_THINGS_TO_ITERATE_OVER and all of the indented code will run again.

This will repeat for each element in LIST_OF_THINGS_TO_ITERATE_OVER.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
95
Q

Describe this code -(4)

for t in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print(“Hello!”)
print(“Hello”,t)

A

In the given code snippet, the for loop iterates over each element in the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

During each iteration, the loop variable ‘t’ takes on the value of the current element in the list.

Within the loop, the first print statement prints “Hello!” for each iteration, resulting in the message being printed 10 times.

The second print statement includes the value of ‘t’, causing “Hello” to be printed along with the current value of ‘t’ for each iteration, producing output where “Hello” is printed 10 times followed by “Hello” and the numbers 1 through 10 respectively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
96
Q

What is the output of this code?

for t in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print(“Hello!”)
print(“Hello”,t)

A

Hello!
Hello 1
Hello!
Hello 2
Hello!
Hello 3
Hello!
Hello 4
Hello!
Hello 5
Hello!
Hello 6
Hello!
Hello 7
Hello!
Hello 8
Hello!
Hello 9
Hello!
Hello 10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q

To ident code inside loop you can either use

A

4 spaces or tab

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

Create a for loop that produces 1-10

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q

Output of this code and explain - (4):

A

Meaning:

print(x,x**2) is idented within for loop so we print each element in a list followed by itself squared:

In print(x.5) is not idented within for loop and identation is different from print(x,x2) so left the for loop

print(x,x**.5) square root the last element of the list (‘x’) which is 40 and prints “Done”

Output:
10 100
20 400
30 900
40 1600
6.324555320336759
Done

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

Explain this code and give its output:

A

Meaning:
The loop iterates over each element in the list my_list.

For each iteration, it prints “Hello”.

It computes the square of the current element (x) and stores it in y.

It then prints both the current element (x) and its square (y).

Output:
Hello
10 100
Hello
20 400
Hello
30 900
Hello
40 1600

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
101
Q

You can run any code you want inside of a loop. One thing which you should not do however, is to - (2)

A

delete an item in a list whilst you are looping over the list.

This will cause hard to find problems in your code and almost certainly not do what you want

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

Write a code that has a list 10-100 stored in my_list = [] var

For loop that loops over that list and prints out value of x and its x squared and its square root on each iteration

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
103
Q

What is output of the code?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
104
Q

What is nested for loops? - (3)

A

situation where one for loop is contained within another for loop.

This means that one loop runs inside another loop.

Each time the outer loop runs once, the inner loop can potentially run multiple times, depending on its own iteration behavior.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
105
Q

For nested for loops it is

A

important to follow the indentation carefully reading this code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
106
Q

What is range() in Python? - (2)

A

built-in function used to generate a sequence of numbers.

It’s commonly used in loops to iterate over a specific range of numbers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
107
Q

3 ways to use/call range() function - (3)

A
  1. range(stop)
  2. range(start,stop)
  3. range(start,stop,setp)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
108
Q

What is range(stop)

A

This generates a sequence of numbers starting from 0 up to (but not including) the specified stop value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
109
Q

What is range(start,stop)?

A

This generates a sequence of numbers starting from start up to (but not including) the stop value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
110
Q

What is range(start,stop,step) - (2)

A

This generates a sequence of numbers starting from start up to (but not including) the stop value, with a specified step size between each number.

The step parameter is optional and defaults to 1 if not provided

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
111
Q

In python, all stop-style parameters are exclusive; i.e. - (3)

A

they are not included in the list which is returned.

This means that if we ask for range(0, 4), we will get the numbers 0, 1, 2, 3.

Forgetting how this works is a common source of bugs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
112
Q

What will this output give you?

x = range(5)
print(type(x))
print(x)

A

<class ‘range’>
range(0, 5)
print the generator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
113
Q

What will this code give you?

x = list(range(5))
print(type(x))
print(x)

0 it is convert to list and print

A

<class ‘list’>
[0, 1, 2, 3, 4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
114
Q

What will this code give you?

x = list(range(1, 500))
print(x)

A

[1, 2, 3, 4, 5, …., 499]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
115
Q

The step parameter in range… - (2)

A

sets the increment or decrement.

Setting this to be negative lets us count backwards.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
116
Q

What will these code give? - (3)

A

[1, 3]
[5, 4, 3, 2, 1]
[4, 3, 2, 1, 0]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
117
Q

range function generates a sequence of integer numbers within a specified range.

If you want to use floating point numbers then

A

use the arange function from the numpy module – we will cover this in a future session.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
118
Q

Sample exam questions
Q1.1
name = ‘Alice”
# What is wrong with this line of code? - (3)

A

The quotes do not match.

Either use all single quotes or all double quotes.

For example, name=’Alice’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
119
Q

Q1.2
age = ‘23’
print(age + 2)
# Why does this code raise an error? - (2)

A

age is a string variable but you are adding an integer to it.

Variable types have to match when doing arithmetic

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
120
Q

Q1.3
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits[3] = ‘orange’
# What is incorrect with this code? - (2)

A

The list only has 3 entries but you are trying to access the fourth one.

Python indexing starts at zero.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
121
Q

Q1.4
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)
# What will this print, and why might it confuse a beginner? - (2)

A

This will concatenate the lists: [1,2,3,4,5,6]

You might be expecting it to add them element by element [5,7,9], or even include list2 as a member of list 1 [1,2,3,[4,5,6]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
122
Q

Q1.5
my_tuple = (1, 2, 3)
my_tuple[1] = 4
# What concept does this example illustrate, and what is the mistake? - (3)

A

You cannot change tuples once you make them.

Here you are trying to alter the second element in the tupe.

You can’t.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
123
Q

Q1.6
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(num)
# Identify and correct the mistake in this loop - (2)

A

The variable ‘num’ is not defined. That line should read

print(number)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
124
Q

for i in range(5):
print(“Number is: “, i)
# What will be the output of this loop, and what common misunderstanding might this clarify? - (2)

A

0,1,2,3,4

It will demonstrate that python ranges are zero indexed and exclusive (they start at zero and do not include the last number)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
125
Q

for i in range(3):
for j in range(2):
print(i, j)
# What will be the output of this nested loop, and what concept does it illustrate? - (3)

A

0 0

0 1

1 0

1 1

2 0

2 1

Ranges start at zero and exclude the highest element. Also loop blocks are defined by indentation.

And nested loops are evaluated from the deepest loop out.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
126
Q

name = “John”
greeting = “Hello, name!”
print(greeting)
# Why doesn’t this code snippet print “Hello, John!”? - (3)

A

The variable ‘name’ and the word ‘name’ inside the string are different things.

You could write
print(“Hello”,name)

To get the right answer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
127
Q

def multiply(x, y):
return x * y
print(multiply(2))
# What error will this code produce and why?

A

function looks like it takes two arguments (x and y) but you are only providing one argument when you call it (2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
128
Q

%pwd
%cd ..
%ls
# Explain what each of these ‘magic’ / or ‘shell’ commands does - (3)

A

pwd = print the working directory

cd = change directory (in this case to the one above)

ls = list the contents of the current directory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
129
Q

my_string = “Hello, World!”
print(my_string[-1])
What will be printed when executing this code, and what concept does it illustrate? - (2)

A

The code will print the last character of the string, which is “!”.

This illustrates the concept of negative indexing in Python, where -1 refers to the last element, -2 refers to the second last, and so on.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
130
Q

my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
What output will this code produce, and why? - (3)

A

The code will print [3, 4].

This is because slicing with the notation [start:stop] returns a sublist containing elements from index start up to (but not including) index stop.

In this case, it extracts elements at indices 2 and 3 from my_list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
131
Q

my_list = [1, 2, 3, 4, 5]
my_list[1:4] = [8, 9, 10]
print(my_list)
What will the final contents of my_list be after executing this code? - (2)

A

The final contents of my_list will be [1, 8, 9, 10, 5].

This code replaces elements at indices 1, 2, and 3 in my_list with the elements [8, 9, 10], resulting in the modified list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
132
Q

my_list = [‘apple’, ‘banana’, ‘cherry’]
print(my_list[::-1])
What will be printed when running this code, and what is the purpose of the slicing notation used? - (2)

A

The code will print [‘cherry’, ‘banana’, ‘apple’], which is the reversed version of my_list.

The slicing notation [start:stop:step] with step as -1 is used to reverse the order of elements in the list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
133
Q

What is a modern and preferred method for combining data and strings for output formatting in Python, beside using commas?

A

Using f-strings, which provide a more elegant and concise way to format output by embedding variables directly into strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
134
Q

What does f-strings stand for in Python?

A

An f-string, short for “formatted string literal,”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
135
Q

How do you create an f-string in Python?

A

Prefix the string with the letter ‘f’, (just before te quote marks) then use curly braces {} to enclose the variable names you want to include in the string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
136
Q

What happens when an f-string is evaluated in Python?

A

When an f-string is evaluated, Python replaces the expressions enclosed within curly braces {} with their corresponding values at runtime, resulting in a formatted string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
137
Q

Explain this code - (4)

A

the variable my_variable is assigned a value of 100.

Then, an f-string named foo is created, where the value of my_variable (100) is embedded within the string using curly braces {} .

When foo is printed, it will display the string “My variable contains the value 100”.

The ‘f’ prefix before the string indicates that it is an f-string, and Python replaces the expression {my_variable} within the string with the value of the variable during runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
138
Q

Example of adding multiple variables in f-string in Python

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
139
Q

How can you force a value to occupy a certain amount of space using f-strings in Python? -

A

By adding a colon followed by the desired width after the variable name inside curly braces {} in the f-string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
140
Q

What would be output of this code?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
141
Q

Q: Explain the purpose of the following f-string

myvar = ‘Test’
print(f’==={myvar:20}===’): - (3)

A

The output ===Test === consists of the string “===” at the beginning and end, with the variable myvar (“Test”) occupying 20 spaces.

Output is:
===Test ===

Since the word “Test” has only 4 characters, it is followed by 16 spaces to fill the specified width.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
142
Q

How to change allignment of variable in f-string?

A

You can change the alignment by adding a character before the width number inside curly braces {} in the f-string:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
143
Q

What is the default alignment behavior of a string in f-strings?

A

By default, strings are left-centered in the space provided within an f-string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
144
Q

What is the output of the following f-string?

A

The output would be ===TestText ===, with the string “TestText” occupying 8 characters and the remaining 12 spaces filled with whitespace to the right, resulting in left alignment of string “TestText” within the specified width.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
145
Q

What is the output of the following f-string?

A

The output would be
‘=== TestText===’, with the string “TestText” occupying 8 characters and the remaining 12 spaces filled with whitespace to the left, resulting in right alignment of string “TestText” within the specified width.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
146
Q

What is output of the following f-string? - (2)

A

The output would be:
=== TestText ===

with the string “TestText” occupying 8 characters and evenly distributed whitespace of 12 spaces on each side, resulting in center alignment of string “TestText” within the specified width.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
147
Q

How does f-string handle space expansion when the inserted string is longer than the specified width?

A

F-strings expand the space to fit the entire string when it is longer than the specified width

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
148
Q

What is the output of this code? - (3)

A

variable myvar containing the string ‘TestTextVeryLong’ is inserted into the f-string with a specified width of 5 characters

Despite the specified width being only 5 characters, Python expands the space to accommodate the entire string when necessary

So output becomes: 
===TestTextVeryLong===
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
149
Q

What is the output of the code print(f’==={myvar:^7}===’) where myvar = 500000090? - (2)

A

The output is ===500000090===, which shows the large number 500000090 centered within a 7-character space.

Since the number itself is longer than the specified width, the f-string expands the space to accommodate the entire number, ensuring no truncation occurs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
150
Q

What is the purpose of zero-padding integers in Python (using f-strings with numbers)? - (3)

A

Zero-padding integers involves adding leading zeros to the integer to ensure it fills a specific width.

This adding 0s before the number to fill the space rather than spaces

This is often useful when naming files to make sure that they sort correctly (e.g. if using participant numbers).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
151
Q

What is the output of the code print(f’{mynum:03}’) where mynum = 5? - (2)

A

The output is 005, which demonstrates the integer 5 zero-padded to fill a width of 3 characters

Since 5 is 1 character, it adds 3 zeros before to fill the width of 3 characters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
152
Q

How can you control the number of decimal places in floating point numbers using f-strings?

A

You can control the number of decimal places in floating point numbers by specifying the desired number of digits after the decimal point in the format specifier, such as {myval:10.4f}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
153
Q

What is the output of
print(f’=={myval:10.4f}==’)
where myval = 10.219? - (3)

A

The output is
== 10.2190==

This displays the floating-point number 10.219 with a total width of 10 characters, including three leading spaces followed by the number with four digits after the decimal point.

The zero at the end is added to fill the specified precision of four decimal places.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
154
Q

What is the output of print(f’=={myval:7.2f}==’)

where myval = 10.219? - (3)

A

The output is == 10.22==. This result is achieved because the formatting specifier 7.2f is used, indicating that the number should be displayed with a total width of 7 characters, including two digits after the decimal point.

Python rounds the number 10.219 to 10.22 to meet the specified formatting requirements - width and precision of decimal places

Additionally, two leading spaces are added to ensure that the number is properly aligned within the specified width.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
155
Q

What happens if you ask for fewer decimal places in f-strings in Python?

A

Python rounds the numbers to the specified number of decimal places

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
156
Q

What character is used for scientific notation in f-strings?

A

The e formatting character is used for scientific notation in f-strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
157
Q

How is scientific notation represented using the “e” formatting character? - (2)

A

Scientific notation using the “e” formatting character is expressed as a number multiplied by 10 raised to a power, denoted by “e”.

For example, “1.0e-6” represents 1.0 × 10^(-6).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
158
Q

What is the output of the code print(f’==={myval:e}===’)

where myval = 0.000001?

A

The output is “===1.000000e-06===”, which represents the number 0.000001 in scientific notation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
159
Q

How can you control the number of decimal places in scientific notation when using the “e” formatting character in f-string? - (2)

A

You can control the number of decimal places in scientific notation by specifying the desired precision after the colon, similar to using the “f” formatting character.

For example, print(f’==={myval:.1e}===’) will display the number in scientific notation with one decimal place.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
160
Q

What happens if the provided number of spaces is not sufficient for the number when using the “e” formatting character?

A

If the provided number of spaces is not sufficient for the number when using the “e” formatting character, extra spaces will be added to accommodate the full representation of the number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
161
Q

What is the purpose of specifying “.1e” in the code print(f’==={myval:.1e}===’)?

A

Specifying “.1e” limits the number of decimal places to one in the scientific notation representation of the number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
162
Q

What is the output of the code print(f’==={myval:.1e}===’) where myval = 0.000001? - (3)

A

The output is ===1.0e-06===.

This notation represents the number 0.000001 in scientific format, where “1.0” denotes the main numerical value, “e” signifies “times ten to the power of”, and “-06” indicates the exponent, signifying that the number is multiplied by 10 to the power of -6.

The “.1” specifier in the f-string limits the number of decimal places to one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
163
Q

What is the output of the code print(f’==={myval:10.1e}===’) where myval = 0.000001? - (4)

A

he total width specified is 10 characters.

The scientific notation 1.0e-06 itself takes up 7 characters (1.0e-06).

To ensure right alignment within the total width of 10 characters, three additional spaces are added before the number.

Therefore, there are three spaces before the number 1.0e-06 to make up the total width of 10 characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
164
Q

What does ‘d’ mean in f-string formatting?

A

In f-string formatting, ‘d’ is used to specify that the value should be formatted as an integer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
165
Q

What is the purpose of the f-string expression {part_id:03d} in the code - (2)

print(f’| P{part_id:03d} | {num_trials:3d} | {rt:8.3f} |’)?

A

The expression {part_id:03d} formats the integer value part_id with leading zeros to make it three characters wide.

For example, if part_id is 1, it will be formatted as ‘P001’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
166
Q

What is the purpose of the f-string expression {num_trials:3d} in the code print(f’| P{part_id:03d} | {num_trials:3d} | {rt:8.3f} |’)? - (2)

A

The expression {num_trials:3d} right-aligns the integer value num_trials within a minimum width of three characters.

If the integer has fewer than three digits, it will be padded with spaces on the left.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
167
Q

What is the purpose of the f-string expression {rt:8.3f} in the code print(f’| P{part_id:03d} | {num_trials:3d} | {rt:8.3f} |’)? - (2)

A

The expression {rt:8.3f} formats the floating-point number rt with a total width of 8 characters, including three decimal places.

It ensures that the number is right-aligned within the specified width.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
168
Q

What is output of the code?

A

P001 | 100 | 100.210 |

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
169
Q

Explain this code - (2)

A

This code creates a table displaying participant information using three lists: part_ids for participant IDs, trial_counts for the number of trials each participant did, and rts for their reaction times.

It iterates over the indices of the part_ids list using a for loop. Within the loop, it prints a formatted table line for each participant, where their ID is zero-padded to three digits, the trial count is right-aligned with three spaces, and the reaction time is displayed with three decimal places, using f-strings for formatting.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
170
Q

What is the purpose of the input function in Python? - (3)

A

The input function in Python is used to request information from the user.

It takes a string argument, known as the “prompt,” which is displayed to the user, prompting them to input some data.

Once the user provides input, the input function returns the data entered by the user.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
171
Q

What is the data type of the value returned by the input function? - (2)

A

the input() function returns a string data type.

This means that regardless of what the user inputs (whether it’s numbers, letters, or symbols), it will be treated as a string unless explicitly converted to another data type using functions like int(), float(), etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
172
Q

What is the output of the following code snippet? - (3)

data = input(‘Enter a word: ‘)
print(type(data))
print(data)

A

The output of the code snippet depends on the user input.

When prompted to enter a word, if the user enters “zebra,”

the output will be:
<class ‘str’>
zebra

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
173
Q

What is output? if user input is 10

A

Enter a number: 10
‘<class ‘str’>’
10
‘<class ‘int’>’
10
20

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
174
Q

Explain this code if user input is 10 - (2)

A

The user input is initially of type string (str), but after casting it to an integer using int(), its type becomes int.

When the value is multiplied by 2, the result is 20

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
175
Q

Write a script which inputs two numbers. The first should be a number to count from, the second a number to count to. Once the user has input the numbers, you should print - using a loop - all of the numbers between the starting and ending number (inclusive; think carefully about this), one per line.

An example run of the program might look like this:

Starting number: 5

Ending number: 10

5
6
7
8
9
10

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
176
Q

What does the following Python code do? - (3)

first_number = int(input(‘Enter a number to start: ‘))
second_number = int(input(‘Enter a number to end: ‘))

for x in range(first_number, second_number + 1):
print(x)

A

The code begins by prompting the user to input two numbers, which are then converted to integers using the int() function.
It then uses a for loop to iterate over the range from first_number to second_number + 1.

The +1 ensures that the range includes the second_number.
Inside the loop, each number in the range is printed on a separate line.

This allows the loop to print all numbers from first_number to second_number, inclusive.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
177
Q

What is a dictionary in Python?

A

A dictionary in Python is a collection of key-value pairs, where each key is linked to a corresponding value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
178
Q

How are dictionaries defined in Python? - (2)

A

Dictionaries are defined with curly brackets and key-value pairs,

for example: my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
179
Q

Unlike real dictionaries where one word can have many meanings, in Python dictionaries:

Each key can only have a

A

a single value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
180
Q

How do we create an empty dictionary in Python?

A

We create an empty dictionary in Python using curly braces {}.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
181
Q

What is the type of an empty dictionary in Python?

A

The type of an empty dictionary in Python is dict.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
182
Q

What type of brackets are used for indexing in Python dictionaries?

A

Python uses square brackets [] for indexing in dictionaries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
183
Q

Explain the following Python code - (2)

my_dict = {}

print(my_dict)
print(type(my_dict))

A

This code initializes an empty dictionary named my_dict using curly braces {}.

It then prints the contents of the dictionary, which is an empty dictionary {}, and its type, which is <class ‘dict’>.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
184
Q

What is output of this code? - (2)

my_dict = {}

print(my_dict)
print(type(my_dict))

A

{}
<class ‘dict’>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
185
Q

How to add items to a dictionary in Python with an example: - (4)

A

Items can be added to a dictionary in Python using square bracket notation.

Specifically, you assign a value to a key within the dictionary using square brackets.

For example:
my_dict = {}
my_dict[‘mykey’] = 20

This code snippet creates an empty dictionary my_dict and then assigns the value 20 to the key ‘mykey’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
186
Q

What is the output of the code below?

my_dict = {}
my_dict[‘mykey’] = 20
my_dict[‘anotherkey’] = 100
my_dict[‘Averylongkeyblahblahblah’] = 1
my_dict[‘Navin R Johnson’] = ‘253.125 Elm St’
print(my_dict)

A

{‘mykey’: 20, ‘anotherkey’: 100, ‘Averylongkeyblahblahblah’: 1, ‘Navin R Johnson’: ‘253.125 Elm St’}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
187
Q

Explain this code - (2)

my_dict = {}

my_dict[‘mykey’] = 20
my_dict[‘anotherkey’] = 100
my_dict[‘Averylongkeyblahblahblah’] = 1
my_dict[‘Navin R Johnson’] = ‘253.125 Elm St’

print(my_dict)

print(f’There are {len(my_dict)} keys in the dictionary’)

A

This code initializes an empty dictionary my_dict and then adds several key-value pairs to it using square bracket notation.

After printing the dictionary, it also displays the number of keys in the dictionary using the len() function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
188
Q

What will be the output of this code? - (2)

my_dict = {}

my_dict[‘mykey’] = 20
my_dict[‘anotherkey’] = 100
my_dict[‘Averylongkeyblahblahblah’] = 1
my_dict[‘Navin R Johnson’] = ‘253.125 Elm St’

print(my_dict)

print(f’There are {len(my_dict)} keys in the dictionary’)

A

{‘mykey’: 20, ‘anotherkey’: 100, ‘Averylongkeyblahblahblah’: 1, ‘Navin R Johnson’: ‘253.125 Elm St’}

There are 4 keys in the dictionary

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
189
Q

As explained above, we can only have one instance of a single key in a given dictionary at any one time. So, what happens when we try to add a key more than once?

What happens when we try to add a key more than once in a dictionary in Python?

A

When we try to add a key more than once in a dictionary, the existing value associated with that key is replaced by the new value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
190
Q

Example of we try to add a key more than once in a dictionary, the existing value associated with that key is replaced by the new value.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
191
Q

What is output of this code? - (2)

A

{‘mykey’: 20}
{‘mykey’: 2000000}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
192
Q

Explain this code - (6)

A

In this code, we start with an empty dictionary my_dict.

We add a key-value pair to the dictionary where the key is ‘mykey’ and the value is 20.

When we print the dictionary, it displays {‘mykey’: 20}.

Next, we attempt to add another value to the same key ‘mykey’, this time with the value 2000000.

However, since dictionaries in Python can only have unique keys, the existing value associated with ‘mykey’ is replaced by the new value.

Therefore, when we print the dictionary again, it shows {‘mykey’: 2000000}.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
193
Q

How do you extract individual values from a dictionary in Python? - (2)

A

To extract individual values from a dictionary in Python, you use square bracket notation with the key of the desired value.

It is the same index (square bracket) notation used to add entries and also same notation used to extract items in lists

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
194
Q

Example of extracting values in a dictionary

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
195
Q

What is the output of this code? - (2)

A

20
<class ‘int’>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
196
Q

Explain this code snippet - (3)

A

The code initializes an empty dictionary my_dict, then adds a key-value pair where the key is ‘mykey’ and the value is 20.

It extracts the value corresponding to the key ‘mykey’ using square bracket notation which is 20 and assigns it to the variable test_var.

Finally, it prints the value of test_var which is 20 and its type which is <class ‘int’>.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
197
Q

What happens if you try to extract a value using a key that does not exist in the dictionary?

A

you will get a KeyError exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
198
Q

Example of keyerror exception

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
199
Q

How can we extract a value from a dictionary without encountering a KeyError if the key does not exist?

A

We can use the .get() function in Python dictionaries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
200
Q

What does the .get() function return if the specified key does not exist in the dictionary?

A

By default, the .get() function returns None if the specified key does not exist in the dictionary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
201
Q

What is the output of this code? - (3)

A

1000
<class ‘NoneType’>
None

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
202
Q

What does this following code snippet demonstrate? - (4)

A

This code snippet demonstrates the creation of an empty dictionary my_dict, followed by adding a key-value pair to it which has a key of ‘mykey’ and value of 1000

Then an attempt is made to retrieve value associated with non-existent key ‘mykey_notthere’ using .get() and storing in variable ‘my_val’

Since no default value is provided, the function returns None.

Finally, the type and value of my_value are printed which is <class ‘NoneType’> and value is None

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
203
Q

Example of dictionary already having stuff in it

A

This requires use of : and , characters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
204
Q

How can items be deleted from a dictionary in Python?

A

As with lists, Items can be deleted from a dictionary in Python using either the .pop() or del functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
205
Q

What does the .pop() function return when used to delete an item from a dictionary?

A

The .pop() function returns the value of the deleted item.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
206
Q

What does the del function do when deleting items from a dictionary? - (2)

A

The del function in Python is used to remove an item with a specified key from a dictionary.

It deletes the key-value pair associated with the specified key from the dictionary

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
207
Q

Both pop and del functions in lists and dictionaries in general

A

deletes the key-value pair associated with the specified key from the dictionary

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
208
Q

What is the difference between using .pop() and del to delete items from a dictionary?

A

The .pop() function returns the value of the deleted item, while del does not return any value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
209
Q

What does this code snippet do? - (8)

A

This code snippet creates a dictionary called my_new_dict with two key-value pairs: ‘age’: 35 and ‘test_value’: 1000.

It then prints out contents of my_new_dict: {‘age’: 35, ‘test_value’: 1000}

It then demonstrates two methods for deleting items from the dictionary.

First, it uses the pop() function to remove the key ‘age’ from the dictionary my_new_dict .

The value associated with the key ‘age’ (35) is stored in the variable removed_value, which is then printed.

After removal, the dictionary my_new_dict is printed again {‘test_value’: 1000}, showing that the key-value pair ‘age’: 35 has been removed from the dictionary.

Next, it uses the del keyword to delete the key ‘test_value’ from the dictionary called my_new_dict.

Then the updated dictionary my_new_dict is printed which is indeed empty since both key-value pairs have been removed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
210
Q

What is the output of this code? - (4)

A

{‘age’: 35, ‘test_value’: 1000}
35
{‘test_value’: 1000}
{}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
211
Q

How can you check if a specific key exists in a dictionary in Python? - (2)

A

By using the in keyword

In which ‘key’ is in quotes followed by in keyword which is followed by dictionry name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
212
Q

An example of using in keyword in dictionaries

A

For example P1 in ages will return True if P1 is a key in ages

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
213
Q

What is the output of this code? - (2)

A

P1 is a key? : True
P1000 is a key? : False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
214
Q

What does the expression ‘P1000’ in ages return if ages is a dictionary containing keys ‘P1’: 35, ‘P2’: 38, ‘P3’: 21, ‘P4’: 28, ‘P5’: 33?

A

False, because there is no key ‘P1000’ in the ages dictionary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
215
Q

How do you print all the keys in a dictionary in Python? - (2)

A

To print all the keys in a dictionary named ages, you can use the keys() method like this: print(ages.keys()).

This method returns all the keys in the dictionary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
216
Q

Explain this code snippet - (3)

A

This code snippet creates a dictionary called ages with keys representing participant IDs and values representing their ages.

Then, it prints out the keys of the dictionary using the keys() method which gives: dict_keys([‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’])

Finally, it prints the type of the value returned by ages.keys(), which is <class ‘dict_keys’>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
217
Q

What is output of this code? - (2)

A

dict_keys([‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’])
<class ‘dict_keys’>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
218
Q

Although in this example the keys appear to be in order we entered them that is not guaranteed by Python and may need to

A

sort keys using sorted() function or sort() with Python dictionaries (don’t need to convert to list to sort them)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
219
Q

How can you convert dictionary keys/values into a list in Python?

A

You can convert the keys/values into a list by simply ‘casting’ (converting) the return value to the list type using list() function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
220
Q

Explain the following code snippet - (6)

A

It retrieves the keys from the dictionary ages using the keys() method.

It converts these keys into a list using the list() function.

It assigns the resulting list to the variable my_keys.

It prints the datatype of my_keys using type() which is <class ‘list’>

It prints the contents of my_keys: [‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’]

It prints the length of my_keys using len() which is 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
221
Q

What is output of this code? - (3)

A

<class ‘list’>
[‘P1’, ‘P2’, ‘P3’, ‘P4’, ‘P5’]
5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
222
Q

How do you retrieve just the values from a dictionary in Python?

A

Using the .values() function, which returns all the values in the dictionary

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
223
Q

In Python dictionaries, you cannot directly access a key by

A

its value will return exception error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
224
Q

What does the following Python code snippet do? - (4)

A

Has a dictionary age which has participants’ IDs as keys and their ages as values: ages = {‘P1’: 35, ‘P2’: 38, ‘P3’: 21, ‘P4’: 28, ‘P5’: 33}

This code snippet retrieves all values from the ages dictionary using the .values() function, and prints them: dict_values([35, 38, 21, 28, 33])

It then prints the type of the returned values from age dictionary: <class ‘dict_values’>

Additionally, it casts the values from age dictionary into a list using list() and store into variable called ‘my_vals’ and prints out ‘my_vals’: [35, 38, 21, 28, 33]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
225
Q

What is output of this code? - (3)

A

dict_values([35, 38, 21, 28, 33])
<class ‘dict_values’>
[35, 38, 21, 28, 33]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
226
Q

What is output of this code?

A

Mean age of participants is: 37.0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
227
Q

There are several ways to loop over dictionaries to do something to each key/value pair

Two ways are - (2)

A

1) loop over keys and using dict[key]
2) .items() iterator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
228
Q

Example of looping over dictionaries

First method of loop over keys and using dict[ky]

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
229
Q

What will be output of the code?

A

P1 35
P2 38
P3 21
P4 28
P5 33

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
230
Q

What is the default behaviour of a dictionary in a for loop?

A

iterate over the keys:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
231
Q

How does the provided code iterate over a dictionary and print each key along with its corresponding value? - (3)

A

The code iterates over the keys of the dictionary ages using a for loop.

During each iteration, it accesses the key k and retrieves its corresponding value from the dictionary using dictionary indexing (ages[k]).

Then, it prints both the key and its corresponding value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
232
Q

How can we access both the keys and values of a dictionary during each iteration of a loop without using dictionary indexing? - (2)

A

We can use the .items() iterator, which returns key/value pairs one at a time.

This allows us to access both the key and the value directly within the loop without needing to use the dict[key] syntax.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
233
Q

Explain how the given code snippet iterates over a dictionary and prints each key-value pair - (3)

A

The code snippet uses a for loop with the .items() iterator to iterate over the dictionary ages.

During each iteration, the keyThing variable is assigned the key, and the valThing variable is assigned the corresponding value.

These key-value pairs are then printed using the print() function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
234
Q

What is output of the code?

A

P1 35
P2 38
P3 21
P4 28
P5 33

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
235
Q

What is noteworthy about the .items() method used in the given code snippet? - (2)

A

The .items() method returns key-value pairs from the dictionary, and these pairs are automatically unpacked and assigned to the loop variables keyThing and valThing.

This makes the code more concise and readable,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
236
Q

The sorted function in Python sorts the

A

dictionary based on keys not valuees by default

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
237
Q

Explain this code: - (5)

A

The code begins by defining the number of subjects (numSubjects) as 3 and initializes an empty dictionary called ageDict to store participant IDs and ages.

It then enters a loop that iterates three times (for each subject).

Within this loop:
It prompts the user to input a participant ID (partID) and age (partAge).
It stores the entered ID and age as key-value pairs in the ageDict dictionary.

After collecting all the data, it prints out the contents of the ageDict dictionary.

Following this, the code enters another loop that iterates over the sorted items of the ageDict dictionary. This loop:
Uses the sorted() function to sort the dictionary items by keys.
Iterates over the sorted items using the items() iterator, which returns key-value pairs.
Unpacks each key-value pair (ID and age) from the sorted dictionary items.
Formats and prints each ID and age pair using an f-string, ensuring alignment and spacing for readability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
238
Q

What is the difference between a ‘for’ loop and a ‘while’ loop?

A

‘for’ loops iterate over a list of values for a fixed number of times, while ‘while’ loops continue iterating as long as a certain condition is met.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
239
Q

What caution is given regarding ‘while’ loops?

A

‘while’ loops can lead to infinite loops if not properly controlled, potentially causing the program to become unresponsive.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
240
Q

How can one escape an infinite loop?

A

To escape an infinite loop, one can use the Ctrl-C keyboard shortcut (holding down the Ctrl button and pressing C simultaneously) or use the stop button available in coding environments like Colab or Spyder.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
241
Q

What is a while loop in Python? - (2)

A

A while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true.

It continues to execute the block until the condition becomes false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
242
Q

While loops are useful when the

A

number of iterations is not known in advance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
243
Q

Explain the purpose of the while loop in the provided code snippet - (5).

A

The while loop continuously executes the block of code inside it as long as the condition a < 5 remains true.

Inside the loop, a is incremented by 1 each time.

The loop stops when a becomes equal to or greater than 5.

After the loop finishes, “Done” is printed.

Note the += syntax here: this is the same as writing a = a + 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
244
Q

What is output of this code?

A

1
2
3
4
5
Done

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
245
Q

What is the crucial aspect to ensure in a while loop? - (2)

A

The crucial aspect is to ensure that the condition being tested will eventually evaluate to True.

If this condition never becomes False, the loop will continue indefinitely.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
246
Q

2.5.1 Quick Exercise
Create a list containing the words apple, banana, cherry and damson. Write a while loop which iterates over the list and prints out the words one at a time. You will need to have the while loop count over the indices and exit when you get to the end of the list.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
247
Q

A conditional statement is one that allows us to make..

The programme can change what it does - (2)

A

a decision when the program is running.

next depending on what is happening now.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
248
Q

A conditional statement allow the program to execute different blocks of code depending on whether

A

a condition is true or false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
249
Q

The conditional statement is expressed in Python using key word

A

if

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
250
Q

‘else’ keyword is used in conjunction with

A

‘if’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
251
Q

‘else’ provides an

A

alternative block of code to execute when the condition specified with if is false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
252
Q

‘elif’ allows you to check- (3)

A

for multiple conditions sequentially after an initial if statement.

If the condition associated with if is false, it checks the condition associated with elif and executes the corresponding block of code if true.

You can have multiple elif statements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
253
Q

‘if’ statement in Python evaluates - (2)

A

a condition, which can be any expression that results in a boolean value (True or False).

This condition determines whether the subsequent code block associated with the if statement is executed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
254
Q

The general form of if is: if CONDITION. CONDITION can be anything which evaluates to a bool - i.e. True or False. Here we are - (2)

A

we are comparing numbers

e.g., ‘if a > 10’: this condition evaluates whether value of ‘a’ is greater than 10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
255
Q

As with for loops, blocks of statements which are inside an if need to be

A

indented

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
256
Q

Example image of else statement used in conjunction with if CONDITION

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
257
Q

You do not have to have a

A

else statement (i.e., with if statement or in any loops like for and while)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
258
Q

The else statement, if it exists, must always be the final part of the

A

if block

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
259
Q

What is output of this code? - (2)

A

Test subject with age 9999 ignored

The total of all the real ages is 155

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
260
Q

‘elif’ statement is a neat way of stringing together lots of

A

statements in a row

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
261
Q

Write a code:

storing number ‘66’ into variable called subjectAge

if age of pp is greater than 65 it prints: “Age is too big”

if age of pp is less than 18 then print “Age too small!”

Otherwise, it would print subject age okay!

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
262
Q

What is output of this code? - (6)

A

Output: Age too big!

This code evaluates the value of the variable subjectAge, which is initially set to 66.

Since subjectAge is greater than 65, it prints “Age too big!”.

The elif statement checks for additional conditions, but they are not met because subjectAge does not fall below 18.

Hence, it doesn’t print “Age too small!”.

Finally, the else block is bypassed, and the code prints “Subject age okay!”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
263
Q

Explain the code, what would be output and why? - (11)

A

In this code, there are nested if statements. T

he outer if statement checks if the subjectAge is greater than 18.

If this condition is true, it then checks the numberOfFunctionalEyes.

If numberOfFunctionalEyes is equal to 2, it prints “Subject is valid”.

If numberOfFunctionalEyes is not equal to 2, it prints “Right age, wrong number of eyes”.

If the subjectAge is not greater than 18, it prints “Under age, didn’t check the eyes”.

Given subjectAge = 19 and numberOfFunctionalEyes = 1, here’s what happens:

The first condition subjectAge > 18 is true, so it proceeds to the nested if statement.

However, the second condition numberOfFunctionalEyes == 2 is false since numberOfFunctionalEyes is 1.

Therefore, it executes the else block of the nested if statement.

Hence, the output would be “Right age, wrong number of eyes”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
264
Q

In our examples so far, the conditions that we have used have been comparisons (greater than, equal to, less than).

As noted above, if statements work with any statement which can evaluate to a bool value (True or False).

You can also write out more complex statements than just checking the value of a variable.

e.g,.

A

such as using a the ‘modulus’ operator % in if statement and using string operations such as ‘startswith’ and ‘endswith’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
265
Q

Remember:

Modulus operator ‘%’ returns the

A

‘remainder’ when you divide one thing by another thing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
266
Q

Write a code that

stores number 4 into variable ‘a’

Checks if a is odd

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
267
Q

Explain this code - (4):

A

a = 4: This line assigns the value 4 to the variable a.

if (a % 2) == 1:: This line sets up a conditional check. Inside the parentheses, (a % 2) computes the remainder when a is divided by 2, effectively determining whether a is even or odd.
(a % 2) will result in 0 if a is even and 1 if a is odd.

if the condition (a % 2) == 1 evaluates to True (which is the case when a is odd), the program prints “a is odd”.

However, in this case, the condition evaluates to False since a is even.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
268
Q

What is output?- (2)

A

Since the condition (a % 2) == 1 evaluates to False when a is 4 (because 4 % 2 equals 0, not 1), the print(“a is odd”) statement will not be executed.

Therefore, there will be no output for this code when a is assigned the value 4.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
269
Q

How do we compare strings in Python code?

A

we can compare strings using equality operator ==:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
270
Q

Write a code that compares strings to see if “Hello” and “Hello” are the same and if “Hello” and “Hello World” are the same that is stored in variables a, b, c

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
271
Q

What would be output of this code?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
272
Q

Explain this code and why it produces that output? - (4)

A

This code initializes three variables a, b, and c with string values. Then it performs comparisons using the equality operator == to check if the strings are the same.

a = “Hello”: Assigns the string “Hello” to the variable a.
b = “Hello”: Assigns the string “Hello” to the variable b.
c = “Hello World”: Assigns the string “Hello World” to the variable c.

if a == b:: Compares the strings stored in variables a and b. Since both a and b contain the same string “Hello”, this condition evaluates to True. Therefore, it prints “a and b are the same”.

if a == c:: Compares the strings stored in variables a and c. However, a contains “Hello” and c contains “Hello World”, so these strings are different. This condition evaluates to False. Therefore, it prints “a and c are different”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
273
Q

We can also perform advanced string operations such as checking whether one string starts with another using the

A

‘startswith’ member function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
274
Q

Write a code that:

stores

variable a into “hello”

variable b into “world”

variable c with “hello world”

Check if c starts with a and prints a starts with a if not then say it does not

Check if c starts with b and prints c starts with b or if not then say it does not

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
275
Q

What is the output of this code?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
276
Q

Explain the output of the code and justify why it produces that output. - (4)

A

This code snippet initializes three string variables: a with the value “Hello”, b with the value “World”, and c with the value “Hello World”. Then, it utilizes the startswith method to check if the string c starts with the substrings represented by variables a and b.

a = “Hello”: Assigns the string “Hello” to the variable a.
b = “World”: Assigns the string “World” to the variable b.
c = “Hello World”: Assigns the string “Hello World” to the variable c.

if c.startswith(a):: Checks whether the string c starts with the substring represented by variable a (“Hello”). Since the string c does indeed start with “Hello”, this condition evaluates to True, and “c starts with a” will be printed.

if c.startswith(b):: Checks whether the string c starts with the substring represented by variable b (“World”). Since the string c does not start with “World”, this condition evaluates to False, and “c does not start with b” will be printed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
277
Q

There is a corresponding counterpart to ‘startswith’ member function there is also a

A

‘endswith’ that is another advanced string operator ,member function, that checks whether a string ends with a specific substring.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
278
Q

Example of code using endswithmember function

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
279
Q

What is output of this code?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
280
Q

Whats one useful operation that works with strings, lists, tuples and dictionaries?

A

‘in’ keyword

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
281
Q

Whats ‘in’ keyword in Python?

A

checks whether one thing is in the object being checked.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
282
Q

What is output of the code?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
283
Q

Explain t why a certain condition fails to find b in the dictionary e.

A

if b in e:: Checks if the substring “World” is present as a key in the dictionary e. This condition fails to find “World” in the dictionary e because “World” is stored as a value, not a key. In e, “Hello” is a key, not “World”. Therefore, this condition evaluates to False, and no message is printed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
284
Q

If we want to examine the values, we can simply ask the dictionary for a list of its values and check that instead . Like this:

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
285
Q

The ‘not, ‘and’ and ‘or keywords modifies

A

the boolean to ask for the opposite thing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
286
Q

The ‘not operator returns..

A

It returns True if the expression is False, and False if the expression is True.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
287
Q

The ‘and keyword - (2)

A

combines two expressions.

It returns True if both expressions are True, otherwise, it returns False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
288
Q

The ‘or keyword - (2)

A

The or keyword combines two expressions.

It returns True if at least one of the expressions is True, otherwise, it returns False.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
289
Q

we can write conditions that combine multiple requirements using

A

‘and’ and ‘or’ keywords in Python

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
290
Q

What is the output?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
291
Q

You can chain together as many of ‘and and ‘or’ operators but

A

Be careful about which conditions will be combined in which order.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
292
Q

Parentheses can be used when writing multiple conditions to clarify to the

A

reader (esp writing multiple conditions using ‘and’, ‘or and ‘not’ in Python) even if if Python does not need them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
293
Q

Write a code that stores 5,10,15, 20 to variable a,b,c, and d respectively

Then check if a < 10 or b >10 and c< 25 or d < 25 and prints At least one of a/b are < 10 and at least one of c/d are < 25

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
294
Q

Explain what the code does? - (4)

A

a = 5, b = 10, c = 15, and d = 20 are assigned initial values.

The if statement checks two conditions:
(a < 10) or (b < 10) checks if either a or b is less than 10.
(c < 25) or (d < 25) checks if either c or d is less than 25.

If both conditions are met, the message “At least one of a/b are < 10 and at least one of c/d are < 25” is printed

In this specific case, since a = 5 (which is less than 10) and d = 20 (which is less than 25), both conditions are met, so the message will be printed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
295
Q

What is output of this code?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
296
Q

You can use single-character shorthand for

A

‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
297
Q

using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

e.g.,

or =

A

|

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
298
Q

using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

e.g.,

and =

A

&

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
299
Q

using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

e.g.,

not =

A

~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
300
Q

Example code of using using single-character shorthand ‘and’ , ‘or’, ‘not’ operators to achieve the same functionality

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
301
Q

What is the output?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
302
Q

Question 1: String Formatting Issue

What is problem with code?

A

Use {} not [] to embed variables in f-strings

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
303
Q

Question 2: Dictionary Key Error

The above code snippet attempts to print the location of the person. Identify the error and suggest a quick fix. In addition, suggest a general way to handle missing keys in a dictionary so that the code does not produce an error. - (3)

A

There is no key called ‘location’.

Probably ‘city’ is what you wanted.

Use the “get” function to try to access dict values by keys and return a None value rather than an error if the key is missing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
304
Q

Question 3: While Loop Condition Error

Explain why the loop might not work as expected. How would you fix it to count down from 10 to 1. - (3)

A

The loop will never stop because the count is always <=10. There are lots of ways of fixing it. For example…

1: Add in an ‘and’ statement to the while loop (while (count<=10 and count >=1):

2: Just use a for loop with a range statement (for count in range(10,0,-1):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
305
Q

Question 4: Conditional Statement Syntax Error

Identify the syntax error in the conditional statements.

A

The last ‘else’ is missing a colon

else:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
306
Q

Question 5: Incorrect Use of the ‘is’ Operator

Explain why the is operator might not be appropriate in this context and suggest a correct approach. - (2)

A

‘is’ is usually used for lists or dictionaries or strings. For numbers, just use == instead

if (x>3) and (y==10):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
307
Q

Question 6: While loop and conditional

Describe the purpose of the else clause in this while loop and under what circumstances it is executed. - (2)

A

It is evaluated when the countdown gets to zero.

It tells the program what to do when the countdown is not 3,2,1…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
308
Q

Question 7: Rounding and mixing Data Types in F-String

How would you make this f-print statement round to the nearest integer? - (2)

A

Use the formatting string :something.0f following ‘score’ inside the first {}. The something part says how many figures to have in front of the decimal place, the ‘0’ part says to have nothing after the decimal place. For example

print(f”Your rounded score is {score:2.0f}, which is a {result}”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
309
Q

name = “Emily”
age = 35
print(“My name is “ + name + “ and I am “ + age + “ years old.”)

What is the problem with this code? - (4)

A

The problem with this code is that the variable age is of integer type, and it cannot be directly concatenated with strings using the + operator.

To fix this, you should convert the age variable to a string using the str() function before concatenating it with other strings.

Here is corrected answer:

name = “Emily”
age = 35
print(“My name is “ + name + “ and I am “ + str(age) + “ years old.”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
310
Q

numbers = [1, 2, 3, 4, 5]
print(numbers[6])

**Identify the error in the code and suggest a solution to avoid this error - (8)

A

Identify the error:

The error in the code is an “IndexError,” specifically stating that the index is out of range.

This means that the index 6 is beyond the bounds of the list numbers, which has indices ranging from 0 to 4.

Solution:

To avoid this error, ensure that the index used to access elements from the list is within the bounds of the list.

In this case, you should use an index that is valid for the given list.

For example, if you want to access the last element of the list, you can use index 4, not 6 e.g,, print(numbers[4])

Alternatively, you can handle such errors using try-except blocks to gracefully manage situations where an invalid index is used

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
311
Q

Example of using try block for this example:

numbers = [1, 2, 3, 4, 5]
print(numbers[6])

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
312
Q

def greet(name, message):
print(“Hello “ + name)
print(message)
greet(“Alex”)

Identify the syntax error in the function call and suggest a solution. - (5)

A

The syntax error occurs in the function call greet("Alex").

The function definition ‘greet()’ expects two arguments (name and message), but only one argument (name) is provided in the function call.

This results in a TypeError.

To fix this error, provide both name and message arguments in the function call, matching the expected arguments in the function definition.

Example solution:
greet(“Alex”, “Good morning!”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
313
Q

Explain why the loop does not sum the numbers correctly and suggest a fix - (6)

total = 0
i = 1
while i <= 5:
total += i
print(“Total is:”, total)

A

The loop does not sum the numbers correctly because the loop control variable ‘i’ is never incremented inside the loop.

As a result, the loop condition while i <= 5 always remains true, leading to an infinite loop.

Consequently, the program keeps adding the same value of ‘i’ to ‘total’ repeatedly without progressing to the next number in the sequence.

To fix this issue, you should increment the value of ‘i’ inside the loop to ensure that it progresses through the numbers from 1 to 5.

By incrementing ‘i’, the loop iterates through each number in the sequence and correctly accumulates the sum of these numbers in ‘total’.

Example solution:
total = 0
i = 1
while i <= 5:
total += i
i += 1 # Increment ‘i’ inside the loop
print(“Total is:”, total)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
314
Q

What does ‘total+= i’ mean?

total = 0
i = 1
while i <= 5:
total += i
print(“Total is:”, total)

A

total += i is equivalent to total = total + i, which means the value of i is added to the current value of total, and the updated value is stored back in total.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
315
Q

my_list = [1, 2, 3, 4,]
print(my_list)

Identify the syntax error in the list initialization and suggest a fix - (2)

A

The trailing comma after the last element is unnecessary.

Remove it to avoid syntax errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
316
Q

Explain the following Python code - (2)

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.strip())

A

This code removes leading and trailing whitespace characters (such as spaces, tabs, and newline characters) from the string stored in the variable my_string.

The strip() method is used to perform this operation, and the resulting string with whitespace removed is printed to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
317
Q

Explain the following Python code and how it combines string methods - (4)

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.strip().lower())

A

This code demonstrates the combination of string methods in Python.

First, the strip() method is applied to my_string to remove leading and trailing whitespace characters.

Then, the lower() method is applied to the resulting string, converting all characters to lowercase.

The combined effect of these methods is that the string is stripped of whitespace and converted to lowercase before being printed to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
318
Q

Explain the meaning of the following string assignment (i.e., (i.e., “string assignment” refers to the process of assigning a string value to a variable) - (3)

my_string=”\n hello world \t”

A

In the given string assignment, my_string, the escape sequences \n and \t are used.

\n represents a newline character, causing the text “hello world” to start on a new line.

\t represents a tab character, adding tab spaces (equivalent to multiple spaces) before the text “hello world”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
319
Q

Why might using a series of if statements to check for variations in capitalization or leading whitespace be considered clunky? - (2)

e.g.,

if (inputWord==’pencil’) or (inputWord==’PENCIL’) or (inputWord==’Pencil’) or (inputWord=…..

A

Using a series of if statements to check for variations in capitalization or leading whitespace can be considered clunky because it requires writing repetitive code and becomes cumbersome to maintain, especially if the password changes.

Also you may not think of all the variations people can type pencil

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
320
Q

Let’s imagine we have a password system for school district

Each time someone wants to get in they have to type the password (‘pencil’). But, to make things easier, we don’t want it to fail if they have the CAPS LOCK key on, or if they are German And Need To Capitalize Lots Of Words. Or if they have accidentally added a space or tab at the start of the string (YNiC screensaver unlock box - I’m looking at you!).

Second way -Turning any user input to lower case and check against ‘pencil’ - produce this code - target string is ‘pencil’

A

target_string = ‘pencil’

user_input = input(‘Login with user password: ‘)

user_input = user_input.lower()

if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
321
Q

Explain the following Python code - (6)

target_string = ‘pencil’

user_input = input(‘Login with user password: ‘)

user_input = user_input.lower()

if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)

A

This code prompts the user to enter a password and compares it with a target password stored in lower case.

Firstly, the target password ‘pencil’ is stored as all lower-case characters in variable ‘target_string’

Then, the user is prompted to input their password.

The user_input.lower() function converts the user’s input to lower case, ensuring that the comparison is not case-sensitive.

If the user’s input matches the target password, ‘Welcome to the Seattle Public School District DATANET’ is printed; otherwise, ‘Password denied’ is printed.

This approach ensures that the password comparison ignores variations in capitalization and provides a robust password validation mechanism.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
322
Q

Explain the functionality of the split string member function .spilt() in Python.

A

The split string member function is designed to take a string and split it into a list of strings

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
323
Q

What is the default behaviour of .spilt() string member function?

A

By default, it splits the string on any whitespace characters (such as spaces, tabs, or newlines/carriage-return characters),

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
324
Q

Explain the functionality of the provided Python code - (10)

dat = ‘The cat sat on the mat’

res = dat.split()

print(type(res))

print(res)

print(len(res))

A

The provided code utilizes the split() method to split the string “The cat sat on the mat” into individual words.

It initializes a string variable dat with the value ‘The cat sat on the mat’.

The split() method is applied to dat, splitting the string into individual words based on whitespace characters.

The resulting list is stored in the variable res.

It prints the type of res (which confirms it’s a list), the contents of res (the individual words), and the length of res (the number of words in the original string).

Output:

<class ‘list’>
[‘The’, ‘cat’, ‘sat’, ‘on’, ‘the’, ‘mat’]
6

You can see that it takes the string “The cat sat on the mat” and breaks it apart into 6 strings - one for each part of the string between each space character.

The length of the resulting list is 6, corresponding to the number of words in the original string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
325
Q

Explain how to change the character on which the split method splits a string in Python,

A

To change the character on which the split method splits a string, you can pass a desired ‘separator’ character as an argument to the method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
326
Q

Example of change the character on which spilt spilts the string by passing our desired ‘seprator; character as an arguement - (2)

if we have a string which is separated by commas:

dat = ‘Person,Condition,RT’
res = dat.split(‘,’)
print(res)

Explain:

A

In this example, the string dat is split into individual parts at each comma character, and the resulting list is printed:

Output:
[‘Person’, ‘Condition’, ‘RT’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
327
Q

Modify this code below to spilt on a different character like ‘o’:

dat = ‘Person,Condition,RT’

res = dat.split(‘,’)

print(res)

A

dat = ‘Person,Condition,RT’

res = dat.split(‘o’)

print(res)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
328
Q

What is output of this code:
dat = ‘Person,Condition,RT’

res = dat.split(‘o’)

print(res)

A

[‘Pers’, ‘n,C’, ‘nditi’, ‘n,RT’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
329
Q

Explain this code - (5)

dat = ‘Person,Condition,RT’

res = dat.split(‘o’)

print(res)

A

The string ‘Person,Condition,RT’ is stored in the variable dat.

The split(‘o’) method is applied to dat, splitting the string at each occurrence of the letter ‘o’.

The resulting list is stored in the variable res.

It prints the content of res, which contains the parts of the string split at each occurrence of ‘o’.

So output would be: [‘Pers’, ‘n,C’, ‘nditi’, ‘n,RT’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
330
Q

Explain the concept of “white-space” in Python and what it refers to - (2)

A

In Python, “white-space” refers to characters such as tabs, spaces, and newline/carriage-return characters.

These characters are used to format code or data files and are typically invisible when displayed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
331
Q

What does “carriage return” mean in the context of datafiles? - (2)

A

n data files, “carriage return” indicates the end of a line in a datafile.

In Python, it is represented by the special symbol \n, which is interpreted as a “newline” character.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
332
Q

Example of using \n

What i the output of this code?

print(“Hello\nWorld”)

A

Hello
World

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
333
Q

Explain this code and its output - (3)

print(“Hello\nWorld”)

A

The string “Hello\nWorld” is passed to the print() function.

You have inserted a newline in between the two words, so they get printed on different lines such as:

Output
Hello
World

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
334
Q

What is a tab character in Python? - (2)

A

A tab character in Python, represented as \t, is a special type of whitespace character used to align text by moving the cursor to the next tab stop at a fixed interval.

It is commonly used for indentation and formatting purposes in documents, code, or data files.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
335
Q

What is output of code going to be?

print(“This\tis\tindented”)

A

This is indented

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
336
Q

Explain the functionality of the provided Python code - (6)

my_string = ‘Country\t,GDP\t,Happiness\t,Authoritarianism\t\n\r’
string_list = my_string.split(“,”)

for thisString in string_list:
cleanString = thisString.strip()
print(cleanString)

A

This code initializes a string my_string containing tab-separated values (with commas as delimiters) and newline/carriage return characters.

The string is then split into a list of strings using the split() method with a comma delimiter.

Each element in the resulting list retains the tab characters (\t).

The for loop iterates over each element in string_list, and the strip() method is applied to remove any leading or trailing whitespace, including the tab characters, from each element.

Finally, it prints each cleaned string:

Country
GDP
Happiness
Authoritarianism

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
337
Q

What is output of this code?

my_string = ‘Country\t,GDP\t,Happiness\t,Authoritarianism\t\n\r’
string_list = my_string.split(“,”)

for thisString in string_list:
cleanString = thisString.strip()
print(cleanString)

A

Country
GDP
Happiness
Authoritarianism

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
338
Q

A full pathname for a file on a computer consists of a.. together these elements uniquelty identifiy - (2)

A

directory (or folder) and a filename, which must be unique within the directory.

Together, these elements uniquely identify the location of the file within the file system.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
339
Q

Explain the concepts of absolute and relative paths in computing

A

An absolute path provides the complete address of a file or directory starting from the root directory, whereas a relative path specifies the location of a file relative to the current working directory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
340
Q

Provide an example of an absolute path in computing - (2)

A

An example of an absolute path in computing is

/home/user/documents/my_file.txt.

This path specifies the complete address of the file my_file.txt, starting from the root directory (/) and including all intermediate directories (home, user, documents).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
341
Q

Give an example of a relative path in computing - (3)

A

An example of a relative path in computing is data/my_data.csv.

This path specifies the location of the file my_data.csv relative to the current working directory.

It indicates that the file is located within a directory named data within the current working directory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
342
Q

If a filename does not have a full directory component (i.e. it does not start with / or C: on Windows), it is said to be

A

relative.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
343
Q

Why is understanding absolute and relative paths important? - (2)

A

so that you understand where your program will look for files (when you are reading data in) and write files out (when you save data, figures etc out).

Understanding absolute and relative paths is important for determining where files will be located or saved when working with programs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
344
Q

Explain the rationale behind using os.getcwd() in Python scripts. than %cwd? - (2)

A

os.getcwd() is preferred in Python scripts for retrieving the current working directory due to its portability and consistency across different environments.

Unlike %cwd, which is specific to Colab and may not work in other environments, os.getcwd() is a standard Python library function that works reliably across various platforms

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
345
Q

What function can you use within a Python script to find the current working directory? - (2)

A

Within a Python script, you can use the os.getcwd() function to find the current working directory.

This function returns a string representing the current directory path.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
346
Q

How can you change the current working directory within a Python script? - (2)

A

You can change the current working directory within a Python script using the os.chdir(dirname) function, where dirname is a string containing the directory path to which you wish to change.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
347
Q

Before using os.getcwd() or os.chdir(dirname) and os.listdir(), we have to import module called

A

os

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
348
Q

What does module os provide?

A

provides functions for interacting with the operating system.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
349
Q

Explain this code:

import os

print(os.getcwd()) - (3)

A

The code snippet imports the os module in Python, which provides functions for interacting with the operating system.

It then uses the os.getcwd() function to retrieve the current working directory.

The output of os.getcwd() will be the current directory in which the Python script is being executed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
350
Q

Explain the functionality of os.listdir().

A

os.listdir() is a function in Python’s os module that returns contents , by default, of the current working directory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
351
Q

Why is it good to use abolsute file path names?

A

One reason is that if your programme crashes while you are in a different directory you might not be in the place you expect when you restart it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
352
Q

If, when you are reading data, you are getting errors such as “No such file or directory”, it is probably because you are using a - (2)

A

relative file path and are not in the correct directory.

Or you have just typed the filename wrong.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
353
Q

What is the function used for joining parts of a file path together?

A

The function used for joining parts of a file path together is os.path.join.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
354
Q

Why is joining parts of a file together using os.path.join() useful?

A

This is particularly useful if we want to open many files from the same directory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
355
Q

In os.path.join () we can simply

A

pass it as many components of the path as we have, and it will join them in the correct manner.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
356
Q

Explain what does code does - (4)

from os.path import join

my_dir = ‘/content/sample_data/’

my_file = ‘mnist_test.csv’

my_filename = join(my_dir, my_file)

print(my_filename)

A

The code snippet demonstrates the usage of the join function from the os.path module which joins together directory and file names, creating full file paths (with separators appropriate to the file system you are on).

then defines a directory path (my_dir) and a file name (my_file).

Using os.path.join, it joins the directory path and file name to create a full file path to store in variable (my_filename).

It then prints my_filename which will be: /content/sample_data/mnist_test.csv

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
357
Q

os.path.join() can also take a

A

string instead of a variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
358
Q

What does the provided code snippet do? - (2)

my_filename2 = join(my_dir, ‘california_housing_test.csv’)

print(my_filename2)

A

The code snippet combines a directory path (my_dir) with a filename (‘california_housing_test.csv’) to create a full file path (my_filename2).

The resulting file path is then printed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
359
Q

What is the output of this code?

my_filename2 = join(my_dir, ‘california_housing_test.csv’)

print(my_filename2)

A

/content/sample_data/california_housing_test.csv

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
360
Q

You can also pass multiple individual dictionaries to to the join function e.g,

A

print(join(‘/home’,my_dir, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’,’file.txt’))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
361
Q

What does this code do? - (3)

from os.path import join

my_dir = ‘alex’

print(join(‘/home’,my_dir, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’,’file.txt’))

A

The code snippet showcases the usage of the join function from the os.path module to create a full directory path by joining together multiple individual directory names.

Starting from the root directory /home, it sequentially adds each directory name (‘alex’, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’) along with the filename ‘file.txt’.

The resulting full directory path is then printe

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
362
Q

What is output of this code?

from os.path import join

my_dir = ‘alex’

print(join(‘/home’,my_dir, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’,’file.txt’))

A

/home/alex/ynic/presentations/teaching/pin/file.txt

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
363
Q

What is the output of this code?

from os.path import join
base_path=’/home/pin/my_data/’

nSubjects=10 # Because what if we collect more subjects? All we have to do is change this

b=10
a=f’My favourite number is {b} ‘
print(a)

for thisSub in range(1,nSubjects+1): # The +1 is to make sure we go from 1 to 10 inclusive
fileName = f”S{thisSub:02}.txt”

print(join(base_path,fileName))

A

/home/pin/my_data/S01.txt
/home/pin/my_data/S02.txt
/home/pin/my_data/S03.txt
/home/pin/my_data/S04.txt
/home/pin/my_data/S05.txt
/home/pin/my_data/S06.txt
/home/pin/my_data/S07.txt
/home/pin/my_data/S08.txt
/home/pin/my_data/S09.txt
/home/pin/my_data/S10.txt

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
364
Q

Comma-separated value (CSV) files are - (2)

A

plain-text files (meaning you can open them in a normal text editor and look at the data) where data items are separated by commas and where new sets of fields are placed on different lines (by means of a new-line character).

They are easy to understand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
365
Q

Example of CSV files

A

Wade,Alex,49

Smith,Joe,21

Doe,Jane, 23

West,Mae,29

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
366
Q

CSV files are common and can be

A

exported from spreadsheet software and are easy to read and write in just about all programming languages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
367
Q

What does the CSV module in Python facilitate? - (2)

A

The CSV module in Python facilitates the reading and writing of data from and to CSV (Comma-Separated Value) files.

It provides functions specifically designed to handle CSV file operations efficiently.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
368
Q

How to import CSV module in python?

A

Type:
import csv

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
369
Q

What are the 3 modules that have in built CSV readers?

A
  1. Pandas
  2. Numpy
  3. Python CSV module
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
370
Q

Explain this code - (6) that opens the entire CSV file

A

import csv: Imports the CSV module, allowing us to work with CSV files.

  • ## with open('/content/sample_data/california_housing_test.csv', 'r') as csvfile:: Opens the CSV file in read mode (‘r’). The file path is provided in absolute format.
  • reader = csv.reader(csvfile, delimiter=','): Creates a CSV reader object named reader.
  • The delimiter=',' argument specifies that fields in the CSV file are separated by commas.
  • for row in reader:: Iterates through each row in the CSV file
  • print(', '.join(row)): Joins the items in the current row with commas and prints them
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
371
Q

What is PANDAS?

A

a Python module designed for reading in and processing data tables, it introduces a new data type called DataFrame

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
372
Q

Pandas is the most common and easiest way to

A

load in and process .CSV files

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
373
Q

Example of reading in csv folder in pandas:

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
374
Q

How about the average?

Explain this code - (3):

import pandas as pd
housingTable=pd.read_csv(‘/content/sample_data/california_housing_test.csv’)
housingTable.latitude

averageLatitude=housingTable.latitude.mean()
print(f’Mean latitude={averageLatitude:3.3f}’)

A

This Python code imports the Pandas library as ‘pd’ and reads a CSV file named ‘california_housing_test.csv’ located in the ‘/content/sample_data/’ directory.

The data from the CSV file is loaded into a Pandas DataFrame named ‘housingTable’.

Then, it calculates the mean latitude from the ‘latitude’ column of the DataFrame using the mean() function and prints it with 3 minium width (of entire string) and to 3 DP

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
375
Q

You can also convert dataframe (pandas) to something you are comfortable with like - (3)

A

a list

e.g., import pandas as pd
housingTable=pd.read_csv(‘/content/sample_data/california_housing_test.csv’)

housingList = housingTable.values.tolist()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
376
Q

How about the average?

Explain what this code does - (6)

import pandas as pd
housingTable=pd.read_csv(‘/content/sample_data/california_housing_test.csv’)
housingTable.latitude

print(f’Mean lat: {housingTable.latitude.mean():3.3f}’)

housingList = housingTable.values.tolist()

latitude=housingTable[‘latitude’].tolist()

A

The code imports the Pandas library under the alias pd.

It reads a CSV file named california_housing_test.csv located in the specified path /content/sample_data/ into a Pandas DataFrame named housingTable.

It accesses the latitude column of the housingTable DataFrame.

It calculates the mean of the latitude column using the mean() method and prints it with prints it with 3 minium width (entire string) and to three decimal places.

It converts the DataFrame housingTable into a list of lists using the values.tolist() method and stores it in housingList.

It extracts all values from the latitude column of the housingTable DataFrame and converts them into a list stored in the variable latitude.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
377
Q

import pandas as pd
data = pd.read_csv(“/content/sample_data/california_housing_test.csv”)
print(data.head())

This code aims to read a CSV file using pandas.

What is the purpose of the head() method, and why is it used in this context? - (2)

A

The purpose of the head() method in pandas is to display the first few rows of the DataFrame.

It provides a quick overview of the data structure and its contents, helping users understand the data better.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
378
Q

Q1:
import pandas as pd
df = pd.read_csv(“content/sample_data/california_housing_test.csv”)
print(df.head())

Something is wrong with the following code. Explain what is wrong - and why.

A

The path name is missing a leading slash to indicate that it starts at the root.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
379
Q

To convert from celsius to fahrenheit you multiply by 9/5 and add 32. What is wrong with the following code? How might you fix it?

Note - there are two potential issues here - try to make the conversion as accurate as possible. - (2)

A

First, the list is made of strings but you are trying to multiply them by a number.

Second, you append ‘C’ not ‘F’ to the list so you never store the Fahrenheit value –> So, The code indeed appends the original Celsius value (C) to the list instead of the calculated Fahrenheit value (F), so it doesn’t store the converted Fahrenheit temperatures.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
380
Q

Password hell. What is the matter with this code?

A

The input statement is not in the loop so if you get it wrong once, you enter an infinite loop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
381
Q

s = “Python_Data_Science”
words = s.split(‘-‘)
print(words)

I’m trying to split the string ‘s’ into individual words. What is going wrong?

A

It’s splitting on a hyphen (-) but the string has underscores in it (_)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
382
Q

Q3.5
I’m trying to read in a file using the Python csv reader. I think I almost have it but it doesn’t quite work…

Can you see what is wrong?

A

You should parse each row in csv_reader. csv_file does not exist

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
383
Q

Broadly, what are the two types of errors in programming? - (2)

A
  1. Errors that stop you running the code (‘syntax errors’) - These are often easy to spot. These days the editor will usually show you where they are.
  2. Errors that happen while you are running the code - These are the ones that keep you up at night. Some of them crash the programme. That is good! The other ones just do the wrong thing but don’t throw an error. That is bad! -runtime errors
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
384
Q

Provide an example of syntax error - (2)

A

print(‘Welcome to the programming course!)

Unterminated string literal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
385
Q

Example of an error that only pops up when you are running your code - (3)

A

myNum = int(input(‘Enter a number’))

Giving input as string instead of a number

Running this code will produce an ValueError exeception as Python does not know what ‘ten’ is

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
386
Q

What is ValueError exception in Python?

A

A ValueError exception occurs in Python when a function expects a certain type of input, such as a string or a number, but the actual value provided is not valid or appropriate for that type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
387
Q

What is an exception?

A

An error that occurs while the code is running.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
388
Q

What does a traceback in Python indicate? - (2)

A

traceback in Python indicates that an exception has occurred during the program’s execution.

It provides information about where the exception happened in the code, often marked by a little arrow or a message like ‘An error occurred on line xx’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
389
Q

The exact line number in your traceback may differ depending on how you have structured your script, but the

A

message will be similar.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
390
Q

What does the error message “Invalid literal for int() with base 10” mean? - (2)

A

This error message indicates that Python attempted to convert a string into an integer (of base 10 – normal decimal numbers), but the string doesn’t resemble a number.

This is not something which can be done, so Python raises an ValueError exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
391
Q

Describe in more detail about the try and except blocks

A

try means that we will attempt the code within the block and, if an exception is found, we will move to the except block (or blocks).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
392
Q

Describe the purpose of the try-except block in the provided example - (2)

A

The try-except block attempts to convert user input into an integer.

If a ValueError exception occurs (if the input is not a number), the except block handles it by printing a message and the exception itself (e is returned as the exception)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
393
Q

What is the output of this code - if input is ‘hi’

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
394
Q

Note when an exception is caught and handled using a try-except block, we do not get a - (2)

A

Note that we no longer get a full traceback.

Instead, it executes the code in the except block, which typically includes a message and the error message itself (ValueError exception) and the programme stops but critically it does not crash.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
395
Q

How to extend this code in which we should just ask again until the user gives us something sensible.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
396
Q

You can use try and except blocks if you suspect code may

A

crash

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
397
Q

What is output of the code if i my input is hi then hi then 9?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
398
Q

How can you handle multiple potential errors using except blocks in Python?

A

You can handle multiple potential errors by including multiple except blocks, each corresponding to a specific type of error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
399
Q

Explain this code - (8)

A

This code prompts the user to input a number to calculate its reciprocal. It begins by setting recip to None, indicating that no valid reciprocal has been calculated yet.

The while loop continues until a valid reciprocal is calculated.

Within the loop, the try block attempts to convert the user input into an integer and calculate the reciprocal.

If the user provides a non-integer input (e.g., a string), a ValueError is raised, and the program prints “Please enter a valid integer.” The program then re-prompts the user for input.

If the user attempts to divide by zero, a ZeroDivisionError is raised, and the program prints “Cannot divide by zero. Please enter a non-zero number.”

Only when the user provides a valid integer input will the code proceed to attempt the calculation of the reciprocal.

Once a valid non-zero integer is entered, the reciprocal is calculated, and the loop exits.

Finally, the calculated reciprocal is displayed with three decimal places using f-string formatting.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
400
Q

What is output of the code if i give 0,0 then ten?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
401
Q

Explain what happens to the code when i give 0 as input? - (5)

A

You input 0 when prompted.

The program attempts to calculate the reciprocal, which is 1 divided by the input number (0).

Division by zero occurs, triggering the ZeroDivisionError.
The program executes the corresponding except ZeroDivisionError block, printing “Cannot divide by zero. Please enter a non-zero number.”

The loop continues, prompting you to input another number.

Until you input a non-zero number, the program will keep repeating this process, not proceeding to calculate the reciprocal until valid input is provided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
402
Q

Explain what happens to the code if give ‘ten’ (as string) as user input? - (6)

A

You input ‘ten’ when prompted.

The program attempts to convert the input into an integer using int(‘ten’).

Since ‘ten’ cannot be converted into an integer, a ValueError occurs.

The program executes the corresponding except ValueError block, printing “Please enter a valid integer.”

The loop continues, prompting you to input another number.

Until you input a valid integer, the program will keep repeating this process, not proceeding to calculate the reciprocal until valid input is provided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
403
Q

What happens if the try block fails in the provided code?

A

If the try block fails, the variable recip will remain as ‘None’, as indicated by the comment: “# Here is the place where we try to get an input. Note that if it fails, start will stay as ‘None’.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
404
Q

What are functions? - (3)

A

Functions are bits of code that take arguments (parameters), perform operations with them, and optionally return values.

unctions allow code to be written and reused cleanly.

Once a function is defined for a specific task, it can be used multiple times throughout the program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
405
Q

Can funcions be changed together?

A

Yes e.g.,, print(list(range(5)))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
406
Q

Explain the code (example of chaining functions together):

print(list(range(5))) - (3)

A

In the example given, the return value from the range() function is passed to list() which casts the return value from range() into a list.

Subsequently, the resulting list is passed as an argument to the print() function, which then prints the list.

In each case, the return value from the innermost function becomes the argument to the next function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
407
Q

Functions in Python can return multiple values either as a

A

tuple (single variable) or break them out into separate variables:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
408
Q

Provide an example of a function that returns multiple values.

A

divmod() function,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
409
Q

What does divmod () function return?

A

returns the integer division of a number as well as its modulus (remaineder) when an integer is divided by another integer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
410
Q

For example,

whatt would divmod (5,2) return?

A

we will get the numbers 2 (integer division), remainder 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
411
Q

For divmod(5, 2), we will get the numbers 2 (integer division), remainder 1. We can either - (2)

A

take these return values into a single variable as a tupe

or expand the values out into multiple variables

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
412
Q

Example of just printing the return value of divmod

A

print(divmod(5, 2))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
413
Q

Example of sttoring the return value of divmod(5,2) into a single variable

A

Code:

ret = divmod(5,2)
print(“ret is “, ret)

Output
ret is (2,1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
414
Q

Example of storing return value of divmod(5,2) into 2 variables:

A

Code:

d,r = divmod(5,2)
print(“d is:”, d)
print(“r is:”, r)

Output
d is : 2
r is: 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
415
Q

Describe the purpose of the code: d, r = divmod(5, 2) - (2)

A

The function returns a tuple containing two values: the he integer division (quotient) and the remainder from integer division of integer 5 divided by integer 2 which is 2,1

These returned values are directly assigned to the variables d and r, respectively, and then printed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
416
Q

Explain what the following code does: ret = divmod(5, 2). - (2)

A

his code calls the divmod() function with arguments 5 and 2, which returns a tuple containing the quotient (integer division) and the remainder of dividing 5 by 2.

Returns these two values into a tuple and then stored into variable called ‘ret’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
417
Q

What are the two types of functions? - (2)

A
  1. ‘Standalone’ functions
  2. ‘Member’ functions
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
418
Q

What are ‘standalone’ functions?

A

functions that take all of their arguments in the parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
419
Q

Example of ‘standalone’ functions

A

range, type and print.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
420
Q

What are ‘Member’ functions, and why are they called that?

A

Member’ functions are functions that are “bound” to a specific object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
421
Q

Why are ‘member’ functions called ‘member’ functions? - (2)

A

They are called ‘Member’ functions because they are part of the object (i.e., variable) on which they are called,

e.g., or instance, .append() is automatically part of any list variable which you create

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
422
Q

How can you see all the member functions of an object in Python?

A

You can use the dir() function, passing the object (i.e., variable) as an argument.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
423
Q

Explain the purpose of the code:
my_var = [1, 2, 3]
print(dir(my_var)).

A

This code initializes a list variable my_var with values [1, 2, 3], and then uses the dir() function to display all the member functions associated with the list object my_var

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
424
Q

Explain the output of this code - what do underscores

my_var = [1, 2, 3]

print(dir(my_var))

A

In addition to the ‘private methods’ (indicated with underscores - we are not supposed to use them), we can see our old friend append - along with other methods which we talked about including index and pop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
425
Q

Structure of member funciton

A

VARIABLENAME.FUNCTIONAME()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
426
Q

TThe idea of a member function is tha it will affect the variable it is a part of so append will

A

cause the list to have additional items added to it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
427
Q

What is the difference between normal and member functions? - (4)

A

When you call normal functions don’t need to specifcy the data structure - They are called by specifying the function name followed by parentheses and passing arguments inside the parentheses.

With member funcions, you mustt provide the data structure and they operate on the data contained within that object.

n Python, for example, when we call append() on a list (my_list.append(4)), append() is a member function because it operates specifically on the list object my_list and modifies it directly.

However, when we call print(my_list), print() is a normal function because it’s a built-in function that is not associated with any specific object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
428
Q

Many Python editors will help you out by ‘prompting’ you with possible member functions when you are writing code. For example, after defining a = [1,2,3,4….1]

A

writing a. , Colab will provide a little ‘menu’ of all the member functions (purple boxes) avaliable to you - can do this instead of using dir

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
429
Q

Python has a concept of collections of functions which are called

A

modules

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
430
Q

Describe the purpose of the random module in Python - (2)

A

The random module in Python is part of the standard library and provides functions for working with random numbers.

It offers various functionalities for generating random numbers, shuffling sequences, and many more

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
431
Q

Explain the process of importing modules in Python and accessing their content - (2)

A

To use a module in Python, you first need to import it using the import keyword.

In environments like Spyder, iPython3, and Colab, after importing a module, you can type the module name followed by a dot (.) and then press the tab key (or wait) to get a list of available content within that module.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
432
Q

What does this code do? - (2)

import random

print(dir(random))

A

First, the random module is imported using the import keyword

Then, the dir() function is used on random module to list all its associated functions and is outputted using print()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
433
Q

Output of this code

import random
print(dir(random)

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
434
Q

is shuffle one of the functions in random module?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
435
Q

What is the shuffle function in random module used?

A

This function is used to randomise the order of a list -

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
436
Q

Why is shuffle important? - (2)

A

We do this in experiments quite a bit:

For example, when putting stimuli on a screen it’s often important to randomise the order so that the subject can’t tell what is coming next

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
437
Q

Explain the code snippet - (5)

A

After importing the random module, a list a containing integers [1, 2, 3, 4] is defined. T

The original order of the list is printed using the print() function.

Next, the shuffle() function is called on the list a, which randomizes the order of its elements in the list.

The shuffled list is printed using the print() function to display the new order.

Finally, the shuffle() function is called again on the same list a, further randomizing its order of elements in that list, and the shuffled list is printed once more.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
438
Q

What would be the possible output of this code snippet?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
439
Q

How to produce a list storing in variable a from values 0 to 100 inclusive.

A

a = list(range(101)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
440
Q

We call the function as random.shuffle because we

A

imported the shuffle module using import random and the function is “inside” the module.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
441
Q

Describe the purpose and behavior of the randint() function in the random module - (3)

A

he randint() function in the random module generates a random integer between two specified numbers.

It takes two arguments representing the lower and upper bounds of the range, inclusively.

When called, randint() returns a random integer within this range.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
442
Q

Explain how random.randint() is used to generate random integers between 1 and 5 inclusively in the provided code snippet - (3)

A

In the code snippet, the random.randint() function is called multiple times, each time with arguments (1, 5).

This specifies the range from which the random integer should be generated, starting from 1 and ending at 5, inclusive.

Therefore, each call to random.randint(1, 5) produces a random integer between 1 and 5, with the possibility of including both endpoints.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
443
Q

While both shuffle() and randint() are functions in the random module, they serve different purposes. - (2)

A

shuffle() rearranges the elements of a list in a random order, effectively shuffling its contents.

randint() generates a single random integer within a specified range, inclusive of both endpoints.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
444
Q

Describe how to create a loop to generate 100 random numbers between 1 and 10 using Python - (4)

A

To achieve this, import the random module.

Then, utilize a for loop to iterate 100 times using the range() function.

Within the loop, call random.randint(1, 10) to generate a random integer between 1 and 10 on each iteration and store into variable random_num

Print each generated number to output console by printing random_num

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
445
Q

How to import numpy?

A

Using the same method as before we did with random

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
446
Q

What is numpy module in Python?

A

a module for processing numbers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
447
Q

To avoid some typing, we can use a feature in Python ‘as’ keyword which allows us to rename the module as we imprt it:

A

import numpy as np # This is always how people name numpy when they import it.

print(dir(np))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
448
Q

Describe the advantages of using aliases when importing modules in Python. - (2)

A

Importing modules with aliases, such as import numpy as np, offers several benefits.

It reduces typing effort, enhances code readability by shortening module names, and promotes cleaner code appearance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
449
Q

By using the import MODULE as SHORTNAME variant, we

A

import numpy in exactly the same way as before, but we make its contents available as np.SOMETHING instead of numpy.SOMETHING.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
450
Q

Importing numpy as ‘np’ has also become the common

A

convention in most scientific code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
451
Q

We should note that modules can have modules within them - (2)

e.g.,

A

Numpy module has a random module called numpy.random

Distinct from main Python random module and has different functions inside it e.g,:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
452
Q

What does as keyword do in Python?

A

It’s commonly used in import statements to provide an alternative name for a module or to shorten the module name for brevity and readability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
453
Q

Explain this code - (2)

A

The code imports the NumPy library as np (using ‘as’ keyword) and then prints the contents of the numpy.random submodule using the dir() function.

This allows users to explore the available functions and attributes within the numpy.random submodule.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
454
Q

One other form of import which you may come across is used if you only want a - (2)

A

few functions or classes from a module and would rather that they have short names

e.g., from numpy import zeros, ones

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
455
Q

Explain the code snippet - (3)

A

This code snippet imports the zeros and ones functions from the numpy module.

The print(type(zeros)) line confirms that the zeros function has been imported, displaying its type as <class ‘function’>.

Finally, print(zeros(10)) calls the zeros function to create an array of size 10 filled with zeros, which is then printed to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
456
Q

What is the output of this code?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
457
Q

What do the zeros and ones functions do?

A

These functions, imported from the numpy module, create arrays filled with zeros and ones respectively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
458
Q

Produce a code that prints out of one-dimensional array of ones with size 10 - (2)

A

from numpy import zeros, ones

print(ones(10))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
459
Q

What is going to be the output of this code?

from numpy import zeros, ones

print(ones(10))

A

[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
460
Q

Explain the code snippet. - (3)

A

he code imports the zeros and ones functions from the NumPy module.

Then, it prints a 1-D array of ones with length 10 using ones(10).

Additionally, it prints a 2-D array of ones with dimensions 10x10 using ones((10,10)).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
461
Q

Arrays can be

A

1D or 2D or 3D

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
462
Q

What is output of this code snippet?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
463
Q

When we import it in this way:

e.g., from numpy import zeros, ones

A

we just use the names that we import without any module name prefixing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
464
Q

When do I import things? - (2)

A

Import modules **at the top of your script, not halfway through it.

Putting imports at the top of your script allows the reader to get an idea of what sort of functionality will be used and is considered good practice.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
465
Q

What would print(ones((10,10,10))) print to output console/terminal? - (2)

A

be a 3D array filled with ones, with dimensions 10x10x10. Each element of the array would be a 1.

10 lots of these: (image)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
466
Q

You can also produce your own functions using

A

def

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
467
Q

What is the syntax for defining a function in Python? - (2)

A

In Python, the syntax for defining a function involves using the def keyword followed by the function name and parentheses containing any parameters.

The body of the function is indented and contains the code to be executed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
468
Q

Explain this code - (5)

A

defines a function named printNTimes that takes two parameters: my_string, which represents the string to be printed, and n, which represents the number of times the string should be printed.

Inside the function, a for loop iterates over the range from 0 to n-1.

During each iteration, the value of my_string is printed to the console.

So, when you call this function with a string and a number n, it will print the string n times.

However, this function been defined but have not called printNTimes function so there is no output

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
469
Q

What is the output of this code?

A

(Nothing)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
470
Q

Why is the output nothing when you run the code? - (3)

A

No output appears because the function printNTimes is defined but not called with specific arguments.

To execute its instructions, you need to call the function with a string (my_string) and a number (n).

e.g., printNTimes(‘hello world’ ,9)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
471
Q

This function takes two arguements (my_string, n) which you must supply otherwise

A

the function will fail- TypeError

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
472
Q

What happens when you try to call the function printNTimes() without any arguments?

A

Calling the function printNTimes() without providing the required arguments (my_string and n) will result in a TypeError because the function expects two arguments but none were provided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
473
Q

What is the output if we call function printNTimes: printNTimes (‘:)’,5)

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
474
Q

Def functions are useful for

A

doing things again and again without replicating code for

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
475
Q

Functions do things (i.e., execute tasks/code) and they also (usually) ‘return’

A

one or more values

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
476
Q

Example of def function returning values

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
477
Q

Explain the code and its output - (3)

def square(x):
y=x*x
return(y)

answer=square(5)
print(answer)

A

The square function takes an argument x and calculates the square of this input number.

It stores the result in the variable y and returns it. In the code snippet, square(5) is called, computing the square of 5, resulting in 25.

This value is stored in the variable answer, which is then printed, producing the output: 25.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
478
Q

What does the code print(‘#’*n) accomplish, given n=100?

A

It prints 100 hashtags in a row.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
479
Q

Explain the purpose of the def function: def print_underline(inputString,underlineCharacter)

A

This function, print_underline, takes two arguments: inputString and underlineCharacter.

It calculates the length of inputString using the len() function and stores it in the variable stringLength.

Then, it prints inputString, followed by an underline made of underlineCharacter repeated for the length of inputString.

Finally, it returns the length of the inputString

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
480
Q

What would be output if print_underline was given inputString as ‘Hello World’ and underlineCharacter of ‘#’ and then:

my_value = print_underline(‘Hello World’, ‘#’)
print(f’Length is {my_value}’)

A

Hello World
###########
Length is 11

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
481
Q

For larger scale data analysis (usually with neuroimagning data) we can use pre-existing modules and core tool for this in Python is

A

numpy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
482
Q

Numpy works with

A

large blocks of numbers called ‘matrices’ (or sometimes ‘arrays’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
483
Q

Matrices are often rectangular blocks that are

A

stored as rows x columns

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
484
Q

Matrices are often rectangular blocks that are stored as rows x columns.

For instance:

A

3 rows by 2 columns so it would have shape (3, 2).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
485
Q

The order of the dimensions of matrices is always

A

(rows, columns).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
486
Q

For most of the time we will be working with 2D matrices, however numpy will cope with any number of dimension from

A

(from 1D up to any number of dimensions).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
487
Q

Matrices are usually two-dimensional whereas arrays can be

A

have any number of dimensions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
488
Q

when performing addition, subtraction, multiplication, or division on matrices, they must be of

A

he same size, meaning they must have the same number of rows and columns.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
489
Q

Example of addition of matrices

A
490
Q

Example of subtraction of matrices:

A
491
Q

Example of multiplication and division of matrices - element by element mulplication/division|

A
492
Q

numpy and scipy are two modules that support for much of the

A

scientific work that you will want to do in Python

493
Q

numpy provides “low-level” routines for manipulating matrices like

A

linear algebra routines (e.g. inverting a matrix), Fourier transforms and random number capabilities (using a range of distributions).

494
Q

scipy provides “higher-level” routines for science and engineering and uses numpy as base and then adds

A

additional algorithms for things like image and signal processing.

495
Q

matplotlib is a

A

plotting library that lets you produce a range of different graphs

496
Q

Numpy uses the numpy.array class to store

A

arrays of numbers

497
Q

Numpy arrays can be any

A

number of dimensions and any size

498
Q

Python is a 0-indexed language. This means that if we have a2x2 array

A

the two rows are referred to using indices 0 and 1 and the two columns are referred to using indices 0 and 1.

499
Q

When indexing into numpy arrays, we use

A

square brackets (similar to lists).

500
Q

We can also use a range separated by a colon (:) in array which is exclusive of last number (similar to range function) e.g., - (2)

A

data[0:100, 0:100] This gives us a 100x100 subarray of the data array

data[50:, :] This gives us the 51st row onwards and all of the columns –> In Python, indexing starts from 0, so the 51st row corresponds to index 50. T

501
Q
A
502
Q

Explain the code please - (5)

A

import numpy as np: This line imports the NumPy library and aliases it as np, allowing us to refer to NumPy functions and objects using the shorter name np.

z = np.zeros((2, 3)): This line creates a 2x3 matrix filled with zeros.

The numbers (2, 3) inside the parentheses represent the dimensions of the matrix, with 2 rows and 3 columns.

print(‘Here is an array of zeros’): This line prints a descriptive message to indicate that the following array contains all zeros.

print(z): This line prints the array z containing zeros to the console.

503
Q

What is the output of the code?

A

Here is an array of zeros
[[0. 0. 0.]
[0. 0. 0.]]

504
Q

What does z[0, 0] = 1.0 do? - (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets the element at the first row and first column of the matrix z to 1.0.

In other words, it modifies the top-left element of the matrix.

505
Q

What does z[0, :] = 2.0 - (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets all elements in the first row (all columns) of the matrix z to 2.0.

It fills the entire first row with the value 2.0.

506
Q
A
507
Q

What does z[:, 1] = 3.0- (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets all elements in the second column (all rows) of the matrix z to 3.0.

It fills the entire second column with the value 3.0.

508
Q

What does z[0, :] = 2.0 - (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets all elements in the first row (all columns) of the matrix z to 2.0.

It fills the entire first row with the value 2.0.

509
Q

What does z[:, 1] = 3.0- (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets all elements in the second column (all rows) of the matrix z to 3.0.

It fills the entire second column with the value 3.0.

510
Q

What does single_num = z[0,1] do if we print it out? - (2)

z = np.zeros((2,3)) producing 2x3 matrix of zeros

A

Extracts a single number from the first row and first column of the matrix

The item at z[0,1] is 0.0

511
Q
A
512
Q

What does a_row = z[0,:] do if we print it out? - (3)

z = np.zeros((2,3)) producing 2x3 matrix of zeros

A

In the context of array indexing in NumPy, the comma separates the row index from the column index.

In this expression, z[0, :], 0 indicates the row index (specifically the first row), and : indicates that all columns in that row are selected.

Output:
[0. 0. 0.]

513
Q

So with matrices we can set

A

certain elements to be certain values as well as extract single and multiple numbers

514
Q
A
515
Q

What does rArray=np.random.rand(200,200) do?

A

This line initializes a NumPy array named rArray with dimensions 200x200 filled with random numbers generated using np.random.rand().

516
Q

What does print(f’Array size={rArray.size}’) display?
if rArray=np.random.rand(200,200)

A

This line prints the total number of elements in the rArray array which is 4000

517
Q

What does rint(f’Array shape={rArray.shape}’)display?
if rArray=np.random.rand(200,200) - (2)

A

This line prints the shape of the rArray array, which represents its dimensions as a tuple (rows, columns)

output: Array shape=(200, 200)

518
Q

What does smallerArray=rArray[0:100,0:100] do

if rArray = np.random.rand(200,200)

A

This line creates a subset of the rArray array, selecting rows from index 0 to 99 and columns from index 0 to 99, effectively creating a smaller 100x100 array from the original 200x200 array.

519
Q

: How can the size parameter in np.zeros be represented, according to the comment # The size thing here is a tuple - it can also be a list?

A

The size parameter in np.zeros can be represented as either a tuple or a list, allowing flexibility in specifying the dimensions of the array to be created.

520
Q

Explain the code - (4)

import numpy as np

z = np.zeros((2, 3)) # The size thing here is a tuple - it can also be a list
print(‘Here is an array of zeros’)
print(z) #array of 2x3 zeros

print(‘Now I set the bottom right element (1,2) to 9’)
z[1,2]=9 #Work out how to do this

print(z [1,:])

A

This code snippet begins by importing the NumPy library and aliasing it as np.

It then initializes a 2x3 NumPy array named z filled with zeros.

The line z[1, 2] = 9 modifies the bottom-right element of the array to 9.

Finally, it prints the second row of the array using print(z[1, :]), where z[1, :] selects the entire second row of the array.

521
Q

What is the output of this code?

import numpy as np

z = np.zeros((2, 3)) # The size thing here is a tuple - it can also be a list
print(‘Here is an array of zeros’)
print(z) #array of 2x3 zeros

print(‘Now I set the bottom right element (1,2) to 9’)
z[1,2]=9 #Work out how to do this

print(z [1,:])

A
522
Q

What does the comment mean: # The size thing here is a tuple - it can also be a list - (4)

A

refers to the argument passed to np.zeros(), which specifies the dimensions of the array.

In Python, dimensions are often represented as tuples, where the first element indicates the number of rows and the second element indicates the number of columns.

However, this argument could also be provided as a list.

523
Q

We can also produce an array filled with ones instead of zeros using

A

np.ones((3,4)

524
Q

Explain what this code does - (3)

A

his code imports the NumPy library with the alias np

a 3x4 matrix filled with ones using the np.ones function and stores it in the variable o.

Finally, it prints the contents of the o matrix to the output console.

525
Q

What is the output of this code?

A
526
Q

If we want to type in some data we can produce an array by hand using np.array function e.g., - (2)

A

Create a 2x4 array of numbers - we do this by converting a list of lists to an array.

a = np.array([[1, 2, 3,8], [4, 5, 6,9]])

527
Q

Explain this code - (3)

A

This code imports the NumPy library as np and creates a 2x4 NumPy array named “a” by converting a list of lists into an array.

The array contains the elements [[1, 2, 3, 8], [4, 5, 6, 9]].

Finally, it prints out the array “a”.

528
Q

What is the output of this code?

A
529
Q

If you entered all integers in your array then

A

it produces an int array

530
Q

There are 3 ways to produce a float array - (3)

A
  1. Force a float array by making at least one number floating point with a decimal point
  2. Force a float array by specifying it to numpy at creation time using dtype
  3. Force a float array by explicitly casting an int array
531
Q

Ways to produce float array

  1. Force a float array by making at least one number floating point with a decimal point
A

a = np.array([[1.0, 2, 3], [4, 5, 6]])
print(a)

Output:
[[1. 2. 3.]
[4. 5. 6.]]

532
Q

Ways to produce float array

  1. # Force a float array by specifying it to numpy at creation time
A

a = np.array([[1, 2, 3], [4, 5, 6]], dtype=float) # <— that dtype thing tells numpy to make it floats
print(a)

output:
[[1. 2. 3.]
[4. 5. 6.]]

533
Q

What does single_num = z[0,1] do if we print it out? - (2)

z = np.zeros((2,3)) producing 2x3 matrix of zeros

A

Extracts a single number from the first row and first column of the matrix

The item at z[0,1] is 0.0

534
Q

Ways to produce float array

  1. Force a float array by explicitly casting an int array
A

a = np.array([[1, 2, 3], [4, 5, 6]]) # Initially it’s an int array…
a = a.astype(float) # … but now we’ve ‘floated’ it!

print(a)

output:
[[1. 2. 3.]
[4. 5. 6.]]

535
Q

explain code - (5)

a = np.array([[1.0, 2, 3], [4, 5, 6]])
print(a)

A

This code creates a NumPy array named a containing two rows and three columns.

It ensures the array contains floating-point numbers by including at least one number with a decimal point (1.0).

By including a floating-point number (1.0) in the array, it forces NumPy to interpret all numbers in the array as floating-point numbers.

Therefore, even though some numbers are entered as integers (2, 3, 4, 5, 6), they will be converted to floats when the array is created.

Finally, it prints the array a.

536
Q

explain this code:

a = np.array([[1, 2, 3], [4, 5, 6]], dtype=float) # <— that dtype thing tells numpy to make it floats
print(a)

A

This code initializes a 2x3 NumPy array with the values [[1, 2, 3], [4, 5, 6]] and forces every integer value to be a float by specifying dtype=float and prints the resulting array.

537
Q

Break down what a = np.array ([[1.0,2,3],[4,5,6]]) mean - (3)

A

So, [[1.0, 2, 3], [4, 5, 6]] creates a 2x3 array - 3 elements in the list so 3 columns and 2 lists meaning 2 rows

The first inner list [1.0, 2, 3] represents the first row of the array. It contains three elements: 1.0, 2, and 3.

The second inner list [4, 5, 6] represents the second row of the array. It also contains three elements: 4, 5, and 6.

538
Q

Explain thsi code - (4)

A

This code initializes a NumPy array a with integer values in a 2x3 format, meaning it has 2 rows and 3 columns.

Then, it uses the astype method to explicitly cast the data type of the array a to float.

This operation overrides the original array a and changes its data type from integer to float.

Finally, it prints the modified array a, now containing floating-point values.

539
Q

You can also replace dtype as float with

A

int e.g., a = np.array([[1, 2, 3.3], [4, 5, 6]], dtype= int)

540
Q

Explain this code - (4)

A

This code initializes a NumPy array a with values in a 2x3 format.

It specifies the data type of the array as int, which forces all elements to be integers, even if they were floats initially.

This is achieved using the dtype=int parameter in the np.array function call.

Finally, it prints the resulting array a.

541
Q

What is output of the code going to be - going to be same even if its 3.6 instead of 3.6

A
542
Q

when specifying the data type as int using dtype=int, any float values are truncated to integers. So, for example, if a value is 3.6, it will be

A

converted to 3.

543
Q

In numpy module, you can also use other data types such as

A

as np.complex for complex numbers, np.bool for arrays of bools and a range of more specialist types if you need to.

544
Q

You can also produce a list then

A

convert to array using np.array

545
Q

Example of converting list to numpy array

A
546
Q

What will be output of the code?

A
547
Q

Explain this code - (4):

A

This code first imports the NumPy library and then defines a list of numbers (my_numbers) containing two sub-lists.

Next, it converts the list my_numbers into a NumPy array using the np.array() function which is stored in variable ‘a’

The resulting array a is a 2D array with the same structure as the original list and a size of 2x3 (2 rows and 3 columns).

Finally, it prints the array a,

548
Q

For many reasons, we often want to make … in arrays

A

ranges of numbers in arrays

549
Q

For many reasons, we often want to make ranges of numbers in arrays.

There are quite a few ways to do this but the two it is important to remember and know about are - (2)

A

np.arange and np.linspace

550
Q

What are the main differences between np.arange and the built-in range function? - (2)

A

The main differences are:
np.arange returns a NumPy array object of dtype int or float depending on what data type is specificed, while range returns a sequence of integers

np.arange can handle floating-point numbers, whereas range only works with integers.

551
Q

Explain this code - (3)

A

In the first example (a = np.arange(3)), it creates an array containing numbers from 0 up to (but not including) 3.

In the second example (b = np.arange(1, 3)), it creates an array containing numbers from 1 up to (but not including) 3.

In the third example (c = np.arange(1, 3, 0.5)), it creates an array containing numbers from 1 up to (but not including) 3, with a step size of 0.5,

552
Q

What would be the output of this code?

A
553
Q

Explain the code snippet (output attached) - (4)

A

This code snippet first imports the matplotlib.pyplot module and the numpy module as plt and np,
respectively.

It then generates an array of ‘x’ values from 1 to 5 with a step size of 1 using np.arange(1, 6, 1).

Next, it calculates ‘y’ values by squaring each ‘x’ value.

Finally, it plots the data with ‘x’ values on the x-axis and ‘y’ values on the y-axis using plt.plot() and displays the plot using plt.show().

554
Q

Normally leaving this line out of plt.show() will still show plot in colab but might be

A

a warning

555
Q

How to produce x range from -5 to 5 inclusive with steps of 1?

A

x = np.arrange(-5,6,1)

556
Q

What is the purpose of np.linspace in Python?

A

np.linspace is used to generate a specified number of evenly spaced numbers between a start and stop value.

557
Q

What are the arguements to the function called np.linspace?

A

(start, stop, count)

558
Q

Get 5 equally spaced numbers between 0.0 and 1.0 inclusive

What does the following code snippet do? - (4)

import numpy as np

a = np.linspace(0.0, 1.0, 5)
print(a)

A

This code uses np.linspace to generate an array a containing 5 equally spaced numbers between 0.0 and 1.0 (inclusive).

The np.linspace function takes three arguments: the start value (0.0), the stop value (1.0), and the number of values to generate (5).

It returns an array with equally spaced numbers, including both the start and stop values.

The resulting array a is then printed.

559
Q

Get 5 equally spaced numbers between 0.0 and 1.0 inclusive

Output of this code

import numpy as np

a = np.linspace(0.0, 1.0, 5)
print(a)

A

[0. 0.25 0.5 0.75 1. ]

560
Q

Modify the code below to plot a nice smooth cubic function (x to the power of 3) between -5 and 5 with exactly 100 steps:

A
561
Q

Explain this code - (4)

A

This code snippet imports the matplotlib.pyplot module and the numpy module as plt and np, respectively.

It then generates an array x containing 100 equally spaced numbers between -5 and 6 using np.linspace(-5, 6, 100).

Next, it calculates ‘y’ values by cubing each ‘x’ value.

Finally, it plots the data with ‘x’ values on the x-axis and ‘y’ values on the y-axis using plt.plot(), adds gridlines to the plot using plt.grid(True), and displays the plot using plt.show().

562
Q

To make graphs smoother then change

A

the steps in np.array/counts in np/linspace

563
Q

The np.linspace produces an array? - (2)

A

produces an array.

It generates evenly spaced numbers over a specified interval and returns them as an array.

564
Q

Numpy can produce

A

random numbers

565
Q

Functions for producing random numbers from numpy come from

A

np.random module

566
Q

Output of 1D array vs 2D array:

A
567
Q

The np.random.rand in np.random module for producing random numbers produces

A

evenly distributed numbers between 0 and 1.

568
Q

The parameter we pass to the np.random.rand function is the - (5)

A

size of the array of random numbers that we require.

This parameter determines the shape of the output array in terms of rows and columns.

For example:

np.random.rand(5) will generate a 1D array with 5 elements.
np.random.rand(3, 4) will generate a 2D array with 3 rows and 4 columns.

569
Q

What does the following code snippet do? - (2)

import numpy as np

r = np.random.rand(2, 2)
print(r)

A

This code snippet uses np.random.rand() to generate a 2D array r with 2 rows and 2 columns, filled with random numbers between 0 and 1.

It then prints the generated array r

570
Q

All of the generated numbers here lie between 0 and 1 (as well as colour bar runs from 0 to1)

A

Each number is equally likely to be chosen - we say that the distribution is ‘uniform’.

571
Q

Another function in numpy to produce random numbers in np.random module is

A

np.random.randn

572
Q

The randn function in Numpypy produces… - (2)

A

The randn function in NumPy generates random numbers drawn from a normal distribution.

The ‘n’ at the end of the function name indicates that it follows a normal distribution.

573
Q

Explain this code snippet - (4)

A

This code snippet generates a 50x50 array of random numbers drawn from a normal distribution using np.random.randn().

It then displays the array rn as an image using plt.imshow(), with colors representing the values of the numbers.

Additionally, it adds a color bar to the side of the plot using plt.colorbar(), which helps interpret the colors.

Finally, it displays the plot using plt.show().

574
Q

We can visualise these two sets of numbers side-by-side using the

A

subplots function of matplotlib

575
Q

Explain this code - (4)

A

This code snippet generates a 20x20 array of random numbers between 0 and 1 using np.random.rand().

It then displays the array r as an image using plt.imshow(), with colors representing the values of the numbers (When displaying numerical data as an image, each numerical value in the array is mapped to a color)

Additionally, it adds a color bar to the side of the plot using plt.colorbar(), which helps interpret the colors.

Finally, it displays the plot using plt.show().

576
Q

Explain this code - (3) - assuming previous code of defining ‘r’ and ‘rn’ and producing their graphs

fig,a = plt.subplots(1,2)

fig,a = plt.subplots(1,2)

a[0].imshow(rn) #This function shows your normal-random array as an image

a[1].imshow(r) #This function shows your uniform-random array as an image

A

fig, a = plt.subplots(1, 2): This line creates a figure with two subplots arranged side by side. The subplots() function returns a figure (fig) and an array of axes (a). In this case, 1 indicates that there is only one row of subplots, and 2 indicates that there are two subplots in total (side by side).

a[0].imshow(rn): This line displays the first subplot (a[0]) and shows the normal-random array rn as an image using the imshow() function. a[0] refers to the first subplot created by plt.subplots(), and imshow() is a function used to display arrays as images.

a[1].imshow(r): This line displays the second subplot (a[1]) and shows the uniform-random array r as an image using the imshow() function. a[1] refers to the second subplot created by plt.subplots().

577
Q

Explain this code - (5)

A

This code snippet assumes that rn and r have been defined previously as arrays representing different types of random numbers.

It creates a figure with two subplots arranged side by side using plt.subplots(1, 2).

In the first subplot (a[0]), it computes and displays a histogram of all numbers in the array rn after flattening it into a 1D list using flatten(). The histogram is computed with 50 bins.

In the second subplot (a[1]), it computes and displays a histogram of all numbers in the array r. Similar to the first subplot, the histogram is computed with 50 bins.

This allows for a visual comparison of the distributions of two arrays, which may represent different types of random numbers.

578
Q

Arithmetic on numpy arrays works in the way you would probably expect. To perform arithmetic on two arrays, they normally need to be

A

the same size

579
Q

How does scalar arithmetic work with numpy arrays?

A

Scalar arithmetic with numpy arrays involves operating on the entire array with a single number, known as a ‘scalar’.

580
Q

Explain this code - (4)

import numpy as np

a=np.array([[1,2],[3,4]])
b=np.array([[5,6],[7,8]])
c=a+b # Adding two arrays which are the same size
d=a*10 # Multiplying a single array by a scalar
print(a)
print(b)
print(c)
print(d)

A

Two arrays ‘a’ and ‘b’ are defined with the same dimensions, both being 2x2 arrays.

The arrays ‘a’ and ‘b’ are added together element-wise, resulting in array ‘c’.

Array ‘a’ is multiplied by scalar 10, resulting in array ‘d’. Since ‘a’ is a 2x2 array, ‘d’ will also be a 2x2 array where each element of ‘a’ is multiplied by 10.

The arrays ‘a’, ‘b’, ‘c’, and ‘d’ are printed to observe the results of the operations.

581
Q

What will be output of the code?

import numpy as np

a=np.array([[1,2],[3,4]])
b=np.array([[5,6],[7,8]])
c=a+b # Adding two arrays which are the same size
d=a*10 # Multiplying a single array by a scalar
print(a)
print(b)
print(c)
print(d)

A
582
Q

What does the following code snippet do? - (3)

a_mean = a.mean()
print(a_mean)

a_sd = a.std()
print(a_sd)

a_var = a.var()
print(a_var)

A

a_mean = a.mean() calculates the mean (average) of the numbers in array ‘a’ and assigns it to the variable ‘a_mean’. The mean is then printed.

a_sd = a.std() computes the sample standard deviation of the numbers in array ‘a’ and assigns it to the variable ‘a_sd’. The standard deviation is then printed.

a_var = a.var() determines the sample variance of the numbers in array ‘a’ and assigns it to the variable ‘a_var’. The variance is then printed.

583
Q

Q1:
Question: What type of error is demonstrated by attempting to execute print (‘Welcome to the programming course!)?

A

A1:
A syntax error (the bracket and close quote are in the wrong places)

584
Q

Q2:
Question: What happens when you try to convert a string input to an integer using int(input(‘Enter a number’)) but enter a string instead of a number?

A

A2:
You will get an ‘exception’ (Note for the exam we don’t expect you to know what >sort< of exception - just what sort of error it is.

585
Q

Q3:
Question: In the context of exception handling in Python, which keywords are used to catch exceptions that are raised?

A

A3:
‘try’ and ‘except’

586
Q

Q4:
Question: Given the code snippet
data = input(‘Enter a number: ‘)

followed by

print(int(data)+2), what type of error occurs if the user enters a string like “hello”

A

A4:
Again, an exception. Note that the error will happen when the data is cast to ‘int’ , not when it is input.

587
Q

Q5:
Question: In a try-except block, what will the following code do if a ValueError occurs?

try:
start = int(input(‘Starting number: ‘))
except ValueError as e:
print(“Would you please give me an actual number next time?”)
print(e)

A

A5:
It will execute the print statements inside the ‘except’ block: Printing the error message >and< the name of the exception.

588
Q

Q6:
Question: How do you access the error message within an except block?

A

A6:
Via the ‘e’ variable which will contain the error message.

589
Q

Q7:
Question: Given the function below, what will printNTimes(‘Hello, World!’, 3)

output?

def printNTimes(my_string, n):
for x in range(n):
print(my_string)

A

A7:
It will print the string ‘Hello World!’ three times

590
Q

Q8:
Question: What will the following Numpy code snippet output, and why?

import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a[2])

A

A8:
It will print the number ‘3’. This is the third element in the array (and Python starts indexing at zero)

591
Q

Q9:
Question: Consider the following plotting code. What does it aim to plot, and how can you describe the relationship between x and y?

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.show()

A

A9:
It will plot sin(x) as a function of x - in other words a sine wave. There will be 100 points for x values between 0 and 10.

592
Q

Q10:
Question: Analyze the following code snippet that creates a plot. What mistake will prevent the code from executing correctly (plotting y as a function of x)?

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5, 5, 100)
y = x**2

plt.plot(x)
plt.show()

A

A10
The plot statement should take two arguments: x and y. Here it just gets x and it will just plot the values of x (which will be 100 points in a straight line from -5 to 5)

593
Q

What will be the output of the following code?

my_list = [1, 2, 3]
print(my_list[3])

A

An IndexError will occur because the index 3 is out of range for the list my_list.

594
Q

Explain the purpose of the range() function in Python and provide an example - (3)

A

The range() function generates a sequence of numbers within a specified range. It is commonly used for iterating over a sequence of numbers using loops.

Example:

for i in range(5):
print(i)

595
Q

What does the following code snippet do? - (3)

my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
print(my_dict.get(‘d’, 0))

A

The code will print 0.

The .get() method retrieves the value associated with the specified key (‘d’) in the dictionary (my_dict).

If the key does not exist, it returns the default value specified as the second argument, which is 0 in this case.

596
Q

How do you concatenate two lists in Python? - (3)

A

You can concatenate two lists using the + operator or the .extend() method. Example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list)

This will output [1, 2, 3, 4, 5, 6].

597
Q

What is the purpose of the len() function in Python? - (3)

A

The len() function returns the number of items in an object. It can be used to get the length of strings, lists, tuples, dictionaries, and other iterable objects.

Example:

python
Copy code
my_string = “Hello”
print(len(my_string)) # Output: 5

598
Q

When double clicking on polygon, these properities show up - (basic) - (3)

A

It is asking you to name the polygon stimuli in trial routine so far it is set as ‘polygon’

Asking for start and end time

The shape of the polygon is going to a triangle but can alter it at the drop down menu

599
Q

You can also choose a hexagon in polygon properities box by

A

from shape menu select regular polygon with 6 sides - making it a hexagon

600
Q

“In PsychoPy, if both text and polygon stimuli have the same duration, what determines their order of appearance?” - (2)

A

“The order in which stimuli are stacked in the routine determines their presentation order.

Since both text and polygon stimuli have the same duration value (1.0), the polygon stimulus will appear ontop of the text stimulus

601
Q

If we run the experiment with this

A

polygon appears over the text and since polygon is so big, we can’t see the text

602
Q

What does the appearence section of polygon properities box show you? - (5)

A

Fill colour: The colour with which the polygon is filled.

Border colour: The colour of the polygon’s border.

Colour space format for the specified colours.

Opacity of the stimulus: A value of 1 indicates it’s opaque, 0 means fully transparent, and 0.5 represents translucency.

Contrast of the stimulus and width of the shape.”

603
Q

Fiddle with RGB colours so polygon is black ([-1,-1,-1])

A
604
Q

Can fiddle with RGB colours to make it white by

A

setting to [1,1,1]

605
Q

How can we make the polygon move? - (4)

A

“To make a polygon move continuously across the screen:

Go to the polygon properties and click on its ‘layout’ tab.

Find the ‘position’ entry.
Replace the X-coordinate with ‘t,’ representing the current time since the start of the experiment in seconds.

Set the menu setting to the right of the Position to ‘set every frame’ to ensure the position updates on every frame.”

606
Q

Inside Psychopy there are variables just like in a ‘normal’ python program. One of these is simply

A

‘t’

607
Q

What is variable ‘t’ in Psychopy? - (2)

A

the current time since the start of the experiment in seconds.

That number is always getting bigger.

608
Q

What happens when we replce the ‘x’ coordinate of position with t? - (3)

A

tell Psychopy to update the position of polygon on every frame then the polygon will move across the screen:

causes the stimulus to move horizontally across the screen over time.

This is because ‘t’ represents the current time since the start of the experiment in seconds, and it continuously increases as the experiment progresses.”

609
Q

variable ‘t’ represents

A

time

610
Q

How to make the polygon move to the left? - (3)

A

Replace the ‘x’ coordinate of the position with ‘-t’. This means that the position along the x-axis will decrease as time increases, effectively moving the polygon to the left.

Psychopy needs to update the position on every frame to ensure continuous movement.

To do this, change the menu setting next to the position property to ‘set every frame’.”

611
Q

What does replacing ‘t’ in x coordinate of position with sin(t * 2 * pi

A

As ‘t’ time gets bigger, polygon goes up and down (along horizontal axis) like a sine wave

612
Q

How to make the polygon rotate in the centre? - (5)

A

Make the orientation of the object dependent on time (instead of position)

Set position to 0,0 (x,y) at the centre

The orientation is set by degrees

So after 1s , move 1 degree and after 2s move 2 degrees which is not fast if orientation set to just ‘t’

So to make polygon spin faster, we can set ‘t’ to 20 so after 1 s, orientation of polygion moves by 20 degrees, after 2s orientation of polygon moves by 40 degrees etc..

Ensure orientation is updated on every frame by setting the menu setting next to the orientation parameter to ‘set every frame’.”

613
Q

To make polygon randomly move to the left, right or stay in the middle - (8)

A

Start by adding a code component to your PsychoPy Builder project. This component allows you to insert custom Python code into your experiment.

Inside the code component, navigate to the ‘Begin Routine’ tab. Here, you’ll write code that will be executed at the beginning of each trial or routine.

In the ‘Begin Routine’ tab, insert the following Python code:
direc = randint(-1, 2)

This code utilizes NumPy’s randint function to generate a random integer between -1 (inclusive) and 2 (upper range exclusive) so:

The possible values for direc will be -1, 0, or 1.

This variable direc will determine the direction of movement for the polygon.

Set the polygon’s position parameter to (t * direc, 0), where t represents time. Multiplying t by direc allows for random movement along the x-axis. If direc is -1, the polygon will move left; if direc is 0, it will stay in the middle; if direc is 1, it will move right.

To ensure that the position is updated on every frame, set the menu setting next to the position parameter to ‘set every frame.’ This ensures that the polygon’s position is continuously updated throughout the duration of the routine, allowing for dynamic movement.”

614
Q

direc=randint(-1,2) will

A

It picks an integer at random between -1 and 2 (with the upper range being exclusive - so possible values are -1,0,1)

615
Q

“If we set the position of the polygon to (t * direc, 0) but set it to constant - (5)

A

The polygon’s position is determined by ‘t’ multiplied by ‘direc’ (-1, 0, or 1).

At the beginning of the routine. so it will pick a value for ‘direc’ and then it will stay the same for the whole duration of the routine

However, the polygon remains fixed at this initial position for the entire duration of the routine.

Since the position is constant, the polygon does not update its position over time.

Therefore, it stays stuck at its initial position regardless of any changes in time (‘t’) during the routine.”

616
Q

What does this piece of code do? - (6)

A

When builder creates a psychopy experiment it makes a data structure called ‘thisExp’

‘thisExp’ is a data structure created by PsychoPy that contains all the information about the experiment.

It keeps updating this as it goes along - and at the end it saves it to disk.

If you add in your own variables to the same structure it will save them out as well

We added the variable ‘direc’

It says save my new variable called ‘direc’ (in black) into data structure called ‘thisExp’ and call it ‘direc’ (in grey) - adds it into a column in CSV file

617
Q

you can add this code: thisExp.addData(‘direc’, direc) to - (2)

A

beginning of the routine but make sure it comes >after< you define the variable.

or end routine

618
Q

We can place two dots on either side of trial and ‘press’ okay - (2)

A

And we have produced a loop and asked psychopy to runt his trial many times

In dialog box, we can change the number of trials to ‘15’

619
Q

Since we saved thisExp.addData(‘direc’, direc) we can see in CSV - (2)

A

date = date and moment experiment started down to millisecond, tells participant session and trials - has all info for data analysis

measures framerate - how fast screen is running (e.g., 60 Hz - updates 60 times per second) like depends temp of room, graphics card - records before each trial begins

620
Q

The polygon does move randomly from trial to trial (15 trials) but its haerd to know when some trials start and end - (2)

A

so we add ‘pre’ and ‘post’ trial within the loop by adding a routine

In each new routine add some text: ‘get ready’ and ‘respond’ for 1.0s

621
Q

“What happens if ‘Get Ready’ and ‘Respond’ text components are placed outside of a trial loop that loops 15 times?” - (4)

A

“If ‘Get Ready’ and ‘Respond’ text components are placed outside of a trial loop that loops 15 times:

These text components will be displayed once before the loop begins and once after it ends.

They will not be presented repeatedly for each trial within the loop.

Participants will see the ‘Get Ready’ text at the start of the experiment, followed by 15 trials, and then the ‘Respond’ text at the end.

622
Q

Close to have our experiment complete but one thing is to make measurements in this case for our polygon moving left, right or centre randomly we - (6)

A

collecting a keypress .

We are going to ask subjects to use the arrow keys to tell us whether the stimulus moved left, right or stayed still. ‘Left arrow’, ‘Right arrow’ and ‘up arrow’.

To do this, add another component to the ‘post’ period: a keypress after trial in post routine- allowing participants to respond after stimuli stopped moving for 1.0s

Having allowined keys in this component to be ‘left’ arrow for when polygon moving left, ‘right’ so ‘right arrow’ for when polygoin moving right and ‘up’ arrow for polygon in centre

‘Force end of routine’ ensures that the routine ends immediately after the participant responds to the post-trial instruction -

then trial loop will proceed to the next iteration until the specified number of iterations (e.g., 15) is reached. After completing the specified number of iterations, the trial loop will end,

623
Q

What is a grating stimulus?

A

This is a stripy circle (filled with either a sine wave or ‘hard’ stripes)

624
Q

What does this show for grating stimuli properities?

A

Texture within the grating stimulus has a 1-D sine wave

625
Q

What does the foreground colour show for grating stimulus?

A

Grating stimuli will be black and white

626
Q

How to produce a circular grating stimulus?

A

Going to change the mask to circle

627
Q

How to produce 4 stripes in circular grating stimulus? - (4)

A

setting the Spatial Frequency parameter to 4 will indeed produce 4 stripes (4 vertical black lines and 4 white lines) within the grating stimulus.

In PsychoPy, the Spatial Frequency parameter determines the density of the stripes within the grating.

When you set it to 4, it means that within each unit of space (e.g., pixels), there will be 4 stripes.

This results in a higher frequency of stripes, making the grating appear more densely striped or patterned.

(circle now)

628
Q

Placing our keyboard response withtin the trial to measure RT - (3)

A

using only space keypress response

Also selected ‘force end of routine’

Enabling ‘force end of routine’ means that the routine will end immediately after the participant presses the ‘space’ key - only one trial is done

629
Q

“What happens in a trial routine that includes a ‘Get Ready’ text component displayed for 1.0 second, followed by a grating stimulus shown for 1.0 second, and a keyboard response allowing only ‘space’ with ‘force end of routine’ selected - , all looped for 15 trials? - (4)

A

“In each trial:
The ‘Get Ready’ text component appears for 1.0 second to prepare the participant.

Next, the grating stimulus is presented for 1.0 second, engaging visual perception.

Participants must respond using the ‘space’ key, triggering the ‘force end of routine’ to end the trial immediately upon response.

This entire trial sequence is repeated for a total of 15 trials, ensuring consistency and allowing for data collection across multiple iterations.” - The loop is important because we have to get lots of measurements to make a statistically-reliable estimate of the average RT.

630
Q

Whats wrong with the experiment setup to measure reaction time and solution?: - (2)

“What happens in a trial routine that includes a ‘Get Ready’ text component displayed for 1.0 second, followed by a grating stimulus shown for 1.0 second, and a keyboard response allowing only ‘space’ with ‘force end of routine’ selected - , all looped for 15 trials? - (3)

A

In CSV under key_respon, RT is normal towards start around 200 ms but towards the end, the RT get very short around only 9 ms

What happens is individual is learning to antipcate the stimulus (anticipatory effect), the get ready! cue is taking exavtly 1 s and knowing its coming and get their finger ready and cheat on RT task

Thus, we need to get this get ready period randomised

The random wait is critical, otherwise you will just get into the habit of anticipating the stimulus and your RT will not really be a ‘reaction’.

631
Q

How to randomise the ‘get ready’ cue? - (7)

A

Adding code element in getReady routine in which:

Set duration of ‘Get Ready’ to randTime variable

randTime equals random()*21 which generates a random floating-point number between 0 (inclusive) and 21 (exclusive) and assigns it to the variable “randTime”.

random()” generates a random floating-point number between 0 (inclusive) and 1 (exclusive).

Multiplying by 21 scales this random number to the range between 0 and 21.

. By generating a random value for “randTime”, you’re introducing variability in the timing between the grating stimulus and the onset of the “Get Ready” text.

This variability creates a variable Inter-Stimulus Interval (ISI) between the two stimuli, which can help prevent participants from predicting the onset of the “Get Ready” text

632
Q

Can also add ‘thisExp.addData(‘randTime’, randTime) into

A

Begin routine after defining variable ‘randTime’

633
Q

Q1
In psychopy I have created a polygon. I would like its vertical position to change with time. I have set these parameters:

What’swrong?

A

The position is not being updated every frame. Change the dropdown on the right to ‘Every frame’

634
Q

Q2
I would like to loop my trial 5 times. What is wrong with the experiment shown here?

A

The loop is only placed around the ‘Get ready’ routine, not the trial itself. The dots should be on the left of ‘Get ready’ and the right of ‘Trial’

635
Q

Q3
This code defines a delay before the stimulus is shown. What are the minimum and maximum possible delay values?

A

The rand() function returns a number between 0 and 1. So the min=2, and max=6.

636
Q

Q4
I need to save the value of randTime because I suspect that the delay might influence the reaction time. When I come to look at my experiment data file it has not been saved. Here is the code. What is wrong?

A

There needs to be something to add randTime to the experimental data structure on each trial. Possibly this statement is in the code that is run at the end of the experiment (you can’t see that but the asterix shows that something is there), but that is too late!

637
Q

Q5
I have added a new variable to the code: targetSide. What values can it take? - (4)

A

A5:
This question was (accidentally) a ‘trick’ one. Randint is present both in random (the standard python module) and np.random (part of numpy).

Psychopy will use the numpy version: np.random.randint(x) returns a number between 0 and x-1. So the Values this variable can take are -1 and 1.

But random.randint requires two numbers random.randint(a,b) and returns a value between a and b inclusive!

We will make sure this ambiguity is not in the actual exam.

638
Q

Q6
People sometimes say that the peripheral retina contains more magnocellular cells and is therefore ‘faster’ in some way. Describe two modifications that you might make to the reaction time experiment to test this - (4)

A

You could place the target in the periphery of the screen (off to one side)

You would need to include a ‘fixation point’ to make this work - to keep people looking in the middle.

You might like to interleave targets in the middle and at the edge (to remove session-to-session variance).

Subtle: If you do this, you might leave a position marker at the places where the target >could< appear - or cue the location in advance.

639
Q

First step of analysing data from Google sheet (importing modules) - (8)

A
  1. Importing plotting library ‘matplotlib’
  2. Importing from authentication modules from ‘google.colab’
  3. Importing authorisation libaries for sheets and colab : ‘from google.auth import default’
  4. Importing ‘pandas’
  5. ‘Importing numpy as np’
  6. Importing ‘scipy as ‘scipy’ which is importing scientific python
  7. Importing from psypy a function called ‘lingress’ which does linear regression
  8. Importing gspread which is a toolbox for working/ accessing with google sheets. Allowa Google Colab to reference by columns, rows , by their names so can ask for first 3 rows etc…
640
Q

Second step of analysing data from Google sheet (importing modules) - (4)(authorisation)

auth.authenticate_user()

A

This is where we authenticate to google - asking if you are ‘Gita’

If you authenticate once you do not do it again

Login in to your account (UoY)

In here, we are giving one website (Colab) the permission to access another web document (shared google spreadsheet) using your Google account information

641
Q

Second step of analysing data from Google sheet (importing modules) - (2)(authorisation)

gc = gspread.authorize(cred)

A

This gets you a ‘google cloud’ handle/an authentication token

If you show this token ten Google will believe its ‘you’

642
Q

Third step of analysing data from Google sheet (looking at the data) - (6)

A

Use the handle you just acquired to open the spreadsheet. Going to ask Google to open up spreadsheet of psychopy by giving them the handle to the workbook using web address of spreadsheet

  • ‘wb=gc.open_by_url(‘https://docs.goog…’ : Here we get a handle to the workbook (wb) using the web address of the spreadsheet. That gc module is ‘google cloud’.
  • data.wb.sheet1.get_all_values() - gets all the values from spreadsheet

-dArray = np.array(data) - turns all values of spreadsheet into numpy array which is mix of strings and numbers

  • print(dArray[0,[1,2,3,4]]) - using indices [1,2,3,4] of the first row in ‘dArray’ - Access the first row of the numpy array ‘dArray’ using index 0 - print the header strings
  • print(dArray[1:21,[1,2,3,4]])Print data (numbers) from rows 1 to 20 and columns 1 to 4 of ‘dArray’.
  • fArray=dArray[1:21,[1,2,3,4]].astype(float) - Convert the sliced portion of ‘dArray’ containing numerical data into a numpy array of floats (fArray).
643
Q

We can plot the data including a regression line and we can

A

Plotting the data and fitting a regression line using scipy’s linregress function for dominant and non-dominant hand

644
Q

Reminder of what linear regression is - (4)

A

least sum of squares error) to a group of points. It has a slope (m) and a y-intercept (c).

y=mx+c

m’ represents the slope of the line, indicating the rate of change of y with respect to x.

  • ‘c’ denotes the y-intercept, the value of y when x equals zero.
645
Q

Code plotting the linear regression of dominant and non-dominant hand - explanation

A

RTs=(fArray[0:,[0,1]]) - # Extract RTs and other important variables. The variable ‘RTs’ will contain the data from columns 0 and 1 of ‘fArray’, which represent the RTs for the dominant and non-dominant hands respectively.

handedness=fArray[0:,2] - This line extracts the data from the third column of ‘fArray’, which represents handedness.

height=fArray[0:,3] This line extracts the data from the fourth column of ‘fArray’, which represents height.

for thisRTHand in range(2): - This line initializes a loop that iterates twice, once for each hand (dominant and non-dominant).

plt.subplot(1,2,thisRTHand+1) # Two subplots
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=1, hspace=0) # Make the spacing nice
- These lines set up the subplot configuration, creating two subplots side by side.
They adjust the spacing between subplots for better visualization.

plt.scatter(height,RTs[:,thisRTHand]) - This line creates a scatter plot with height on the x-axis and RTs for the current hand (dominant or non-dominant) on the y-axis.

(m, c, rvalue, pvalue, stderr) = linregress(height,RTs[:,thisRTHand]) # height on x axis and RT on y axis - This line performs linear regression analysis to calculate the slope (m), intercept (c), correlation coefficient (rvalue), p-value (pvalue), and standard error (stderr) of the regression line -height on x axis and RT on y axis, m gradient, c offset, r value and p-value

y_pred = c + m*height # Make predictive y values based on height
plt.plot(height,y_pred, color=”red”, label=”Fit”)

These lines generate the predicted values (y_pred) using the equation of the regression line.
They plot the regression line on the scatter plot, indicating the relationship between height and RTs as a red line

plt.text(175,325,f”p={pvalue:.2f}”) # Places p-value of each scatter plot and r value
plt.text(175,340,f”r={rvalue:.2f}”) -These lines add text to the plot, displaying the p-value and correlation coefficient (r-value) with appropriate formatting - showing how much variation is explained in r value

plt.ylim(150,400) # Scale all plots to the same axes
plt.xlabel(“Height (cm)”)
plt.ylabel(“RT (s)”)

These lines set the y-axis limits for consistency across all plots and label the axes appropriately.

plt.show() - This line displays the plot to the user interface.

646
Q

Output of this code:

A
647
Q

What does this code show? - (2)

A

There doesn’t seem to be a general effect of height on either LH or RH reaction times. We could pool all the RTs in some way to get a more robust estimate but it is still almost certainly n.s.

One thing we might expect is that the dominant hand is faster than the non-dominant hand. To check this we can use a a t-test test.

648
Q

scipy has all these statistical tests in them like

A

linear regression, t-tests etc…

649
Q

Before you conduct at-test you should plot the data - (3)

A

Plotting data from categories is often best done with a boxplot.

This gives you a nice way of comparing the data ‘side by side’ and also computes and plots measures of spread automatically.

The ‘notch’ in the boxplot is very useful: It is a measure of the confidence interval. If notches from two groups don’t overlap it’s a good indication that they have different central tendencies.

650
Q

Explain this code of producing boxplot before conducting t-test:

Boxplots of for the reaction times (RTs) of dominant and non-dominant hands - (7)

A

‘notch=True’ adds a notch indicating the confidence interval around the median - gives estimation of CI around the centre (median)

Label the x-axis ticks as ‘Dominant’ and ‘NonDom’ corresponding to the two boxplots.

plt.show() - display graph

Perform a paired-sample t-test using scipy.stats.ttest_rel() - asks to psypy for relative value t-test

  • The t-test compares the means of two paired groups to determine if there is a significant difference.
  • ‘RTs[:,0]’ and ‘RTs[:,1]’ represent the RTs for dominant and non-dominant hands respectively - of first and second column

Print the results of the paired t-test including the t-value and p-value with 3 significant figures - print(f’Paired t-test t={t:.3} | p={p:.3}’)

651
Q

What does the output show? - (3)

A
  • Shows the dots and extreme values, someone people have extreme RTs - very slow or very fast
  • Orange lines is median values, these are similar in dominant and non-dominant hand
  • V shape is the notices and rule of thumb is notches overlap probably no sig difference - so we don’t have sig diff - no relationship of RT and height, no relationship between RT and dominantness of hand
652
Q

But very often we want to have intermixed conditions. For example, we might like to

A

intermix left and right hands at random in the same experiment.

653
Q

Here we will use an external data file (in .csv or .xls format) to control the

A

conditions.

654
Q

To make 2 conditions in psychopy experiment make csv file containing

A
655
Q

We save this csv file as the

A

n the same directory as your experiment. We will soon import this file into psychopy.

656
Q

In psychopy, in this csv file - (2)

A

Psychopy interprets the column headers as variable names.

And for each ‘iteration’ of the loop it can assign the values from one row to those variables - each containing a number and string from two column

657
Q

Now in our RT experiment from last week (W5) we can add the csv file of two conditions

This tells… - (3)

A

We want psychopy as it loops around the trial, in each iteration of loop we would like to pick a random finger and show us something on screen which finger to use

The way in which psychopy we have a data file available that lists conditions is in conditions tab - we tell where conditions list file CSV and tells you found 5 conditions (how many rows you got), 2 parameters and variables names are called finger, string

Each time Psychopy goes around the loop, it will pick values from one row of each of the 2 variables at random - since set loopType to random

658
Q

We now need to tell the subject which finger to use on each trial. To do this, we will print a little bit of text on the screen just before the trial saying something like Pinky or Thumb.

We will do this by changing the text that originally said ‘Ready’ - (3)

A

Open up the ‘GetReady’ component. There are two items in the timeline: some code (which is used to randomize the ISI) and some text. Last week that text said ‘Ready…’. We will now change it to reflect the finger that you are supposed to use.

Change the text to $String

In each iteration of loop, we want psychopy to tell what value of string is and place into textbox

659
Q

$ means - (2)

A

execute some python code-

for $string means embed python code inside your loop

660
Q

Everytime you set to loop

A

you have to update ‘set by frame’ than constant - updates the variable

661
Q

In experiment we have grating come up then ‘middle, pinky’ etc.. to what finger to use when pressing when grating appears after

A

space bar when grating appears

662
Q

How many trials should we have if nReps is 5 and we have 5 conditions?

A

25 trials

663
Q

We can set trial type into sequential in which or staircase

A

sequential is not randomise

664
Q

We can produce a new experiment which randomising faces of images

this is what we have in our face folder once we unzip:

A
665
Q

What would error be if randomising finger and index but trial type set to sequential - (2)

A

Sequential trial type means that the conditions are presented in a fixed order - that the experiment will progress through the rows of the conditions file in the order they are listed, moving sequentially from one row to the next.

whereas random trial type would allow for randomization of conditions - means that the experiment will randomly select rows from the conditions file for each trial, rather than following a fixed sequence

666
Q

To add our face images, we can add a ‘picture’ stimulus to my trial

can make a CSV file called ‘faceFile’ column and adding images into CSV file from our folder

then name of the picture will be a variable called $faceFile

note… names in column A must match the filenames of the images you just downloaded in the face file

A
667
Q

Finally, add a loop around the image presentation. In the loop point it to your .csv file. It should say that it found 1 parameter with three values… like this:

A
668
Q

If you have done all this correctly, when you run the experiment, it will load the face images in ‘on the fly’ according to which image is currently selected in the (random) loop.

A
669
Q

If you have lots and lots of images then sometimes it’s annoying to have them in the same directory as your experiment. You want to ‘tuck them away neatly’ in a subfolder like this:

A
670
Q

In that case, you just need to tell Psychopy where they are relative to the experiment. There are lots of ways to do this. One way is to add the subdirectory into the “image” location in the image properties - (2)

A

Notice what we have done here - we have embedded some python code directly into the entry box in the image properties tab (os.path.join(xxx,yyy)). To do this, you should preface the code with a dollar sign ($)

There are lots of other ways to make this happen: One way is to include the directory name into the file name in the .csv file. Or you could add a bit of code in the stimulus routine that builds a filename from a constant and the faceFile variable.

671
Q

Calbiration

A

Scientists want to make sure that the stimuli they run are the same no matter where in the world they are. This way someone can replicate your experiments and check your results.

If you make a stimulus that is ‘40% of the screen’ or ‘100 pixels wide’ then it is very hard to know how big it actually appears to someone. How big was the screen? How far away was the subject? What were the brightness / contrast settings? Was it a gaming monitor or a projector or what?

As we all know, things that are far away can appear small.

To standardise our measurements, vision scientists like to measure the size of things in ‘visual angle’. This is the angle that lines from the edges of your stimulus make at your eye. As a rule of thumb (literally), your thumb is about 1.5-2 degrees of visual angle at arm’s length. They also measure other things like the brightness of the screen and how the colors look.

This process of setting up a display is called ‘calibration’. Your experiment right now is using a standard calibration that is often more or less okay. You can see the monitors available to you under the ‘monitor’ menu (Tools->Monitor Centre). Probably there is only one.

The monitor that you are actually using for your experiment is defined in the ‘Experiment settings’ panel. Under ‘screen’ you tell it the monitor name and some other things….

Notice that at the moment you are defining all your measurements in units of ‘screen height’. That’s not ideal - screens have different heights and people can sit at different distances from the screen. In the future we will change this to ‘degrees’ (deg) and define all our sizes in terms of visual angle.

672
Q

It would be this if laid out like this

A

with faceFile as column header of csv

673
Q

Would be this is laid out like this

A
674
Q

The RP2040 is a computer. Like all computers it needs an

You are used to… - (2)

A

‘operating system’.

You are used to computers already coming with different operating systems (Windows, Linux, macOS)… but you will need to install one on the RP2040.

675
Q

You will download an operating system for the RP2040 from a website and then

A

install it over the USB cable

676
Q

here are lots of possible operating systems you can put on this RP2040 device

We are going to install operating system called

A

Circuitpython on the RP2040 device - lets Python run on RP2040 device

677
Q

Inside CIRCUITPY (D:) it has a file called ‘code.py’

A

this is where purpose of this computer device is to find code.py in directory and then run whatever code is in it

678
Q

However, today we will settle for making the onboard LED flash different colours.

The LED is the

A

white dot between the two buttons.

679
Q

To make the onboard LED flash different colours, we need to add a

A

add a single ‘library’ to the ones that come bundled with CircuitPython. “neopixel” that doesnt have in toolkit which comes from Ada fruit to allow to flash LED

680
Q

We can download neopixel via a link and - (3)

A

drag neopixel.mpy into ‘lib’ (where it likes to store all its libaries)

The library file you downloaded is called neopixel.mpy

Drag this over to the lib folder on the RP2040 in the file explorer

681
Q

At top is the code the device is run and at the bottom is the - (4)

A

input and output of the computer

What your desktop is doing is talking to the other machine the other computer through a serial line (this pops up when pressing ‘Serial’ (‘S’ in USB’) and if machine prints something it outputs in serial terminal

If you enter some text, it will go back to the other computer

Can reload things by saying Control D

682
Q

Explain this code that we will put in muEditor line by line - (10)

A

import time: This line imports the time module, which provides various time-related functions.

import board: This line imports the board module, which provides access to the pins on the microcontroller board.

import neopixel: This line imports the neopixel module, which allows control of NeoPixel LEDs.

led = neopixel.NeoPixel(board.NEOPIXEL, 1): This line creates a NeoPixel object named ‘led’ using the neopixel library. It specifies that the LED is connected to the pin labeled NEOPIXEL on the microcontroller board, and there is only one LED.

led.brightness = 0.3: This line sets the ongoing brightness of the LED to 30% of its maximum brightness.

while True:: This line starts an infinite loop that will continuously execute the code block that follows.

led[0] = (255, 0, 0): This line sets the color of the LED to red. The NeoPixel library represents colors as tuples of three integers, representing the amount of red, green, and blue respectively. Here, (255, 0, 0) represents full red, no green, and no blue.

time.sleep(0.5): This line pauses the execution of the program for 0.5 seconds, causing a half-second delay.

led[0] = (0, 0, 0): This line turns off the LED by setting its color to black. In the NeoPixel library, (0, 0, 0) represents no red, no green, and no blue, effectively turning off the LED.

time.sleep(0.5): This line again pauses the execution of the program for 0.5 seconds, creating another half-second delay before the loop repeats.

683
Q

What would this code effectively do?

A

The board will automatically reboot (thanks to the magic of muEditor) and a red light should blink on and off.

684
Q

led.brightness = 0.99 would make.. - (2)

A

Setting the LED brightness to 0.99 makes the LED nearly at its maximum brightness.

In the NeoPixel library, the brightness attribute ranges from 0 (off) to 1 (full brightness).

685
Q

Code: Setting both to be the same - (2)
time.sleep(0.5)
time.sleep(0.5)

A

Setting both time.sleep() calls to the same duration, such as 0.5 seconds each, creates a square wave pattern with a 50% duty cycle.

This means the LED blinks on and off at regular intervals, with each state lasting for the same amount of time.

686
Q

If I alter duty cycle by having - (2)

time.sleep(0.8)
time.sleep(0.2)

A

By setting time.sleep(0.8) for the on state and time.sleep(0.2) for the off state, the duty cycle of the square wave pattern is altered.

The LED will be on for a longer duration compared to being off, resulting in an increased duty cycle.

687
Q

If you divide time.sleep by 10 , LED will flicker

A

faster

688
Q

Explain what this code would do if we put in muEditor of file code.py? - (13)

A

import time: Imports the time module, which provides various time-related functions.

import board: Imports the board module, which provides access to the pins on the microcontroller board.

import math: Imports the math module, which provides mathematical functions. - importing another library to do maths

import neopixel: Imports the neopixel module, which allows control of NeoPixel LEDs.

led = neopixel.NeoPixel(board.NEOPIXEL, 1): Initializes a NeoPixel object named ‘led’ using the neopixel library. It specifies that the LED is connected to the pin labeled NEOPIXEL on the microcontroller board, and there is only one LED.

led.brightness = 0.3: Sets the ongoing brightness of the LED to 30% of its maximum brightness.

freq=2: Sets the frequency of the sinusoidal wave to 2 Hz.

startTime=time.monotonic(): returns the current elapsed time since the device was turned on in second using time.monotonic()

while True:: Starts an infinite loop that will continuously execute the code block that follows.

eTime=time.monotonic()-startTime: Calculates the elapsed time since the loop started using time.monotonic() in seconds

val=int(math.sin(eTime2freq3.1415)127+128): Calculates the brightness value for the LED based on a sinusoidal function. math.sin() calculates the sine of the input value (in radians), and the result is scaled to fit the range of NeoPixel brightness values (0-255). - basically calculating sine based on what the current elapsed time is (‘eTime’)

led[0] = (val,val,val): Sets the color of the LED to a grayscale value determined by ‘val’. This creates a pulsating effect from black to white based on the sine function - RBG all the same - black to white

time.sleep(.05): Pauses the execution of the program for 0.05 seconds, creating a delay between each iteration of the loop. This controls the speed of the pulsating effect.

689
Q

What would happen to the LED?

A

The LED brightness would pulsate in a sinusoidal pattern, transitioning from black to white and back again, at a frequency of 2 Hz.

690
Q

How to make the LED pulsate a bit slower? - (2)

A

To make the LED pulsate slower, adjust the frequency of the sinusoidal wave.

By changing the value of freq to a lower number, such as 0.5 Hz, the LED will pulsate at a slower rate, resulting in a the LED will pulsate at a slower rate, resulting in a slower transition between brightness levels, with one cycle occurring every 2 seconds or freq to 0.25 within a very slow transition between brightness levels, with one cycle occurring every 4 seconds.

691
Q

To make LED pulsate faster then change freq variable to values like - (2)

A

To make the LED pulsate faster, increase the frequency of the sinusoidal wave. By changing the value of freq to a higher number, such as 2 Hz, the LED will pulsate at a faster rate, resulting in a quicker transition between brightness levels, with two cycles occurring every second.

OR To make the LED pulsate even faster, further increase the frequency of the sinusoidal wave. By changing the value of freq to a higher number, such as 5 Hz, the LED will pulsate at a rapid rate, resulting in a very quick transition between brightness levels, with five cycles occurring every second.

692
Q

If you change led[0] to not be all val but instead be

led[0] = (val, 0, val) then… - (2)

A

By modifying the LED color to (val, 0, val), you’re creating shades of purple, as it mixes red and blue while keeping green constant at 0.

This changes the LED’s color from grayscale to various shades of purple, transitioning in a sinusoidal pattern as the brightness value (val) changes over time.

693
Q

If you change led[0] to different stuff like:

led[0] = (val, 0, 0) - (3)

A

By setting led[0] = (val, 0, 0) - Adjusts LED brightness, creating red pulsating from off to bright red.

led[0] = (0, val, 0) - Adjusts LED brightness, creating green pulsating from off to bright green.

led[0] = (0, 0, val) - Adjusts LED brightness, creating blue pulsating from off to bright blue.

694
Q

In this code, we set to muEditor, we doing something super fancy, such as setting each R,G,B component at slightly different frequency and as they drift apart and together in phase, you should see the LED make all the different possible colours like a rainbow and pulsate at different colours

A
695
Q

Explain this code line by line - (9)

A

Imports necessary modules: import time, import board, import neopixel, and import math.

  • Defines frequencies and constants: f1=1.1, f2=1.2, f3=1.3, and pi=3.1415.
  • Initializes NeoPixel object: led = neopixel.NeoPixel(board.NEOPIXEL, 1).
  • Sets LED brightness: led.brightness = 0.3.
  • Records the start time: startTime=time.monotonic().
  • Starts an infinite loop: while True:.
  • Calculates elapsed time: thisTime=time.monotonic()-startTime.
  • Computes brightness values for RGB components:
    • a1=(math.sin(thisTime*2*pi*f1)*127+128)
    • a2=(math.sin(thisTime*2*pi*f2)*127+128)
    • a3=(math.sin(thisTime*2*pi*f3)*127+128).
  • Sets LED color: led[0] = (a1,a2,a3).
696
Q

What happens setting all the different frequencies close together? f1,f2,f3? - (2)

f1=1.17
f2=1.2
f3=1.22

A

By making the frequencies closer together, such as setting f1=0.5, f2=0.6, and f3=0.7, the LED’s color modulation (colour shift) occurs at a slower rate.

This adjustment results in a smoother color transition with less noticeable changes, as the frequencies drift apart and together at a slower pace.

697
Q

If you open the plotting panel:

A

It plots the data( numbers) it receives from the computer board

698
Q

The thing that determines how quickly colours change is

A

difference between the three different frequencies: f1,f2,f3 not the frequencies themselves

699
Q

muEditor has a built-in plotter that will plot numbers it receives on the

A

serial line (output) if you send them as tuples (enclosed in round brackets like this: (10,20,30)

700
Q

muEditor has a built-in plotter that will plot numbers it receives on the serial line if you send them as tuples (enclosed in round brackets like this: (10,20,30). For example, try this code and switch to the plotter mode:

A
701
Q

Explain this code line by line - (7)

A

Imports necessary modules: import time and import random are used to import modules providing time-related functions and random number generation, respectively.

  • Starts an infinite loop: while True: initiates a loop that will run indefinitely.
  • Introduces a pause: time.sleep(0.05) introduces a 0.05-second pause between iterations of the loop. This pause prevents flooding the serial line with data.
  • Generates random temperature data: random.randint() is used to generate random integers representing temperature readings.
    • The first temperature (random.randint(0, 100)) is generated within the range 0 to 100, representing temperatures between 0°C and 100°C.
    • The second temperature (random.randint(-100, 0)) is generated within the range -100 to 0, representing temperatures between -100°C and 0°C.
    • The third temperature (random.randint(-50, 50)) is generated within the range -50 to 50, representing temperatures between -50°C and 50°C.
  • Prints temperature data: print() function is used to print the generated temperature data as tuples (temperature1, temperature2, temperature3) to the serial line.
702
Q

What is the output of this code? - (4)

A

The code is paused in while loop for 0.05 s

This code will produce three random numbers (stored in tuples) and plots them

Then goes stop of code and repeats that

These tuples of random numbers can be plotted using a serial plotter tool in the development environment.”

703
Q

It prints the output because The way in which it gets the numbers out of the device is making them as a tuple , the brackets and separate them by comma

meaning…

  • (3)
A

“The ‘device’ refers to the RP2040 microcontroller.

It generates the random numbers as tuples, encapsulating them within parentheses and separating them by commas.

This formatting ensures that the numbers are structured as a tuple before being transmitted through the serial line to the computer.”

704
Q

The RP2040 has a built-in thermometer that will read the temperature. You can read this thermometer like this: - (2)

A

“This code snippet utilizes the microcontroller module to access the built-in thermometer of the RP2040 microcontroller.

Specifically, it reads the temperature using the cpu.temperature attribute, which retrieves the temperature of the RP2040 microcontroller itself, and assigns the temperature value to the variable temp.”

705
Q

Explain this code - (7) (remove dot at the end)

A
  • Accessing Microcontroller Temperature: The code utilizes the microcontroller module to access the built-in thermometer of the RP2040 microcontroller. Specifically, it reads the temperature using microcontroller.cpu.temperature.
  • Storing Temperature in Variable: The temperature value is read and stored in the variable temp.
  • Sending Temperature as Tuple: The temperature value stored in temp is sent out as a tuple along with reference values of 0 and 37.5°C. This tuple is printed to the output.
  • Looping Continuously: The code runs in an infinite loop (while True:) to continuously read and send temperature data.
  • Introducing Pause: time.sleep(0.1) introduces a short pause of 0.1 seconds between each iteration of the loop to prevent overwhelming the serial line.
  • Temperature Variation: By placing the device in hand, the temperature sensed by the microcontroller may vary, leading to changes in the temperature readings stored in temp.
  • Visualizing Data in muEditor: The additional reference points of 0 and 37.5 help muEditor to autoscale the plotter for better visualization of the temperature data.
706
Q

Explain this code - (6)

A

These lines import necessary modules: time for time-related functions, microcontroller for accessing microcontroller-specific functionalities, neopixel for controlling NeoPixel LEDs, and board for accessing pin mappings. - importing at top

This function create_colormap(n) generates a colormap with n steps, transitioning from blue to green to red. It loops over a range of n values and calculates RGB values based on the current step. The colors transition from blue to green for the first half of steps and from green to red for the second half. - def function

This line initializes a NeoPixel object led to control the onboard LED connected to the pin NEOPIXEL. - led = neopixel.NeoPixel(board.NEOPIXEL, 1)

These lines define parameters: nSteps specifies the number of steps in the colormap, while minTemp and maxTemp set the temperature range to measure over. - nSteps = 20
minTemp = 32.0, maxTemp = 42.0

This line calls the create_colormap() function to generate the colormap based on the specified number of steps - cMap = create_colormap(nSteps)

while true loop - This block of code runs in an infinite loop (while True:) to continuously monitor the temperature.
time.sleep(1) introduces a 1-second delay between temperature readings to avoid flooding the CPU.
temp = microcontroller.cpu.temperature reads the temperature from the microcontroller.
index calculates the index within the colormap based on the temperature reading.
Conditional statements ensure that the calculated index stays within the valid range.
led[0] = cMap[int(index)] sets the color of the onboard LED based on the colormap and the calculated index.
print((0, temp, 37)) prints the current temperature, along with reference values of 0°C and 37°C, as a tuple.

707
Q

What does this code achieve? - (3)

A

We can make the RP2040 into a very primitive ‘standalone’ thermometer.

Write code based on the two examples above to set the LED colour based on the temperature. The tricky bit here is working out the colours. We want to set the colours over a range from about 30 to 42c with 30 being ‘blue, 37 (ish) being ‘green’ and 42 being red.

Probably the easiest way to do this is to make three lists of numbers for the R, G anb B LEDs. They will go from (255 ->0->0) for B, (0->255->0) for G and (0->0->255) for R with 200 numbers or so in each range. Then we will pick the R,G,B values based on the current temperature.

708
Q

Explain the def function - (6)

A
  • Function Definition: The create_colormap() function is defined to generate a colormap with a specified number of steps (n).
  • Colormap Initialization: An empty list colormap is initialized to store the RGB values of each step in the colormap.
  • Looping Over Range: The function iterates over a range of values from 0 to n-1 using a for loop.
  • Color Calculation: Depending on the value of i, the function calculates the RGB values for each step of the colormap.
    • For values of i less than n // 2, it calculates the green component (g) based on the ratio of i to half of n, and the blue component (b) as the complement to 255.
    • For values of i greater than or equal to n // 2, it calculates the red component (r) based on the ratio of the difference between i and half of n to half of n, and the green component (g) as the complement to 255. The blue component (b) is set to 0.
  • Appending to Colormap: The calculated RGB values are appended to the colormap list as tuples (r, g, b).
  • Returning Colormap: Finally, the function returns the generated colormap.
709
Q

One way to find out what is in a directory is with the

A

listdir command (part of os).

710
Q

Two ways of listening contents that is in a directory - (2)

A
  1. glob
  2. listdir command (part of os)
711
Q

What does this code do? - (6)

A
  • This code is used to download a smaller version of a repository called ‘pin-material’ from a specific URL.
  • The ‘!cd /content’ command changes the directory to ‘/content’.
  • ‘!git clone –branch small –depth 1 https://vcs.ynic.york.ac.uk/cn/pin-material.git’ is the main command.
  • It clones the ‘small’ branch of the repository with a depth of 1, meaning it only gets the latest version of the files, not the entire history.
  • The comment explains that this smaller version doesn’t include neuroimaging data, making it much smaller than the full repository.
  • The ‘!ls -lat’ command lists the contents of the current directory in detail, showing the latest changes first.
712
Q

Explain this code (using YNiC’s git server to download useful files like pin-material-git) - (8)

A
  • This code uses the os module
  • os.getcwd() prints the current working directory.
  • os.listdir('.') lists the contents of the current directory.and stores in variable called ‘contents’
  • '.' represents the current directory.
  • type(contents) prints the type of the variable contents.
  • print(contents) prints the contents of the current directory.
  • os.listdir('/content/pin-material') lists the contents of the ‘/content/pin-material’ directory - different directory and stores into variable ‘newcontents’
  • contents of ‘newcontents’ variable is printed out
713
Q

Output of this code

A
714
Q

Both os.listdir('.') and os.listdir() refer to the same thing,, listening

A

listing the contents of the current directory.

715
Q

Remember .. means ‘

A

‘go up one directory’

716
Q

’.’ means

A

‘this directory’

717
Q

This is what pin-material directory looks like in file format:

A
718
Q

os.listdir() includes hidden files, which start with a…

Hidden files may….

You may need to fitler… - (3)

A

with a dot (e.g., .DS_Store)

  • Hidden files may not be useful and can clutter the list.
  • You may need to filter out hidden files from the list returned by os.listdir()
719
Q

Example of os.listdir() including hidden files (e.g., .DS_Store)

A
720
Q
  • The glob function from the glob module is used to
A

find files and directories matching a specific pattern.

721
Q

The ‘glob’ function from glob module allows you to use special characters such as ‘*’ and ‘?’ to

A

search for strings that match certain patterns.

722
Q

Example of using glob on YNiC pin material

A
723
Q

Example of using YNiC pin material directory

Explain the code - (5)

A
  • Importing the glob function is achieved with from glob import glob.
  • filelist = glob('/content/pin-material/*.jpg') finds all .jpg files in the ‘pin-material’ directory.
  • print(filelist) displays the list of .jpg files found.
  • pyFiles= glob('/content/pin-material/*.py') finds all Python script files.
  • print(sorted(pyFiles)) prints the Python script files as a sorted list - in ascending order
724
Q

Output of this code:

A
725
Q

Can use sorted function to find these hidden files first when using os.listdir

A
726
Q

What are wildcard characters in the context of glob?

A

Wildcard characters are special symbols used in glob patterns to match filenames or paths.

727
Q

Explain the wildcard ‘*’ in glob - (2)

A
  • It matches any set of characters, including no characters at all.
  • For example, ‘file*.txt’ matches ‘file.txt’, ‘file123.txt’,
728
Q

What does the ‘?’ wildcard match in glob? - (2)

A
  • It matches any single character.
  • For example, ‘file?.txt’ matches ‘file1.txt’, ‘fileA.txt’, but not ‘file12.txt’.
729
Q

How does the wildcard ‘[1234]’ work in glob? - (2)

A
  • ‘[1234]’ is a wildcard character in glob that matches any single character from the list [1234].
  • For example, ‘file[1234].txt’ matches ‘file1.txt’, ‘file2.txt’, but not ‘file5.txt’.
730
Q

Explain the ‘[1-9]’ wildcard in glob - (2)

A
  • ‘[1-9]’ is a wildcard character in glob that matches any single character in the range from 1 to 9.
  • For example, ‘file[1-9].txt’ matches ‘file1.txt’, ‘file2.txt’, but not ‘file10.txt’.
731
Q

List all the wildcard characters using in glob function - (4)

A
    • (an asterix)
  1. ? (a question mark)
  2. [1234] a list of characters -
  3. [1-9] a range of characters -
732
Q

Here are the files in the directory:

[pop2_tidy_script2.py’
, ‘s3’,
‘README.md’,
‘app_headshape.xlsx’,
‘fft_colour.jpg’,
‘pop2_tidy_script1.py’,
‘fft_bw.jpg’,
‘.DS_Store’,
‘s4’,
‘app_headshape.bin’,
‘pop2_debug_script2.py’,
‘pop2_debug_script1.py’,
‘.git’,
‘pop3_test_script.py’]

What would glob(‘/content/pin-material/pop?_*’) print? - (7)

A

The glob pattern ‘/content/pin-material/pop?_’ utilizes two wildcard characters: ‘?’ and ‘’.

  • ’?’ matches any single character, allowing for flexibility in matching filenames.
  • ‘*’ matches any set of characters, including no characters at all.
  • Therefore, the pattern matches files in the ‘/content/pin-material’ directory that start with ‘pop’, followed by any single character, and then an underscore, and then any set of characters.
  • Based on this pattern:
    • Files like ‘pop2_tidy_script2.py’, ‘pop2_tidy_script1.py’, ‘pop2_debug_script2.py’, and ‘pop2_debug_script1.py’ would match.
  • Therefore, glob(‘/content/pin-material/pop?_*’) would print [‘pop2_tidy_script2.py’, ‘pop2_tidy_script1.py’, ‘pop2_debug_script2.py’, ‘pop2_debug_script1.py’].
733
Q

Here are the files in the directory:

[pop2_tidy_script2.py’
, ‘s3’,
‘README.md’,
‘app_headshape.xlsx’,
‘fft_colour.jpg’,
‘pop2_tidy_script1.py’,
‘fft_bw.jpg’,
‘.DS_Store’,
‘s4’,
‘app_headshape.bin’,
‘pop2_debug_script2.py’,
‘pop2_debug_script1.py’,
‘.git’,
‘pop3_test_script.py’]

What would glob(‘/content/pin-material/pop?_tidy_script[1-2]*’) print? - (6)

A
  • The glob pattern ‘/content/pin-material/pop?_tidy_script[1-2]*’ matches files in the ‘/content/pin-material’ directory that start with ‘pop’, followed by any single character, then ‘_tidy_script’, then either ‘1’ or ‘2’, and then any set of characters.
  • ’?’ matches any single character, allowing flexibility in matching filenames.
  • ‘[1-2]’ matches either ‘1’ or ‘2’.
  • ‘*’ matches any set of characters, including no characters at all.
  • From the given list of files, ‘pop2_tidy_script2.py’ and ‘pop2_tidy_script1.py’ match the pattern.
  • Therefore, glob(‘/content/pin-material/pop?_tidy_script[1-2]*’) would print [‘pop2_tidy_script2.py’, ‘pop2_tidy_script1.py’].
734
Q

Here are the files in the directory:

[pop2_tidy_script2.py’
, ‘s3’,
‘README.md’,
‘app_headshape.xlsx’,
‘fft_colour.jpg’,
‘pop2_tidy_script1.py’,
‘fft_bw.jpg’,
‘.DS_Store’,
‘s4’,
‘app_headshape.bin’,
‘pop2_debug_script2.py’,
‘pop2_debug_script1.py’,
‘.git’,
‘pop3_test_script.py’]

What would glob(‘/content/pin-material/fft*.jpg’’) print? - (4)

A
  • The glob pattern ‘/content/pin-material/fft*.jpg’ matches files in the ‘/content/pin-material’ directory that start with ‘fft’, followed by any set of characters, and end with ‘.jpg’.
  • ‘*’ matches any set of characters, including no characters at all.
  • From the given list of files, ‘fft_colour.jpg’ and ‘fft_bw.jpg’ match the pattern.
  • Therefore, glob(‘/content/pin-material/fft*.jpg’) would print [‘fft_colour.jpg’, ‘fft_bw.jpg’].
735
Q

How to import three os functions that help you with spilting full file paths using os module?

basename, dirname, split text?

A
736
Q

Explain the basename function from the os.path module - (3)

A
  • The basename function, from the os.path module, extracts the filename from a full path.
  • It returns the last component of the path, excluding the directory.
  • For example, basename(‘/content/pin-contents/s4/s4_rt_data_part01.hdf5’) would return ‘s4_rt_data_part01.hdf5’.
737
Q

Explain the dirname function from the os.path module.

A
  • The dirname function, from the os.path module, extracts the directory name from a full path.
  • It returns the directory component of the path, excluding the filename.
  • For example, dirname(‘/content/pin-contents/s4/s4_rt_data_part01.hdf5’) would return ‘/content/pin-contents/s4’.
738
Q

Explain the splitext function from the os.path module - (3)

A
  • The splitext function, from the os.path module, splits a filename into its base name and extension.
  • It returns a tuple containing the base name and the extension separately.
  • For example, splitext(‘/content/pin-contents/s4/s4_rt_data_part01.hdf5’) would return (‘/content/pin-contents/s4/s4_rt_data_part01’, ‘.hdf5’)
739
Q

What does the splitext function do when applied to the full path? - (3)

A
  • The splitext function splits the full path into its base name and extension.
  • When applied to the full path, it returns a tuple containing the base name and the extension separately.
  • For example, splitext(‘/content/pin-contents/s4/s4_rt_data_part01.hdf5’) would return (‘/content/pin-contents/s4/s4_rt_data_part01’, ‘.hdf5’).
740
Q

What does the splitext function do when applied to just the filename? - (3)

A
  • When applied to just the filename, the splitext function splits the filename into its base name and extension.
  • It returns a tuple containing the base name and the extension separately.
  • For example, if fname is ‘s4_rt_data_part01.hdf5’, splitext(fname) would return (‘s4_rt_data_part01’, ‘.hdf5’).
741
Q

Explain this code - (8)

A

The code first imports necessary modules from glob module and basename, split text and dirname functions from os module

Use glob to find files:
The glob function searches for all files ending with ‘.hdf5’ in the ‘/content/pin-material/s4/’ directory.
The resulting list of file paths is stored in the fileList variable.

A for loop iterates over each file path in fileList.

In each iteration of element in fileList,

fNameOnly stores the filename extracted from the full path thisFileName (e.g., if thisFileName is ‘/content/pin-material/s4/s4_rt_data_part04.hdf5’, then fNameOnly will store ‘s4_rt_data_part04.hdf5’.

parts variable = splitext (fNameOnly) so splitext splits the filename stored in fNameOnly into its base name and extension. The base name is stored in parts[0].
For example, if fNameOnly is ‘s4_rt_data_part04.hdf5’, then after splitting:
parts[0] will store ‘s4_rt_data_part04’ (the base name).

print(parts[0]):Only the base name stored in parts[0] is printed. For example, if parts[0] is ‘s4_rt_data_part04’, then this base name will be printed.

For loop continues until each element of list in fileList is covered

742
Q

Output of this code

A
743
Q

For cases where we need to implement a simple transformation like this (such as multiplying by a number or calling a function on each member of a list), like in this example,

A

Python gives us an alternative: the list comprehension.

744
Q

What is list comprehension mean in python?

A

A list comprehension is simply a statement inside of square brackets which tells Python how to contruct the list.

745
Q

How to write this list ‘outputlist’ into list comprehension?

A
746
Q

Explain this code - (2)

A

The example above therefore reads as (x * 2) for each value (x) in range(10). i.e., for each value in the list produced by range(10), put it in the variable x, then put the value x*2 into the list.

Note that the variable x is just a placeholder and could be called anything.

747
Q

What would be output of this code?

A

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

748
Q

Explain this code - (6)

A
  • original_data = ['Alex', 'Bob', 'Catherine', 'Dina']: Defines a list named original_data containing four strings.
  • new_list = ['Hello ' + x for x in original_data]: Utilizes list comprehension to create a new list named new_list.
    • For each element x in original_data, the expression 'Hello ' + x concatenates ‘Hello ‘ with the value of x, which represents each name in original_data.
    • The resulting strings are added to new_list.
  • print(original_data): Prints the contents of original_data, displaying the original list of names.
  • print(new_list): Prints the contents of new_list, displaying each name prefixed with ‘Hello ‘.
749
Q

What would be output of this code?

A
750
Q

Explain this code - (6)

A
  • original_data = ['This', 'is', 'a', 'test']: Defines a list named original_data containing four strings.
  • new_list = [len(x) for x in original_data]: Utilizes list comprehension to create a new list named new_list.
    • For each element x in original_data, the expression len(x) calculates the length of the string x.
    • The resulting lengths are added to new_list.
  • print(new_list): Prints the contents of new_list, displaying the length of each string in original_data.
  • For example, ‘This’ has 4 characters, ‘is’ has 2 characters, ‘a’ has 1 character, and ‘test’ has 4 characters.
751
Q

What would be output of this code?

A
752
Q

What would be output of this code?

A
753
Q

What would be output of this code?

A
754
Q

What is the purpose of the pass statement in Python? - (2)

A

The pass statement in Python serves as a placeholder and does nothing when executed.

It is often used to create empty loops, functions, or classes.

755
Q

Example of using pass in an empty loop - (5)

A
  • data1 = [10, 20, 30] creates a list of numbers from 10 to 30.
    • The for loop iterates over each item in data1.
    • Inside the loop, a comment explains that the loop is pointless but serves as a placeholder for future code.
    • The pass statement is used to indicate that no action needs to be taken inside the loop.
  • Essentially, pass allows the loop to exist without any executable code inside it, avoiding syntax errors in situations where a loop is required but no action is necessary.
756
Q

What would be output of this code? - (3)

A

The pass statement itself does nothing when executed and serves as a placeholder.

  • As a result, there are no print statements or other operations that would produce output

NO OUTPUT

757
Q

Explain the use of break in this code snippet - (5)

A
  • It imports the randint function from the random module to generate random integer numbers.
  • Inside a while loop that runs indefinitely (while True), random numbers between 0 and 5 (inclusive) are generated and printed.
  • If a randomly generated number is equal to 0 printed, the break statement is executed.
  • The break statement immediately terminates the while loop, exiting the loop and ending the program execution.
  • This allows the program to stop generating random numbers once a 0 is encountered.
758
Q

Python produces error if a for loop has

A

no code to execute inside it

759
Q

In some files the data are stored as ‘plain text’. You can open them in a text editor (like Spyder or Notepad or you can look at them using cat on the command line) and read them although they might not make a lot of sense

A

iles like this include .csv files, files ending in .txt and most types of programming language ‘source code’ like python files (.py) and web pages (.html).

760
Q

The other ‘family’ of files store their data in formats where you cannot easily read them into a

A

text editor.

761
Q

The other ‘family’ of files store their data in formats where you cannot easily read them into a text editor. These files usually contain - (2)

A

‘numbers’ of some sort stored in a way that computers like to read.

We call them ‘binary’ files.

762
Q

Example of binary files

A

. Files like this include the image and video formats that you might be familiar with (.jpg, .gif, .mp4).

763
Q

In neuroimaging, the brain data files we use tend to be in binary format (e.g.

A

nii, .mat)

764
Q

In neuroimaging, the brain data files we use tend to be in binary format (e.g. .nii, .mat) while the files describing other stuff like experiment structure and subject responses are in

A

plain text’ (.csv, .txt).

765
Q

Plain text files can be formatted in a number of ways, but a common way for numerical data is:

A

i.e., numbers separated - either by spaces, tabs or commas with one row per line of text.

766
Q

Up until now we have used Pandas to load in .csv files. But numpy also knows how to load in data and sometimes we just want to have the data

A

appear directly in a numpy array.

767
Q

We are going to load some MEG data from the file s4_meg_sensor_data.txt in the

A

pin-materials s4 sub-directory using this code:

768
Q

Explain what this code does - (6)

!ls -lh pin-material/s4

A

The ls command lists the contents of a directory.

  • -lh is a combination of options:
    • -l lists detailed information about each file, including permissions, owner, size, and modification time.
    • -h displays file sizes in a human-readable format (e.g., kilobytes, megabytes).
  • pin-material/s4 specifies the directory whose contents will be listed.
  • Therefore, this command lists detailed information about the contents of the “s4” subdirectory within the “pin-material” directory.
769
Q

Explain what this code does - (3)

!head pin-material/s4/s4_meg_sensor_data.txt

A

The head command displays the beginning of a file.

  • pin-material/s4/s4_meg_sensor_data.txt specifies the file whose beginning will be displayed.
  • This command shows the first few lines of the “s4_meg_sensor_data.txt” file located within the “s4” subdirectory of the “pin-material” directory.
770
Q

By executing this code:

A

It gives us this output

771
Q

This output shows - (8)

A

We can see that the first line of the file contains some column headings.

We make a note of these as we will need them later on:

Column 0: Time
Column 1: Left Mean
Column 2: Left Lower CI
Column 3: Left Upper CI
Column 4: Right Mean
Column 5: Right Lower CI
Column 6: Right Upper CI

772
Q

Executing this code line gives us this output:

A
773
Q

We can use the tail command on MEG data to check 10 lines of the file are really numbers

A
774
Q

What does the following code snippet do, and why might it encounter an issue?

A

The code snippet uses NumPy’s “loadtxt” function to load numerical data from a text file.

  • It attempts to load data from the file “s4_meg_sensor_data.txt” located within the “s4” subdirectory of the “pin-material” directory.
  • However, it may encounter an issue if the first line of the file contains column names or non-numeric data instead of numerical values.
  • By default, “loadtxt” expects numeric data and will raise an ValueError error if it encounters non-numeric content in the first row.
775
Q

We can correct this by:

A

telling nump to skip the first line (skip first row) which contains t is the header with column names which is string - words

776
Q

What would be the shape of the data and type?

A

(400, 7) - 400 rows and 7 columns
float64

777
Q

After loading plain text files using np.loadtxt (e.g., ‘pin-material/s4/s4_meg_sensor_data.txt’, skiprows=1), we can save them out using

A

np.savetxt.

778
Q

Explain the code - (9)

A

This code snippet uses NumPy’s “loadtxt” function to load numerical data from a text file.

  • It loads data from the file “s4_meg_sensor_data.txt” located within the “s4” subdirectory of the “pin-material” directory, skipping the first row (which likely contains column names or non-numeric information).
  • The loaded data is stored in the variable “importedData”.
  • This line extracts a subset of the loaded data (“importedData”).
  • It selects columns 1, 2, and 3 (exclusive indexing) from the loaded data.
  • The extracted data, representing the timecourse and confidence intervals, is stored in the variable “ourdata”.
  • The “savetxt” function from NumPy is used to save the extracted data (“ourdata”) to a new text file named “my_new_meg_data.txt”.
  • This file is saved in the “/content/pin-material” directory.
  • After saving the data, the “!ls -lth” command is executed to list the files in the directory, providing information about file sizes and modification times.
779
Q

explain what this line np.savetxt mean in this code - (6)

A

np.savetxt: This function from the NumPy library is used to save data to a text file.

‘my_new_meg_data.txt’: Specifies the name of the text file where the data will be saved.

ourdata: Represents the data to be saved. This variable holds the extracted subset of the loaded data, which includes columns 1, 2, and 3.

header=’Mean UppcrCI LowerCI’: Defines a header string that will be written at the beginning of the file.

This header typically contains column names or other descriptive information. In this case, the header string specifies the column names as “Mean”, “UppcrCI”, and “LowerCI”.

fmt=’%1.4e’: Specifies the format string for writing the data. The %1.4e format specifier formats floating-point numbers with scientific notation (exponential format) and exactly 4 digits after the decimal point. This ensures that the data is written with a precision of 4 decimal places.

780
Q

Usually in MEG we present the same stimulus many times and combine the recordings from each presentation to get an

A

‘average’ response.

781
Q

Previously we loaded or made small arrays and plotted them with matplotlib. We can pass data to matplotlib either as a

A

list or as a numpy array.

782
Q

Plot data as a list - example code

Explain whats happening in plt.plot([0,1,2,3]) - (4)

A

Since only one set of values is passed, these values will be used as the y-values, and the x-values will be automatically generated as the indices of the data points (0, 1, 2, 3).

In this example, we did not supply an ‘X’ axis. matplotlib assumed that we just wanted 0,1,2,3 and so on.

So we really plotted (0, 2), (1, 3), (2, 4) and (3, 5) and joined them up with a straight line.

When matplotlib draws a line in this way, it joins the points with straight lines by default.

783
Q

We might, however, want to look at the individual data points. To do this, we can add a ‘format’ string - (2)

A

This is a string which describes how to format the data in the plot.

Here we do this by just adding an ‘o’ to the function call.

784
Q

What does this line of code do?

plt.plot([2, 3, 4, 5], ‘o’)

A

The first line plots the data points as circles (‘o’) without joining lines, creating a scatter plot.

785
Q

What does this line of code do?

plt.plot([2, 3, 4, 5], ‘og’)

A

The second line plots the same data points as green circles (‘og’) without joining lines.

786
Q

What does this line of code do?

plt.plot([2, 3, 4, 5], ‘o–’)

A

The third line plots the data points as circles with a dashed line (‘o–’) joining them.

787
Q

What are some commonly used markers in Matplotlib? - (8)

A

In Matplotlib, markers are symbols used to denote individual data points in plots.

Here are some commonly used markers:

  • ’.’: Point marker
  • ‘o’: Circle marker
  • ‘v’: Downward triangle marker
  • ’^’: Upward triangle marker
  • ’+’: Plus marker
  • ‘*’: Star marker
788
Q

As well with plotting markers, there is also you can also change the line type here in matplotlib

A

For instance, – means used a dashed line whilst -. means use a dash/dotted line

789
Q

In matplot we can also

A

adjust the colour of our lines or markers using the format string.

790
Q

y default, matplotlib will use its own colour cycling scheme to choose colours for us but

A

but we can override this

791
Q

We can combine markers and colours in same format string:

A
792
Q

Explain what this code does and output - (5)

A
  1. import matplotlib.pyplot as plt: Imports the Matplotlib library and aliases it as plt for convenience.
  2. plt.cla(): Clears the current axes to ensure a fresh plot.
  3. plt.plot([2, 3, 4, 5], 'r+'): Plots the data points [2, 3, 4, 5] with red plus markers (‘r+’).

The ‘r’ indicates the color red, and the ‘+’ specifies the marker style as a plus sign.

The datapoints are not joined by a line

793
Q

How can we specify basic colors in Matplotlib? - (8)

A
  • ‘b’: blue
  • ‘g’: green
  • ‘r’: red
  • ‘c’: cyan
  • ‘m’: magenta
  • ‘y’: yellow
  • ‘k’: black
  • ‘w’: white
794
Q

What does this code line do?

A

This code plots the points [2, 3, 4, 5] using blue stars at each data point with a dash-dotted line in between.

795
Q

We can pass two lists/arrays of numbers first will be x value and second y values like this:

A
796
Q

What does this code do: plt.plot([-2, 1.5, 2, 4], [2, 3, 4, 5], ‘g*’)?

A

This code plots a graph with green star markers at the coordinates (-2, 2), (1.5, 3), (2, 4), and (4, 5),

797
Q

Why does this code not join the points together: plt.plot([-2, 1.5, 2, 4], [2, 3, 4, 5], ‘g*’)?

A

The absence of a line in the plot is due to the format string ‘g’, where ‘g’ denotes green color and ‘’ denotes star markers, but no line style is specified.

798
Q

The default behaviour of matplotlib is to add plots of new data to the

A

existing figure

799
Q

The default behaviour of matplotlib is to add plots of new data to the existing figure.

This allows us to

A

create complex plots from multiple components

800
Q

E.g.,

The default behaviour of matplotlib is to add plots of new data to the existing figure. This allows us to create complex plots from multiple components.

A

A simple example would be a line plot with many lines of data, or a scatter plot where we show different types of data with different symbols

801
Q

What does plt.ylim do?

A

set limits of y axis go from -3 to +4

802
Q

What does plt.grid() do?

A

even put a beautiful grid on it

803
Q

What does plt.savefig(‘my_figure.png’, dpi=300)

A

This code saves the current figure as an image file named “my_figure.png” with a resolution of 300 dots per inch (dpi).

804
Q

You might want to save out your figures to include them in your papers or dissertation.

You can do this using the

A

savefig function

805
Q

. There are two ways to use this savefig function

A

You can either select the figure and then use plt.savefig() or you can use the .savefig() method directly on the figure object.

806
Q

Using can either select the figure and then use plt.savefig()

A
807
Q

can use the .savefig() method directly on the figure object.

A

figureHandle = plt.figure()#Generate a new figure. Hold its ‘ID’ or ‘Handle’ in a variable

808
Q

What does plt.close(‘all’) do?

A

Close all existing figures

809
Q

what does legend part do in this code: import matplotlib.pyplot as plt? - (2)

A

The plt.legend() function adds a legend to the plot, which provides labels for the plotted lines.

In this code, it labels the first line as “A straight line” and the second line as “A wiggly line”.

810
Q

Legends tell you what each line on a

A

plot means.

811
Q

The ‘newline’ character (‘\n’) forces a new line inside a

A

string.

812
Q

We can add new line character inside x-axis label and y-axis level via:

A
813
Q

Why is one line blue and one line green in this code and plot? - (3)

A

In the provided code, the line plt.plot([2, 3, 4, 5]) creates a plot with only y-values, so it auto-generates x-values as sequential integers starting from 0.

This line is plotted in the default color, which is blue.

The subsequent line plt.plot([-2, 1.5, 2, 4], [2, 3, 4, 5], ‘g’) plots the provided x and y values in green color as specified by the ‘g’ argument.

814
Q

We can also add text in your plot by

A

use plt.title to add a title to our plot and plt.text allows us to plot text at arbitrary positions in our figure.

815
Q

What does plt.text do in this code? - (2)

A

The plt.text() function in this code adds text to the plot at a specified location.

In this case, it adds the text “Hello World” at the position (2, 2) on the plot, with the color set to red.

816
Q

Explain this code plotting MEG data - (6)

A

np.loadtxt() loads data from a text file, skipping the first row.

Time data is stored in the first column (t).

Sensor readings from columns 1 and 4 are extracted (plot_dat).

plot_dat.shape prints the size of the extracted data - (400, 2) rows column

plt.plot(t, plot_dat) plots sensor data over time.

Legends and gridlines are added for clarity.

817
Q

Wait in this code

There are two lines but only one plt.plot call! What has happened? - (3)

A

Until this point, each of our plt.plot() calls has only plotted a single line. If there are multiple columns in the data passed to plot_dat, matplotlib will automatically plot multiple lines - magic!

We have passed values for the x axis in (t: the time variable),

Notice that we have time before 0s. Time 0 is the time we present the stimulus (in this case a ‘beep’). We see that we get a large deviation in the signals shortly after the presentation of the stimulus.

818
Q

The MEG signals we have plotted so far are the

A

are mean response across multiple presentations of the same ‘beep’

819
Q

Someone has also computed a 95% Confidence Interval. We would like to visualise this. To do this, we will use the

A

plt.fill_between()

820
Q

The plt.fill_between() allows us to add ‘error bars’

A

(perhaps an ‘error envelope’ is better desccription) to our plots.

821
Q

The plt.fill_between is a function in matplotlib for

A

filling the area between two curves

822
Q

What does plt.fill_between show? - (4)

A

Plots the error enevelope - shaded area between let_lower_ci and left_upper ci on the plot along time axis

t parameter is added to define x-axis values

left_lower_ci = data[:, 2] - extracts data from column 2 lower CI

left_upper_ci = data[:, 3] - extracts data from column 3 of upper CI

823
Q

We would also like to plot the mean line (as well as error envelop) by

A

first plotting the mean line in black using plot.plot() (color=’k’), then plotting the error envelope over the top (plt.fill_between()).

When we plot over the top we have to set the color to be a bit transparent otherwise you will not see the line below.

Computers often refer to the transparency or ‘solidness’ of a color as its ‘alpha’ value. So if we set ‘alpha’ to 0.5, it will become 50% see-through. 20% is even more see-through.

824
Q

We can also provide a colour argument to - (3)

A

plt.plot and plt.fill_betweeen() where we use ‘shorthand’ for colors where ‘green’ is ‘g’, ‘blue’ is ‘b’, ‘black’ is ‘k’ and so on.

e.g., plt.plot(data[:,0],color=’r’)

e.g. plt.fill_between(t, left_lower_ci, left_upper_ci,alpha=0.5, color=’g’)

825
Q

We can specficy colours to plt.plot in different ways such as - (3)

A

specificy single letter ‘r’ = ‘red’

Red , green, blue format

Using colour names like aquamarine, mediumseagreen

826
Q

To visualise a distribution of

A

numbers are hirstograms (frequency plots) and boxplots.

827
Q

What does plt.plot(data[:,0], colour = ‘r’) mean? - (4)

A

data produces 2-D array with 10 rows and 4 columns filled with randomly generated numbers between interval 0 and 1 - numbers between 0 and 1 (exclusive)

data[:,0] selects all the rows of array of the first column (0) and plots them on y axis

Since no x axis values are explicitly mentioned, indices on x axis are generated –> x indices would be 0 to 9 since there are 10 rows in data array

Plots the values from data on y axis and indices of that on x axis as red line

828
Q

What does data1 = np.random.randn(10000) mean? - (2)

A

This produces an array containing random numbers 10,000 random numbers drawn from standard normal distribution (mean = 0, SD = 1) - unlike rand that produces numbers from flat distribution

Majority of numbers would fall around mean (0)

829
Q

What does data2 = np.random.randn(10000)?

A

Produce an array containing 10,000 random numbers drawn from standard normal distribution but majority of numbers fall around 1.8 than 0

830
Q

Wha does plt.figure() and plt.hist(data1, bins = 50) show?

A

plt.figure() - produce a figure for the histogram

plt.hist(data1, bins = 50)

x axis = range of values in dataset data1 divided by 50 bins

Y axis is frequency or count of occurence of data points falling within each bin on x axis

specifices bins - how lumpy i want histogram to be

831
Q

How to produce transparent histograms? - (2)

A

Specificying alpha parameter in plt.hist()

Alpha parameter controls the transparency of the histograms

832
Q

What does plt.hist with alpha value 0.3 mean?

A

Alpha value of 0.3 means bars in histogram are somewhat transparent

833
Q

The higher the alpha parameter is in plt.hist() the

A

less transparent the histogram will be

834
Q

What does

binEdges=np.linspace(-10,10,100)

and what does it mean when specificed in histograms?

A

binEdges = np.linspace (-10,10,1000) produces array of bin edges ranging from -10 to 10 inclusive with 1000 evenly spaced interval - each interval defines boundaries of a bin of histogram

In plt.hist(data1, bins = binEdges) - bin parameter used to specificy bin edges to use for histogram

835
Q

Box and whisker plots are often used to illustrate data which may have a

A

skewed distribution.

836
Q

A box and whisker plot makes it easy to see the interquartile range

A

(25-75% range) as well as the median (50% value). Outlier points (as defined by a multiple of the interquartile range) are plotted as individual points outside the whiskers of the plot.

837
Q

Explain this code which produces a boxplot - (6)

A
  • data = np.random.rand(1000,3) - produces 1000x3 Numpy array filled with random numbers between 0 and 1 with uniform distribution

data[:,1] = data[:,1]*2 + 1 - this multiples the second column of data array (all rows) by 2 and adds 1 to value - scales and shifts values in second column

data[:,2] = data[:,2]*1.5 +- 1 - this multiplties the values in the third column of data array by 1.5 and subtracts 1 from each value - shifts and scales values from third column

plt.figure() - produces figure for plot

plt.boxplot(data)- produces boxplot using data in data array - each column has a different dataet

plt.show() - displays plot with boxplot

838
Q

What is output of the boxplot?

A
839
Q

What does plt.xticks ([1,2,3], [‘Set1’, ‘Set2’,’Set3’])

A

Adds label for the 3 boxplots by setting first boxplot Set 1, second boxplot Set 2 and third boxplot is Set 3

840
Q

xticks does not use a

A

zero-referenced system.

841
Q

what does it show here:

plt.xticks([1, 2, 3],[‘Mouse’,’Elephant’,’Badger’])

A

The first argument is a list of numbers indicating the different categories.

The second argument is a list of strings saying what to call them.

842
Q

The ‘style’ of your plots is the default way everything looks. Stuff like

A

he color of the background, the line thickness, the font.

843
Q

Matplotlib has a default plotting style. It also has the ability to change this style: either by means of

A

individual tweaks to plotting layouts, colours etc, or by changing all of its settings in one go.

844
Q

ou can set the plotting style using the

A

plt.style.use() function

845
Q

We can change the plotting style using

plt.style.use() funtion

using

plt.style.use(‘ggplot’)

which shows:

A
846
Q

We can change the plotting style using

plt.style.use() funtion

using

plt.style.use(‘fivethirtyeight’)

which shows:

A
847
Q

Question 1
Consider the following code snippet:

What is wrong with this code? How should it be corrected?

A

Technically this might execute but the file_path is not an absolute path as expected. Almost certainly it is missing the initial ‘/’

848
Q

Identify the problem in this code and suggest a fix. - (2)

A

The plt.show() command fixes the image so the last two lines do not do anything.

Place them before the plt.show() command.

849
Q

This code makes an assumption - what is it? - (2)

A

It assumes there is at least one line of data in the file as well as the header.

If this it not true, it will throw an exception.

850
Q

This code has a similar bug to that in Q2. What is it? - (2)

A

Again - the plt.show() command stops the next line from working.

Change their order.

851
Q

How might this code run into problems depending on the platform it runs on?

A

The ‘directory’ variable hard-codes the ‘/’ separators. This might fail on Windows where the separator should be ‘'

852
Q

This code is designed to plot two random time series. What mistake does it make? - (3)

A

Data is defined as a 2 (down) by 10 (across) array.

So it will plot 10 random time series with two points each.

Change to rand(10,2) to make it work.

853
Q

Again, this code might work or it might not depending on the operating system, even if you are sure that the directory ‘plots’ exists. What line makes it so ‘fragile’ and how could you fix it? - (3)

A

Line of error - plt.savefig(‘/plots/parabola.png’)

Windows uses \ instead of /. - fix it by plt.savefig(‘\plots\parabola.png’)

Use os.path.join to glue together all the bits in a platform-independent manner.

854
Q

Which one of these boxplots will have the highest median value (as indicated by the bar across the middle)? - (2)

A

A
The second one (‘Group 2’). The offset is defined by the +2. The spread is defined by the *.5. So this one will have a median at +2 which is bigger than any of the others.

This is because offset (+2) directly adds a constant value to each data point, it has a more significant impact on the median compared to the spread (*.5).

855
Q

Q10
A directory contains the following files - (2)

A

a: apple.txt, allFruit.csv, allFruit.xls, allFruit.tsv, apple.jpg

b: apple.jpg, banana.jpg

856
Q

What command do you use to clone the relevant git repository for the fMRI analysis?

A

!git clone -b s7_fmri –single-branch https://vcs.ynic.york.ac.uk/cn/pin-material.git

857
Q

What command do you use to install Nilearn, a required module for fMRI analysis in Colab?

A

!pip install nilearn

858
Q

How do you change the directory to ‘s7_fmri’ in a Python script?

A

import os
os.chdir(‘/content/pin-material/s7_fmri’)

859
Q

We have now seen the main methods for loading and saving MRI and fMRI data in Python and we have performed a simple frequency domain analysis.

We needed … to do this

A

We just needed the nibabel nib.load() function to get data into numpy.

860
Q

What type of file is “filtered_func_data_MNI3mm.nii.gz” typically used for in fMRI analysis?

A

It is typically used as the preprocessed functional MRI (fMRI) data, often after spatial normalization to a standard brain template (MNI3mm).

861
Q

Command that sees ‘filtered_func_data_MNI3MM.nii.gz

A
862
Q

We are going to move onto how to do some analysis of fMRI data in a more modern way using a module called

A

nilearn

863
Q

nilearn comes from a same family of neuroimaging software as nibabel and implemenets

A

a whole bunch of fMRI analysis tools from simple to complex.

864
Q

Nilearn works with other modules and uses

A

a cool statistics and machine learning package called Scikit-Learn (sklearn: SKL) to do all sorts of fancy 21st-centure machine learning things.

865
Q

Nilearn contains routines for performing

A

he standard univariate analyses that we show you at YNiC

866
Q

What module is used for fMRI analysis in a modern manner, integrating with Scikit-Learn?

A

Nilearn

867
Q

The hardest part of any fMRI analysis is telling the analysis software

A

what event happened, when it happened and how long they lasted

868
Q

Often, the hardest part of any fMRI analysis is telling the analysis software what event happened and when. And how long they lasted.

It’s easy to get this wrong - as…

A

for example, by forgetting to take into account offsets in the fMRI start times, mistaking the length of the TRs or using the wrong stimulus files

869
Q

If you are ever sitting in front of a ‘failed’ fMRI analysis, first check your

A

event files!

870
Q

Describe the experimental design used in the example provided in notes for applying nilearn, including the duration, TR, trial types, and characteristics of each trial type - (4)

A

The experiment lasted 320s with a TR of 2.0s, resulting in 160 volumes of data.

It involved two trial types, Hand movement, and Visual flickering grating, running simultaneously.

The Hand movement condition comprised 16s of finger movement followed by 16s of rest, starting at 6s into the experiment.

The Visual flickering grating appeared on the screen at 0s, stayed on for 10s, off for 10s, and then repeated.

871
Q

Summary of experiment used for nilearn - hand movement and visual grating

To summarise, our experiment involved the following timeline, shown for the first minute of the experiment. + in the table below means that the given stimulus is ‘on’.

A
872
Q

What format does Nilearn require for describing stimuli, and what are the necessary components? - (3)

A

Nilearn requires stimuli to be described in a ‘TAB separated file’ (TSV) format.

The necessary components include the onset time of the events (in seconds), the type of event (trial_type), and the duration of each event.

Wants these values in columns

873
Q

What would our TSV file look like for our hand movement and visual grating experiment?

A
874
Q

TSVs are just like CSVs except the columns are

A

separated by tabs (\t).

875
Q

We can read TSV file into

A

a Pandas dataframe and pass it directly to the fMRI analysis code.

876
Q

First step in producing TSV file for an experiment of hand duration and vision duration is that - (3)

A

We will use pandas to generate a nice structure to hold the information (a table with the names, onsets and durations)

Pandas can then write that table directly to disk.

. We will also define the hand and vision stimulus durations as variables at the start - Then, if we need to change them for some reason (perhaps to analyze another dataset) we only have to change those lines.

877
Q

Second time in constructing TSV , after constructing duration, is the

A

constructing variables containing a list of onset times

878
Q

Second step of TSV

Constructing onset times for hand movement which said Constructing onset times for hand movement which said where the condition starts at 6 seconds into the experiment and alternates every 32 seconds. Each cycle consists of 16 seconds of activity followed by 16 seconds of rest. :

hand_duration = 16s

explaining this code - (2)

A

The ‘range()’ function is used to generate a list of onset times, starting at 6 and ending before 320 (the duration of the experiment), with a step size of ‘hand_duration * 2’.

Since ‘hand_duration’ is 16 seconds, ‘hand_duration * 2’ equals 32 seconds, ensuring the desired alternating pattern of 16s on and 16s off.

879
Q

What would be output?

A
880
Q

Second step of TSV

Constructing onset times for visual grating - which
starting at 0s and alternating every 20s (10s on, 10s off)

explain this code - (2)

vision_onsets = list(range(0, 320, vision_duration*2))

vision_duration = 10s

A

The ‘range()’ function is used to generate a list of onset times, starting at 0 and ending before 320 (the duration of the experiment), with a step size of ‘vision_duration * 2’.

Since ‘vision_duration’ is 10 seconds, ‘vision_duration * 2’ equals 20 seconds, ensuring the desired alternating pattern of 10s on and 10s off.

881
Q

What would be output of this code?

A
882
Q

After constructing onset and duration variables for hand movement and visual we need to make

A

two Pandas dataframes - One is for the hand movements, the other is for the vision things.

ithin each data frame we keep the same ‘duration’.

883
Q

Third step producing pandas dataframe

Explain the creation of the dataframe for the Hand Movement condition - (2)

A

We create a dataframe using Pandas from dictionary type key (value-pairs), where each row represents a trial of the Hand Movement condition.

The dataframe consists of three columns: ‘trial_type’, indicating the type of trial (hand_movement); ‘onset’, containing the onset times calculated previously; and ‘duration’, representing the duration of each hand movement trial (calculated hand_onset and hand_duration previously)

884
Q

Third step producing pandas dataframe

Explain the creation of the dataframe for the Vision condition- (2)

A

Similar to the Hand Movement dataframe, we create a dataframe for the Vision condition.

Each row represents a trial of the Vision condition. The dataframe contains three columns: ‘trial_type’, indicating the type of trial (vision); ‘onset’, containing the onset times calculated previously; and ‘duration’, representing the duration of each vision trial.

885
Q

What is the fourth step of producing TSV file of experiment after constructing onset and duration of each condition and produce data frame of each condition? - (2)

A

Finally, we stack (‘concatenate’) the two data frames on top of each other and save them out using pandas’ dedicated CSV writer.

We tell this routine to use ‘TAB’ rather than ‘COMMA” as a separator by specifying the \t separator.

The .to_csv is a member function of the dataframe.

886
Q

Explain final step of constructing TSV - (9)

A

The final step involves combining the dataframes representing the Hand Movement and Vision conditions into a single dataframe named ‘conditions_df’.

This is achieved using the ‘pd.concat()’ function, which concatenates the two dataframes along their rows.

Once the dataframe is constructed, the next task is to save it as a TSV file.

For this purpose, a file path ‘tsv_path’ is defined, specifying the location and name of the TSV file to be created.

Then, the ‘to_csv()’ function is called on the ‘conditions_df’ dataframe.

This function writes the contents of the dataframe to a CSV file.

By setting the ‘sep’ parameter to ‘\t’, we specify that the file should be tab-separated, as required for a TSV file.

Additionally, ‘index=False’ is used to exclude row indices from the file.

This final step ensures that all trial information, including trial type, onset times, and durations, is saved into a properly formatted TSV file, ready to be used in further analysis.

887
Q

produce flashcard of steps constructin TSV file- (8)

A
  1. Define Duration Variables:
    • Define variables for the duration of each stimulus condition (e.g., hand_duration for hand movement and vision_duration for vision).
  2. Calculate Onset Times:
    • Calculate onset times for each stimulus condition using appropriate intervals and durations (e.g., hand_movement_onsets and vision_onsets).
  3. Create Dataframes:
    • Create separate dataframes for each condition (hand movement and vision) using Pandas, specifying trial type, onset times, and duration columns.
  4. Combine Dataframes:
    • Combine the separate dataframes into a single dataframe (conditions_df) using ‘pd.concat()’, ensuring all trial information is aggregated.
  5. Define File Path:
    • Define a file path (tsv_path) specifying the location and name of the TSV file to be created.
  6. Save to TSV File:
    • Use the ‘to_csv()’ function on the combined dataframe (conditions_df) to save its contents to a TSV file.
  7. Set File Format:
    • Set the ‘sep’ parameter to ‘\t’ to specify tab-separated format for the TSV file, ensuring compatibility with Nilearn.
  8. Exclude Row Indices:
    • Use ‘index=False’ to exclude row indices from being included in the TSV file, maintaining a clean structure.
888
Q

When constructing the TSV file,

A

Note that although people often have the onsets roughly in chronological order in the stimulus file, this is not required. In principle, we can list all the motor stimuli, then all the vision stimuli.

889
Q

Explain this code - plotting the timecourse of each condition - (6)

A

This code snippet begins by importing the necessary Python libraries: Pandas for data manipulation and Matplotlib for data visualization. It then proceeds to read a TSV (Tab-Separated Values) file containing trial information into a Pandas dataframe using ‘pd.read_csv()’, where the ‘\t’ (TAB) separator is specified to ensure proper parsing of the file.

Next, it defines the total duration of the experiment (320 seconds) and initializes two lists, ‘time_series[‘hand_movement’]’ and ‘time_series[‘vision’]’, with zeros. These lists will be used to represent the time courses for hand movement and vision conditions, respectively.

The code iterates through each row of the dataframe using the ‘iterrows()’ function, extracting the onset and duration of each event. For each event, it calculates the start and end time points.

Subsequently, it identifies the type of event (hand movement or vision) and updates the corresponding elements in the time series lists to 1, indicating the presence of the stimulus during the event’s duration.

Once the time series data is populated, it plots the time courses using Matplotlib. The x-axis represents time in seconds, while the y-axis indicates stimulus activity (0 for inactive and 1 for active). The plot visually represents the temporal patterns of stimulus presentation for both hand movement and vision conditions throughout the experiment.

Overall, this code snippet demonstrates how to read trial information from a TSV file, process the data to create time courses, and visualize the temporal dynamics of stimulus presentation during an fMRI experiment.

890
Q

Compare the plot of the stimulus time course with the actual fMRI data - (6)

First produced from TSV and another using nibabel from data of time series of two voxels

A

The stimulus time course, represented by the plot in the previous flashcard, is more blocky and binary in nature, with values restricted to either 0 or 1 to indicate the presence or absence of the stimulus.

In contrast, the plot of the actual fMRI data depicts the time-series signals from two voxel positions within the brain (visual and motor cortex).

These signals exhibit more dynamic behavior, reflecting the complex hemodynamic response associated with neural activity.

The fMRI signals show fluctuations over time, influenced by various physiological and neurological factors.

The stimulus time course serves as a simplified representation of the experimental conditions, while the fMRI data provides a more detailed view of brain activity patterns in response to these conditions.

Before performing the General Linear Model (GLM) analysis, the stimulus time course is convolved with a hemodynamic response function (HRF) to simulate the expected fMRI response to the experimental stimuli.

891
Q

Why do we use a step size of duration*2 when making lists of onsets? Provide a potential scenario where this approach might not be correct, particularly in event-related designs. - (4)

A

Using a step size of duration*2 ensures events are properly spaced in time series data.

However, it may not suit event-related designs where stimuli overlap or have variable durations, potentially leading to inaccuracies in timing representation.

The situation where it is not correct is using event-related designs where there is brief moments of stimulus of different conditions presented

More suited with block design with 50% duty cycle with blocks of stimuli coming on and off

892
Q

We now have all the elements to run L1 analysis with nilearn of.. and bring them together using the magic of Nilearn! - (2)

A

A nifti file (with some fMRI data) and

a TSV file with onsets and durations.

893
Q

We are going to use a slightly different version of the functional data for this section. It is the same data that we used before but

A

aligned to an MNI 152 brain

894
Q

We are going to use a slightly different fMRI data set that is aligned to MNI brain and going to load the image using nilearn:

Explain this code snippet:

A
  • Imports the ‘image’ class from the nilearn library, which deals with fMRI data.
  • Loads an fMRI dataset from the specified path using the ‘load_img’ function.
  • Stores the loaded fMRI image in the variable ‘fmri_img’.
  • Prints the shape of the loaded fMRI image, which includes information about its dimensions (e.g., number of TRs).
895
Q

Explain output of this code snippet: (45,54,45,160)

A

so the volume size is slightly different: 45x54x45x160 (the size of one functional volume) but still 160 volumes long

896
Q

We can also look at a single image from functional volume using nilearn from our functional data aligned to MNI brain by this code

explain it- (6)

A

Imports the ‘plotting’ module from nilearn, which contains functions for visualizing neuroimaging data.

  • Imports the ‘image’ module from nilearn, which deals with loading and manipulating neuroimaging data.
  • Selects the first volume (timepoint) of an fMRI image using ‘image.index_img’.
  • Plots the selected volume using ‘plotting.plot_epi’, which displays one slice of the brain at one moment in time.
  • Includes a color bar in the plot to indicate signal intensity.
  • Displays the plotted image using ‘plotting.show()’.
897
Q

What is output of this code and explain it - (6)

A

These are the raw EPI amplitudes for a single TR of fMRI data. You are not seeing the functional responses to the stimuli here - just the mean signal levels.

The functional signals are modulations of about 1% in the mean signal.

Notice that the amplitude of the signal drops from the outside to the inside of the brain.

This is driven by two things:

1: The BOLD amplitude is biggest in the gray matter (and the surface blood vessels).

2: The coils are most sensitive to things that are near them - and the centre of the brain is far away.

898
Q

We can also load and plot T1 anatomical data using image from nilearn and plotting from nilearn as well

explain this code - (6)

A
  • Imports the ‘image’ module from nilearn, which handles loading and manipulating neuroimaging data.
  • Imports the ‘plotting’ module from nilearn, containing functions for visualizing neuroimaging data.
  • Specifies the path to the anatomical (structural) MRI image file.
  • Loads the anatomical image using ‘image.load_img’.
  • Plots the loaded anatomical image using ‘plotting.plot_anat’.
  • Displays the plotted anatomical image, providing a visual representation of the brain’s structure.
899
Q

plot_img instead of plot_epi but otherwise it’s the

A

same…

900
Q

Output of this code

A
901
Q

Can do analysis in Spyder by changing following.. and adding this code after loading one image from functional.. - (8)

A

subject_anat_path=’/pin-material/s7_fmri//highres.nii.gz’ # You have to change this bit

This code Creates an interactive HTML view of the specified fMRI image (‘first_TR’) using Nilearn’s ‘view_img’ function.

  • Sets visualization parameters such as threshold (2000), maximum intensity value (vmax) of 30000, and coordinates for cutting planes.
  • Specifies the title of the HTML view as “Raw fMRI”.
  • Disables the background image using ‘bg_img=False’.
  • Opens the interactive HTML view in a web browser using ‘html_view.open_in_browser()’. - allows to browse the data in web browser
  • Allows interactive exploration of the fMRI data in the web browser, providing a convenient way to inspect the image with adjustable settings.
  • Provides a note about the alternative approach of saving the data to disk and loading it using the nibabel library.
902
Q

What are the two main components needed to run a General Linear Model (GLM) analysis in neuroimaging? - (2)

A
  1. The functional data.
  2. A file indicating when events occurred.
903
Q

What is the purpose of the design matrix in GLM analysis?

A
  • Providing simulated timecourses representing different events.
  • Facilitating regression analysis at each voxel to determine the contribution of each event to the measured timecourse.
904
Q

What is a ‘beta value’ in the context of GLM analysis? - (2)

A
  • The amount of each simulated timecourse needed to explain the measured timecourse at each voxel.
  • The contribution of each event to the measured timecourse.
905
Q

What is the process involved in simulating a BOLD timecourse using the design matrix? - (2)

A
  • Convolving the onsets and offsets of the stimulus with an estimate of the hemodynamic response function (HRF).
  • Generating a comprehensive list of simulated BOLD timecourses, typically plotted with time running downwards.
906
Q

How does Nilearn facilitate the creation of the design matrix? - (2)

A
  • Automatically generating it from a .TSV file containing event timing information.
  • Streamlining the entire analysis process, encouraging users to perform the analysis in a single workflow.
907
Q

Whats a first-level model? - (2)

A

A first-level model focuses on characterizing brain activity patterns at the level of individual subjects, typically using observed fMRI data from a single subject.

  • In contrast, a second-level model aggregates data across multiple subjects to make inferences at the group level, such as identifying consistent effects across individuals or comparing groups.
908
Q

How to instanll nilearn?

A

!pip install nilearn - not import nilearn

909
Q

Building a first level-analysis model using GLM in nilearn

Explain this code - (6)

A
  • Imports necessary modules from Nilearn for setting up and fitting a first-level General Linear Model (GLM) to functional MRI (fMRI) data.
  • Loads event information from a TSV file into a pandas DataFrame, representing experimental conditions and timing.
  • Loads fMRI data from a specified path using Nilearn’s load_img function.
  • Determines the repetition time (TR) of the fMRI data, a crucial parameter in fMRI analysis.
  • Sets up a FirstLevelModel object, specifying TR and high-pass filtering parameters for the GLM analysis.
  • This code snippet prepares the necessary components for conducting a first-level analysis of fMRI data, including loading data, defining experimental conditions, and setting up the GLM model.
910
Q

We have build a ‘first level model’ in nilearn. It is empty so far - we need to feed it with data but we can look at its parameters before we do that. - (3)

A

For example, by default it uses an estimate of the hemodynamic response function that is specified in an old paper from Gary Glover at Stanford:

We know this because we can ask about the hrf_model:

Here are the two main models you can use (‘SPM’, ‘glover’ - which are about the same) - plus another one (‘MION’) which is super-weird and used only for a special type of contrast agent.

911
Q

Exlain what this code does feeding our first-level model with fMRI data - (3)

A

his code snippet fits the first-level GLM model to the fMRI data by calling the .fit member function of the FirstLevelModel object.

  • The .fit function takes two main arguments: the fMRI data (fmri_img) and the events dataframe (events) containing experimental conditions and timing information.
  • By calling .fit, the GLM analysis is performed, and the design matrix is built ‘on the fly’, meaning it is constructed dynamically during the fitting process.
912
Q

After fitting fMRI data to GLM, we can access the design matrix:

Explain this code - (4)

A
  • After fitting the first-level GLM model to the fMRI data, the design matrix can be accessed using the ‘design_matrices_’ attribute of the FirstLevelModel object.
  • In this code snippet, the design matrix is obtained from the first element (index 0) of the list of design matrices.
  • The design matrix represents the relationship between the experimental conditions (e.g., hand movement, vision) and the observed fMRI data, with each row typically corresponding to a time point (TR) and each column representing a different experimental condition or regressor.
  • The design matrix is visualized using Nilearn’s plot_design_matrix function, providing insight into how the experimental design is encoded in the GLM analysis.
913
Q

Output of this code

A
914
Q

Explain this code producing contrasts of beta values obtained from GLM model - (5)

A
  • This code snippet computes contrasts using the beta values obtained from the fitted first-level GLM model.
  • Two contrast vectors, contrast_motor and contrast_vision, are created as numpy arrays of zeros, with the length equal to the number of columns in the design matrix.
  • A value of ‘1’ is set at the index corresponding to the trial type of interest in each contrast vector, allowing examination of the beta values associated with specific trial types.
  • The compute_contrast method of the FirstLevelModel object is then used to compute contrasts based on these vectors, producing beta maps for the specified trial types (motor and vision).
  • These beta maps provide information about the effect size of each trial type relative to the baseline or reference condition.
915
Q

We have extracted the beta maps into two arrays. We have lots of options for plotting them. Here, for example is nilearn’s ‘mosaic’ option for plotting a stat_map

Explain the code - (6)

A
  • This code snippet utilizes Nilearn’s plot_stat_map function to visualize the beta maps computed for the motor and vision stimuli.
  • Each plot_stat_map call plots a beta map for a specific stimulus, with titles indicating the corresponding trial type (‘motor’ or ‘vision’).
  • The ‘mosaic’ option for the display_mode parameter plots the beta maps in sagittal, coronal, and axial views simultaneously.
  • The black_bg=True parameter sets the background color of the plot to black.
  • A threshold value of 0.25 is applied to display only voxels with absolute effect sizes greater than or equal to 0.25.
  • The plotting.show() function displays the plotted beta maps.
916
Q

Output of this code

A

1: The data are automatically overlaid on an MNI brain. So we have lots of anatomical landmarks to help us see where we are. We can do this because we are using a version of the functional data that we have aligned to the MNI brain already (using FSL’s FLIRT command).

2: The subject was instructed to use their right hand to tap with. You might therefore expect to see motor cortex activity only on the left - but it’s present in both hemispheres (stronger on the left). I don’t know why this is but it is a common observation.

3: The visual stimulus flickered on the left side of the screen and this response is localized to the right hemisphere. That is what we expect from the strict retinotopy of the visual cortex.

4: You can see small regions in visual cortex that respond to both motor and vision stimuli. Again, not clear why - perhaps the motor activity was cued by a visual cue?

917
Q

First step of doing first-level analysis in nilearn -overall:

from nilearn.plotting import plot_design_matrix
from nilearn.glm.first_level import FirstLevelModel
import numpy as np
import pandas as pd

  • making TSV file - (6)
A
  • This code snippet demonstrates the process of creating a TSV (Tab-Separated Values) file for defining experimental conditions and their timing in an fMRI experiment.
  • It involves defining the paths for the fMRI data (subject_data_path) and the TSV file (tsv_path).
  • Duration values for each stimulus block (hand_duration and vision_duration) are specified in seconds.
  • Onset times for the ‘hand_movement’ and ‘vision’ conditions are generated using lists created with the range() function, representing the start times of each stimulus block.
  • Dataframes (hand_movement_df and vision_df) are created for each condition, specifying columns such as ‘trial_type’, ‘onset’, and ‘duration’.
  • These dataframes are then concatenated into a single dataframe (conditions_df) representing all experimental conditions.
  • Finally, the dataframe is saved to a TSV file (tsv_path) using the to_csv method, with ‘\t’ as the separator and index=False to omit row indices.
918
Q

Second step of doing first-level analysis in nilearn -overall:

loading fMRI data and TSV file and do GLM

(9)

A
  • This code snippet continues the analysis process after creating the TSV file and loading fMRI data.
  • The TSV file containing experimental conditions and timing information is loaded into a pandas DataFrame (events) using pd.read_table.
  • Functional MRI (fMRI) data is loaded from the specified path (subject_data_path) using Nilearn’s load_img function.
  • The repetition time (TR) of the fMRI data is determined either directly or from the image header.
  • A FirstLevelModel object is instantiated to set up the first-level GLM analysis, specifying parameters such as TR and high-pass filtering.
  • The GLM model is fitted to the fMRI data using the fit method of the FirstLevelModel object, with the events DataFrame supplied as input.
  • The design matrix of the fitted GLM model is obtained from the design_matrices_ attribute.
  • Contrasts are defined and computed using the compute_contrast method of the FirstLevelModel object, producing beta maps for specific stimuli.
  • Finally, beta maps for motor and vision stimuli are visualized using Nilearn’s plot_stat_map function, with the ‘mosaic’ display mode.
919
Q

print(first_level_model.hrf_model) - (2)

A

This code snippet prints the hemodynamic response function (HRF) model used by the first-level model.

By default, Nilearn’s FirstLevelModel uses the Glover slow hemodynamic response function.

920
Q

Fit L1 GLM:
first_level_model.fit(fmri_img, events=events) - (2)

A

This code snippet fits the first-level GLM model to the fMRI data and event information using the .fit method of the FirstLevelModel object.

Upon calling this function, Nilearn performs a full L1 GLM analysis.

921
Q

Installing Nilearn - (2)

A

Nilearn can be installed using pip, a package manager for Python.

To install Nilearn, you can run the command ‘pip install nilearn’ in your terminal or command prompt. A

fter installation, you can import Nilearn in your Python scripts to use its functionalities for neuroimaging data analysis.

922
Q

ModuleNotFoundError - (2)

A

A ModuleNotFoundError occurs when Python cannot find a module required by the script.

In this case, the error likely occurred because the Nilearn module was not installed in the Python environment.

923
Q

Q1
I am using nilearn to run a GLM on a nifti file fmri_img.

I have generated a events structure events already from a .tsv file output while the scan ran. The scanner collected individual data volumes (64x64 inplane resolution, 40 slices) once every 3s. The code I am running to perform the GLM is this:

The code runs but the resulting contrast maps seem to show only noise. I was expecting a large and reliable effect and it is not there. What error have I have made?

A

The TR of the stimulus was 3s but you have specified it as 5s in the model.

924
Q

Q2
I am generating a .TSV file to store timing information for a nilearn analysis. The experiment had two visual stimuli: one on the left and one on the right. On the left, the first stimulus appeared at 6s and the stimulus duration was 10s. On the right the offset was 0s and the duration was 12s. The TR of the experiment was 2s and the scanner ran for 160 TRs.

Part of the TSV generation code looks like this:

A

The durations have been specified in TRs but they should be in seconds. They are therefore half as long as they should be.

925
Q

Explain what will happen in overall experiment - (3)

A

For the left visual flicker condition:
- The stimuli start appearing at 6 seconds into the experiment and alternate every 24 seconds (12 blocks), with 12 seconds of flickering followed by 12 seconds without flickering.

For the right visual flicker condition:
- The stimuli start appearing immediately at the beginning of the experiment (0 seconds) and alternate every 24 seconds (12 blocks), with 12 seconds of flickering followed by 12 seconds without flickering.

The stimulus on th left lags that on the right by 6s.

926
Q

Q4
I am about to start an analysis using nilearn. I run this code but get error message

What has probably gone wrong and how do I fix it?

A

You have not installed the ‘nilearn’ module. Use pip install nilearn to install it.

927
Q

Q5
If I have three different stimulus event types in my .TSV file, and I set the high_pass parameter to 0.0001 in a 320s experiment (as above), how many columns do I expect to see in the design_matrix?

A

Four: Three columns for the events and 1 for the constant amplitude. The very low ‘high_pass’ parameter means you will not model any slow drifts.

928
Q

What is MNE?

A

a Python module for analysing MEG and EEG data.

929
Q

Many of the code below will run in Spyder for example, - (2)

A

the interactive plots are not interactive in Colab.

We will try to run our code in Spyder today but use Colab for ‘testing’

930
Q

Previously, we have learned to install additional python modules using

A

‘pip’

931
Q

To install MNE on Google Colab or Windows/Spyder machines, we enter:

A
932
Q

To install MNE on Spyder, you type this (‘pip install mne’) on the - (2)

A

in the terminal to the bottom right.

Remember to ‘restart kernel’ after you do this. You might also have to set the Graphics output type to ‘QT - to ensure plots in Spyder are interactive

933
Q

MEG data come in a variety of formats. Most of the existing data which is available at YNiC is from a

A

4-D system like this:

934
Q

All the file paths in this section is relative to s8_meg directory in the material directory, so need to change the directory you are working in Spyder or replace the full paths such as.. C:\Users\gs1211\ . . .

A
935
Q

This code is saying that:

A

This code fetches a specific branch (s8_meg) from a Git repository (https://vcs.ynic.york.ac.uk/cn/pin-material.git) and clones it into the current directory

936
Q

We can check git repository is there by saying:

A

This command lists the contents of the directory s8_meg within the pin-material directory, showing details such as permissions, ownership, size, and modification time, with the most recently modified files appearing first.

937
Q

We have loaded in the MNE python module. And We have loaded in the MNE python module. And we have also git-cloned some MEG data. Now we can use a

A

python script to look at the data:

938
Q

First we want to change the directory where s8_meg live by saying the following code - (2):

A

This code imports the Python libraries ‘os’ and ‘mne’.

Then, it changes the current working directory to ‘/content/pin-material/s8_meg/’ using the ‘os.chdir()’ function.

939
Q

For spyder to change directory we can change

os.chdir(‘/content/pin-material/s8_meg/’) to..

A

You need to change this on Windows - something like C:\Users\aw890\pin-material\s8_meg

940
Q

What is the difference between the use of backslashes () and forward slashes (/) in file paths?

A

Backslashes () are typically used in Windows file paths, while forward slashes (/) are used in Unix-based systems like Linux or macOS.

941
Q

What is the main difference between the organization of MEG data and fMRI data?

A

MEG data is organized by sensors, whereas fMRI data is organized by voxels in the brain.

942
Q

How are sensors positioned in MEG data collection?

A

Sensors in MEG are fixed in space within a helmet, detecting brain activity at a distance.

943
Q

What is the purpose of registration in MEG data analysis?

A

Registration ensures accurate positioning of sensors relative to the head and brain.

944
Q

What is the role of a 3D digitizer like a ‘Polhemus’ in MEG data analysis?

A

A 3D digitizer like a ‘Polhemus’ measures head and facial features to facilitate accurate sensor positioning.

945
Q

What is the next step after examining position data in an old MEG dataset?

A

The subsequent step involves analyzing individual MEG timecourse data.

946
Q

What is the purpose of the following code snippet?

A

This code reads MEG data from a file and extracts different parts of the MEG dataset for analysis.

947
Q

What function is used to read the MEG data from a file from mne?

A

The mne.io.read_raw_bti() function from the MNE module is used to read the MEG data from the specified file.

948
Q

What does this line of code mean?

raw = mne.io.read_raw_bti(‘./R1025_P1119a_4/c,rfDC’) - (2)

A

This line of code reads MEG data from a file of participant R1025_P1119a_4 using the read_raw_bti function from the MNE module.

The specified file path is ‘./R1025_P1119a_4/c,rfDC’.

949
Q

What is output of

raw = mne.io.read_raw_bti(‘./R1025_P1119a_4/c,rfDC’

print(raw)

A
950
Q

What does the raw.info object contain?

if raw = mne.io.read_raw_bti(‘./R1025_P1119a_4/c,rfDC’

A

The raw.info object contains basic information about the MEG data, such as the number of channels and device information.

951
Q

Outputting

print(raw.info)

raw - loaded mne data

A
952
Q

The raw object containing meg data loaded via mne

has a member called info which is.. - (2)

A

his is an mne Info structure which behaves something like a dictionary.

It has a number of elements which refer to details about the scan (rather than the raw data).

953
Q

What does this output show of raw.info? - (7)

A

Going from top to bottom, we can see that at present there are no bads set: i.e. we have not configured bad channels yet.

There is a list of channel names in the ch_list attribute, and the chs attribute is actually a list of all channel details; when printed, it simply shows a summary of what types of channels we have.

On our MEG system system, the main MEG channels are referred to as A1 to A248. When loading the data into MNE, these are mapped into MEG 001 to MEG 248; the reference channels are also remapped in the same way. We therefore need to remember to refer to the channel names in the way that MNE expects.

The next few lines refer to the transform which is calculated based on the “Coil-on-Head” calculations and the movement into the standard space that MNE uses: we ignore this for now.

Under dig, we see that we have 1558 digitisation points: these come from the Polhemus head digitisation system which is used with the 4D MEG scanner.

We can also see that the data were filtered between 0 and 339.1Hz.

We then get some information about the date of the scan, the total number of channels and then the sfreq: the sampling frequency.

954
Q

What valuable information does raw.info.keys() provide? - (2)

A

By printing the keys available in the raw.info structure, we gain insight into the metadata associated with the MEG data being analyzed.

This metadata may include information such as acquisition parameters, stimulus information, device configuration, channel information, data processing history, and more. .

955
Q

What does this following code snippet do? - (4)

A

Accessing the keys in the raw.info structure

This code snippet extracts digitisation data from the MEG dataset, storing it in a variable named ‘dig’.

It then prints the type of data contained in ‘dig’ and displays the first few elements of the digitisation data, providing insight into the location of critical head structures.

Finally, it prints the total number of elements in the digitisation data.

956
Q

What does the line dig = raw.info['dig'] accomplish? - (2)

A

This line extracts digitisation data from the MEG dataset, specifically the set of 3D points in space that indicate the location of critical head structures. I

t stores this data in a variable named ‘dig’.

957
Q

What does the code print(type(dig)) do?

A

The code print(type(dig)) prints the type of data contained in the variable ‘dig’, which is <class ‘list’>

958
Q

What information does the line print(dig[0:5]) provide? - (2)

A

The line print(dig[0:5]) displays the first five elements of the digitisation data stored in the variable ‘dig’.

These elements represent 3D points indicating critical head structures, such as the nasion and inion as well as extra points when the stylus stroked the head structure

959
Q

What does the code print(len(dig)) show?

A

The code print(len(dig)) prints the total number of elements in the digitisation data, providing insight into the overall size

960
Q

Explain the output - (3)

[<DigPoint | LPA : (-74.6, 0.0, 0.0) mm, ….., Extra #2 : (-19.5, 66.3, 39.6) mm…]

A

We see that the digitisation points are stored as a list of objects of type DigPoint.

If we want to plot these data, we will need to extract them.

We see that the first three are different to the rest which seem to be called Extra X.

Those first three points define the coordinate system and although they are both interesting and useful, we don´t need them right now. Instead we will focus on the Éxtra’points which contain the shape of the head.

961
Q

What does the code ex_1 = dig[3] do? - (2)

A

The code ex_1 = dig[3] extracts a digitisation point from the digitisation data stored in the variable ‘dig’.

Specifically, it selects the digitisation point after the first three points and assigns it to the variable ‘ex_1’.

962
Q

What does the code print(type(ex_1)) reveal?

A

The code print(type(ex_1)) prints the class of the object stored in the variable ‘ex_1’, indicating that it belongs to the class mne_fiff.digitisation.DigPoint, representing a digitisation point.

963
Q

What does the code print(dir(ex_1)) accomplish? - (2)

A

The code print(dir(ex_1)) lists all methods and attributes associated with the digitisation point stored in the variable ‘ex_1’.

However, the output can be cluttered, making it difficult to discern relevant information.

964
Q

What does ([x for x in dir(ex_1) if not x.startswith(‘_’)]) do? - (2)

A

The code [x for x in dir(ex_1) if not x.startswith('_')] produces a cleaner version of the list by filtering out methods and attributes that start with an underscore (‘_’).

This list comprehension generates a new list containing only the methods and attributes accessible for the digitisation point, making it easier to navigate.

965
Q

What does the method startswith() accomplish? - (2)

A

The method startswith() checks whether a string starts with a specified prefix.

It returns True if the string starts with the prefix, and False otherwise.

966
Q

These are all

A

lot of private methods (things which start with an underscore “_something”) which clutter up our view, so we decide to exclude them using a list comprehension.

967
Q

what does this mean:

[x for x in dir(ex_1) if not x.startswith(‘_’)]

A

It says that we are going to loop over every item in dir(ex_1) and we will keep it (x for x in) if it doesn’t start with an underscore: (if not x.startswith(‘_’)).

968
Q

What does this code do? - (2)

A
  1. It first prints the data type (float) and the value of the sampling frequency (sfreq) associated with the MEG data.
  2. Then, it prints the data type (list) and the list of channel names (ch_names) in the MEG data.
969
Q

Output of this code

A
970
Q

What does the code print(ex_1.keys()) accomplish?

A

The code print(ex_1.keys()) prints out the keys associated with the digitisation point ex_1,

971
Q

What does the code print(ex_1['r']) display?

A

The code print(ex_1['r']) prints out the values of the ‘r’ key associated with the digitisation point ex_1, which represent the x, y, and z coordinates of the point in a tuple where Polheums is pointing to

972
Q

What does the code print(ex_1['ident']) reveal? - (2)

A

The code print(ex_1['ident']) displays the value associated with the ‘ident’ key for the digitisation point ex_1.

In this case, it indicates the identification of the point, which might not hold significant information.

973
Q

What information does the code print(ex_1['kind']) provide? - (2)

A

The code print(ex_1['kind']) reveals the type of point represented by the digitisation point ex_1.

It indicates that the point is of type ‘FIFFV_POINT_EXTRA’, which suggests that it is an extra point originating from the Polhemus.

974
Q

What does the code print(ex_1['coord_frame']) indicate? - (2)

A

The code print(ex_1['coord_frame']) displays the coordinate frame associated with the digitisation point ex_1.

In this case, it indicates that the coordinates are referenced to the head coordinate system (‘FIFFV_COORD_HEAD’).

975
Q

What is the purpose of the following code snippet? - (2)

A

The purpose of this code snippet is to extract digitisation points from the ‘digitisation’ data stored in the variable ‘dig’.

It specifically selects points originating from the Polhemus device and stores their coordinates in a numpy array.

976
Q

What does the line if pt['kind'] == mne.io.constants.FIFF.FIFFV_POINT_EXTRA: check for? - (2)

A

The line if pt['kind'] == mne.io.constants.FIFF.FIFFV_POINT_EXTRA: checks whether a digitisation point is of the type ‘FIFFV_POINT_EXTRA’, indicating that it originated from the Polhemus device.

These are the types (or ‘kind’) of things we want! They are ‘extra’ because they come from the Polhemus and not the scanner hardware itself.

977
Q

What does the code out_pts.append(pt['r']) accomplish?

A

The code out_pts.append(pt['r']) extracts the coordinates of digitisation points in a tuple of (x,y,z) originating from the Polhemus device and appends them to a list called ‘out_pts’. - specifcying location of digitsation point in 3D space

978
Q

What does the line print(f'Here are the dimensions of the point array: {out_pts.shape}') display? - (3)

A

prints the dimensions of the numpy array containing the digitisation points.

Here are the dimensions of the point array: (1555, 3)

So, we finish with 1555 Polhemus points. We started (back in the info structure) with 1558 points, and found that 3 of them were “cardinal points”, so this makes sense.

979
Q

The three reference points typically found in digitisation data that we don’t want are: - (3)

A

Nasion: The point at the bridge of the nose.

Left preauricular: The point in front of the left ear.

Right preauricular: The point in front of the right ear.

980
Q

What does this code do?- - (3)

A

This code snippet utilizes numpy and matplotlib to create a 3D scatter plot of digitisation points stored in the numpy array ‘out_pts’.

It first creates a figure and an axis with 3D projection, extracts the x, y, and z coordinates from ‘out_pts’, and then plots these points as a scatter plot in 3D space using the ‘scatter’ function.

Finally, it displays the plot.

981
Q

from mpl_toolkits.mplot3d import axes3d

explain - (2)

A

This line imports the axes3d module from the mpl_toolkits.mplot3d package.

The axes3d module provides functions and classes for creating and manipulating 3D plots in Matplotlib.

982
Q

Output of this code

A
983
Q

At this point we want to interact with the plot - maybe use spyder but we can do 3D plotting in the browser like this:

A

Code:
import plotly.express as px

fig = px.scatter_3d(x=x, y=y, z=z, opacity=.5)
fig.show()

984
Q

What does this code do? - (3)

A

This code snippet uses Plotly Express to create a 3D interactive scatter plot.

It takes the x, y, and z coordinates of the points and creates a 3D scatter plot with a specified opacity level.

The fig.show() function then displays the interactive plot.

985
Q

What does this code do? - (2)

A

This code snippet uses Plotly Graph Objects to render a surface plot.

It creates a mesh plot using the x, y, and z coordinates of the points, setting the color to gray and opacity to 1.

The fig.show() function then displays the rendered surface plot.

986
Q

What does the code raw.plot_sensors(kind='3d')
plt.show() do? - (3)

A

This code utilizes the plot_sensors function from the MNE library to create a 3D plot showing the relative positions of all sensors in the MEG data.

Each sensor’s position is represented in three dimensions.

987
Q

What does the code raw.plot_sensors() do?
plt.show() - (2)

A

This code uses the plot_sensors function from the MNE library to create a 2D plot showing the relative positions of all sensors in the MEG data.

Each sensor’s position is represented in two dimensions.

988
Q

What library is imported with the statement from matplotlib import figure?

A

The statement from matplotlib import figure imports the figure module from the Matplotlib library. This module provides the functionality to create and customize figures for plotting.

989
Q

What does the code raw.plot() do? - (2)

A

The code raw.plot() utilizes core routines from the MNE library to create a plot showing the raw MEG data.

This plot displays the burst of energy detected by each sensor across time, providing an overview of the MEG data.

990
Q

What observation is made about the behavior of raw.plot() on certain platforms like Colab?

A

On certain platforms like Colab, the interactive window might be plotted twice when using raw.plot(), and it may not be interactive as expected.

991
Q

What does the comment “# producing the burst of energy of heart at every sensor across time - something we would want to remove” suggest about the plot generated by raw.plot()? -(2)

A

The comment suggests that the plot generated by raw.plot()displays cardiac artefacts - not part of brain and the part of heart

These artifacts are undesirable and may need to be removed from the data.

Also see very fast ripples which are called line noise- noise coming from electromagnetic enviroment e.g., light from MEG room and taket them out as well

992
Q

What does the code raw.pick_types(meg=True).plot(butterfly=True) accomplish?

A

raw.pick_types(meg=True).plot(butterfly=True) selects only the MEG channels from the raw data and plots them in a ‘butterfly’ format

In the butterfly plot, each channel’s signal is displayed along a single line, allowing for easy comparison of signals across channels

This format is particularly useful for visualizing MEG data, as it helps to identify patterns and abnormalities in the signals.

993
Q

What observation is made about the noise in the data shown below the code snippet? - (2)

A

The comment suggests that there is a significant amount of noise present in the data shown below the code snippet.

This noise can obscure the underlying signal and may need to be filtered or removed for further analysis.

994
Q

Need to also import:

from matplotlib import figure for

A

MEG butterfly plot

995
Q

How do you plot 50 seconds worth of MEG data using the raw.plot() function? - (2)

A

To plot 50 seconds worth of MEG data, use the duration option in the raw.plot() function: raw.plot(duration=50).

This will zoom out to display a longer segment of the data.

996
Q

How do you plot 1 second of MEG data starting at 6 seconds using the raw.plot() function? - (2)

A

To plot 1 second of MEG data starting at 6 seconds, use the start and duration options in the raw.plot() function:

raw.plot(start=6, duration=1). This will zoom in to display a short, specific segment of the data.

997
Q

What does raw.plot(start=6, duration=1) plot? - (2)

A

plots a standard time series of the MEG data for all selected channels, showing the data from the 6th second to the 7th second.

Each channel’s data is displayed separately, rather than overlaid as in a butterfly plot

998
Q

What effect does plotting 1 second of data starting at 6 seconds have on the visualization? - (2)

A

Plotting 1 second of data starting at 6 seconds zooms in on a short, specific segment of the data, allowing for finer detail to be seen.

This can help in identifying and analyzing individual events, such as heartbeats picked up by a single sensor.

999
Q

How can you mark a channel as bad in the interactive MEG data plot in Spyder, and how can you check which channels are marked as bad? - (2)

A

You can mark a channel as bad by selecting it in the interactive plot.

After closing the plotting window, you can check which channels are marked as bad by running print(raw.info['bads']).

The marked channels will be listed in raw.info['bads'].

1000
Q

How do you programmatically clear the list of bad channels in an MNE raw dataset?

A

You can clear the list of bad channels by setting raw.info['bads'] = [], which will empty the list and unmark any previously marked channels as bad.

1001
Q

Why might you want to “chop” MEG data into trials or epochs, and where is the information for doing this usually stored? - (2)

A

You might want to chop MEG data into trials or epochs to analyze specific segments of the data that correspond to experimental conditions or stimuli.

The information for doing this is usually stored on a trigger or stimulus channel

1002
Q

What is the purpose of the following code snippet in the context of MEG data analysis?

A

This code snippet isolates the trigger (stimulus) channels from the raw MEG dataset, prints the names of the remaining channels, and plots the trigger channel over a duration of 60 seconds to visualize the event trace.

1003
Q

What does the output of this code show? - (2)

A

The typical output would display the names of the channels present in the trig_chan dataset, such as “STI 014” and “STI 013”.

Additionally, it would show a plot of the trigger channel over a duration of 60 seconds, with the x-axis representing time (in seconds) and the y-axis indicating the presence of trigger events.

Each line on the plot corresponds to a different trigger event recorded in the MEG data.

1004
Q

What important point should be remembered when using the pick_types function in Python? - (2)

A

When using the pick_types function to select specific channels from a dataset, it’s crucial to remember that this function operates on the dataset in place unless explicitly applied to a copy of the dataset.

Failure to make a copy before using pick_types can result in unintentional modifications to the original dataset. (the raw existing dataset)

1005
Q

What is the potential consequence of not making a copy of the dataset before using the pick_types function? - (2)

A

The potential consequence of not making a copy before using pick_types is that any modifications made to the selected channels will directly affect the original raw dataset.

This can lead to unexpected changes in the data and unintended side effects in subsequent analyses.

1006
Q

How can you explicitly make a copy of a list or dataset in Python? - (2)

A

To explicitly make a copy of a list or dataset in Python, you can use the .copy() method/statement.

For example:
This ensures that b is a separate copy of a, allowing independent modifications without affecting the original list or dataset.

1007
Q

What does the pick_types function in MNE-Python allow us to do? - (2)

A

The pick_types function in MNE-Python allows us to create a copy of the dataset containing only certain channels of interest.

This function helps in selecting specific types of channels, such as stimulus channels or MEG channels, for further analysis.

1008
Q

What is the purpose of using the find_events function in MNE-Python? - (2)

A

The find_events function in MNE-Python is used to extract event timing information from the dataset.

It searches for triggers or events recorded in the data and returns an array containing the timing and event code for each detected event.

1009
Q

What information does the numpy array returned by the find_events function contain? - (4)

A

The numpy array returned by the find_events function contains three columns:

  1. The start index in time.
  2. An irrelevant column (not used in the current context).
  3. The event code representing the type of event detected.
1010
Q

What does the shape (600, 3) of the events array indicate? - (2)

A

The shape (600, 3) of the events array indicates that there are 600 events detected in the dataset.

Each event is represented by three pieces of information: the start index in time, an irrelevant column (not used), and the event code.

1011
Q

What does the event code 4196 signify in the context of the MNE-Python dataset? - (2)

A

In the context of the MNE-Python dataset, the event code 4196 represents a specific type of event or trigger recorded in the data.

It could correspond to a particular stimulus presentation, experimental condition, or other predefined event in the experimental paradigm.

1012
Q

What is the purpose of the np.diff function in NumPy? - (2)

A

The np.diff function in NumPy is used to compute the difference between consecutive elements in an array. I

t calculates the gap or change between adjacent values in the array.

1013
Q

How can the np.diff function be used to analyze trigger events in MNE-Python datasets? - (2)

A

In MNE-Python datasets, the np.diff function can be applied to the timestamps of trigger events to compute the time differences between consecutive events.

This helps in analyzing the inter-trigger intervals or gaps in milliseconds.

1014
Q

What does the function np.diff([1,2,3,4,5]) return and why? - (3)

A

The function np.diff([1,2,3,4,5]) returns an array [1,1,1,1].

This is because it computes the difference between consecutive elements in the array.

In this case, the difference between 2-1=1, 3-2=1, 4-3=1, and 5-4=1, resulting in an array of consecutive 1s representing the gaps between the original elements.

1015
Q

Why is it preferable to use descriptive names like ‘visual’ instead of event codes like ‘4196’? - (2)

A

Using descriptive names like ‘visual’ instead of event codes like ‘4196’ makes the code more readable and understandable.

It provides context and clarity to the purpose of the event, enhancing interpretability.

1016
Q

What does the event_dict = {‘visual’: 4196} line of code accomplish? - (2)

A

The event_dict = {‘visual’: 4196} line creates a dictionary that maps descriptive names (‘visual’) to event codes (‘4196’).

This allows for more intuitive labeling of triggers in the plot.

1017
Q

What does the plt.figure(figsize=(15,3)) line of code do? - (2)

A

The plt.figure(figsize=(15,3)) line sets the size of the figure for plotting events.

It specifies a figure size of 15 inches in width and 3 inches in height, ensuring appropriate visualization.

1018
Q

What does the mne.viz.plot_events(events, sfreq=raw.info[‘sfreq’], event_id=event_dict, axes=h) function call do? - (2)

A

The mne.viz.plot_events() function plots the time-series of events.

It takes the events data, the sampling frequency (sfreq), the event dictionary (event_dict) for labeling, and the axes (axes=h) for plotting.

1019
Q

What does output of this code show? - (4)

A

pot the time-series of events. We see that there were some gaps in events, presumably to give the participant a short break.

. Each line corresponds to a specific event ID, in this case, ‘4196’. These lines are spaced apart with gaps indicating periods where no trigger events occurred.

Bunch of them up to 110s then a gap…

Participant se flash on screen then a gap and then flash

1020
Q

What does the blue lines represent when plotting the original data with events marked on?| - (2)

A

The blue lines represent the events marked on the plot.

Each line corresponds to a specific event, and the position along the time axis indicates the timing of the event occurrence.

1021
Q

What does the plot() function do in the context of meg_chan.plot(butterfly=True, clipping=None,start=100,duration=1)?

A

It plots the MEG data in a butterfly format, where each sensor’s data is represented on a separate line for better visualization.

1022
Q

What does raw.copy().pick_types(meg=True, stim=False) do?

A

It selects only the MEG channels from the raw data while excluding the stimulus channels.

1023
Q

Why is it important to high-pass filter the data before running ICA?

A

High-pass filtering removes slow components like drifts from the data, which can otherwise lead to artefactual components in the ICA decomposition.

1024
Q

What does the random_state=97 parameter in the ICA instantiation achieve?

A

It ensures reproducibility of the ICA decomposition across different runs of the algorithm, which is particularly useful for teaching purposes or when consistency in results is desired.

1025
Q

What does the output “Filtering raw data in 1 contiguous segment” indicate?

A

It indicates that the raw data is being filtered to remove very slow components, such as drifts, before applying ICA.

1026
Q

How many ICA components were requested in the code?

A

Fifteen ICA components were requested by setting n_components=15 in the ICA instantiation.

1027
Q

does it do low or high apss fitlering in this code?: - (2)

A

This code performs high-pass filtering. This is evident from the parameter l_freq=1 in the filter method, which specifies the lower frequency cutoff for the high-pass filter.

The absence of h_freq parameter means there is no upper frequency cutoff, indicating that only high-pass filtering is applied.

1028
Q

What is the low-frequency cutoff? - (2)

A

The low-frequency cutoff is 1 Hz. This is specified by the parameter l_freq=1 in the filter method.

By applying a high-pass filter with a cutoff frequency of 1 Hz, it removes very slow components, such as drifts, from the data

1029
Q

What does the function ica.plot_components() do?

A

It plots the component topographies, allowing us to visually inspect the spatial patterns of the independent components.

1030
Q

Output of ica.plot_components() explained: (2)

A

We are looking for artifacts coming from two places: Eye movements (which will show up either side of the front of the head) and cardiac (heartbeat) artifacts which come from far far away and so might just smear out over the whole brain.

We are immediately suspicious of components ICA000 looks like it originates very low down in the brain…. sources like this could be real data from deep brain structures but often they are actually interference from the electrical activity of the heart (which is firing a big ‘pulse’ every second or so). 0005 is pretty much centred on the eyes… TBH I’m not excited about 0002 either but let’s take a look…

1031
Q

What does the function ica.plot_sources(raw, show_scrollbars=False) do?

A

It visualizes the timecourse of the sources identified by ICA, allowing us to inspect potential artefacts such as cardiac activity, eye movements, or breathing patterns.

1032
Q

What does it indicate if a component isolates a cardiac-style trace? e.g., , ICA000 looks like it has isolated a cardiac-style trace.

A

t suggests that the component may be capturing electrical activity related to the heartbeat, which is considered an artefact in MEG and EEG data analysis.

1033
Q

How can we identify potential artefacts such as eye movements or breathing patterns in the timecourse of the sources?

A

By visually inspecting the traces generated by ica.plot_sources(), we can observe characteristic patterns that resemble known artefacts, such as rapid fluctuations indicative of eye movements or periodic patterns corresponding to breathing.

ICA005 also appears to have isolated something which may be eye movement. Looking at the traces, however, it is also possible that ICA006 has done the same. ICA010 also appears to be some form of breathing artefact.

1034
Q

Question: How do we identify which components to remove in ICA?

A

By visually inspecting the timecourse of the sources, we look for components that isolate artefacts such as cardiac activity, eye movements, or breathing patterns.

1035
Q

Which components are decided to be removed in this case, and why?

A

Components 0, 5, 6, and 10 are marked for removal as they appear to isolate artefacts such as cardiac activity, eye movements, or breathing patterns, which we aim to eliminate from the data.

1036
Q

What does ica.exclude = [0, 5, 6, 10] do?

ica.exclude = [0, 5, 6, 10]
ica.plot_sources(raw, show_scrollbars=False)

A

This line of code excludes specific Independent Components identified as artefacts from the ICA analysis, marking components 0, 5, 6, and 10 for removal.

1037
Q

What does ica.plot_sources(raw, show_scrollbars=False) accomplish? - (2)

A

This function plots the time series of the sources for each Independent Component identified by ICA.

By visualizing the timecourse of each component, analysts can identify artefactual patterns such as cardiac activity or eye movements for further inspection and potential removal.

1038
Q

What does the following code snippet do? - (2)

raw.load_data()
ica.plot_overlay(raw, picks=’meg’)

A

This code snippet loads the original raw data and then overlays the cleaned signals obtained after removing the specified Independent Components (ICs) onto the original signals.

It allows for a visual comparison between the original data and the cleaned data, highlighting the impact of IC removal on specific channels.

1039
Q

What does the following code snippet - (3) accomplish?

A

This code snippet applies the Independent Components Analysis (ICA) cleaning process to the copied raw data.

The original raw data remains unchanged, while the cleaned data is stored in the reconst_raw variable.

This allows for the comparison between the original and cleaned datasets, preserving the integrity of the original data.

1040
Q

What does the following code snippet do, and what does the resulting visualization show? - (5)

A

This code snippet compares the original raw dataset (raw) with the dataset after Independent Components Analysis (ICA) de-noising (reconst_raw).

It selects specific MEG channels specified in the chans list and plots their data side by side.

The visualization titled “Original” displays the raw data, while the visualization titled “Cleaned” displays the data after ICA de-noising.

By comparing the two plots, users can observe the effects of the de-noising process, such as the removal of regular cardiac artifacts and eye movements, as well as any potential loss of variance in the data.

Above is the original raw dataset and below is the dataset after ICA de-noising. You can see that we have removed the regular cardiac artefacts and we have also removed some eye movements (see around 6s in channels 153 and 154).

1041
Q

What is the purpose of deleting the original raw data (raw) using del raw? - (2)

A

Deleting the original raw data (raw) using del raw frees up memory resources by removing the data from memory.

This step is taken after the ICA de-noising process to ensure that memory is efficiently managed, especially if the dataset is large.

1042
Q

How is the ICA de-noised data saved in the provided code snippet? - (3)

A

The ICA de-noised data is saved to disk in compressed FIFF format using the save() method.

The filename used for saving the data is ‘R1025_P1114_4-raw.fif.gz’.

This ensures that the cleaned data is preserved and can be easily accessed in future sessions.

1043
Q

What function can be used to load the saved ICA de-noised data back into memory in future sessions? - ((3)

A

The mne.io.read_raw_fif() function can be used to load the saved ICA de-noised data back into memory in future sessions.

This function takes the filename of the saved data (‘R1025_P1114_4-raw.fif.gz’) as an argument and returns the data as a raw objec

However, it’s important to note that event timings and other related computations may need to be recomputed after loading the data.

1044
Q

What is the purpose of filtering the data between 3 and 30Hz? - (2)

A

Filtering the data between 3 and 30Hz helps isolate the frequency band associated with evoked activity, which is the focus of the subsequent analysis.

This filtering step removes high-frequency noise and low-frequency drifts, enhancing the signal-to-noise ratio for further analysis.

1045
Q

What precaution is taken before filtering the data? (3 Hz to 30 Hz) - (2)

A

Before filtering the data, the load_data() method is called to ensure that the data is loaded into memory.

This step is essential, especially when the file has just been re-loaded, to ensure that the data is available for filtering.

1046
Q

What filtering options are used in the provided code snippet? - (2)

A

A band-pass filter between 3 and 30Hz is applied to the data using an Finite Impulse Response (FIR) filter.

This filter selectively allows frequencies within the specified range to pass through while attenuating frequencies outside the range.

1047
Q

How can the original and filtered data be plotted for comparison? - (2)

A

Both the original and filtered data can be plotted using the plot() method.

For the original data, raw.plot(start=6, duration=2) is used, while for the filtered data, filt.plot(start=6, duration=2) is used.

This allows visual inspection of the effects of filtering on the data.

1048
Q

Does the provided code snippet apply a low-pass filter to the data? - (2)

Filter between 3 and 30Hz
raw.load_data()
filt = raw.copy().filter(l_freq=3, h_freq=30, n_jobs=-1)

A

Yes, the provided code snippet applies a low-pass filter as part of the band-pass filtering process.

While explicitly mentioning the low-pass filter is not done in the code, the band-pass filter inherently includes both high-pass and low-pass filtering components.

1049
Q

Can the filtered data be saved and re-loaded for future use? - (2)

Save the filtered data
filt.save(‘filtered_data.fif.gz’)

Re-load the filtered data
filt = mne.io.read_raw_fif(‘filtered_data.fif.gz’)

A

Yes, the filtered data can be saved using the save() method and re-loaded using the read_raw_fif() function.

This allows for preservation of the filtered data and avoids the need to repeat the filtering step in future sessions.

1050
Q

What is the purpose of epoching the data? - (2)

A

The purpose of epoching the data is to segment it into smaller, trial-like segments centered around specific event timings.

This allows for the analysis of neural activity in response to experimental events, facilitating the investigation of event-related potentials (ERPs) or event-related oscillations (EROs).

1051
Q

Explain the code - (7) - epoching the MEG data

A

This code epochs the filtered data using MNE.

filt: Filtered data to be epoched.

events: Event timings extracted from the filtered data.

event_id: Dictionary mapping event labels to event codes.

tmin: Start time of each epoch relative to event onset (-0.2 seconds).

tmax: End time of each epoch relative to event onset (0.5 seconds).

preload: Indicates whether to load all data into memory at once (True).

1052
Q

What does the output of filt_epochs represent?

A

We have 600 trials (as expected) and each of our epochs runs from -0.2 to 0.5s.

1053
Q

After epoching the MEG data, we can individually plot our epochs
…. - (2)

A

The time-axis here is now based on the epoch number rather than in seconds. All of the data in between the epochs has been thrown away

We can now compute an average. As we only have one condition, this is easy. We will, however, do it as if we had multiple conditions ( i.e. specify the condition name) so that you can follow how you would deal with the multiple condition case:

1054
Q

What does filt_avg.plot() visualize?

A

The average time-series of epochs with spatial colors and global field power (GFP), allowing for topology plots of sensors.

1055
Q

What does filt_avg.plot_topomap() display?

A

Topomap plots of sensor spatial distribution at specific time points, indicating brain activity patterns.

1056
Q

What does the output show? - (5)

A

The initial plot will show the average time-series.

Outside the notebooks, you can click and drag on this plot to draw a topology plot of the sensors over a given time-window.

The example above shows this for the first real peak (just before 100ms).

We can see from this that there is a right-lateralised dipole over where we would assume that occipital cortex would be.

This experiment involved showing a visual stimulus to the left-hand visual field, so this is somewhat reassuring.

1057
Q

What does filt_avg.plot_joint() visualize?

A

A combined plot showing the average time-series, topomap plots, and sensor data along with spatial distribution at specific time points.

1058
Q

How does plot_joint determine the times to plot by default?

A

It guesses based on peaks in the data.

1059
Q

How can you override the default times in filt_avg.plot_joint()?

A

By specifying the times argument, like filt_avg.plot_joint(times=[0.08, 0.31]).

1060
Q

In this session, we will start looking at how to

A

to manipulate neuroimaging data in Python.

1061
Q

We are going to be using a module called

A

nibabel to load MRI and fMRI data to Python and save out overlays and statistical maps in the same format - old way of doing it

1062
Q

Going to be using Spyder

A

which is used for scientific programming in Python and can run python directly from machine (as compared to Colab - running it from cloud) and can produce interactive plots

1063
Q

All of the files for this section can be found in the - (2)

A

course materials repository.

They are in the s7_fmri directory.

1064
Q

Obtaining the data files needed for this lecture which is found in s7_fMRI directory by running this code:

A
1065
Q

What does this code mean?

A

git is accessing remote reposities and borrows data from YNiC (s7_fMRI directory) to local content directory

1066
Q

Output of this code:

A
1067
Q

After running the code:

We can check the current working directory

List the contents inside the current working directory

List what is inside pin-materials and s7_fMRI

A
1068
Q

What are these files when listening what is inside s7_fMRI? (last part) - (4)

A

These are all data files

‘highres.nii.gz’ is a anatomical file - 3D high-resolution structural image (T1) of someone’s brain

‘highres_brain.nii.gz’ - word brain means we have stripped away the skull and just looking at the brain (skull-stripped image of the brain) - using FSL command called BET

There are two functional imaging data files here/datasets which are 3D snapshots of the brain taken every 2 seconds (TR) while its doing a task: 1) filtered_func_data.nii.gz and func_data.nii.gz

1069
Q

What does

A
1070
Q

‘ls-l’ mean?

A

Listening contents of files and directories in long format (“l” at bottom)

1071
Q

The ‘Babel’ part of nibabel refers to

A

the ‘Tower of Babel’.

1072
Q

The nibabel module has

A

reading and writing routines for various neuroimaging formats - so that we can all speak the same neuroimaging ‘language’ or something.

1073
Q

Most MRI data are taken off scanners in a format known as

A

DICOM

1074
Q

What does DICOM stand for?

A

Digital Imaging and Communications in Medicine)

1075
Q

Most MRI data are taken off the scanners in a format known as DICOM - this format is

A

very complex so scientists almost always convert the DICOM images from the scanner into NIFTI

1076
Q

What does NIFTI stand for?

A

Neuroimaging Informatics Technology Initiative

1077
Q

Most MRI data are taken off scanners in a format known as DICOM which is complex and scientist always conert to NIFTI and at YNIC this is done

A

automatically

1078
Q

NIFTI files end in

A

nii.gz, gz means the file is compressed so does not take up much space on disk

1079
Q

What are the two parts of NIFTI files, and what does each part contain? - (3)

A

NIFTI files consist of a ‘header,’ which contains information about

the image (e.g., how big the image is, how big the voxels are, many voxels there are in each direction, number of volumes, TR),

and the actual imaging data which is just an array of numbers: usually integers for raw data that has come from scanner; often floating point for processed data

1080
Q

The first dataset we will look at is in the folder is a high-resolution anatomy file called ‘highres.nii.gz’ which contains - (2)

A

a single T1-weighted scan of a brain

It was acquired slice by slice : 176 slices running >across< the head from Left to Right in steps of 1mm with 256x256 1mm x 1mm voxels in each slice.

1081
Q

Let’s move into the s7_fMRI which contains ‘highres.nii.gz’ directory for rest of tutorial by doing this which means

A

This code changes the current working directory to ‘/content/pin-material/s7_fmri’

1082
Q

So we are going to examine the ‘highres.nii.gz’ by loading it using nibabel

Thus, we need to import the module first:

A

This is common practice, analogous to importing numpy as np.

1083
Q

We will now use nibabel to load an fMRI file into Python and examine it of ‘highres.nii.gz’ using nibabel:

A
1084
Q

Explain this code:

anatImage = nib.load(‘highres.nii.gz’) - (2)

A

This code utilizes the ‘nibabel’ library to load a structural NIFTI file named ‘highres.nii.gz’.

The function ‘nib.load()’ reads the file and stores its contents in the variable ‘anatImage’, which includes both the header information and the data of the image - two partsof NIFITY

1085
Q

After using nibabel nib.load to load the structural NIFITI file (‘highres.nii.gz’) we can check the type of object returned by file and what type of object is returned which prints out…

A

this prints out: <class ‘nibabel.nifti1.Nifti1Image’>

1086
Q

We can also make a variable and store header info using anatImage.header and check its type which prints out…

A
1087
Q

this prints out:

A
1088
Q

We can also look at the keys of the header using

this print(hdr.leys()) is - (2)

A

This code prints out the keys present in the header of a NIFTI file.

Think of these keys as analogous to columns in a table. They provide information about various attributes and properties of the NIFTI image data.

1089
Q

The output of this code is

A
1090
Q

Explain this output:

A

These are all the stuff you would acquire as you run the MRI scanner such as extent of the data, how big the head was, what is sequence is, how tiny voxels are, coverage of brain, how was imaging planes oriented to acquire data

1091
Q

There are many items in the header but we are interested in

A

dim and pixdim entries

1092
Q

We can also look at the dim entries in which treating header like a dictionary and requesting ‘dim’ key from it using

print(hdr[‘dim’]) and see as output

A
1093
Q

What does this mean from print(hdr[‘dim’]) - (3)

A

When we look at dim, we find an array of integers

The 0th element (3 in this case) refers to how many dimensions of data there are; as this is a structural or anatomical dataset, there are 3-dimensions.

The remaining values tell us the number of voxels in each of the dimensions. As we only have three dimensions, only elements 1 to 3 (inclusive) have any meaning; the rest can be ignored.

1094
Q

When we show pixel dimensions header print(hdr[‘pixdim’]) - explain - (6)

A

In this code snippet, we’re accessing the ‘pixdim’ header in the NIFTI file, which provides information about the size of each voxel in millimeters.

These numbers are floats because they refer to the size in mm:

The printed array, [1. 1. 1. 1. 2.3 0. 0. 0.], contains float values representing voxel sizes.

Positions 1 to 3 (1.0) are relevant, indicating the voxel sizes in each dimension.

In this example, the numbers are all 1.0 which makes sense because the voxel sizes are 1mm in all dimensions

Additionally, the value in position 4 (2.3) refers to the ‘repetition time’ (TR) of the image, which might be relevant depending on the type of MRI data.

1095
Q

More detail on this output - (2)

A

We have taken 176 slices in sagittal plane/direction (going through middle of brain)

Each sagittal section is 256 by 256 voxels

1096
Q

Explain this output in more detail - (5)

A

Position 1: Width of the image in mm.

Position 2: Height of the image in mm.

Position 3: Depth or slice thickness of the image in mm.

For example, if positions 1 to 3 contain [1.0, 1.0, 1.0], it indicates that each voxel (3D pixel) in the image is 1mm x 1mm x 1mm in size.

So, if we’re considering the array [1. 1. 1. 1. 2.3 0. 0. 0.], positions are typically indexed starting from 0.

1097
Q

Next, we can load the actual image data of ‘highres.nii.gz’ using nib.looad instead of its header

A
1098
Q

Explain this code - (7)

A

import nibabel as nib: Importing the Nibabel library, used for reading and working with neuroimaging data.

anatImage = nib.load(‘highres.nii.gz’)`: Loading a structural NIFTI image from a file called ‘highres.nii.gz’.

data = anatImage.get_fdata(): Extracting the data from the loaded NIFTI image, storing it as floating-point numbers.

print(data.shape)`: Printing the dimensions of the data array, indicating the size of the image - (176 by 256 by 256)

print(data.dtype)`: Printing the data type of the elements in the data array, indicating they are floating-point numbers - float64

print(data[88, 127, 127]): Printing the value of a voxel located at coordinates (88, 127, 127) within the image. - 274.0 - saying how big the voxel is

print(data[1, 1, 1])`: Printing the value of a voxel located at coordinates (1, 1, 1), typically near the edge of the image (more likely to be small number as most black space near the head) - 4.0

1099
Q

Output of this code

A
1100
Q

Instead of looking at the value at one voxel, we can instead peek at one slice of data and to do this we need to

A

import pyplot using import matplotlib.pyplot as plt

1101
Q

Code producing one slice of data instead of one voxel

A
1102
Q

Explain this code - (4)

A

import matplotlib.pyplot as plt: Importing the Matplotlib library for visualization.

aSlice = data[124,:,:]: Extracting a single sagittal slice of brain data from a 3D volume stored in the variable ‘data’. This slice is located at index 124 (pass midpoint off the edge) along the first axis, which typically represents the sagittal plane (out of 176 slices) if we say index 88 its more or else down the middle

plt.grid(True): Configuring the plot to display grid lines for better visualization.

  • plt.imshow(aSlice): Displaying the extracted sagittal slice using Matplotlib's imshow()` function, which visualizes a 2D array as an image. In this case, it displays the 2D slice of brain data.
1103
Q

Output of this code:

A
1104
Q

matplot lib has a function called

A

plt.imshow() which if you give a two-dimensional slice of data then it will make a picture of it

1105
Q

First of all the output of this is messy as it

A

t is standing up on its nose and the colour map is weird.

1106
Q

We can then load the data again

A
1107
Q

To change the colour map of the output - (2)

A

We can do this

plt.imshow(slc, cmap=’gray’) - # change colour map to grey

1108
Q

What does this code mean in more detail? - (6)

A

take 124 elemens through one dimension, : take every row and column through 124 slices of the head

We pick slice 124

The dimensions here (see Advanced material below) are

L-R, P-A and I-S

Slice 124 from the first dimension is more or less through the middle of the right hemisphere

The remaining dimensions are P-A and I-S

1109
Q

What does this output display - white stuff and grey stuff - (2)

A
  • white stuff is fat
  • grey stuff is neurons - convey communication between different parts of grey matter
1110
Q

Highlight positions on the head

A
1111
Q

We would like to flip the image the right way around - (3)

A

plt.show() then using tranpose function which takes a data set and spins it around the axis - it swaprs the dimensions so swaps vertical and horizontal axis

It would need anterior and posterior running along x axis - be upside down

so to fix then take that slice and resample in opposite direction [::-1,:] - pick all rows and columns but pick them in reverse order

1112
Q

Flipping image on right way around - first tranpose

What does this code do first? - (7)

A

It selects a single slice (slc) from the 3D brain data (data), specifically the slice at index 124 along the first axis.

It plots the selected slice using plt.imshow() with a grayscale colormap (cmap=’gray’).

It adds a title ‘Original’ to the plot.

It displays the plot using plt.show().

After plotting the original slice, the code recognizes that the image orientation needs adjustment for proper display.

It transposes the dimensions of the slice (slc.transpose(1, 0)) to swap the axes, changing the orientation from [I-S, P-A] to [P-A, I-S].

It plots the transposed slice using plt.imshow() with the same grayscale colormap.

1113
Q

After tranposing we need to reverse the image

Explain the reverse part - (7)

A

Remember how we can use the -1 operator to reverse the order in which we choose numbers from a list? - resample to opposite direction so all row and columns to minus 1

list[<start>:<stop>:<step>]</step></stop></start>

if you leave out an argument it just assumes ‘the start’ or ‘the end’ or ‘1’

So slc[::-1,:] means ‘I want the 2D matrix from slc but give me the first dimension (the rows) stepping ‘backwards’ in steps of 1,

and then leave the other dimension (the columns) unchanged’

his operation effectively flips the image vertically, changing the orientation from inferior-superior (I-S) to superior-inferior (S-I).

remeber dimensions are : # L-R, P-A and I-S

1114
Q

Explain rest of this code: after tranposing we want to we would like to have the axes labelled correctly in mm.
# So we need to know how big
# the image is on each side. That is found from the header:
# pixelSize * numberOfPixels - (8)

A

ap_npix = anatData.header[‘dim’][2]`: Retrieves the number of pixels along the anterior-posterior (A-P) direction from the image header.

  • si_npix = anatData.header['dim'][3]: Retrieves the number of pixels along the inferior-superior (I-S) direction from the image header.
  • ap_pixdim = anatData.header['pixdim'][2]: Retrieves the pixel dimensions (in millimeters) along the A-P direction from the image header.
  • si_pixdim = anatData.header['pixdim'][3]: Retrieves the pixel dimensions (in millimeters) along the I-S direction from the image header.
  • Setting Image Extent:
    • extent = (0, si_npix*si_pixdim, 0, ap_npix*ap_pixdim): Calculates the extent parameter for the image plot, which defines the spatial dimensions in millimeters. It specifies the extent of the image along the x-axis (I-S) and y-axis (A-P) based on the number of pixels and pixel dimensions.
  • Plotting the Image:
    • plt.imshow(slc, cmap='gray', extent=extent): Plots the image (slc) using Matplotlib’s imshow() function with a grayscale colormap (cmap='gray') and the calculated extent parameter. This ensures correct scaling and spatial representation of the image in millimeters.
    • plt.title('Final image'): Sets the title of the plot to ‘Final image’ using plt.title().
    • plt.show(): Displays the final image plot.
1115
Q

Output after tranposing, reversing and setting image extent:

A
1116
Q

The dimensions of our image are: [L-R, P-A, I-S]. We have taken a single slice in the left-right direction which means that we are left with data which is [P-A, I-S].

We are using the matplotlib imshow() routine whch

A

This takes data as if it were a photograph, i.e. the bottom left hand entry in our data matrix will be at the bottom left of the displayed image.

1117
Q

More detail what does transpose do and reverse? - (3)

A

At present, we have [P-A, I-S], so we start by using the .transpose() function to reverse the orders of the axes, ending up with [I-S, P-A].

This looks nearly right, except that we want our data in row 0 to be the most superior data and the data in the last row (255) to be the most inferior: i.e. our I-S axis needs to be S-I.

To do this, we just reverse the data in that dimension using the ::-1 syntax`(see below).

1118
Q

What does plt.show() and extent() do near end of code? - (7)

A

Now that we have re-ordered our data, we can pass it to imshow().

In the imshow() call, we use an extra argument which we have not seen before: extent.

This allows us to set the pixel dimensions for the image.

This is not actually that important in this case because the MRI image pixel size is 1x1mm, so it makes no difference.

If, however, your image was 1.13x1mm or similar, you would end up with a distorted image if you do not make this correction.

What we do is to multiply the number of pixels in each dimension by the size of the pixels in that dimension.

This makes matplotlib scale the image properly.

1119
Q

What does red plot do near end of code?

A

To show off, we also show that we can plot points on the same plot - so, we add a red point at a specific point on the image; we could also add text, arrows and anything else which we can do in matplotlib.

1120
Q

hat you have there is a ‘sagittal’ slice. There are two other types of slice you can make: ‘axial’ and ‘coronal’. - (2) which are..

A

Axial slices are parallel to the ground if you are standing up

Coronal slices are vertical (if you are standing up) and run across the brain from left to right (so, for example, there is a coronal slice at the front of the head that has both of your eyes and your nose and teeth in it - we call this ‘Scary Slice’)

1121
Q

Explain this part of the code that tranposes and reverses brain image NIFTI file that it got to right orientation - (18)

A
  • Loading Data:
    • import os: Imports the os module to interact with the operating system.
    • import nibabel as nib: Imports the nibabel library for working with neuroimaging data.
    • import matplotlib.pyplot as plt: Imports the matplotlib library for plotting.
    • os.chdir('/content/pin-material/s7_fmri'): Changes the current working directory to ‘/content/pin-material/s7_fmri’.
    • s = nib.load('highres.nii.gz'): Loads the structural NIFTI file named ‘highres.nii.gz’.
    • data = s.get_fdata(): Loads the image data from the NIFTI file as floating point numbers.
  • Plotting Original Slice:
    • slc = data[:, :, 100]: The syntax [:, :, 100] selects all rows and columns (full 2D slice) at the specific index 100 along the third axis (I-S direction) of the data volume.
    • plt.imshow(slc, cmap='gray'): Plots the selected slice with a grayscale colormap.
    • plt.title('Original'): Sets the title of the plot to ‘Original’.
    • plt.show(): Displays the plot.
  • Adjusting Orientation:
    • slc = slc.transpose(1, 0): Transposes the dimensions of the slice, effectively swapping the axes from inferior-superior (I-S) to posterior-anterior (P-A).
      • This operation changes the orientation of the slice by exchanging the axes, which can be useful for adjusting the display orientation.
    • slc = slc[::-1, :]:
      • By reversing the rows, the orientation of the slice is corrected, ensuring proper anatomical orientation. effectively reverses the order of rows in the 2D array slc, flipping the slice vertically. This operation ensures that the slice is properly oriented along the inferior-superior (I-S) axis,
  • Plotting Final Slice:
    • plt.imshow(slc, cmap='gray'): Plots the adjusted slice with a grayscale colormap.
    • plt.title('Final'): Sets the title of the plot to ‘Final’.
    • plt.grid(True): Adds grid lines to the plot for better visualization.
    • plt.show(): Displays the final plot.
1122
Q

Regardless of the selected slice (slc = data[:, 124, :], slc = data[124,:,:], or slc = data[:,:,124]), the following steps adjust its orientation - (2)

A

Transpose Operation: slc = slc.transpose(1, 0)
- Swaps the axes of the 2D slice, effectively rotating it.

2. Reverse Operation: `slc = slc[::-1, :]`
   - Flips the slice vertically by reversing the order of its rows.
1123
Q

When slc =data[:, 124, :], what happens when transposing and reversing the NIFIT image? - (3)

A

slc = data[:, 124, :]: This selects a single slice from the MRI volume. The colon : indicates that all elements are selected along the first and third dimensions (likely the left-right and inferior-superior directions), while selects one slice at index 124 along the second dimension (likely the anterior-posterior direction).

slc = slc.transpose(1, 0): This transposes the selected slice. Therefore, [::-1, :] effectively reverses the order along the second axis (P-A) while keeping all elements along the first axis (L-R) and third axis (I-S) unchanged

slc = slc[::-1, :]: This reverses the order of rows in the slice, flipping it vertically. The [::-1, :] syntax means reversing the order along the first axis (anterior-posterior) while leaving the second axis (left-right) unchanged. This step ensures proper anatomical orientation, aligning the slice from inferior to superior. GOES P-A THEN A-P

1124
Q

When
slc = data[:, :, 124], what happens when transposing and reversing the NIFIT image? - (3)

A

slc = data[:, :, 124]: This selects a single axial slice from the MRI volume. The colon : indicates that all elements are selected along the first and second dimensions (likely the left-right and anterior-posterior directions), while selects on slice at index 124 along the third dimension (likely the inferior-superior direction).

slc = slc.transpose(1, 0): This transposes the selected slice. The axes are swapped, effectively rotating the slice. Therefore, [::-1, :] effectively reverses the order along the second axis (P-A) while keeping all elements along the first axis (L-R) and third axis (I-S) unchanged.

slc = slc[::-1, :]: This reverses the order of rows in the slice, flipping it vertically. The [::-1, :] syntax means reversing the order along the first axis (anterior-posterior). This step ensures proper anatomical orientation, aligning the slice from inferior to superior.

1125
Q

Transposing and reversing seems like a lot of work so it gives you a shortcut - (3)

A

e.g, using these member functions

Get the data and the qform matrix
data = s.get_fdata()
qform = s.get_qform()

s.orthoview()

1126
Q

Explain this code - (6)

A

The code imports the necessary libraries: nibabel (as nib) and matplotlib.pyplot (as plt).

It then loads a structural NIFTI file named ‘highres.nii.gz’ using the ‘nib.load()’ function and stores it in the variable ‘s’.

The ‘s.get_fdata()’ function retrieves the image data from the NIFTI file and stores it in the variable ‘data’.
in floating-point format

Additionally, the ‘s.get_qform()’ function retrieves the affine transformation matrix (qform matrix) associated with the NIFTI file and stores it in the variable ‘qform’.

This matrix contains information about the spatial orientation and voxel dimensions.

Finally, the ‘s.orthoview()’ function is called, which automatically produces three views of the data, labeling them as anterior, posterior, superior, and inferior.

1127
Q

Output of this code:

A
1128
Q

To run this code of spyder have to change

s = nib.load(‘highres.nii.gz’) which works in Colab

to

A

s = nib.load(‘C:\Users\gs1211 (whatever usename you have)\pin-material\s7_fmri\highres.nii.gz’)

1129
Q

In this output - (2)

A

labels left on left and right is on right

However, in FSL this is flipped other way as in radiological convention so be careful looking at fMRI should be labelled

1130
Q

In the notebook this will just print out three static views of the data. That’s fine but we can do better. If you run it in Spyder it will bring up a complete volume browser that you - (2)

A

you can click around in spyder by simply uploading same code you did in Colab and changing

s = nib.load(‘highres.nii.gz’) which works in Colab to
s = nib.load(‘C:\Users\gs1211 (whatever usename you have)\pin-material\s7_fmri\highres.nii.gz’)

1131
Q

How to tell spyder to install nibabel? - (2)

A

In the Spyder Console (Bottom Right) type:

pip install nibabel

1132
Q

How to check if sypder installed nibabel? - (3)

A

You can check that it has worked by typing (on the console again)

import nibabel as nib

There should be no complaints!

1133
Q

How to tell spyder we want interactive graphics? - (5)

A

Go into the Preferences window like this

Tools->Preferences

From the iPython Console settings:

Select Graphics -> Graphics Backend -> Qt5

And hit ‘Apply’

1134
Q

Quite often you may perform some analysis on MRI/fMRI data and then want to save it out in a

A

new file

1135
Q

Quite often you may perform some analysis on MRI/fMRI data and then want to save it out in a new file.
For instance, - (3)

A

you might want to create a ‘mask’ for a specific area based on some criteria.

This is a bit more complex than writing things out in normal files as you must make sure that the header information is correct.

The easiest way is to start from the type of file that you are analysing.

1136
Q

What is the process involved in saving new NIFTI images in MRI or fMRI analysis? - (5)

A

When working with MRI or fMRI data, you might need to perform analyses and then save the results in a new NIFTI file.

This process involves ensuring that the header information is correct to maintain data integrity.

One common use case is creating a mask for specific areas based on certain criteria.

For example, you might want to create a mask where only certain voxels are set to a value like 255.0, while others remain at 0.0.

This mask can then be used for further analysis.

1137
Q

If spyder crashes press or any changes you make to Python pipline then

A

restart the kernel

1138
Q

Explain this code -(5)

producing mask

A

This code snippet performs several operations on a structural NIFTI file to create a mask and save it. Let’s break down each step:

  1. Loading the NIFTI File:
    • The code starts by loading a structural NIFTI file named ‘highres.nii.gz’ using the nib.load() function from the nibabel library. This file contains MRI data.
  2. Extracting Structural Data:
    • Once the file is loaded, the structural data is extracted using the get_fdata() method, and it’s stored in a variable named data.
    • The print(data.shape) statement displays the shape of the extracted data. This provides information about the dimensions of the MRI data. - (176, 256, 256)
  3. Modifying Data to Create Mask:
    • Next, a specific region within the data is modified to create a mask. The code sets voxels in a box-shaped region (with indices ranging from 100 to 169 along each axis) to the value 255. This operation effectively creates a mask where the selected region is marked with 255, indicating the presence of the mask. - #setting all one partof the data to be the same value of ‘255’ - inserting bick of 255 values inside someone’s head
    • This process allows for the creation of a mask that can be used to isolate specific areas of interest within the MRI data.
  4. Creating a New NIFTI Image in memory:
    • After modifying the data to create the mask, a new NIFTI image is created in memory using the modified data. This is achieved using the Nifti1Image constructor from nibabel.
    • The constructor requires three arguments: the modified data (mask), the affine transformation (s.affine), and the header information (s.header) obtained from the original NIFTI file.
  5. Writing/Saving to the Overlay:
    • Finally, the newly created NIFTI image (mask) is saved as ‘my_overlay.nii.gz’ using the nib.save() function. This function takes two arguments: the new image object (new_image) and the desired filename (‘my_overlay.nii.gz’). - #takes 2 arguements, dataset you made and name it
1139
Q

What mask does this code produce? - (2)

A

The code defines a box-shaped region within the MRI data, with boundaries set along the left-right (L-R), posterior-anterior (P-A), and inferior-superior (I-S) axes, corresponding to the X, Y, and Z dimensions, respectively.

Within this defined region, the voxel intensities are set to 255, effectively creating a binary mask where this specific region is highlighted, while the rest of the voxels remain unchanged.

1140
Q

What is output of this code? (spyder)

A

change to be smaller e.g., 100:110 to all

1141
Q

So far, we have only loaded in structural MRI data into Python. But we can also load

A

functional data

1142
Q

In s7 directory we glone from pin-materials there is a

A

n fMRI time-series in the file func_data.nii.gz.

1143
Q

Explain this code which loads the fMRI data, extracts header information, and prints some details about the data

A
1144
Q

What is a purpose of producing a mask?

A

Masking out parts of brain (ROIs) and extract data from that or sometimes ROIs to mark parts of brain as not interesting so analysis does not include them - e.g., don’t include damaged brain parts from stroke patients

1145
Q

Explain this code that loads the fMRI data, extracts header information, and prints some details about the data - (6)

A
  • The code begins by importing necessary libraries: nibabel for working with NIFTI files, matplotlib.pyplot for plotting, and numpy for numerical operations.
  • It loads fMRI data from a NIFTI file named ‘func_data.nii.gz’ using the nibabel.load() function.
  • The header and data are then extracted from the loaded file using the .header and .get_fdata() methods, respectively.
  • The header contains essential information about the data, such as its dimensions and pixel dimensions, which are printed using the hdr[‘dim’] and hdr[‘pixdim’] statements.
  • The size and type of the data array are printed using the data.shape and type(data) statements, respectively.
  • This provides an overview of the fMRI data, including its dimensions and voxel size, facilitating further analysis or visualization.
1146
Q

Explain the output from this code of loading and extracting info of fMRI data - (6)

A

The first line [ 4 80 80 64 160 0 0 0] represents the dimensions of the data. Each number corresponds to a specific dimension:

The first number (4) indicates that the data has four dimensions - we have four-dimensional data. This makes sense as we now also have a time dimension.

The subsequent numbers (80, 80, 64, 160) represent the size of each dimension: 80 voxels along the first dimension, 80 voxels along the second dimension, 64 voxels along the third dimension, and 160 time points along the fourth dimension.

Looking at the next four numbers, we find that each of our images is (80, 80, 64) and that we have 160 of them (so 160 time-points).

The pixel dimensions tell us that the voxel size in this case is 3x3x3; i.e. we have a 3x3mm acquisition with 3mm slices. The next number in the pixdim array is the TR: in this case that is 2s. - blocks of brain collected every 2s and dimensins of block 3,3,3mm

The third line (80, 80, 64, 160) - this shape specification indicates that the data array comprises 80 voxels in the x-direction, 80 voxels in the y-direction, 64 voxels in the z-direction, and 160 time points, forming a four-dimensional array.

1147
Q

We can add f.orthoview()
at end to make it interactive:

A
1148
Q

Extending this code to produce graphs of voxel from two different positions - explain the code - (8) with output

A

This code plots the time-series for two voxel positions using data obtained from fMRI.

It uses the ‘ggplot’ style for visualization and plots the signals from two different voxels in blue and red, respectively.

It also adds labels for the x-axis and y-axis, as well as a legend to distinguish between the two voxel positions.

Because we now have data available as a numpy array, we can plot it.

This time we choose two (very non-accidentally chosen) voxels and plot the timeseries for each of them:

The first thing to note is that this is the raw image-space data from the scanner; it has not been pre-processed in any way.

The second thing is that it looks like we have almost periodic responses in each of these voxels. In Voxel 1 (plotted in blue) we have 10 cycles through the experiment (32 seconds per cycle).

In Voxel 2 (plotted in red) we have 16 cycles through the experiment (20 seconds per cycle). It is almost as though the person was doing two different tasks or having different parts of their brain stimulated at different frequencies.

1149
Q

What is the goal of manual fMRI analysis using numpy?

A

The goal is to replicate part of a first-level FSL analysis, inspired by old-school electrophysiology methods.

1150
Q

What technique is used to identify voxel responses at stimulus frequencies?

A

Fourier Transform (FT) is used to break down voxel time series into frequency components.

1151
Q

How does Fourier Transform (FT) help in fMRI analysis?

A

FT allows us to examine voxel responses at specific frequencies, indicating neural activity synchronized with experimental stimuli.

1152
Q

What does “np.fft” stand for in numpy?

A

np.fft” stands for NumPy’s Fast Fourier Transform, used for efficient Fourier analysis of voxel time series data.

1153
Q

What is the significance of bright patches in frequency volumes obtained from Fourier Transform?

A

Bright patches indicate voxels that are active at specific frequencies, suggesting neural responses to experimental stimuli.

1154
Q

Here is the simplest possible fMRI analysis you could ever do - (4)

A

Load the data (4D)

Compute the FT of the data across time for every voxel (4D). This gives us a data volume at every frequency. The amplitude of each voxel in a volume ‘f’ tells us how much that voxel was responding at frequency ‘f’.

Take a look at the volumes for frequencies ‘10’ and ‘16’ times per experiment.

Bright patches of voxels in those volume are ‘active’ at those frequencies.

1155
Q

Explain this code that plots three different voxels - (5)

A

Imports necessary libraries: nibabel for working with NIFTI files, matplotlib.pyplot for plotting, and numpy for numerical operations.

Loads the fMRI data from the file named ‘filtered_func_data.nii.gz’.

Extracts header information (hdr), voxel data (data), and the qform matrix (qform) from the loaded NIFTI file.

Prints some header information, including the dimensions (hdr[‘dim’]), pixel dimensions (hdr[‘pixdim’]), and shape of the data array (data.shape).

Plots the time-series data for three specific voxels (p1, p2, and p3) on the same graph p1: represents voxel data at position (29, 29, 40), p2 represents voxel data at position (50, 29, 40)., p3 represents voxel data at position (46, 9, 30).

1156
Q

What is the qform matrix? - (2)

A

The qform matrix, extracted from a NIFTI file, represents the transformation matrix that maps voxel coordinates to the scanner’s spatial coordinate system.

It defines the orientation, position, and scaling of the image data in physical space.

1157
Q

What do the coordinates represent in the context of the code snippet p1=data[29, 29, 40, :], p2=data[50, 29, 40, :], and p3=data[46, 9, 30]? - (4)

A

In the context of fMRI data, the coordinates represent the spatial location of specific voxels within the brain volume.

Each set of coordinates specifies the position of a voxel along the x, y, and z axes, respectively.

For example, in p1=data[29, 29, 40, :], the voxel is located at coordinates (29, 29, 40), indicating its position along the x-axis (29 units), y-axis (29 units), and z-axis (40 units).

Similarly, p2=data[50, 29, 40, :] and p3=data[46, 9, 30] represent voxels located at different spatial coordinates within the fMRI volume.

1158
Q

Output of this code

A

Those are the two voxels we looked at before plus another one that doesn’t seem to be active.

1159
Q

We can then produce fourier transform of each voxel using this code

Explain it - (6)

A
  1. fp1=abs(np.fft.fft(p1)), fp2=abs(np.fft.fft(p2)), and fp3=abs(np.fft.fft(p3)): These lines apply the Fourier Transform to each voxel time series (p1, p2, and p3) to compute the amplitude of each frequency component.
  2. plt.figure(figsize=(15,5)): Creates a new figure for plotting with a specific size.
  3. plt.bar(np.arange(29)+.8,fp1[1:30],width=0.2), plt.bar(np.arange(29)+1,fp2[1:30],width=0.2), plt.bar(np.arange(29)+1.2,fp3[1:30],width=0.2): These lines generate bar charts for each voxel’s Fourier transform. They plot the amplitudes of the Fourier transform components (from frequencies 1 to 29) along the x-axis, with slight adjustments to the bar positions to avoid overlap.
  4. plt.xlabel('Frequency (cycles/expt)'), plt.ylabel('Signal amp (au)'): Sets labels for the x-axis and y-axis of the plot.
  5. plt.legend(['Voxel 1', 'Voxel 2','Voxel 3']): Adds a legend to the plot indicating which voxel each set of bars represents.
  6. plt.show(): Displays the plot.
1160
Q

What does output show of fourier transform of each voxel? - (3)

A

voxel 1 (red) clearly responding at 10 cycles per second - has 1 input

voxel 3 (lilac) responding at 10 and 16 cycles per second - has 2 inputs

voxe 2 (blue) that is weak has some power at every frequency - call white noise

1161
Q

The grande finale is that we would like to see

A

where these are in the brain and if they are part of larger groups of similar voxels. To do this we just compute the FFT on all the voxels at once and make nice response maps at all the different frequencies!

1162
Q

explain in more detail what line of code does - (5)

plt.bar(np.arange(29)+1.2,fp3[1:30],width=0.2)

A

np.arange(29): Generates an array of integers from 0 to 28, representing the indices of the frequencies.

+1.2: Adds a small offset to the x-axis values, ensuring that the bars for each frequency are evenly spaced.

fp3[1:30]: Extracts the Fourier transform magnitudes for frequencies 1 to 29 (indexing is zero-based in Python).

width=0.2: Sets the width of the bars to 0.2 units.

Together, this line positions and plots the bars representing the Fourier transform magnitudes of the third voxel’s time-series data, ensuring proper spacing and visualization of the frequency spectrum.

1163
Q

Explain this code- (7)

A

Fourier Transform (FT) Calculation: The code begins by computing the Fourier transform of the entire fMRI data array (data) using NumPy’s Fast Fourier Transform (FFT) function (np.fft.fft()). The FFT is applied along the first dimension, which represents time. This step decomposes the time series data into its frequency components, providing insights into how different frequencies contribute to the signal.

Magnitude Extraction: After computing the FFT, the code uses the abs() function to extract the magnitude of the resulting complex numbers. This is necessary because the FFT output includes both real and imaginary components. By taking the absolute value, we obtain the magnitude of each frequency component, which represents the strength or amplitude of the signal at that frequency.

Frequency Response Extraction: Next, the code extracts the frequency responses at 10 and 16 times per experiment from the magnitude data (fData). These frequencies are of interest because they may correspond to specific experimental conditions or stimuli. The extracted responses are stored in arrays response10 and response16, respectively, creating 3D maps of response magnitudes across all voxels in the fMRI data.

Slice Selection: To visualize the frequency responses, the code selects specific slices (s10 and s16) from the response maps. These slices represent responses at particular voxels within the brain. However, since the orientation of the data may not be optimal for visualization, the code applies a transpose operation and reverses the order of elements along the second axis to ensure correct orientation ([:, :, ::-1].transpose()).

Plotting: The selected response slices (s10 and s16) are plotted side by side using Matplotlib’s imshow() function. Each subplot displays the response map at either 10 or 16 cycles per second. The ‘jet’ color map is utilized to visualize the intensity of responses, with warmer colors indicating higher response magnitudes. Additionally, titles are added to each subplot to denote the corresponding frequency.

Save Output: Finally, the code saves the generated response maps as NIFTI files (10cycles.nii.gz and 16cycles.nii.gz). These files can be further analyzed or visualized using neuroimaging software.

List Files: As a final step, the code executes a command (!ls -lat) to list the files in the current directory, providing an overview of the saved output files.

1164
Q

What does plt.subplot(1,2,1) mean? - (2)

A

The code utilizes Matplotlib’s subplot() function to organize the visualization of the frequency response maps.

By specifying (1,2,1) as the argument for the first subplot, it instructs Matplotlib to create a grid of subplots with one row and two columns and select the first subplot for the current plot.

1165
Q

What does response10=fData[:,:,:,10] do in code?

A

In the given code snippet, response10[29, :, ::-1] reverses the order of elements along the last axis of response10, ensuring proper orientation of the data for visualization

1166
Q

What is output

A
1167
Q

I have loaded in anantomical nifti file using nibabel like this:

What does the ‘dim’ key in the header represent?

A

The 3D or 4D dimensions of the image in voxels (and TRs if appropriate)

1168
Q

Q2:
Similarly, there is another field called ‘pixdim’. What is that?

A

The size of each voxel in mm

1169
Q

Q3:
I have loaded in two files from a function dataset. myData_r.nii.gz and myData_f.nii.gz . They are exactly the same dimensions but when I plot the same pixel location from each file in turn the timeseries is subtly different - one seems to be smaller and smoother than the other. What might ‘r’ and ‘f’ mean in the headers?

A

‘Raw’ and ‘Filtered’ - this is how we refered to them in the lecture the filtered image has probably been smoothed in time or space or both.

1170
Q

Q4:
I run an fMRI experiment in which I flash two checkerboards on and then off at different frequencies. One checkerboard is in the left visual field, the other is in the right visual field.

In the left visual field I flash at 10 cycles per experiment. In the right visual field I flash at 7 cycles per experiment.

a) What would I expect to see in the FT of a voxel from left hemisphere V1?

b) Some voxels in the brain seem to have Fourier Transform peaks at both 7 and 10 cycles per experiment. What must be true about at least some of the receptive fields in those voxels? - (2)

A

a) A peak at 7 cycles per experiment - in the Fourier Transform (FT) of a voxel from the left hemisphere V1, you would expect to see a peak at 7 cycles per experiment. This corresponds to the frequency of the checkerboard stimuli presented in the right visual field, as the left visual field is represented in the right hemisphere.

b) They must have inputs from both visual fields

1171
Q

5:
I have a nifti file and I want to plot two different voxels of data from it. However although the data loads, I only see one line. What is wrong with this code and how can I fix it?

A

You are plotting p1 twice. Change the second ‘plt.plot’ statement to use p2 not p1

1172
Q

The provided code snippet, using slc.transpose(1, 0), only transposes the - (3)

A

In this case, it swaps the first and second dimensions, effectively exchanging the P-A (posterior-anterior) and I-S (inferior-superior) axes.

So, if the original orientation of the slice was (L-R, P-A, I-S), it would become (L-R, I-S, P-A) after this operation.

does not affect L-R

1173
Q

What does slc.tranpose(0,1) do? - (2)

A

it swaps the first and second dimensions, effectively exchanging the L-R (left-right) and P-A (posterior-anterior) axes.

So, if the original orientation of the slice was (L-R, P-A, I-S), it would become (P-A, L-R, I-S) after this operation.

1174
Q

User
so slc is always [::-1,:] regardles if slice is L-R, P-A or I-S?

A

he slicing operation slc[::-1, :] is independent of the orientation of the slice. It always reverses the order of rows in the 2D array slc, regardless of whether the slice represents left-right (L-R), posterior-anterior (P-A), or inferior-superior (I-S) orientation.

1175
Q

What is missing in this code?

A

Quotes are missing around the string.

1176
Q

What is the (main) mistake in this Python script intended to check if a number is divisible by
3?

A

The second print statement is always executed regardless of the output of the ‘if’ statement

1177
Q

What is wrong with the indentation in the following code? Explain your answer.

A

The line after the if statement should be indented

1178
Q

Identify and describe the error in this code snippet:

A

data and DATA are different variables because one is in upper case and the other is in lower
case.

1179
Q

Identify the issue with the input handling in the following code. How might you fix it? - (2)

A

The user might input a string for age and then the programme would crash.

You could use
try / except statement to loop until they enter a number.

1180
Q

What is the matter with this code?

A

There should be a : after the def doubleNumber(x)

1181
Q

I am trying to print the last element in this list. What is going wrong? How can I fix it?

A

len will give you a result of 5. You should use listLen-1 on the last line because lists are
zero-indexed.

1182
Q

I am printing some elements in a list in reverse order using range’s [start,stop,step] format.
Why isn’t it working? If I fix the bug, what numbers will it print? - (2)

A

The colon (:) is missing at the end of the second line.

If you fix it it will print 17,13,11,7,5,3

1183
Q

Why would using the .get member function make this code safer?

A

Because if someone enters a key that is not in the dict then at the moment it will crash on
line 3. .get will return ‘None’ if the key does not exist.

1184
Q

Here are two lists - (2)

How can I join them to make a new list called list3 which is:

[2,4,6,8,10,20,30,40]

A

(Two possible good answers) 1: Use + to join them: i.e. print (list1+list2) 2:

Use the .extend
member function: i.e. list1.extend(list2) print(list1)

1185
Q

f-strings allow me to include variable values inside print statements. What would be the output
of the following code:

A

2.32
1.202
001

1186
Q

In the course we learned that tuples are a bit like lists. They are not exactly the same - name
one significant difference. (2 marks) - (2)

A

You cannot modify a tuple

(Probably I would also accept :“They are defined with round brackets not square brackets.”
)

1187
Q

This code uses the range(start, stop, step) format to print the results of dividing 10 by lots of
different even numbers. It will throw an error right at the end - why and how can I fix it? - (2)

A

The last number is zero so you get a ‘Divide by Zero’ error.

You could change the range to stop before zero. Or check to make sure ‘a’ is not zero with an
‘if’ statement.

1188
Q

Here is a function to raise one number to the power of another. What is going wrong when I
call it inside the print statement?

A

The function does not return a value so the part inside the bracket will return ‘None’ for every
call.

1189
Q

I’m trying to write a while loop but it’s not running at all. Can you see why?

A

It should be a==1 at the while statement (to test if a equals 1).

1190
Q

I am using Psychopy to display a triangle on the screen that moves top to bottom in a single
trial. I use a Polygon stimulus for the dot (with ‘Triangle’ selected) and set the size correctly.
I also set the Location of the dot to depend on time. Specifically, I set the ‘y’ location of the
dot to be ‘t’ which is the internal variable for time in Psychopy like this in the dialog box
Position [x,y]$ = (0,t). I also set the position to ‘Update Every Repeat’.

When I run the code, the triangle appears but it does not move. Why?

A

You should set it to update every frame, not every repeat.

1191
Q

I have inherited a Psychopy experiment from an old lab member and I want to run it on our
newest machine. There is a .csv file that lists filenames that comes with the experiment. The
filenames are oldImages/Image1.jpg, oldimages/Image2.jpg, oldImages/Image3.jpg,
oldImages/Image4.jpg and so on. The experiment runs, shows the intro screen, then
crashes.

The .csv file and the psychopy experiment file are both in the same directory. Can you think
of a reason why the code might not be running properly. - (2)

A

The image directory might not exist , or be in the wrong place relative to the code.

(I would also accept other plausible scenarios like “The directory does not contain any images”,
“the image names are wrong” and, possibly even, “the filenames should have instead of / slashes
on some machines”)

1192
Q

I have a psychopy reaction time task with three components. They are:

A

25s (Average ISI is 1.5s, the rest is 1s, total=2.5s, 10 repeats)

1193
Q

I would like the ISI to be an average of 2s with a max of 2.5s. What should the expression for
the duration change to? (2 marks)

A

random()*1+1.5
(or just random()+1.5)

1194
Q

I accidentally set the ISI to this:

When I look at the reaction times they are much shorter - some of them are almost zero. How
can this be?

A

The ISI is always the same (1) so people can anticipate the cue

1195
Q

I am using CircuitPython to flash an onboard LED red, then green with each colour coming
on for 500ms. The code below does not seem to work - the light just stays on white. Assuming
all the libraries are present and loaded correctly, what’s the problem?

A

The led values should be (255,0,0) for RED and (0,255,0) for GREEN

1196
Q

This code is supposed to flicker the LED randomly at 50Hz. It just fails to run at all. The
library random is present and random.randint(x,y) returns a random integer between x and
y.
I can’t see the error on the terminal - can you suggest what the issue might be?

A

You are not importing the neopixel library

1197
Q

As an exercise I am trying to use list comprehension to generate a new list and then do exactly
the same thing with a for loop. However, the two lists are not the same. Here is the code.

Why do they not match? - (2)

A

You should append x to myList2 in the for loop.

So myList2.append(x) not myList2=x

1198
Q

What will this function do? - (4)

A

The quick answer is ‘It checks to see if the number is prime’

Stepping through the code: First it checks to see if it’s <2 (1 is not prime) or 2 (2 is prime).

Then it goes through all the numbers up to n-1 and sees if any of them divide into n with no
remainder.

If they >do< then the function returns ‘False’. Otherwise you get to the end and
there are no factors so it returns ‘True’.

1199
Q

I am using matplotlib to make nice plots. Here is one: - (4)

Briefly describe what it looks like

A

The variable x is created using np.arange(-10, 11, 1), which generates an array of integers from -10 to 10, inclusive.

The y-values are calculated as x * 2. This means each y-value is twice the corresponding x-value, forming a linear relationship.

The plot displays green circular markers at coordinates (x, 2x) for each x in the range from -10 to 10.

The x-axis ranges from -10 to 10, and the y-axis ranges from -20 to 20 to accommodate the y-values.

1200
Q

Here are two distributions plotted as histograms. Which one (data1 or data2) will have the
smallest standard deviation?

A

data1 -

1201
Q

In the code below, the data file rawdata_mcf.nii.gz exists and is loaded correctly. The file
contains a 4D array and has 120 TRs of data.

When the data are plotted they look very noisy. There are lots of drifts, mean offsets and
high frequency noise components. The file has already been motion-corrected.

What simple
thing might you do to make the data nicer to look at initially? Just describe the operation,
you don’t have to know the exact command.

A

Filter the data using a band-pass filter to remove very high and low frequencies

1202
Q

I have a sagittal slice through an anatomical MRI head dataset. The dataset is 256x256x256
voxels covering the whole head at 1x1x1mm resolution. The slice is taken from the left side of
the head close to the mid-saggital plane.

The orientation of the slice is such that when I use plt.imshow() to look at it, the top of the
head is on the left, the bottom of the neck is on the right, the nose is at the top and the back
of the head is on the bottom.

What operation can I perform to make the image oriented so that AP runs from left to righ
and SI runs from top to bottom?

Describe or name the operation, you don’t need to know the exact command.

A

Transpose - mirrors the array along the diagonal

1203
Q

In nilearn I can set up a ‘First Level Model’ and fit the GLM in one go like this:

a) What do these columns represent?

b) How might I reduce the number of additional columns?

A

a: Models of the low-frequency drifts

b: Change the ‘high_pass’ parameter to something lower like .001

1204
Q

I am looking at some MEG data from another lab. My results seem to be pretty noisy. I use
an MNE function called compute_psd to compute the ‘power spectral density’: the power at
each frequency like this:

When I look at the frequency power spectrum of the data it has big spikes at 60Hz and
120Hz.

a) What might these spikes be due to

b) Suggest a simple way to remove them. Describe the operation, you do not need to know
the exact syntax.

A

a) “Line noise” - electrical interference at the mains frequency

b) A notch filter : Specifically notch filter at 60 and 120Hz

1205
Q

What is missing in this code to correctly import the math module and use the sqrt function?

result = sqrt(16)
print(result)

A

You need to import the math module.

1206
Q

What will be the output of the following code and why? - (2)

A

The output will be: x is greater than 5

Because 10 is greater than 5, the condition x > 5 evaluates to True.

1207
Q

Explain why the following code does not print “Hello, World!”. - (2)

A

The print statement inside the function needs to be indented.

The correct code is:

1208
Q

Identify and describe the error in this code snippet: - (3)

A

The index 3 is out of range because the list numbers has only three elements,

indexed from 0 to 2.

Attempting to access numbers[3] will cause an IndexError.

1209
Q

How can you modify this code to ensure it handles potential exceptions when converting input to an integer?

A

You can use a try/except block to handle exceptions:

1210
Q

What is the problem with this loop, and how can you fix it?

A

The print statement and the increment should be indented within the while loop.

1211
Q

Identify the issue with the function and suggest a fix. - (2)

A

The function call add(5) is missing a second argument.

The correct call should be add(5, b) where b is defined. For example:

1212
Q

What will be the output of this code and why? - (2)

A

0
1
2

The loop stops when i equals 3 due to the break statement.

1213
Q

Explain the error in the following code and how to correct it.

A

The = operator is used for assignment, not comparison.

The correct operator is ==. The correct code is:

1214
Q

What is the error in this dictionary operation and how can it be fixed? - (2)

A

The key ‘gender’ does not exist in the dictionary, which will cause a KeyError.

You can use the .get() method to provide a default value:

1215
Q

What will be printed by the following code? Explain your answer - (2)

A

Both x and y will be [1, 2, 3, 4] because y is a reference to the same list as x.

Changes to y affect x as well.

1216
Q

Describe what this code does and provide the output. - (2)

A

This code creates a new list squared containing the squares of the numbers in the nums list.

The output will be:

1217
Q

What is wrong with the following code that is supposed to blink a NeoPixel LED red for 1 second and off for 1 second? - (5)

A

The code itself is correct and should theoretically blink the NeoPixel LED red for 1 second and then turn it off for 1 second in an infinite loop. However, there might be an actual error related to hardware or connection issues. Some potential reasons for the code not working as expected could be:

Incorrect Wiring: Ensure that the NeoPixel LED is connected to the correct pin on the microcontroller board.

Power Issues: Ensure that the NeoPixel LED is receiving sufficient power to function properly.

Defective Hardware: The NeoPixel LED or the microcontroller board might be defective.

Library Compatibility: Check if the neopixel library is compatible with the specific microcontroller board being used.

1218
Q

Explain what this code snippet does:

A

This code initializes 8 NeoPixel LEDs and sequentially lights each one green for 0.5 seconds before turning it off

1219
Q

Explain what the following NiBabel code does:

A

This code loads a NIfTI file (example.nii.gz), extracts the data array, and calculates the mean across the last axis (usually time) of the 4D fMRI data, resulting in a 3D mean image.

1220
Q

What is the purpose of the high_pass filter in this Nilearn FirstLevelModel setup?

A

The high_pass filter is used to remove low-frequency drifts from the fMRI signal, ensuring that only high-frequency signals (above 0.01 Hz) are analyzed.

1221
Q

Describe what the following MNE code does:

A

This code loads an MEG/EEG raw data file, applies a band-pass filter between 1 Hz and 40 Hz to remove low-frequency drifts and high-frequency noise, and plots the power spectral density (PSD) of the filtered data.