forked from junlabucsd/mm3
-
Notifications
You must be signed in to change notification settings - Fork 2
/
mm3_plots.py
executable file
·4624 lines (3789 loc) · 185 KB
/
mm3_plots.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
#!/usr/bin/python
from __future__ import print_function
import six
# import modules
import os # interacting with file systems
# number modules
import numpy as np
import scipy.stats as sps
from scipy.optimize import least_squares, curve_fit
import pandas as pd
from random import sample
# image analysis modules
from skimage.measure import regionprops # used for creating lineages
# plotting modules
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.gridspec as gridspec
import matplotlib.lines as mlines
import seaborn as sns
sns.set(style='ticks', color_codes=True)
sns.set_palette('deep')
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['ps.fonttype'] = 42
mpl.rcParams['font.family'] = 'sans-serif'
SMALL_SIZE = 6
MEDIUM_SIZE = 8
BIGGER_SIZE = 10
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
# set axes and tick width
plt.rc('axes', linewidth=0.5)
mpl.rcParams['xtick.major.size'] = 2
mpl.rcParams['xtick.major.width'] = 0.5
mpl.rcParams['xtick.minor.size'] = 2
mpl.rcParams['xtick.minor.width'] = 0.5
mpl.rcParams['ytick.major.size'] = 2
mpl.rcParams['ytick.major.width'] = 0.5
mpl.rcParams['ytick.minor.size'] = 2
mpl.rcParams['ytick.minor.width'] = 0.5
# additional parameters
mpl.rcParams['lines.linewidth'] = 0.5
import mm3_helpers as mm3
### Data conversion functions ######################################################################
def cells2df(Cells, rescale=False):
'''
Take cell data (a dicionary of Cell objects) and return a dataframe.
rescale : boolean
If rescale is set to True, then the 6 major parameters are rescaled by their mean.
'''
# columns to include
columns = ['fov', 'peak', 'birth_label',
'birth_time', 'division_time',
'sb', 'sd', 'width', 'delta', 'tau', 'elong_rate', 'septum_position']
rescale_columns = ['sb', 'sd', 'width', 'delta', 'tau', 'elong_rate', 'septum_position']
# should not need this as of unet
# for cell_tmp in Cells:
# Cells[cell_tmp].width = np.mean(Cells[cell_tmp].widths_w_div)
# Make dataframe for plotting variables
Cells_dict = cells2dict(Cells)
Cells_df = pd.DataFrame(Cells_dict).transpose() # must be transposed so data is in columns
# Cells_df = Cells_df.sort(columns=['fov', 'peak', 'birth_time', 'birth_label']) # sort for convinience
Cells_df = Cells_df.sort_values(by=['fov', 'peak', 'birth_time', 'birth_label'])
Cells_df = Cells_df[columns].apply(pd.to_numeric)
if rescale:
for column in rescale_columns:
Cells_df[column] = Cells_df[column] / Cells_df[column].mean()
return Cells_df
def cells2_ccdf(Cells, add_volume=True):
'''
Take cell data (a dicionary of Cell objects) and return a dataframe. Looks for cell cycle info as well.
'''
# columns to include
columns_w_seg = ['fov', 'peak', 'birth_label',
'birth_time', 'division_time',
'sb', 'sd', 'width', 'delta', 'tau', 'elong_rate', 'septum_position',
'initiation_time', 'termination_time', 'n_oc',
'true_initiation_length', 'initiation_length',
'true_initiation_volume', 'initiation_volume',
'unit_cell', 'initiation_delta',
'B', 'C', 'D', 'tau_cyc',
'segregation_time', 'segregation_length', 'segregation_volume',
'termination_length', 'termination_volume',
'S', 'IS', 'TS',
'segregation_delta', 'termination_delta',
'segregation_delta_mother', 'segregation_length_mother']
columns_no_seg = columns_w_seg[:25]
# should not need this as of unet
# for cell_tmp in Cells:
# Cells[cell_tmp].width = np.mean(Cells[cell_tmp].widths_w_div)
# Make dataframe for plotting variables
Cells_dict = cells2dict(Cells)
Cells_df = pd.DataFrame(Cells_dict).transpose() # must be transposed so data is in columns
Cells_df = Cells_df.sort_values(by=['fov', 'peak', 'birth_time', 'birth_label'])
try:
Cells_df = Cells_df[columns_w_seg].apply(pd.to_numeric)
except:
print('No nucleoid segregation or termination size data.')
Cells_df = Cells_df[columns_no_seg].apply(pd.to_numeric)
# add birth and division volume
if add_volume:
Cells_df['birth_volume'] = ((Cells_df['sb'] - Cells_df['width']) * np.pi *
(Cells_df['width']/2)**2 +
(4/3) * np.pi * (Cells_df['width']/2)**3)
Cells_df['division_volume'] = ((Cells_df['sd'] - Cells_df['width']) * np.pi *
(Cells_df['width']/2)**2 +
(4/3) * np.pi * (Cells_df['width']/2)**3)
return Cells_df
def cells2dict(Cells):
'''
Take a dictionary of Cells and returns a dictionary of dictionaries
'''
Cells_dict = {cell_id : vars(cell) for cell_id, cell in six.iteritems(Cells)}
return Cells_dict
### Filtering functions ############################################################################
def find_cells_of_birth_label(Cells, label_num=1):
'''Return only cells whose starting region label is given.
If no birth_label is given, returns the mother cells.
label_num can also be a list to include cells of many birth labels
'''
fCells = {} # f is for filtered
if type(label_num) is int:
label_num = [label_num]
for cell_id in Cells:
if Cells[cell_id].birth_label in label_num:
fCells[cell_id] = Cells[cell_id]
return fCells
def find_cells_of_fov(Cells, FOVs=[]):
'''Return only cells from certain FOVs.
Parameters
----------
FOVs : int or list of ints
'''
fCells = {} # f is for filtered
if type(FOVs) is int:
FOVs = [FOVs]
fCells = {cell_id : cell_tmp for cell_id, cell_tmp in six.iteritems(Cells) if cell_tmp.fov in FOVs}
return fCells
def find_cells_of_fov_and_peak(Cells, fov_id, peak_id):
'''Return only cells from a specific fov/peak
Parameters
----------
fov_id : int corresponding to FOV
peak_id : int correstonging to peak
'''
fCells = {} # f is for filtered
for cell_id in Cells:
if Cells[cell_id].fov == fov_id and Cells[cell_id].peak == peak_id:
fCells[cell_id] = Cells[cell_id]
return fCells
def find_cells_born_before(Cells, born_before=None):
'''
Returns Cells dictionary of cells with a birth_time before the value specified
'''
if born_before == None:
return Cells
fCells = {cell_id : Cell for cell_id, Cell in six.iteritems(Cells) if Cell.birth_time <= born_before}
return fCells
def find_cells_born_after(Cells, born_after=None):
'''
Returns Cells dictionary of cells with a birth_time after the value specified
'''
if born_after == None:
return Cells
fCells = {cell_id : Cell for cell_id, Cell in six.iteritems(Cells) if Cell.birth_time >= born_after}
return fCells
def filter_by_stat(Cells, center_stat='mean', std_distance=3):
'''
Filters a dictionary of Cells by ensuring all of the 6 major parameters are
within some number of standard deviations away from either the mean or median
'''
# Calculate stats.
Cells_df = cells2df(Cells)
stats_columns = ['sb', 'sd', 'delta', 'elong_rate', 'tau', 'septum_position']
cell_stats = Cells_df[stats_columns].describe()
# set low and high bounds for each stat attribute
bounds = {}
for label in stats_columns:
low_bound = cell_stats[label][center_stat] - std_distance*cell_stats[label]['std']
high_bound = cell_stats[label][center_stat] + std_distance*cell_stats[label]['std']
bounds[label] = {'low' : low_bound,
'high' : high_bound}
# add filtered cells to dict
fCells = {} # dict to hold filtered cells
for cell_id, Cell in six.iteritems(Cells):
benchmark = 0 # this needs to equal 6, so it passes all tests
for label in stats_columns:
attribute = getattr(Cell, label) # current value of this attribute for cell
if attribute > bounds[label]['low'] and attribute < bounds[label]['high']:
benchmark += 1
if benchmark == 6:
fCells[cell_id] = Cells[cell_id]
return fCells
def find_last_daughter(cell, Cells):
'''Finds the last daughter in a lineage starting with a earlier cell.
Helper function for find_continuous_lineages'''
# go into the daugther cell if the daughter exists
if cell.daughters[0] in Cells:
cell = Cells[cell.daughters[0]]
cell = find_last_daughter(cell, Cells)
else:
# otherwise just give back this cell
return cell
# finally, return the deepest cell
return cell
def get_lineage_list(cell, all_cell_ids):
'''Finds the cells in a lineage after cell passed to function'''
# work back to original cell in lineage
while ((cell.parent is not None) and (cell.parent in all_cell_ids)):
cell = cell.parent
# initialize the list of cells in the lineage
lineage_list = [cell.id]
# if this cell has daughters, do the following
while cell.daughters is not None:
cell = cell.daughters[0]
lineage_list.append(cell.id)
lineage_list.sort()
# finally, return the list of cell id's in the lineage
return lineage_list
def find_all_lineages(Cells):
'''
Generates lists of cell_id's.
Each list corresponds to the cells in a single continuous
lineage
'''
all_cell_ids = [cell_id for cell_id in Cells.keys()]
all_cell_ids.sort()
all_lineages = []
while len(all_cell_ids) > 0:
cell_lineage = get_lineage_list(Cells[all_cell_ids[0]], all_cell_ids)
for lineage_cell_id in cell_lineage:
if lineage_cell_id in all_cell_ids:
all_cell_ids.pop(all_cell_ids.index(lineage_cell_id))
all_lineages.append(cell_lineage)
return all_lineages
def find_continuous_lineages(Cells, specs, t1=0, t2=1000):
'''
Uses a recursive function to only return cells that have continuous
lineages between two time points. Takes a "lineage" form of Cells and
returns a dictionary of the same format. Good for plotting
with saw_tooth_plot()
t1 : int
First cell in lineage must be born before this time point
t2 : int
Last cell in lineage must be born after this time point
'''
Lineages = organize_cells_by_channel(Cells, specs)
# This is a mirror of the lineages dictionary, just for the continuous cells
Continuous_Lineages = {}
for fov, peaks in six.iteritems(Lineages):
# print("fov = {:d}".format(fov))
# Create a dictionary to hold this FOV
Continuous_Lineages[fov] = {}
for peak, Cells in six.iteritems(peaks):
# print("{:<4s}peak = {:d}".format("",peak))
# sort the cells by time in a list for this peak
cells_sorted = [(cell_id, cell) for cell_id, cell in six.iteritems(Cells)]
cells_sorted = sorted(cells_sorted, key=lambda x: x[1].birth_time)
# Sometimes there are not any cells for the channel even if it was to be analyzed
if not cells_sorted:
continue
# look through list to find the cell born immediately before t1
# and divides after t1, but not after t2
for i, cell_data in enumerate(cells_sorted):
cell_id, cell = cell_data
if cell.birth_time < t1 and t1 <= cell.division_time < t2:
first_cell_index = i
break
# filter cell_sorted or skip if you got to the end of the list
if i == len(cells_sorted) - 1:
continue
else:
cells_sorted = cells_sorted[i:]
# get the first cell and it's last contiguous daughter
first_cell = cells_sorted[0][1]
last_daughter = find_last_daughter(first_cell, Cells)
# check to the daughter makes the second cut off
if last_daughter.birth_time > t2:
# print(fov, peak, 'Made it')
# now retrieve only those cells within the two times
# use the function to easily return in dictionary format
Cells_cont = find_cells_born_after(Cells, born_after=t1)
# Cells_cont = find_cells_born_before(Cells_cont, born_before=t2)
# append the first cell which was filtered out in the above step
Cells_cont[first_cell.id] = first_cell
# and add it to the big dictionary
Continuous_Lineages[fov][peak] = Cells_cont
# remove keys that do not have any lineages
if not Continuous_Lineages[fov]:
Continuous_Lineages.pop(fov)
Cells = lineages_to_dict(Continuous_Lineages) # revert back to return
return Cells
def find_lineages(Cells, specs):
'''
Uses a recursive function to only return cells that have continuous
lineages between two time points. Takes a "lineage" form of Cells and
returns a dictionary of the same format. Good for plotting
with saw_tooth_plot()
t1 : int
First cell in lineage must be born before this time point
t2 : int
Last cell in lineage must be born after this time point
'''
Lineages = organize_cells_by_channel(Cells, specs)
# This is a mirror of the lineages dictionary, just for the continuous cells
Continuous_Lineages = {}
for fov, peaks in six.iteritems(Lineages):
# print("fov = {:d}".format(fov))
# Create a dictionary to hold this FOV
Continuous_Lineages[fov] = {}
for peak, Cells in six.iteritems(peaks):
# print("{:<4s}peak = {:d}".format("",peak))
# sort the cells by time in a list for this peak
cells_sorted = [(cell_id, cell) for cell_id, cell in six.iteritems(Cells)]
cells_sorted = sorted(cells_sorted, key=lambda x: x[1].birth_time)
# Sometimes there are not any cells for the channel even if it was to be analyzed
if not cells_sorted:
continue
# look through list to find the cell born immediately before t1
# and divides after t1, but not after t2
first_cell_index = 0
# for i, cell_data in enumerate(cells_sorted):
# cell_id, cell = cell_data
# if cell.birth_time < t1 and t1 <= cell.division_time < t2:
# first_cell_index = i
# break
# filter cell_sorted or skip if you got to the end of the list
if i == len(cells_sorted) - 1:
continue
else:
cells_sorted = cells_sorted[i:]
# get the first cell and it's last contiguous daughter
first_cell = cells_sorted[0][1]
last_daughter = find_last_daughter(first_cell, Cells)
# check to the daughter makes the second cut off
if last_daughter.birth_time > t2:
# print(fov, peak, 'Made it')
# now retrieve only those cells within the two times
# use the function to easily return in dictionary format
Cells_cont = find_cells_born_after(Cells, born_after=t1)
# Cells_cont = find_cells_born_before(Cells_cont, born_before=t2)
# append the first cell which was filtered out in the above step
Cells_cont[first_cell.id] = first_cell
# and add it to the big dictionary
Continuous_Lineages[fov][peak] = Cells_cont
# remove keys that do not have any lineages
if not Continuous_Lineages[fov]:
Continuous_Lineages.pop(fov)
Cells = lineages_to_dict(Continuous_Lineages) # revert back to return
return Cells
def find_generation_gap(cell, Cells, gen):
'''Finds how many continuous ancestors this cell has.'''
if cell.parent in Cells:
gen += 1
gen = find_generation_gap(Cells[cell.parent], Cells, gen)
return gen
def return_ancestors(cell, Cells, ancestors=[]):
'''Returns all ancestors of a cell. Returns them in reverse age.'''
if cell.parent in Cells:
ancestors.append(cell.parent)
ancestors = return_ancestors(Cells[cell.parent], Cells, ancestors)
return ancestors
def find_lineages_of_length(Cells, n_gens=5, remove_ends=False):
'''Returns cell lineages of at least a certain length, indicated by n_gens.
Parameters
----------
Cells - Dictionary of cell objects
n_gens - int. Minimum number generations in lineage to be included.
remove_ends : bool. Remove the first and last cell from the list. So number of minimum cells in a lineage is n_gens - 2.
'''
filtered_cells = []
for cell_id, cell_tmp in six.iteritems(Cells):
# find the last continuous daughter
last_daughter = find_last_daughter(cell_tmp, Cells)
# check if last daughter is n generations away from this cell
gen = 0
gen = find_generation_gap(last_daughter, Cells, gen)
if gen >= n_gens:
ancestors = return_ancestors(last_daughter, Cells, [last_daughter.id])
# remove first cell and last cell, they may be weird
if remove_ends:
ancestors = ancestors[1:-1]
filtered_cells += ancestors
# remove all the doubles
filtered_cells = sorted(list(set(filtered_cells)))
# add all the cells that made it back to a new dictionary.
Filtered_Cells = {}
for cell_id in filtered_cells:
Filtered_Cells[cell_id] = Cells[cell_id]
return Filtered_Cells
def organize_cells_by_channel(Cells, specs):
'''
Returns a nested dictionary where the keys are first
the fov_id and then the peak_id (similar to specs),
and the final value is a dictiary of cell objects that go in that
specific channel, in the same format as normal {cell_id : Cell, ...}
'''
# make a nested dictionary that holds lists of cells for one fov/peak
Cells_by_peak = {}
for fov_id in specs.keys():
Cells_by_peak[fov_id] = {}
for peak_id, spec in specs[fov_id].items():
# only make a space for channels that are analyized
if spec == 1:
Cells_by_peak[fov_id][peak_id] = {}
# organize the cells
for cell_id, Cell in Cells.items():
Cells_by_peak[Cell.fov][Cell.peak][cell_id] = Cell
# remove peaks and that do not contain cells
remove_fovs = []
for fov_id, peaks in six.iteritems(Cells_by_peak):
remove_peaks = []
for peak_id in peaks.keys():
if not peaks[peak_id]:
remove_peaks.append(peak_id)
for peak_id in remove_peaks:
peaks.pop(peak_id)
if not Cells_by_peak[fov_id]:
remove_fovs.append(fov_id)
for fov_id in remove_fovs:
Cells_by_peak.pop(fov_id)
return Cells_by_peak
def lineages_to_dict(Lineages):
'''Converts the lineage structure of cells organized by peak back
to a dictionary of cells. Useful for filtering but then using the
dictionary based plotting functions'''
Cells = {}
for fov, peaks in six.iteritems(Lineages):
for peak, cells in six.iteritems(peaks):
Cells.update(cells)
return Cells
### Statistics and analysis functions ##############################################################
def stats_table(Cells_df):
'''Returns a Pandas dataframe with statistics about the 6 major cell parameters.
'''
columns = ['sb', 'sd', 'width', 'delta', 'tau', 'elong_rate', 'septum_position']
cell_stats = Cells_df[columns].describe() # This is a nifty function
# add a CV row
CVs = [cell_stats[column]['std'] / cell_stats[column]['mean'] for column in columns]
cell_stats = cell_stats.append(pd.Series(CVs, index=columns, name='CV'))
# reorder and remove rows
index_order = ['mean', 'std', 'CV', '50%', 'min', 'max']
cell_stats = cell_stats.reindex(index_order)
# rename 50% to median because I hate that name
cell_stats = cell_stats.rename(index={'50%': 'median'})
return cell_stats
def channel_locations(channel_file, filetype='specs'):
'''Plot the location of the channels across FOVs
Parameters
----------
channel_dict : dict
Either channels_masks or specs dictionary.
filetype : str, either 'specs' or 'channel_masks'
What type of file is provided, which effects the plot output.
'''
fig = plt.figure(figsize=(4,4))
point_size = 10
# Using the channel masks
if filetype == 'channel_masks':
for key, values in six.iteritems(channel_file):
# print('FOV {} has {} channels'.format(key, len(values)))
y = (np.ones(len(values))) + key - 1
x = values.keys()
plt.scatter(x, y, s=point_size)
# Using the specs file
if filetype == 'specs':
for key, values in six.iteritems(channel_file):
y = list((np.ones(len(values))) + key - 1)
x = list(values.keys())
# green for analyze (==1)
greenx = [x[i] for i, v in enumerate(values.values()) if v == 1]
greeny = [y[i] for i, v in enumerate(values.values()) if v == 1]
plt.scatter(greenx, greeny, color='g', s=point_size)
# blue for empty (==0)
bluex = [x[i] for i, v in enumerate(values.values()) if v == 0]
bluey = [y[i] for i, v in enumerate(values.values()) if v == 0]
plt.scatter(bluex, bluey, color='b', s=point_size)
# red for ignore (==-1)
redx = [x[i] for i, v in enumerate(values.values()) if v == -1]
redy = [y[i] for i, v in enumerate(values.values()) if v == -1]
plt.scatter(redx, redy, color='r', s=point_size)
plt.title('Channel locations across FOVs')
plt.xlabel('peak position [x pixel location of channel in TIFF]')
plt.ylabel('FOV')
plt.tight_layout()
return fig
def cell_counts(Cells, title='counts'):
'''Returns dataframe of counts of cells based on poll age and region number
Parameters
----------
Cells : dict
Dictionary of cell objects.
title : str
Optional column title.
'''
index_names = ['all cells', 'with pole age', 'without pole age',
'mothers', '01 cells', '10 cells', '02 cells', 'other pole age',
'r1 cels', 'r2 cells', 'r3 cells', 'r4 cells', 'r>4 cells']
count_df = pd.DataFrame([], index=index_names)
with_poleage = 0
without_poleage = 0
n1000_0 = 0
n01 = 0
n10 = 0
n02 = 0
n20 = 0
unknown = 0
nr1 = 0
nr2 = 0
nr3 = 0
nr4 = 0
nrmore = 0
for cell_id, cell_tmp in six.iteritems(Cells):
if cell_tmp.poleage:
with_poleage += 1
if cell_tmp.poleage == (1000, 0):
n1000_0 += 1
elif cell_tmp.poleage == (0, 1) and cell_tmp.birth_label <= 2:
n01 += 1
elif cell_tmp.poleage == (1, 0) and cell_tmp.birth_label <= 3:
n10 += 1
elif cell_tmp.poleage == (0, 2):
n02 += 1
else:
unknown += 1
elif cell_tmp.poleage == None:
without_poleage += 1
if cell_tmp.birth_label == 1:
nr1 += 1
elif cell_tmp.birth_label == 2:
nr2 += 1
elif cell_tmp.birth_label == 3:
nr3 += 1
elif cell_tmp.birth_label == 4:
nr4 += 1
else:
nrmore += 1
# make a tuple of this data, which will become a row of the dataframe
count_df[title] = pd.Series([len(Cells), with_poleage, without_poleage, n1000_0, n01, n10, n02, unknown, nr1, nr2, nr3, nr4, nrmore], index=index_names)
return count_df
def add_cc_info(Cells, matlab_df, time_int):
'''Adds cell cycle information from the Matlab Cycle Picker .csv to the Cell objects.
Only cell_id, initiation_time, and termination_time are used from the .csv.
The times in the information from Matlab should be experimental index.
Parameters
----------
Cells : dict
Dictionary of cell objects
matlab_df : DataFrame or Path
Dataframe of .csv or Path to the .csv output from Matlab.
time_int : int or float
Picture taking interval for the experiment.
'''
if isinstance(matlab_df, type(pd.DataFrame())):
pass
elif isinstance(matlab_df, str):
matlab_df = pd.read_csv(matlab_df)
else:
matlab_df = pd.DataFrame(data=['None'], columns=['cell_id'])
# counters for which cells do and do not have cell cycle info
n_in_cc_df = 0
n_not_in_cc_df = 0
population_width = np.mean(cells2df(Cells)['width'])
for cell_id, cell_tmp in six.iteritems(Cells):
# intialize dictionary of attributes to add to cells
attributes = dict(initiation_time=None,
termination_time=None,
n_oc=None,
true_initiation_length=None,
initiation_length=None,
true_initiation_volume=None,
initiation_volume=None,
unit_cell=None,
B=None,
C=None,
D=None,
tau_cyc=None,
initiation_delta=None,
initiation_delta_volume=None)
if matlab_df['cell_id'].str.contains(cell_id).any():
n_in_cc_df += 1
### pull data straight from dataframe
cell_cc_row = matlab_df[matlab_df['cell_id'] == cell_id]
attributes['initiation_time'] = cell_cc_row.iloc[0]['initiation_time'] # time is image interval
attributes['termination_time'] = cell_cc_row.iloc[0]['termination_time']
### calculated values
# get mother and upper generation ids just in case.
mother_id = gmother_id = ggmother_id = None
mother_id = cell_tmp.parent
if mother_id in Cells:
gmother_id = Cells[mother_id].parent
if gmother_id in Cells:
ggmother_id = Cells[gmother_id].parent
# 1 overlapping cell cycle, initiation time is in this cell's times
try:
if attributes['initiation_time'] in cell_tmp.times:
attributes['n_oc'] = 1
init_cell_id = cell_id
elif attributes['initiation_time'] in Cells[mother_id].times:
attributes['n_oc'] = 2
init_cell_id = mother_id
elif attributes['initiation_time'] in Cells[gmother_id].times:
attributes['n_oc'] = 3
init_cell_id = gmother_id
elif attributes['initiation_time'] in Cells[ggmother_id].times:
attributes['n_oc'] = 4
init_cell_id = ggmother_id
else:
print('Initiation cell not found for {}'.format(cell_id))
except:
print('Issue finding init_cell_id for {}'.format(cell_id))
# reset attributes to give this cell no information
attributes['initiation_time'] = None
attributes['termination_time'] = None
attributes['n_oc'] = None
for key, value in attributes.items():
setattr(cell_tmp, key, value)
continue # just skip this cell for the rest of the info
# find index of intiation in that cell. Note if the time was recorded with real time or not
try:
# index in the initiation cell
init_index = Cells[init_cell_id].times.index(attributes['initiation_time'])
except:
print('{} with n_oc {} has initiation index {}'.format(cell_id, attributes['n_oc'], attributes['initiation_time']))
# reset attributes to give this cell no information
attributes['initiation_time'] = None
attributes['termination_time'] = None
attributes['n_oc'] = None
for key, value in attributes.items():
setattr(cell_tmp, key, value)
continue # just skip this cell for the rest of the info
attributes['true_initiation_length'] = Cells[init_cell_id].lengths_w_div[init_index]
attributes['initiation_length'] = (Cells[init_cell_id].lengths_w_div[init_index] /
2**(attributes['n_oc'] - 1))
# print(attributes['initiation_length'], cell_cc_row.iloc[0]['initiation_length'],
# attributes['n_oc'], attributes['true_initiation_length'], cell_tmp.id)
cell_lengths = Cells[init_cell_id].lengths_w_div
cell_width = Cells[init_cell_id].width # average width
cell_volumes_avg_width = ((cell_lengths - cell_width) * np.pi * (cell_width/2)**2 +
(4/3) * np.pi * (cell_width/2)**3)
attributes['true_initiation_volume'] = cell_volumes_avg_width[init_index]
attributes['initiation_volume'] = (cell_volumes_avg_width[init_index] /
2**(attributes['n_oc'] - 1))
# use population width for unit cell
pop_rads = population_width / 2
# volume is cylinder + sphere using with as radius
cyl_lengths = attributes['initiation_length'] - population_width
pop_init_vol = ((4/3) * np.pi * np.power(pop_rads, 3)) + (np.pi * np.power(pop_rads, 2) * cyl_lengths)
attributes['unit_cell'] = pop_init_vol * np.log(2)
# use the time_int to give the true elapsed time in minutes.
attributes['B'] = (Cells[cell_id].birth_time - attributes['initiation_time']) * time_int
attributes['C'] = (attributes['termination_time'] - attributes['initiation_time']) * time_int
attributes['D'] = (Cells[cell_id].division_time - attributes['termination_time']) * time_int
attributes['tau_cyc'] = attributes['C'] + attributes['D']
else:
n_not_in_cc_df += 1
for key, value in attributes.items():
setattr(cell_tmp, key, value)
print('There are {} cells with cell cycle info and {} not.'.format(n_in_cc_df, n_not_in_cc_df))
# Loop through cells again to determine initiation adder size
# Fangwei's definition is the added unit cell size between a cell and it's daughter
n_init_delta = 0
for cell_id, cell_tmp in six.iteritems(Cells):
# this cell must have a unit cell size, a daughter, and that daughter must have an So
# We always use daughter 1 for cell cycle picking.
if cell_tmp.initiation_length != None and cell_tmp.daughters[0] in Cells:
if Cells[cell_tmp.daughters[0]].initiation_length != None:
# if cell_tmp.n_oc == Cells[cell_tmp.daughters[0]].n_oc:
cell_tmp.initiation_delta = (2*Cells[cell_tmp.daughters[0]].initiation_length -
cell_tmp.initiation_length)
n_init_delta += 1
# added initiation volume is hard to measure really because of width uncertainty
# cell_tmp.initiation_delta_volume = (2*Cells[cell_tmp.daughters[0]].initiation_volume -
# cell_tmp.initiation_volume)
print('There are {} cells with an initiation delta'.format(n_init_delta))
return Cells
def add_seg_info(Cells, matlab_df, time_int):
'''Adds nucleoid segregation information from the Matlab .csv to the Cell objects.
Only cell_id and seg_time are used from the .csv.
The times in the information from Matlab should be experimental time index.
Parameters
----------
Cells : dict
Dictionary of cell objects
matlab_df : DataFrame or Path
Dataframe of .csv or Path to the .csv output from Matlab.
time_int : int or float
Picture taking interval for the experiment.
'''
if isinstance(matlab_df, type(pd.DataFrame())):
pass
elif isinstance(matlab_df, str):
matlab_df = pd.read_csv(matlab_df)
else:
matlab_df = pd.DataFrame(data=['None'], columns=['cell_id'])
# counters for which cells do and do not have nuc seg info
n_in_seg_df = 0
n_not_in_seg_df = 0
for cell_id, cell_tmp in six.iteritems(Cells):
# intialize dictionary of attributes to add to cells
attributes = dict(segregation_time=None,
segregation_length=None,
segregation_volume=None,
segregation_delta=None, # length added between this segregation and last.
segregation_length_mother=None, # used for better comparison of seg delta
segregation_delta_mother=None,
S=None,
IS=None, # initiation to segregation
TS=None) # termination to segregation
if matlab_df['cell_id'].str.contains(cell_id).any():
n_in_seg_df += 1
### pull data straight from dataframe
cell_seg_row = matlab_df[matlab_df['cell_id'] == cell_id]
attributes['segregation_time'] = cell_seg_row.iloc[0]['seg_time'] # time is image interval
# find index of intiation in that cell. Note if the time was recorded with real time or not
try:
# index in the initiation cell
seg_index = cell_tmp.times.index(attributes['segregation_time'])
except:
# these cells do not have lengths at this time.
print('{} with segregation time {}'.format(cell_id, attributes['segregation_time']))
# reset attributes to give this cell no information
attributes['segregation_time'] = None
for key, value in attributes.items():
setattr(cell_tmp, key, value)
continue # just skip this cell for the rest of the info
attributes['segregation_length'] = cell_tmp.lengths_w_div[seg_index]
cell_lengths = cell_tmp.lengths_w_div
cell_width = cell_tmp.width # average width
cell_volumes_avg_width = ((cell_lengths - cell_width) * np.pi * (cell_width/2)**2 +
(4/3) * np.pi * (cell_width/2)**3)
attributes['segregation_volume'] = cell_volumes_avg_width[seg_index]
attributes['S'] = (cell_tmp.division_time - attributes['segregation_time']) * time_int
if cell_tmp.initiation_time:
attributes['IS'] = (attributes['segregation_time'] - cell_tmp.initiation_time) * time_int
attributes['TS'] = (attributes['segregation_time'] - cell_tmp.termination_time) * time_int
else:
n_not_in_seg_df += 1
for key, value in attributes.items():
setattr(cell_tmp, key, value)
print('There are {} cells with segregation info and {} not.'.format(n_in_seg_df, n_not_in_seg_df))
n_seg_delta = 0
for cell_id, cell_tmp in six.iteritems(Cells):
# Checking added segregation size towards daughter
if cell_tmp.segregation_length != None and cell_tmp.daughters[0] in Cells:
if Cells[cell_tmp.daughters[0]].segregation_length != None:
cell_tmp.segregation_delta = (2*Cells[cell_tmp.daughters[0]].segregation_length -
cell_tmp.segregation_length)
n_seg_delta += 1
# this is added segregation size towards mother, which makes it more comparable do the others.
if cell_tmp.segregation_length != None and cell_tmp.parent in Cells:
if Cells[cell_tmp.parent].segregation_length != None:
cell_tmp.segregation_delta_mother = (2*cell_tmp.segregation_length -
Cells[cell_tmp.parent].segregation_length)
cell_tmp.segregation_length_mother = Cells[cell_tmp.parent].segregation_length
print('There are {} cells with segregation delta.'.format(n_seg_delta))
return Cells
def add_termination_info(Cells):
'''hack to add temination length and volume to the cells. Should be part of add_cc_info'''
cells_w_termination_length = 0
cells_wo_termination_length = 0
for cell_id, cell_tmp in six.iteritems(Cells):
# intialize dictionary of attributes to add to cells
attributes = dict(termination_length=None,
termination_volume=None,
termination_delta=None) # length added between two terminations