-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
168 lines (120 loc) · 3.78 KB
/
utils.py
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
"""
Helper utilities
"""
from __future__ import print_function
from contextlib import contextmanager
from scipy.stats import pearsonr
from os import mkdir, uname, getlogin
from os.path import join, expanduser
from time import strftime
from collections import namedtuple
import numpy as np
import sys
import csv
__all__ = ['notify', 'rolling_window', 'mksavedir', 'tocsv', 'save_markdown',
'metric', 'Batch']
Batch = namedtuple('Batch', ['X', 'y'])
@contextmanager
def notify(title):
"""
Context manager for printing messages of the form 'Loading... Done.'
Parameters
----------
title : string
A message / title to print
Usage
-----
with notify('Loading'):
# do long running task
time.sleep(0.5)
>>> Loading... Done.
"""
print(title + '... ', end='')
sys.stdout.flush()
try:
yield
finally:
print('Done.')
def mksavedir(basedir='~/Dropbox/deep-retina/saved', prefix=''):
"""
Makes a new directory for saving models
Parameters
----------
basedir : string, optional
Base directory to store model results in
prefix : string, optional
Prefix to add to the folder (name of the model or some other identifier)
"""
assert type(prefix) is str, "prefix must be a string"
# get the current date and time
now = strftime("%Y-%m-%d %H.%M.%S") + " " + prefix
# the save directory is the given base directory plus the current date/time
userdir = uname()[1] + '.' + getlogin()
savedir = join(expanduser(basedir), userdir, now)
# create the directory
mkdir(savedir)
return savedir
def tocsv(filename, array, fmt=''):
"""
Write the data in the given array to a CSV file
"""
row = [('{' + fmt + '}').format(x) for x in array]
# add .csv to the filename if necessary
if not filename.endswith('.csv'):
filename += '.csv'
with open(filename, 'a') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(row)
def tomarkdown(filename, lines):
"""
Write the given lines to a markdown file
"""
# add .csv to the filename if necessary
if not filename.endswith('.md'):
filename += '.md'
with open(filename, 'a') as f:
f.write('\n'.join(lines))
def metric(yhat,yobs):
"""
Metric for comparing predicted and observed firing rates
"""
return pearsonr(yhat.flatten(), yobs.flatten())[0]
def rolling_window(array, window, time_axis=0):
"""
Make an ndarray with a rolling window of the last dimension
Parameters
----------
array : array_like
Array to add rolling window to
window : int
Size of rolling window
time_axis : 'first' or 'last', optional
The axis of the time dimension (default: 'first')
Returns
-------
Array that is a view of the original array with a added dimension
of size `window`.
Examples
--------
>>> x=np.arange(10).reshape((2,5))
>>> rolling_window(x, 3)
array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
[[5, 6, 7], [6, 7, 8], [7, 8, 9]]])
Calculate rolling mean of last dimension:
>>> np.mean(rolling_window(x, 3), -1)
array([[ 1., 2., 3.],
[ 6., 7., 8.]])
"""
# flip array dimensinos if the time axis is the first axis
if time_axis == 0:
array = array.T
elif time_axis == -1:
pass
else:
raise ValueError("Time axis must be 0 or -1")
assert window >= 1, "`window` must be at least 1."
assert window < array.shape[-1], "`window` is too long."
# with strides
shape = array.shape[:-1] + (array.shape[-1] - window, window)
strides = array.strides + (array.strides[-1],)
return np.lib.stride_tricks.as_strided(array, shape=shape, strides=strides)