-
Notifications
You must be signed in to change notification settings - Fork 0
/
GU_analyze.py
1919 lines (1556 loc) · 67.2 KB
/
GU_analyze.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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# import the Stimfit input/output module:
import stfio
import numpy as np
import matplotlib.pyplot as plt
# For patches/fields in figures
from matplotlib.patches import Rectangle, Circle
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
# For saving the list of dicts produced by plt_cGlu_pos
from pickle import dump, load
import csv
from scipy.interpolate import UnivariateSpline
from scipy.stats import linregress
from os import listdir
from os.path import expanduser
from spectral import rmlines, clip_lines
from scipy.ndimage.interpolation import rotate, shift, zoom
from numpy.linalg import norm
def read_cGlu_log(filename):
"""
Reads log files from the caged glutamate experiment.
For example 20111205_180824cGlu.txt
File contents are returned in a dict with keys corresponding to column
headers in the log file.
Hjalmar Turesson, 11-12-12, mod 12-02-09
"""
f = open(filename , 'r')
data = {}
data['notes'] = f.readline().strip()
data['date'] = f.readline().strip()
f.readline()
data['data_filename'] = f.readline().replace("Data_filename:","").strip()
data['photo_stim_duration'] = int(f.readline().replace("Photo_stm_duration:","").replace("ms","").strip())
f.readline()
headers = f.readline().strip().split(',')
n_heads = len(headers)
for head in headers:
data[head] = []
for line in f:
fields = line.strip().split(',', n_heads - 1)
for i, number in enumerate( fields ):
data[headers[i]].append(eval(number))
return data
def __flip_x_slice(slice_photo, transforms):
# NOTE: find a faster way of flipping
transforms.append({'type': 'flip_x', 'x': 0.0,
'y': 0.0, 'angle': 0.0})
return slice_photo[:,-1::-1,:], transforms
def __shift_slice(slice_photo, transforms):
print(' Click 1st on a point in the slice and then on\n ' +
'the corresponding point in the template.\n')
shift_xy = np.array(plt.ginput(n=2))
shift_xy = np.diff(shift_xy, axis=0)
shift_x = shift_xy[0][0]
shift_y = shift_xy[0][1]
slice_photo = shift(slice_photo, [shift_y, shift_x, 0.0],
mode='constant', cval=0.5)
transforms.append({'type': 'shift', 'x': shift_x,
'y': shift_y, 'angle': 0.0})
return slice_photo, transforms
def __zoom_slice(slice_photo, axis, transforms):
zoom_x, zoom_y = 1.0, 1.0
if axis.upper() == 'X' or axis.upper() == 'B':
print(' Click 1st on 2 points along x in the slice and then on' +
' \n corresponding points in the template.\n')
zoom_x = np.array(plt.ginput(n=4))
zoom_x = np.diff(zoom_x[:,0])
zoom_x = zoom_x[-1]/zoom_x[0]
if axis.upper() == 'Y' or axis.upper() == 'B':
print(' Click 1st on 2 points along y in the slice and then on' +
' \n corresponding points in the template.\n')
zoom_y = np.array(plt.ginput(n=4))
zoom_y = np.diff(zoom_y[:,1])
zoom_y = zoom_y[-1]/zoom_y[0]
slice_photo = zoom(slice_photo, [zoom_y, zoom_x, 1.0],
mode='constant', cval = 0.5)
transforms.append({'type': 'zoom',
'x': zoom_x,
'y': zoom_y,
'angle': 0.0 })
return slice_photo, transforms
def __reshape_slice_photo(old_sz, slice_photo):
"""
"""
old_sz_y, old_sz_x, old_sz_z = old_sz
new_sz_y, new_sz_x = slice_photo.shape[:2]
dsz_x = new_sz_x - old_sz_x
dsz_y = new_sz_y - old_sz_y
offset_x = abs(dsz_x / 2)
offset_y = abs(dsz_y / 2)
if (dsz_x <= 0) and (dsz_y <= 0):
reshaped_sp = np.ones((old_sz_y, old_sz_x, old_sz_z)) * 0.5
reshaped_sp[offset_y : offset_y + new_sz_y,
offset_x : offset_x + new_sz_x, :] = slice_photo
elif (dsz_x > 0) and (dsz_y > 0):
reshaped_sp = slice_photo[offset_y : offset_y + old_sz_y,
offset_x : offset_x + old_sz_x, :]
elif (dsz_x <= 0) and (dsz_y > 0):
reshaped_sp = np.ones((old_sz_y, old_sz_x, old_sz_z)) * 0.5
reshaped_sp[:, offset_x : offset_x + new_sz_x, :] = \
slice_photo[offset_y : offset_y + old_sz_y, :, :]
elif (dsz_x > 0) and (dsz_y <= 0):
reshaped_sp = np.ones((old_sz_y, old_sz_x, old_sz_z)) * 0.5
reshaped_sp[offset_y : offset_y + new_sz_y, :, :] = \
slice_photo[:, offset_x : offset_x + old_sz_x, :]
return reshaped_sp
def __rotate_slice(slice_photo, transforms):
s = raw_input(' Degrees to rotate (+- 180, or 0 - 360)?\n')
alpha = float(s)
slice_photo = rotate(slice_photo, -alpha, reshape=True,
mode='constant', cval=0.5)
transforms.append({'type': 'rotation', 'x': 0.0,
'y': 0.0, 'angle': alpha})
return slice_photo, transforms
def transform_xy(xy, transforms):
"""
Parameters
----------
xy - A numpy array/ndarray of xy postions w. x in the 1st column
and y in the 2nd.
transforms - A recarray of transforms w. following fields:
'angle', 'type', 'x' & 'y'
Returns
-------
xy - A numpy array/ndarray of transformed xy postions
w. x in the 1st column and y in the 2nd.
"""
if (type(xy) is tuple) or (type(xy) is list):
xy = np.array(xy)
for trf in transforms:
if trf[1]:
xy = __update_xy(xy, trf)
if xy[0] == 0 and xy[1] == 0: import pdb;pdb.set_trace()
return xy
def __update_xy(previous_xy, transform):
"""
"""
if transform['type'] == 'flip_x':
curr_x = - previous_xy[0]
curr_y = previous_xy[1]
elif transform['type'] == 'shift':
curr_x = previous_xy[0] + transform['x']
curr_y = previous_xy[1] + transform['y']
elif transform['type'] == 'zoom':
curr_x = previous_xy[0] * transform['x']
curr_y = previous_xy[1] * transform['y']
elif transform['type'] == 'rotation':
curr_alpha = transform['angle']
d = norm(previous_xy)
previous_alpha = np.angle(previous_xy[0] + 1j * previous_xy[1])
curr_x = d * np.cos(np.deg2rad(curr_alpha) + previous_alpha)
curr_y = d * np.sin(np.deg2rad(curr_alpha) + previous_alpha)
else:
return 0
return np.array([curr_x, curr_y])
def __update_xy_list(start_xy, transforms):
previous_xy = start_xy
if transforms:
for transform in transforms:
curr_xy = __update_xy(previous_xy, transform)
previous_xy = curr_xy
else:
curr_xy = start_xy
return curr_xy
def __undo_last_trans(slice_photo, transforms):
utrans = transforms[-1]
if utrans['type'] == 'flip_x':
slice_photo = slice_photo[:,-1::-1,:]
elif utrans['type'] == 'shift':
shift_xyz = [ -utrans['y'],-utrans['x'], 0.0 ]
slice_photo = shift(slice_photo, shift_xyz, mode='constant', cval=0.5)
elif utrans['type'] == 'zoom':
zoom_yxz = [ 1.0 / utrans['y'], 1.0 / utrans['x'], 1.0 ]
slice_photo = zoom(slice_photo, zoom_yxz, mode='constant', cval=0.5)
elif utrans['type'] == 'rotation':
slice_photo = rotate(slice_photo, utrans['angle'],
reshape=False, mode='constant', cval=0.5)
if len(transforms) == 1:
transforms = []
else:
transforms.pop()
return slice_photo, transforms
def __draw_template(ax, xlim, ylim, template_fn, template_obj=None):
"""
"""
# Show template fig on top of slice photo
if template_obj:
selections = ''
for ix, tmp in enumerate(template_fn):
selections += (' ' + tmp.split('/')[-1] +
':\t' + str(ix) + '\n')
s = raw_input(' Select template file:\n' + selections)
if s.isdigit() and (int(s) < len(template_fn)):
# Load selected template fig
selected_template_fn = template_fn[int(s)]
template = plt.imread(selected_template_fn)
template = template[-1::-1,:,:] # Flip y-axis
template_obj.set_data(template)
else:
# NOTE Try recursive
# It should let the user try to select again, if he/she messed up.
__draw_template(ax, xlim, ylim, template_fn, template_obj)
else:
# Default template fig is 1st in list
selected_template_fn = template_fn[0]
template = plt.imread(selected_template_fn)
template = template[-1::-1,:,:] # Flip y-axis
template_obj = ax.imshow(template, origin = 'lower')
template_obj.set_extent((xlim[0], xlim[1], ylim[0], ylim[1]))
plt.draw()
return template_obj, selected_template_fn
def match_slice_to_template(slice_photo_fn, log_fn=None, fig=None):
# Whats left:
# TEST!!!
debug = False
tmpl_dir = expanduser('~') + '/Pictures/BST_templates'
template_fn = [tmpl_dir + '/BST_Fig35_Pare.png',
tmpl_dir + '/BST_Fig33_Pare.png',
tmpl_dir + '/BST_Fig34_Pare.png',
tmpl_dir + '/BST_Fig32_Pare.png']
# Load slice photo
slice_photo = plt.imread(slice_photo_fn)
# Flip y-axis
# arrays are counted from top to bottom, but in the fig we want to count
# from bottom to top
slice_photo = slice_photo[-1::-1,:,:]
if not fig:
# Draw slice figure, and get its original size
fig = plt.figure()
ax = fig.add_subplot(111)
sp_obj = ax.imshow(slice_photo, origin='lower')
original_slice_sz = slice_photo.shape
# Center figure. Find center pixel and place origo there
xlim = ax.get_xlim()
xlim -= np.diff(xlim) / 2.0
ylim = ax.get_ylim()
ylim -= abs(np.diff(ylim)) / 2.0
sp_obj.set_extent((xlim[0], xlim[1], ylim[0], ylim[1]))
# Get conversion from physical distance to pixels
# from scalebar in slice_photos
ax.axis([-345,-305+100,-50,80])
plt.draw()
print 'Click on the top and the bottom of the scalebar.\n'
sclbar_xy = plt.ginput(n=2)
ax.axis((xlim[0], xlim[1], ylim[0], ylim[1]))
sclbar_x_px = (sclbar_xy[0][0] + sclbar_xy[1][0])/2.0
sclbar_y_px = np.array([sclbar_xy[0][1], sclbar_xy[1][1]])
sclbar_len_px = abs(np.diff(sclbar_y_px))[0]
# Assumes scale bar length 500 microns
um_to_px = sclbar_len_px / 500.0
# Plot scalebar
ax.plot([sclbar_x_px-5, sclbar_x_px+5],
[sclbar_y_px.min(), sclbar_y_px.min()], '-r')
ax.plot([sclbar_x_px-5, sclbar_x_px+5],
[sclbar_y_px.min() + sclbar_len_px,
sclbar_y_px.min() + sclbar_len_px], '-r')
ax.plot([sclbar_x_px, sclbar_x_px],
[sclbar_y_px.min(), sclbar_y_px.min() + sclbar_len_px], '-r', lw=2)
ax.set_title(slice_photo_fn.split('/')[-1].split('.')[0])
# Get pippette tip/cell location, stimulation sites will be drawn relative
# to this
print ' Click on pipette tip/cell.\n'
cell_xy = np.array(plt.ginput(n=1, timeout=60))[0]
print cell_xy
cell_xy_raw = cell_xy.copy()
if debug:
ax.plot([cell_xy[0]-5, cell_xy[0]+5],
[cell_xy[1]-5,cell_xy[1]+5], '-w')
ax.plot([cell_xy[0]-5, cell_xy[0]+5],
[cell_xy[1]+5,cell_xy[1]-5], '-w')
ax.plot([cell_xy[0], 0], [cell_xy[1], 0],'-g')
ax.set_xlim(xlim)
ax.set_ylim(ylim)
# Draw template_fn[0] as a default
template_obj, selected_template_fn = __draw_template(ax, xlim, ylim, template_fn)
# Initialize list to record transforms
transforms = []
s = ''
s = raw_input( ' Select transformation\n' +
' ---------------------\n' +
' Flip slice along x-axis:\tf\n' +
' Shift along x and y axes:\ts\n' +
' Zoom x-axis:\t\t\tzx\n' +
' Zoom y-axis:\t\t\tzy\n' +
' Rotate around center:\t\tr\n' +
' Change template:\t\tt\n' +
' Undo last action:\t\tu\n' +
' Quit:\t\t\t\tq\n')
while s.lower() != 'q':
trans = True
if s.lower() == 'f':
# Flip slice photo to right hemisphere.
slice_photo, transforms = __flip_x_slice(slice_photo, transforms)
elif s.lower() == 's':
# Shift slice photo in x and y to be approximately aligned on top of
# slice photo.
slice_photo, transforms = __shift_slice(slice_photo, transforms)
elif s.lower() == 'zx':
# Scale/zoom template fig in x to be of approximately of the same
# size as the BNTS in slice photo.
slice_photo, transforms = __zoom_slice(slice_photo,
'x', transforms)
elif s.lower() == 'zy':
# Scale/zoom template fig in y to be of approximately of the same
# size as the BNTS in slice photo.
slice_photo, transforms = __zoom_slice(slice_photo,
'y', transforms)
elif s.lower() == 'r':
# Rotate template fig to fig slice photo.
slice_photo, transfroms = __rotate_slice(slice_photo, transforms)
elif s.lower() == 't':
# Change template
template_obj, selected_template_fn = __draw_template(ax,
xlim,
ylim,
template_fn,
template_obj)
trans = False
elif s.lower() == 'u':
# Undo last action/transform
slice_photo, transforms = __undo_last_trans(slice_photo,
transforms)
else:
trans = False
if trans:
# Refresh slice fig, but show only the original number of pixels
reshaped_sp = __reshape_slice_photo(original_slice_sz, slice_photo)
sp_obj.set_data(reshaped_sp)
plt.draw()
s = raw_input('\n flip [f], shift [s], zoom_x [zx],' +
' zoom_y [zy], rotate [r], template [t],' +
' undo [u], quit [q]\n')
if log_fn:
stm_xy = __draw_scan_grid(ax, log_fn, transforms, um_to_px, cell_xy)[0]
cell_xy = __update_xy_list(cell_xy, transforms)
# Mark the location of recorded cell
ax.plot([cell_xy[0] - 5, cell_xy[0]+5],
[cell_xy[1]-5, cell_xy[1]+5], '-w', lw=2)
ax.plot([cell_xy[0] - 5, cell_xy[0]+5],
[cell_xy[1]+5, cell_xy[1]-5], '-w', lw=2)
if debug:
ax.plot([0, cell_xy[0]], [0, cell_xy[1]], '-g')
ax.axis((xlim[0], xlim[1], ylim[0], ylim[1]))
plt.draw()
if not transforms:
reshaped_sp = slice_photo
if log_fn:
return stm_xy, cell_xy, cell_xy_raw, transforms, \
selected_template_fn, um_to_px, fig, reshaped_sp
else:
return cell_xy, cell_xy_raw, transforms, \
selected_template_fn, um_to_px, fig, reshaped_sp
def __draw_scan_grid(ax,
filename,
transforms,
um_to_px,
cell_xy,
response_xy=None,
num_on=True,
path_on=True,
circ_on=False):
#NOTE: Fix scaling of illum circles, so that they match template
# radius of illuminated spot in micrometer scaled to px
illum_radius = 100.0 * um_to_px
data = read_cGlu_log(filename)
# convert from microns to pixel dist.
stm_x = np.array(data['position_x']) * um_to_px
# The minus sign below is needed because "up" in the slice picture, and
# thus up in the figure, is towards the wall in the recording rig, and
# towards the wall is negative y-steps when controllig the stepper motors
# from tmca_experiment.py.
stm_y = - np.array(data['position_y']) * um_to_px
# Places the scan grids zero pos at cell_xy
stm_x += cell_xy[0]; stm_y += cell_xy[1]
# Transform stimulation coordinates to match template
stm_xy = np.c_[stm_x, stm_y]
for ix, xy in enumerate(stm_xy):
stm_xy[ix] = __update_xy_list(xy, transforms)
# Plot stimulation positions
path_n = len(stm_xy) - 1
for ix, xy in enumerate(stm_xy):
if path_on and ix < path_n:
ax.plot([xy[0], stm_xy[ix+1,0]], [xy[1], stm_xy[ix+1,1]], c='k')
if circ_on:
# Create and draw a circle showing photo stimulation area
circ = Circle((xy[0], xy[1]), illum_radius, ec='r', fill=False)
ax.add_patch(circ)
if num_on:
ax.text(xy[0], xy[1], str(ix+1))
# If response coordinates are supplied
# Scale, shift, transform and then plot them
if response_xy:
# convert from microns to pixel dist.
response_xy[:,0] *= um_to_px
response_xy[:,1] *= -um_to_px # See above for the magic minus
# Places the scan grids zero pos at cell_xy
response_xy[:,0] += cell_xy[0]
response_xy[:1] += cell_xy[1]
for ix, xy in enumerate(response_xy):
xy = __update_xy_list(xy, transforms)
response_xy[ix] = xy
# Create and draw a circle showing photo stimulation area
circ = Circle(xy[0], xy[1], illum_radius, ec='none', fc=[1,0,0])
ax.add_patch(circ)
else: response_xy = np.empty(0)
return stm_xy, response_xy
def fill_cell_position(cell_xy, ar, xlim, ylim, um_to_px,
fill_value=1, radius=50.0):
dxy = [np.diff(xlim)/ar.shape[1], np.diff(ylim)/ar.shape[0]]
x_index = np.arange(xlim[0], xlim[1], dxy[0], dtype = int)
y_index = np.arange(ylim[0], ylim[1], dxy[1], dtype = int)
spot_x, spot_y = __get_template_spot(radius, dxy, um_to_px)
sp_x = spot_x + int(round(cell_xy[0]))
sp_y = spot_y + int(round(cell_xy[1]))
sp_bool_x = np.logical_and(sp_x >= min(x_index), sp_x <= max(x_index))
sp_bool_y = np.logical_and(sp_y >= min(y_index), sp_y <= max(y_index))
sp_x = sp_x[np.logical_and(sp_bool_x, sp_bool_y)]
sp_y = sp_y[np.logical_and(sp_bool_x, sp_bool_y)]
x = x_index[sp_x]
y = y_index[sp_y]
ar[y,x] = fill_value
return ar
def fill_positions_fancy(pos_xy, ar, xlim, ylim, radius=150.0):
smooth_factor = 15.0 #
min_radius, max_radius = radius - smooth_factor, radius + smooth_factor
radii = np.linspace(min_radius, max_radius, 15, endpoint=False)
fill_values = np.cos(np.linspace(0,np.pi,15, endpoint=False)) + 1.0
fill_values /= fill_values.sum()
for ix, r in enumerate(radii):
fill_positions(pos_xy, ar, xlim, ylim,
fill_value=fill_values[ix], radius=r)
def fill_positions(pos_xy, ar, xlim, ylim, fill_value=1.0, radius=150.0):
"""
"""
nrow, ncol = ar.shape
if pos_xy.ndim == 1: pos_xy = pos_xy.reshape(1, 2)
n = pos_xy.shape[0]
y, x = np.ogrid[-radius: radius, -radius: radius]
index = x**2 + y**2 <= radius**2
k_x = np.float(ncol) / abs(np.diff(xlim))
k_y = np.float(nrow) / abs(np.diff(ylim))
m_x, m_y = - xlim[0], - ylim[1]
posxy = pos_xy.copy()
posxy[:,0] = (pos_xy[:,0] + m_x) * k_x
posxy[:,1] = - (pos_xy[:,1] + m_y) * k_y
X0 = (posxy[:,0] - radius).round()
X1 = (posxy[:,0] + radius).round()
Y0 = (posxy[:,1] - radius).round()
Y1 = (posxy[:,1] + radius).round()
rm_bix_x = np.logical_and((X1 > 0), (X0 < ncol))
rm_bix_y = np.logical_and(((Y1 > 0)), (Y0 < nrow))
rm_bix = np.logical_and(rm_bix_x,rm_bix_y)
X0, X1 = X0[rm_bix], X1[rm_bix]
Y0, Y1 = Y0[rm_bix], Y1[rm_bix]
n = X0.shape[0]
for ix in range(n):
y_ix = np.arange(Y0[ix],Y1[ix])
x_ix = np.arange(X0[ix],X1[ix])
y_bix = (y_ix >= 0) & (y_ix < nrow)
x_bix = (x_ix >= 0) & (x_ix < ncol)
x0, x1 = x_ix[x_bix][0],x_ix[x_bix][-1]+1
y0, y1 = y_ix[y_bix][0],y_ix[y_bix][-1]+1
ar[y0:y1,x0:x1][index[y_bix,:][:,x_bix]] += fill_value
def __get_template_spot(radius, dxy, um_to_px, npts=256):
# illum_radius = 150.0
circ_x = np.sin(np.linspace(-np.pi,np.pi, npts)) * radius * um_to_px
circ_y = np.cos(np.linspace(-np.pi,np.pi, npts)) * radius * um_to_px
x_index = np.arange(min(circ_x)-1.0, max(circ_x)+1.0, dxy[0], dtype=int)
spot_x, spot_y = np.array([], dtype=int), np.array([], dtype=int)
# first left side
for ix, circy in enumerate(circ_y[0:npts/2]):
tmp_x = x_index[np.logical_and(x_index >= circ_x[ix], x_index < 0.0)]
tmp_y = np.zeros(tmp_x.shape, dtype=int) + int(circy)
spot_x = np.r_[spot_x, tmp_x]
spot_y = np.r_[spot_y, tmp_y]
spot_x = np.r_[spot_x, -spot_x]
spot_y = np.r_[spot_y, spot_y]
# the two right quadrants
# midlines
spot_x = np.r_[spot_x, np.zeros(len(np.unique(spot_y)), dtype=int)]
spot_y = np.r_[spot_y, np.unique(spot_y)]
spot_x = np.r_[spot_x, np.unique(spot_x)]
spot_y = np.r_[spot_y, np.zeros(len(np.unique(spot_x)), dtype=int)]
return spot_x, spot_y
def plot_cGlu_scan_grid(filename, response_pos=None, grid_on=True, num_on=True,
path_on=False, sb_on=True, box_on=True, naked=False):
"""
Plots a grid representing the scanned area, with circles at the stimulated
positions.
Parameters
----------
filename : filename and path to a cGlu log file.
E.g. '/home/hjalmar/Data/111205_1/20111205_150456cGlu.txt'
response_pos : A list or tuple of lists, arrays or tuples of x & y
positions where photo stimulation resulted in responses
(PSPs). Optional.
grid_on : Whether or not to draw the scan grid.
num_on : Add position numbers to the circles, so as to show in which
order the positions where stimulated.
path_on : Whether or not to draw the scan path.
sb_on : Scalebar on/off. Plots 500 micrometer horizontal and vertical
scalebars.
box_on : Whether or not to plot x and y axes and a frame around the grid.
Hjalmar Turesson, 11-12-12
"""
# radius of illuminated spot in micrometer
illum_radius = 75
# length in micrometer of plotted scalebar
sblen = 500
data = read_cGlu_log(filename)
if naked:
grid_on = False
path_on = False
box_on = True
sb_on = True
xpos = data['position_x']
ypos = data['position_y']
x_uniq = np.unique(xpos)
y_uniq = - np.unique(ypos)
x_step = abs(x_uniq[x_uniq != 0]).min()
y_step = abs(y_uniq[y_uniq != 0]).min()
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
if grid_on:
xlim = [x_uniq.min(), x_uniq.max()]
ylim = [y_uniq.min(), y_uniq.max()]
X = np.c_[x_uniq,x_uniq].T
Y = np.c_[y_uniq,y_uniq].T
XLIM = np.tile(xlim,(Y.shape[1],1)).T
YLIM = np.tile(ylim,(X.shape[1],1)).T
ax.plot(X, YLIM, color='k')
ax.plot(XLIM, Y, color='k')
if path_on:
for i in range(len(xpos) - 1):
ax.plot([xpos[i], xpos[i+1]], [-ypos[i], -ypos[i+1]], color='k')
if len(xpos) == len(ypos):
for ix in range(len(xpos)):
# Create and draw a circle showing photo stimulation area
circ = Circle((xpos[ix],-ypos[ix]), illum_radius,
ec=[1, 0, 0], fc='none')
ax.add_patch(circ)
if num_on:
ax.text(xpos[ix], - ypos[ix], str(ix+1))
else:
raise ValueError('Something funny with the log file')
if response_pos:
xrespos = response_pos[0]
yrespos = response_pos[1]
for ix in range(len(xrespos)):
# Create and draw a circle showing photo stimulation area
circ = Circle((xrespos[ix],-yrespos[ix]),illum_radius,
edgecolor = None, facecolor = [1, 0, 0])
ax.add_patch(circ)
if sb_on:
# draw scalebar
sb_pos_x = x_uniq.min() - x_step * 0.95
sb_pos_y = y_uniq.min() - y_step * 0.95
ax.plot([sb_pos_x, sb_pos_x], [sb_pos_y, sb_pos_y+sblen],
'b', linewidth=2)
ax.plot([sb_pos_x, sb_pos_x + sblen], [sb_pos_y, sb_pos_y],
'b', linewidth=2)
ax.text(sb_pos_x + x_step * 0.1, sb_pos_y + y_step * 0.1,
str(sblen) + '$\mu m$')
if not box_on:
# remove box around plot
ax.set_frame_on(True)
# drop axes
for loc, spine in ax.spines.iteritems():
if loc in ['left','bottom']:
spine.set_position(('outward',10)) # outward by 10 points
elif loc in ['right','top']:
spine.set_color('none') # don't draw spine
else:
raise ValueError('unknown spine location: %s'%loc)
# turn off ticks where there is no spine
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Maybe remove some more stuff to really clean up the figure.
ax.set_xticks(x_uniq)
ax.set_yticks(y_uniq)
ax.set_yticklabels(- y_uniq)
ax.set_xlabel(r'x distance ($\mu m$)')
ax.set_ylabel(r'y distance ($\mu m$)')
if naked:
ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel('')
ax.set_ylabel('')
plt.show()
return ax
def __get_data(fname, trace_ix=None, start_ix=0,
end_ix=None, get_ts=False, clean_signal=0):
"""
Reads in some traces.
trace_ix has to be a list, numpy array or tuple
"""
rec = stfio.read(fname)
Fs = 1000.0/rec.dt # dt is in ms
if not trace_ix:
trace_ix = range(len(rec[0]))
if not np.iterable(trace_ix):
trace_ix = [trace_ix]
ntraces = len(trace_ix)
trace_list = [0]*ntraces
n = np.zeros(ntraces)
for ix, tr_ix in enumerate(trace_ix):
trace_list[ix] = rec[0][tr_ix].asarray()[start_ix:end_ix]
n[ix] = len(trace_list[ix])
end_ix = n.min()
# If traces are of unequal lenght, shortent all to the length of the
# shortest.
if np.any(end_ix != n ):
for ix in range(ntraces):
trace_list[ix] = trace_list[ix][0:end_ix]
if clean_signal == 1:
lines = np.array([100.708])
for ix, trace in enumerate(trace_list):
trace_list[ix] = rmlines( trace,
Fs,
lines = 100.708,
pval = 0.01,
pad = 2 )[0]
elif clean_signal == 2:
lines = np.array([50.38, 100.708])
for ix, trace in enumerate(trace_list):
trace_list[ix] = clip_lines( trace,
Fs,
lines = lines )[0]
# Create the time axis (times of sample points) only if requested.
if get_ts:
ts = np.arange(0, end_ix*rec.dt, rec.dt)
return np.array(trace_list).T, Fs, ts
else:
return np.array(trace_list).T, Fs
def plt_cGlu_pos( fname_log, fname_data,
save_dir = '/home/hjalmar/Data/tmp_cGlu/' ):
"""
Hjalmar K Turesson, 14-02-12
"""
start_t = 750.0
end_t = 1050.0
stm_on_t = 800.0
# alt for early recordings.
# 111115_1 & 111115_2
# start_t = 400
# end_t = 750
# stm_on_t = 500
#start_t = 150
#end_t = 450
#stm_on_t = 200
if save_dir[-1] != '/': save_dir += '/'
xlim = [start_t, end_t]
log = read_cGlu_log( fname_log )
if log['data_filename'] != fname_data.split("/")[-1]:
print 'Data file name is not consistent ' + \
' with log file record.'
print 'log file record:', log['data_filename']
print 'data file name:', fname_data.split("/")[-1]
return 0
stm_dur = log['photo_stim_duration']
npos = len(log['stimulus_codes'])
global_events = ['']*(npos+3)
global_events[0] = {'data_filename': log['data_filename'],
'log_filename': fname_log.split("/")[-1],
'cell_name': log['data_filename'][:8],
'n_PSP': 0,
'PSP_index': [],
'n_Direct': 0,
'Direct_index':[],
'n_None': 0,
'None_index': [],
'PSP_x':[],
'PSP_y':[],
'PSP_reversal':[]}
dt = 0.1
Fs = 1/dt
start_ix = np.int_( xlim[0] * Fs )
end_ix = np.int_( xlim[1] * Fs )
stm_on_ix = int( round(stm_on_t * Fs - start_ix) )
fig_size = (8.5,11.0)
fig = plt.figure(figsize=fig_size)
ax = fig.add_subplot( 1, 1, 1 )
for pos_ix, trace_ix_raw in enumerate(log['stimulus_codes']):
# NOTE: very ugly hack. Best would be to change the log files to be
# zero based. Have fun
for ix in range(len(trace_ix_raw)): # to zeros base
trace_ix_raw[ix] -= 1
traces_raw, _, ts = __get_data( fname_data,
trace_ix = trace_ix_raw,
start_ix = start_ix,
end_ix = end_ix,
get_ts = True,
clean_signal = 0)
ntraces = len( trace_ix_raw )
events_state = np.empty(ntraces,dtype=np.bool)
events_state[:] = True
traces_clean = rmean( traces_raw, 5 )
ymin = np.floor(traces_clean.min() / 5.0) * 5.0 - 3
# Not above - 35 mV, will cut spikes
ymax = min(np.ceil(traces_clean.max() / 5.0) * 5.0 + 3, 50.0)
ylim = [ymin, ymax]
# Create and draw a rectangle showing photo stimulation period
rect = Rectangle((stm_on_t, ylim[0]), stm_dur, np.diff(ylim), facecolor="#aaaaaa",
edgecolor='none')
ax.add_patch( rect )
lines = ax.plot( ts, traces_clean )
ax.set_xlabel('Time (ms)')
# store original line colors so as to allow reset.
lines_color = [0]*len(lines)
for ix, l in enumerate(lines): lines_color[ix] = l.get_color()
ax.legend( trace_ix_raw, loc=2, labelspacing=0.1, numpoints = 2 )
ax.set_ylim(ylim)
events = __detect_events(traces_clean,stm_on_ix,start_ix,
2.0,Fs,events_state,trace_ix_raw)
arrows, amp_lines = __draw_events(ax, lines, events )
txt_pos_x = np.diff(xlim)*0.17 + xlim[0]
txt_pos_y = ylim[1] - np.diff(ylim)*0.01
txt = global_events[0]['cell_name'] + '\n' + \
r'$n = ' + str(log['Number'][pos_ix]) + '\, of \,' + str(npos) + \
'$\n$x =' + str(log['position_x'][pos_ix]) + '\mu m' + \
'$\n$y =' + str(log['position_y'][pos_ix]) + '\mu m$'
ax.text(txt_pos_x,txt_pos_y,txt,verticalalignment='top',family='sans-serif')
ax.set_xlim(xlim)
plt.draw()
# Remove bad traces
s = '' # dummy, to be replaced by command line input
while s != 'n':
s = raw_input( ' Traces to exclude?\n Comma separated' +
' traces indeci, "n" for none or "a" for all. \n [n], a, '
+ str(trace_ix_raw).strip('[]') + ':\n ')
if not s: s = 'n' # default option
if s[0] == 'a':
s = str(trace_ix_raw).strip('[]')
if s[0].strip(",").isdigit():
__rm_traces_update_plot(ax,lines,lines_color,
trace_ix_raw,s,events_state)
events = __detect_events(traces_clean,
stm_on_ix,start_ix,2.0,Fs,
events_state,trace_ix_raw)
__move_events( events, arrows, amp_lines, events_state )
plt.draw()
# Accept/reject/change events
# 2 clicks per trace, onset and peak/offset
# No timeout
# Right clicking cancels last input
s = 'x' # x is a dummy value
while s:
s = raw_input( ' Events\n Accept: [Enter], reject: ' +
'"r,tr_num1, tr_num2,..."' +
' or change: "tr_num"?\n ')
if s:
if s[0] is 'r': # Reject traces
if len(s) == 1:
events_state[:] = False
elif s.strip("r,")[0].isdigit():
trace_rm_evt_ix = __intstring_2_intlist(s[1:])
line_rm_evt_ix = [0]*len(trace_rm_evt_ix)
for ix, tr_rm_ix in enumerate(trace_rm_evt_ix):
# Check that entered index is in list
if trace_ix_raw.count(tr_rm_ix):
line_rm_evt_ix[ix] = trace_ix_raw.index(tr_rm_ix)
events_state[line_rm_evt_ix[ix]] = False
# __rm_events( events, events_state, trace_ix_raw)
__move_events( events, arrows, amp_lines, events_state )
plt.draw()
elif s[0].strip(',').isdigit(): # Change on and offsets of events.
trace_ch_evt_ix = __intstring_2_intlist(s)
line_ch_evt_ix = [0]*len(trace_ch_evt_ix)
for ix, tr_ch_ix in enumerate(trace_ch_evt_ix):
if trace_ix_raw.count(tr_ch_ix):
line_ch_evt_ix[ix] = trace_ix_raw.index(tr_ch_ix)
events_state[line_ch_evt_ix[ix]] = True
for l_ix in line_ch_evt_ix:
# Make the selected trace fat in order to highlight it
lines[l_ix].set_linewidth(3)
# Keep zorder for reset
line_zorder = lines[l_ix].get_zorder()
# bring line to front for better visibility
lines[l_ix].set_zorder(100)
print (' Click in figure on the fat trace to' +
' select event onset (1st) and event' +
' offset/peak (2nd).')
while True:
try:
evt_on, evt_off = plt.ginput(n=2, timeout=-1,
mouse_pop=None,
mouse_stop=None)
break
except:
print ' Input failed. Try again.'
# Update events, if trace is in evets['trace_ix']
# if events['trace_ix'].count(trace_ix_raw[l_ix]):
# evt_ix = events['trace_ix'].index(trace_ix_raw[l_ix])
events['on_time'][l_ix], on_ts_ix = \
findnearest( lines[l_ix].get_data()[0], evt_on[0])
events['on_amplitude'][l_ix] = \
np.median(lines[l_ix].get_data()[1]
[on_ts_ix-5:on_ts_ix+5])
events['off_time'][l_ix], off_ts_ix = \
findnearest( lines[l_ix].get_data()[0],
evt_off[0])
events['off_amplitude'][l_ix] = \
np.median(lines[l_ix].get_data()[1]
[off_ts_ix-5:off_ts_ix+5])
events['on_latency'][l_ix] = \
events['on_time'][l_ix] - stm_on_t
events['off_latency'][l_ix] = \
events['off_time'][l_ix] - stm_on_t
events['delta_amplitude'][l_ix] = \
events['off_amplitude'][l_ix] - \