Skip to content

Commit 5d62319

Browse files
committed
Toward Mokas 1.0
visuarlBarkh renamed to mokas_stackimages little bugs fixed
1 parent e45fe87 commit 5d62319

12 files changed

+257
-106
lines changed

Diff for: iniConnector.py

+15-13
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,10 @@ def to_list_of_tuple(s):
5959
class IniConnector:
6060
def __init__(self, filepath, Bz):
6161
self.config = configparser.ConfigParser()
62-
self.config.read(filepath)
63-
self.default = self.config['DEFAULT']
64-
self.__parse_iniFile(Bz)
62+
if filepath:
63+
self.config.read(filepath)
64+
self.default = self.config['DEFAULT']
65+
self.__parse_iniFile(Bz)
6566

6667
def __parse_iniFile(self,Bz):
6768
self.imageParameters = {}
@@ -117,11 +118,12 @@ def __parse_iniFile(self,Bz):
117118

118119
class ExperimentalConnector(IniConnector):
119120
def __init__(self, filepath, Bz):
120-
IniConnector.__init__(self, filepath, Bz)
121-
for i,Bx in enumerate(self.Bx_s):
122-
label = "%s %s" % (self.Bz_label, self.Bx_s_labels[i])
123-
section = self.config[label]
124-
self.varsBx[Bx]['pulse_duration'] = to_float(section['pulse_duration'])
121+
if filepath:
122+
IniConnector.__init__(self, filepath, Bz)
123+
for i,Bx in enumerate(self.Bx_s):
124+
label = "%s %s" % (self.Bz_label, self.Bx_s_labels[i])
125+
section = self.config[label]
126+
self.varsBx[Bx]['pulse_duration'] = to_float(section['pulse_duration'])
125127

126128
@property
127129
def Bz_mT(self):
@@ -147,24 +149,24 @@ def Bz_mT(self):
147149
return 0.1 * self.Bz
148150

149151

150-
def connection_factory(filepath, Bz):
152+
def connection_factory(filepath, Bz, isExperiment=True):
151153
basename = os.path.basename(filepath)
152-
if "_sim.ini" in basename:
154+
if "_sim.ini" in basename or not isExperiment:
153155
connector = SimulationConnector
154-
elif "_exp.ini" in basename:
156+
elif "_exp.ini" in basename or isExperiment:
155157
connector = ExperimentalConnector
156158
else:
157159
raise ValueError('File not found, or the ini file does not end with _sim.ini or _exp.ini')
158160
return connector(filepath, Bz)
159161

160-
def connect_to(filepath, Bz):
162+
def connect_to(filepath, Bz,isExperiment=True):
161163
"""
162164
Connect to one of the classes (Connectors)
163165
for experimental or simulation data
164166
"""
165167
factory = None
166168
try:
167-
factory = connection_factory(filepath, Bz)
169+
factory = connection_factory(filepath, Bz, isExperiment)
168170
except ValueError as ve:
169171
print(ve)
170172
return factory

Diff for: mokas_bubbles.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import numpy as np
33
import matplotlib as mpl
44
import matplotlib.pyplot as plt
5-
from visualBarkh import StackImages
5+
from mokas_stackimages import StackImages
66
import mahotas
77
from skimage import measure
88
import getLogDistributions as gLD

Diff for: mokas_colors.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ def get_colors(num_colors, palette='hue', norm=False):
7575
colors = np.random.permutation(colors)
7676
elif palette == 'pastel':
7777
colors = (np.random.randint(0, 256, (num_colors,3)) + white) / 2
78-
#colors = get_cmap(num_colors)
78+
else:
79+
colors = get_cmap(num_colors, palette)
7980
colors = np.vstack((black,colors))
8081
if norm:
8182
colors = colors/255.

