-
Notifications
You must be signed in to change notification settings - Fork 0
/
platometer_io.py
163 lines (114 loc) · 4.3 KB
/
platometer_io.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
"""Additional Platometer helper functions to open, save and plot data.
"""
import os
import pickle
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.colors import LinearSegmentedColormap
def save_to_p(data, output_file=None):
"""Saves object to a pickle file.
Args:
data (obj): Object to be saved.
output_file (str, optional): Destination path for saving.
"""
if not output_file:
output_file = os.path.join(os.getcwd(), 'output.p')
with open(output_file, 'wb') as handle:
pickle.dump(data, handle)
def load(file_path, version=3, verbose=True):
"""
Loads all objects from a pickle or a HDF5 file.
Args:
file_path (str): Path to the input file.
version (int, optional): Python version (2 or 3) in which the input file was saved.
verbose (bool, optional): If True, show details.
Returns:
obj: The contents of the input file.
"""
[_, file_extension] = os.path.splitext(file_path)
if file_extension == '.h5':
output = {}
with pd.HDFStore(file_path) as store:
fkeys = store.keys()
for k in fkeys:
k = k.lstrip(r'\/')
if verbose:
print(k)
output[k] = pd.read_hdf(file_path, k)
elif file_extension == '.p':
if version == 3:
output = pd.read_pickle(file_path)
else:
pickle_file = open(file_path, 'r')
output = pickle.load(pickle_file)
if verbose:
print(', '.join(output.keys()))
else:
output = {}
print("Extension unknown. Only pickle (.p) and HDF5 (.h5) files are supported.")
return output
def plot_plate(data, colorbar=False, **kwargs):
"""Plots plate as a heatmap of colony sizes.
Args:
data (pandas.DataFrame): A DataFrame containing the quantified colony size data.
colorbar (bool, optional): If True, plots the colorbar.
**kwargs: Additional keyword arguments.
Returns:
matplotlib.axes.Axes containing the plate plot.
"""
plate = np.zeros((32, 48)) + np.nan
rows = data['row'].values.astype(int)
cols = data['col'].values.astype(int)
vals = data['size'].values.astype(float)
plate[rows - 1, cols - 1] = vals
if 'axes' in kwargs:
axes = kwargs['axes']
else:
_, axes = plt.subplots(1, 1, figsize=(20, 10))
vmin = kwargs.get('vmin', np.nanpercentile(vals, 5))
vmax = kwargs.get('vmax', np.nanpercentile(vals, 95))
midrange = kwargs.get('midrange',np.percentile(vals[(vals >= vmin) & (vals <= vmax)], [40, 60]))
if 'ticklabels' in kwargs:
xticklabels = kwargs['ticklabels']
yticklabels = kwargs['ticklabels']
else:
xticklabels = False
yticklabels = False
img = axes.imshow(plate, cmap=red_green(),
norm=MidpointRangeNormalize(midrange=midrange),
interpolation='nearest',
vmin=vmin, vmax=vmax)
axes.set_aspect('equal')
axes.grid(False)
if ~xticklabels:
axes.set_xticks([])
if ~yticklabels:
axes.set_yticks([])
if colorbar:
plt.colorbar(img, ax=axes)
plt.tight_layout()
return axes
def red_green():
"""Creates a divergent colormap centered on black and ranging from red (low) to green (high).
Returns:
LinearSegmentedColormap in the red-black-green range.
"""
color_dict = {'red': ((0.0, 0.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)),
'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0))
}
cmap = LinearSegmentedColormap('RedGreen', color_dict)
cmap.set_bad('gray', 0.5)
return cmap
class MidpointRangeNormalize(colors.Normalize):
"""Normalizes colors to match a specified mid-range.
"""
def __init__(self, vmin=None, vmax=None, midrange=None, clip=False):
self.midrange = midrange
colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
x_values = [self.vmin, self.midrange[0], self.midrange[1], self.vmax]
y_values = [0, 0.5, 0.5, 1]
return np.ma.masked_array(np.interp(value, x_values, y_values))