forked from kilianmandon/alphafold-decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprepare_tutorials.py
More file actions
229 lines (187 loc) · 7.74 KB
/
prepare_tutorials.py
File metadata and controls
229 lines (187 loc) · 7.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import re
import numpy as np
import os
from pathlib import Path
import shutil
import nbformat
def parse_file(filename, out_name):
"""Parses a Jupyter Notebook file, searches for TODO blocks and replaces them
with placeholder text.
Args:
filename: The name of the file to parse.
out_name: The nae of the file to write to.
"""
is_ipynb = filename.endswith('ipynb')
with open(filename, 'r') as f:
lines = f.readlines()
hashtag_inds = [i for i,l in enumerate(lines) if '####################' in l]
assert len(hashtag_inds)%4==0
groups = [hashtag_inds[i:i+4] for i in range(0, len(hashtag_inds), 4)]
to_replace_inds = []
for group_inds in groups:
todo_lines = '\n'.join(lines[group_inds[0]:group_inds[1]])
end_lines = '\n'.join(lines[group_inds[2]:group_inds[3]])
assert 'TODO' in todo_lines
assert 'END OF YOUR CODE' in end_lines
to_replace_inds.append((group_inds[1]+1, group_inds[2]))
def gen_replace_with(leading_whitespace_code, leading_whitespace_ipynb):
if is_ipynb:
basic_line_content = [
'# Replace \\"pass\\" statement with your code',
'pass',
]
else:
basic_line_content = [
'# Replace "pass" statement with your code',
'pass'
]
if is_ipynb:
basic = ' '*leading_whitespace_ipynb + '"\\n",\n'
else:
basic = '\n'
to_return = [basic]
for content in basic_line_content:
if is_ipynb:
line = ' '*leading_whitespace_ipynb + '"' + ' '*leading_whitespace_code + f'{content}\\n",\n'
else:
line = ' '*leading_whitespace_code + f'{content}\n'
to_return.append(line)
to_return += [basic]
return to_return
def calculate_leading_whitespace(line):
if is_ipynb:
quotes = [i for i,c in enumerate(line) if c=='"']
real_line = line[quotes[0]+1:quotes[-1]]
else:
real_line = line
unescaped = real_line.replace('\\n', '\n')
if not any(char.isalnum() for char in unescaped):
return -1
return len(real_line) - len(real_line.lstrip())
for replace_start, replace_stop in reversed(to_replace_inds):
leading_whitespace_code = np.array([calculate_leading_whitespace(a) for a in lines[replace_start:replace_stop]])
leading_whitespace_code = leading_whitespace_code[leading_whitespace_code != -1]
if leading_whitespace_code.size == 0:
leading_whitespace_code = 0
else:
leading_whitespace_code = np.min(leading_whitespace_code)
leading_whitespace_ipynb = np.array([len(l)-len(l.lstrip()) for l in lines[replace_start:replace_stop]])
leading_whitespace_ipynb = np.max(leading_whitespace_ipynb)
lines = lines[:replace_start] + gen_replace_with(leading_whitespace_code, leading_whitespace_ipynb) + lines[replace_stop:]
Path(out_name).parent.mkdir(parents=True, exist_ok=True)
with open(out_name, 'w') as f:
f.writelines(lines)
python_paths = [
'tensor_introduction/tensor_introduction.ipynb',
'machine_learning/machine_learning.ipynb',
'machine_learning/feed_forward.py',
'attention/attention.ipynb',
'attention/mha.py',
'attention/sentiment_analysis.py',
'feature_extraction/feature_extraction.py',
'feature_extraction/feature_extraction.ipynb',
'evoformer/dropout.py',
'evoformer/msa_stack.py',
'evoformer/pair_stack.py',
'evoformer/evoformer.py',
'evoformer/evoformer.ipynb',
'feature_embedding/feature_embedding.ipynb',
'feature_embedding/extra_msa_stack.py',
'feature_embedding/input_embedder.py',
'feature_embedding/recycling_embedder.py',
'geometry/geometry.py',
'geometry/geometry.ipynb',
'geometry/residue_constants.py',
'structure_module/ipa.py',
'structure_module/structure_module.py',
'structure_module/structure_module.ipynb',
'model/utils.py',
'model/model.py',
'model/model.ipynb',
]
file_copy_paths = [
'feature_extraction/alignment_tautomerase.a3m',
'model/download_openfold_params.sh',
]
folder_copy_paths = [
'tensor_introduction/control_values',
'machine_learning/control_values',
'attention/control_values',
'attention/images',
'feature_extraction/control_values',
'evoformer/control_values',
'evoformer/images',
'feature_embedding/control_values',
'feature_embedding/images',
'geometry/control_values',
'structure_module/control_values',
'model/control_values',
]
import glob
# Pattern 1: All __init__.py files directly within a subfolder of tutorials
pattern1 = "solutions/*/__init__.py"
files1 = glob.glob(pattern1)
# Pattern 2: All __init__.py files in a 'control_values' subfolder within tutorials
pattern2 = "solutions/*/control_values/__init__.py"
files2 = glob.glob(pattern2)
# Combine the results
all_init_files = files1 + files2
all_init_files = [path.replace('solutions/', '') for path in all_init_files]
file_copy_paths += all_init_files
def delete_tutorials_contents():
tutorials_path = 'tutorials'
if os.path.exists(tutorials_path):
shutil.rmtree(tutorials_path)
print("The 'tutorials' folder and its contents have been deleted.")
else:
print("The 'tutorials' folder doesn't exist.")
delete_tutorials_contents()
def clear_notebook_outputs(notebook_path):
nb = nbformat.read(notebook_path, as_version=4)
nb.metadata.clear() # Clear metadata first (important for outputs)
for cell in nb.cells:
if cell.cell_type == 'code':
cell.outputs = []
nbformat.write(nb, notebook_path)
# --- Assertions ---
for path in python_paths + file_copy_paths:
full_source = f'solutions/{path}'
full_target = f'tutorials/{path}'
assert os.path.isfile(full_source), f"Source file not found: {full_source}"
for path in folder_copy_paths:
full_source = f'solutions/{path}'
full_target = f'tutorials/{path}'
assert os.path.isdir(full_source), f"Source folder not found: {full_source}"
# --- Copying ---
for path in python_paths:
full_source = f'solutions/{path}'
full_target = f'tutorials/{path}'
parse_file(full_source, full_target)
if full_target.endswith('.ipynb'):
clear_notebook_outputs(full_target)
clear_notebook_outputs(full_source)
for path in folder_copy_paths:
full_source = f'solutions/{path}'
full_target = f'tutorials/{path}'
shutil.copytree(full_source, full_target)
for path in file_copy_paths:
full_source = f'solutions/{path}'
full_target = f'tutorials/{path}'
shutil.copyfile(full_source, full_target)
def remove_overwrite_results_option(filename):
with open(filename, 'r') as f:
data = f.read()
data = re.sub(r"\s*,\s*overwrite_results\s*=\s*False\s*", "", data)
data = re.sub(r"\s*,\s*overwrite_results\s*=\s*overwrite_results\s*", "", data)
pattern = r"^\s*if\s+overwrite_results:\s*(?s:.*?)\n\s*\n"
data = re.sub(pattern, "", data, flags=re.MULTILINE)
with open(filename, 'w') as f:
f.write(data)
control_save_to_remove = [
'tutorials/evoformer/control_values/evoformer_checks.py',
'tutorials/feature_embedding/control_values/embedding_checks.py',
'tutorials/structure_module/control_values/structure_module_checks.py',
'tutorials/model/control_values/model_checks.py',
]
for control_save_remove in control_save_to_remove:
remove_overwrite_results_option(control_save_remove)