Diff for: polar.py renamed to mokas_polar.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,12 @@ def plot_mean_velocity(x,v_mean,v_err,fig=None,ax=None,title=None,label=None,col
103103
#ax.plot(v.columns*180/np.pi,v_mean,'o')
104104
ax.errorbar(to_degree(x),v_mean,v_err,fmt='o',c=color,label=label)
105105
ax.grid(True)
106-
ax.set_xlabel("angle (deg)")
107-
ax.set_xticks(np.arange(-4,5)*45)
108-
ax.set_ylabel("average velocity")
109-
ax.set_title(title)
106+
ax.set_xlabel("angle (deg)", fontsize='xx-small')
107+
ax.set_xticks(np.arange(-2,3)*90)
108+
for tick in ax.xaxis.get_major_ticks():
109+
tick.label.set_fontsize('xx-small')
110+
ax.set_ylabel("average velocity", fontsize='xx-small')
111+
ax.set_title(title, fontsize='xx-small')
110112
return
111113

112114

@@ -160,13 +162,15 @@ def plot_displacement(contours,origin,reference='nucleated_domain',
160162

161163

162164
ax.grid(True)
163-
ax.set_xlabel("angle (deg)")
164-
ax.set_xticks(np.arange(-4,5)*45)
165-
if reference=='nucleated_domain':
166-
ax.set_ylabel("distance from the nucleated domain")
165+
ax.set_xlabel("angle (deg)", fontsize='xx-small')
166+
ax.set_xticks(np.arange(-2,3)*90)
167+
for tick in ax.xaxis.get_major_ticks():
168+
tick.label.set_fontsize('xx-small')
169+
if reference == 'nucleated_domain':
170+
ax.set_ylabel("distance from the nucleated domain", fontsize='xx-small')
167171
else:
168-
ax.set_ylabel("distance from the center")
169-
ax.set_title(title)
172+
ax.set_ylabel("distance from the center", fontsize='xx-small')
173+
ax.set_title(title, fontsize='xx-small')
170174
# return the last contour
171175
# and the n. of frames between the first and the last switches
172176
frames = switches[-1] - switches[1] + 1

Diff for: mokas_run_bubbles.py

+135
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
import sys, os
2+
import glob, re
3+
import pickle
4+
import numpy as np
5+
import matplotlib.pyplot as plt
6+
from natsort import natsorted
7+
import mokas_stackimages as msi
8+
import mokas_bubbles as mkb
9+
from mokas_colors import get_colors
10+
11+
12+
13+
class RunBubbles:
14+
def __init__(self, rootDir, subdir_pattern):
15+
self.rootDir = rootDir
16+
# Get the initial parameters
17+
bubbles_ini = mkb.Bubbles_ini(rootDir)
18+
self.imParameters = bubbles_ini.imParameters
19+
self.experiments = bubbles_ini.experiments
20+
self.thresholds = bubbles_ini.thresholds
21+
try:
22+
erase_small_events_percent = bubbles_ini.erase_small_events_percent
23+
except:
24+
erase_small_events_percent = None
25+
self.erase_small_events_percent = erase_small_events_percent
26+
27+
# Get the directories based on the pattern
28+
sub_dirs = natsorted(glob.glob1(rootDir, subdir_pattern))
29+
sub_dirs = np.array(sub_dirs)
30+
# Prepare to find a match
31+
q = subdir_pattern.replace("*", "(.*)")
32+
all_experiments = [np.int(re.search(q, sd).group(1)) for sd in sub_dirs]
33+
jj = np.array([x in self.experiments for x in all_experiments])
34+
self.sub_dirs = sub_dirs[jj]
35+
#sdirs = [subdir_pattern.replace("*", str(i)) for i in self.experiments]
36+
#self.sub_dirs = [sd for sd in sdirs if sd in sub_dirs]
37+
self.filenames = [d + bubbles_ini.filename_suffix for d in self.sub_dirs]
38+
print("There are %i files to analyse" % len(self.filenames))
39+
if self.experiments is None:
40+
self.n_experiments = len(self.sub_dirs)
41+
self.experiments = range(self.sub_dirs)
42+
else:
43+
self.n_experiments = len(self.experiments)
44+
print(self.filenames[0])
45+
self.full_title = ", ".join(self.filenames[0].split("_")[1:4])
46+
47+
48+
def plot_results(self, plot_contours=True):
49+
"""
50+
Plot the different images for creep in bubbles
51+
"""
52+
# Prepare to plot
53+
plt.close("all")
54+
self.figs = []
55+
self.imArray_collector = {}
56+
# We choose to plot ALL measurements
57+
rows1, cols1 = 1, self.n_experiments
58+
self.fig1, self.axs1 = plt.subplots(rows1, cols1, sharex=True, sharey=True, squeeze=False) # ColorImages
59+
self.figs.append(self.fig1)
60+
self.fig2, self.axs2 = plt.subplots(self.n_experiments, 1, sharey=True, squeeze=False) # Histograms
61+
self.figs.append(self.fig2)
62+
self.fig3, self.axs3 = plt.subplots(cols1, 3*rows1, sharex=True, sharey=True, squeeze=False) # events and clusters
63+
self.figs.append(self.fig3)
64+
#for n in range(self.n_experiments):
65+
#allParameters = self.wireParameters.copy()
66+
67+
for n, experiment in enumerate(self.experiments):
68+
sub_dir = self.sub_dirs[n]
69+
title = str(experiment).rjust(2, "0")
70+
self.imParameters['subDirs'] = [self.rootDir, sub_dir, "", "", ""]
71+
filename = self.filenames[n]
72+
self.imParameters['pattern'] = filename
73+
print("#" * 50)
74+
print("Experiment # %i: %s" % (experiment, filename))
75+
print("The threshold applied is %f" %(self.thresholds[n]))
76+
#imArray = StackImages(**self.imParameters)
77+
#allParameters.update(self.imParameters)
78+
79+
imArray = mkb.Bubbles(**self.imParameters)
80+
if n == 0:
81+
nImages, rows, cols = imArray.shape
82+
pColor = get_colors(nImages, 'pastel', norm=True)
83+
self.imArray_collector[experiment] = imArray
84+
imArray.showColorImage(self.thresholds[n], palette= 'random', #pColor,
85+
plot_contours=True, plotHist=None,
86+
fig=self.fig1, ax=self.axs1[0, n],
87+
title=title, noSwitchColor='black')
88+
imArray.plotHistogram(imArray._switchTimesOverThreshold,
89+
fig=self.fig2, ax=self.axs2[n, 0],
90+
title=title, ylabel=None)
91+
# imArray.find_contours(lines_color='k', remove_bordering=True, plot_centers_of_mass=False,
92+
# invert_y_axis=False, plot_rays=False,
93+
# fig=self.fig3, ax=self.axs3[n], title=title)
94+
#imArray.get_stats_prop()
95+
imArray.getEventsAndClusters(method='edges')
96+
# TO BE FIXED
97+
axs = self.axs3[n,0], self.axs3[n,1], self.axs3[n,2]
98+
imArray.plotEventsAndClustersMaps(fig=self.fig3, axs=axs)
99+
100+
suptitle = " - ".join(self.rootDir.split("/")[-2:])
101+
for fig in self.figs:
102+
fig.suptitle(suptitle, fontsize=30)
103+
plt.show()
104+
105+
106+
107+
def save_hdf5(self):
108+
for experiment in self.imArray_collector:
109+
bubble = self.imArray_collector[experiment]
110+
data = [bubble.cluster2D_start, bubble.cluster2D_end, bubble._switchTimes2D, bubble._switchSteps2D]
111+
labels = ['cluster2D_start', 'cluster2D_end', 'switchTimes2D', 'switchSteps2D']
112+
bubble.hdf5.save_data(data, labels, dtype=np.int16)
113+
# Save histogram
114+
hist = [bubble.N_hist, bubble.bins_hist]
115+
hist_labels = ['N_hist', 'bins_hist']
116+
bubble.hdf5.save_data(hist, hist_labels, dtype=np.float32)
117+
# Save contours
118+
bubble.hdf5.save_data(bubble.contours, 'contours', dtype=np.float32)
119+
# Save waiting time histogram
120+
try:
121+
bubble.hdf5.save_data(bubble.waiting_times_hist, 'waiting_time', dtype=np.int)
122+
except:
123+
pass
124+
125+
126+
127+
def save_figs(self):
128+
res_dir = os.path.join(self.rootDir, 'Results')
129+
if not os.path.isdir(res_dir):
130+
os.mkdir(res_dir)
131+
out_string = "_".join([str(e) for e in self.experiments])
132+
filename = os.path.join(res_dir, "events_and_clusters_exp%s.png" % out_string)
133+
self.fig3.savefig(filename)
134+
135+

Diff for: visualBarkh.py renamed to mokas_stackimages.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import mahotas
2020
#import h5py
2121
import tables
22-
import polar
22+
import mokas_polar as polar
2323
import collect_images
2424
from mokas_colors import get_cmap, getKoreanColors, getPalette
2525
import mokas_gpu as mkGpu
@@ -788,11 +788,16 @@ def _plotColorImage(self, data, colorMap, fig=None, ax=None, title=None, figsize
788788
#ax.pcolormesh(data,cmap=colorMap,norm=self.norm)
789789
ax.imshow(data, cmap=colorMap, norm=self.norm)
790790
ax.axis(extent)
791+
for tick in ax.xaxis.get_major_ticks():
792+
tick.label.set_fontsize('xx-small')
793+
for tick in ax.yaxis.get_major_ticks():
794+
tick.label.set_fontsize('xx-small')
795+
791796
if title is None:
792797
first, last = self.imagesRange
793798
#title = "DW motion from image %i to image %i" % (first, last)
794799
title = self.pattern
795-
ax.title.set_text(title)
800+
ax.set_title(title, fontsize='xx-small')
796801
cid = fig.canvas.mpl_connect('button_press_event', self._call_pixel_time_sequence)
797802
return fig
798803

@@ -815,11 +820,11 @@ def plotHistogram(self, data, fig=None, ax=None, title=None, ylabel=None):
815820
ax = plt.gca()
816821
self.N_hist, self.bins_hist, patches = ax.hist(data, rng)
817822
ax.format_coord = lambda x,y : "image Number: %i, avalanche size (pixels): %i" % (int(x+0.5), int(y+0.5))
818-
ax.set_xlabel("image number")
823+
ax.set_xlabel("image number",fontsize='xx-small')
819824
if title:
820-
ax.set_title(title)
825+
ax.set_title(title, fontsize='xx-small')
821826
if ylabel:
822-
ax.set_ylabel(ylabel)
827+
ax.set_ylabel(ylabel, fontsize='xx-small')
823828
ax.set_xlim(0, ax.get_xlim()[1])
824829
# Set the colors
825830
for thisfrac, thispatch in zip(central_points, patches):

Diff for: mokas_wires.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import configparser
44
import numpy as np
55
import matplotlib.pyplot as plt
6-
from visualBarkh import StackImages
6+
from mokas_stackimages import StackImages
77
import mahotas
88
import skimage.morphology as morph
99
import skimage.feature as feature

0 commit comments

Comments
 (0)