Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9acb5e3

Browse files
committed
restructure, moved image_analysis to project dir
1 parent b6c5a59 commit 9acb5e3

File tree

13 files changed

+1560
-1216
lines changed

13 files changed

+1560
-1216
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ worm_algorithm/bonds_broken.py
1010
worm_algorithm/image_analysis/yannick/*
1111
worm_algorithm/simulation.py
1212
worm_algorithm/utils/*
13+
image_analysis/data/*
14+
image_analysis/yannick/*
15+
image_analysis/__init__.py
1316

1417
*.pyc
1518
*.tex
File renamed without changes.

image_analysis/image_analysis.ipynb

Lines changed: 1370 additions & 0 deletions
Large diffs are not rendered by default.
File renamed without changes.
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import numpy as np
2+
from utils.utils import *
3+
4+
class CountBonds(object):
5+
"""Class to obtain statistics about the average number of bonds <Nb> and
6+
the variance in the average number of bonds, <Nb^2> - <Nb>^2
7+
8+
Args:
9+
image_set (array-like):
10+
Array of images for which <Nb> and <Delta_{N_b}^2> are calculated
11+
and averaged over.
12+
num_blocks (int, default=20):
13+
Number of blocks to be used for block resampling for bootstrap
14+
error analysis.
15+
save (bool, default=False):
16+
Whether or not to save the resulting bond_statistics data.
17+
verbose (bool, default=False):
18+
Whether or not to display information as the analysis is being
19+
performed.
20+
"""
21+
def __init__(self, image_set, num_blocks=20, save=False,
22+
verbose=False):
23+
# if len(image_set.shape) == 1:
24+
# self.reshape_image_set()
25+
self._image_set = image_set
26+
self._num_images, self._Lx, self._Ly = self._image_set.shape
27+
#self._block_val = block_val
28+
self._num_blocks = num_blocks
29+
self._verbose = verbose
30+
# self.bond_stats = None
31+
# if block_val is None:
32+
# self._wx = 2 * self._Lx
33+
# self._wy = 2 * self._Ly
34+
35+
@staticmethod
36+
def reshape_image_set(image_set):
37+
"""Method for reshaping images into a 2D array of pixels, if initally
38+
provided as flattened array."""
39+
pass
40+
41+
def _count_bonds(self, image):
42+
""" Count bonds on single image, and return Nb. """
43+
if image.shape != (self._Lx, self._Ly):
44+
try:
45+
image = image.reshape(self._Lx, self._Ly)
46+
except ValueError:
47+
raise "Unable to properly reshape image."
48+
bond_idxs = [(i, j) for i in range(self._Lx) for j in range(self._Ly)
49+
if (i + j) % 2 == 1]
50+
Nb = np.sum([image[i] for i in bond_idxs])
51+
return Nb
52+
53+
def _calc_averages(self, data_set=None):
54+
"""Calculate <Nb> and <Delta_{Nb}^2> by running _count_bonds method on
55+
each image in self._image_set."""
56+
if data_set is None:
57+
data_set = self._image_set
58+
Nb_arr = np.array([self._count_bonds(image)
59+
for image in data_set])
60+
Nb2_arr = Nb_arr ** 2
61+
Nb_avg = np.mean(Nb_arr)
62+
Nb2_avg = np.mean(Nb2_arr)
63+
Nb_avg2 = Nb_avg ** 2
64+
delta_Nb2 = Nb2_avg - Nb_avg2
65+
return Nb_avg, delta_Nb2
66+
67+
def _count_bonds_with_err(self):
68+
"""Calculate the average number of active bonds (Nb) for the boundary
69+
images using the previously defined methods."""
70+
bond_stats = self._calc_averages()
71+
data_rs = block_resampling(self._image_set, self._num_blocks)
72+
bond_stats_rs = []
73+
err = []
74+
75+
for block in data_rs:
76+
bond_stats_rs.append(self._calc_averages(block))
77+
bond_stats_rs = np.array(bond_stats_rs)
78+
for idx in range(len(bond_stats)):
79+
_err = jackknife_err(y_i=bond_stats_rs[:, idx],
80+
y_full = bond_stats[idx],
81+
num_blocks=self._num_blocks)
82+
err.append(_err)
83+
return bond_stats, err
84+
85+
def count_bonds(self):
86+
"""Calculate bond statistics for entirety of self._image set data,
87+
including error analysis."""
88+
val, err = self._count_bonds_with_err()
89+
bond_stats = np.array([val[0], err[0], val[1], err[1]])
90+
#bond_stats.append(np.array([val[0], err[0], val[1], err[1]]))
91+
return bond_stats
92+
93+
94+
95+
96+
97+
98+
99+
100+
101+
# def count_bonds(image_set):
102+
# """Method for counting 'bonds' in a set of worm-type images."""
103+
# w = image_set[0].shape[0]
104+
# bond_idxs = [(i, j) for i in range(w)
105+
# for j in range(w)
106+
# if (i + j) % 2 == 1]
107+
# bc_arr = np.array([np.sum([image[i] for i in bond_idxs])
108+
# for image in image_set])
109+
# bc2_arr = bc_arr ** 2
110+
# Nb_avg = np.mean(bc_arr)
111+
# Nb2_avg = np.mean(bc2_arr)
112+
# Nb_avg2 = Nb_avg ** 2
113+
# delta_Nb = Nb2_avg - Nb_avg2
114+
# return Nb_avg, delta_Nb
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
4+
def errorbar_plot(values, labels, out_file, limits=None, Tc_line=None,
5+
legend_loc=None, markersize=5, num_graphs=None,
6+
reverse_colors=False):
7+
markers = ['s', 'H', 'd', 'v', 'p', 'P']
8+
colors = ['#2A9Df8', '#FF920B', '#65e41d', '#be67ff', '#ff7e79', '#959595']
9+
markeredgecolors = ['#0256a3', '#ed4c18', '#00B000', '#6633cc',
10+
'#ee2324','#1c2022']
11+
x_values = values['x']
12+
y_values = values['y']
13+
assert x_values.shape == y_values.shape, ('x and y data have different'
14+
+ ' shapes.')
15+
fig_labels = labels['fig_labels']
16+
x_label = labels['x_label']
17+
y_label = labels['y_label']
18+
if legend_loc is None:
19+
legend_loc = 'best'
20+
if num_graphs is None:
21+
num_graphs = len(fig_labels)
22+
else:
23+
num_graphs = num_graphs
24+
try:
25+
y_err = values['y_err']
26+
except KeyError:
27+
# y_err = num_graphs*[np.zeros(y_values.shape)]
28+
y_err = num_graphs*[0]
29+
x_lim = limits.get('x_lim')
30+
y_lim = limits.get('y_lim')
31+
if reverse_colors:
32+
colors = colors[:num_graphs][::-1]
33+
markeredgecolors = markeredgecolors[:num_graphs][::-1]
34+
markers = markers[:num_graphs][::-1]
35+
36+
fig, ax = plt.subplots()
37+
if Tc_line is not None:
38+
ax.axvline(x=Tc_line, linestyle='--', color='k')
39+
for i in range(num_graphs):
40+
try:
41+
ax.errorbar(x_values[i], y_values[i], yerr=y_err[i],
42+
label=fig_labels[i], marker=markers[i],
43+
markersize=markersize, fillstyle='full',
44+
color=colors[i], markeredgecolor=markeredgecolors[i],
45+
ls='-', lw=2., elinewidth=2., capsize=2., capthick=2.)
46+
except ValueError:
47+
ax.errorbar(x_values, y_values, yerr=y_err,
48+
label=fig_labels, marker=markers,
49+
markersize=markersize, fillstyle='full',
50+
color=colors[0], markeredgecolor=markeredgecolors[0],
51+
ls='-', lw=2., elinewidth=2., capsize=2., capthick=2.)
52+
53+
# continue
54+
# import pdb
55+
# pdb.set_trace()
56+
leg = ax.legend(loc=legend_loc, markerscale=1.5, fontsize=14)
57+
ax.set_xlabel(x_label, fontsize=16)
58+
ax.set_ylabel(y_label, fontsize=16)
59+
if x_lim is not None:
60+
ax.set_xlim(x_lim[0], x_lim[1])
61+
if y_lim is not None:
62+
ax.set_ylim(y_lim[0], y_lim[1])
63+
64+
fig.tight_layout()
65+
print(f"Saving file to: {out_file}")
66+
fig.savefig(out_file, dpi=400, bbox_inches='tight')
67+
return fig, ax
68+

worm_algorithm/image_analysis/utils/utils.py renamed to image_analysis/utils/utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import numpy as np
3+
from sklearn.model_selection import KFold
34
from scipy.misc import toimage
45

56
def unpickle(file):
@@ -48,7 +49,7 @@ def block_resampling(data, num_blocks):
4849
if num_blocks < 1:
4950
raise ValueError("Number of resampled blocks must be greater than or"
5051
"equal to 1")
51-
kf = KFold(n_splits == num_blocks)
52+
kf = KFold(n_splits = num_blocks)
5253
resampled_data = []
5354
for i, j in kf.split(data):
5455
resampled_data.append(data[i])

0 commit comments

Comments
 (0)