-
Notifications
You must be signed in to change notification settings - Fork 4
/
GeneSet.m
3891 lines (3189 loc) · 151 KB
/
GeneSet.m
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
% GeneSet: a MATLAB object for analysis of Single-Cell RNASeq Data
% (C) Kenneth D. Harris, 2014-2017
% Any questions or comments, please email kenneth.harris@ucl.ac.uk.
%
% This code may rely on some additional library functions. If you get
% "undefined function or variable" errors, please email me and I will sent
% them.
%
% Released under the GPL
classdef GeneSet
properties
nGenes; % number of genes
nCells; % number of cells
GeneExp; % nGenes x nCells array giving expression levels
GeneName; % Ngenes x 1 cell array with name of each gene
GeneInfo; % struct array giving attributes of each gene
CellInfo; % struct array giving attributes of each cell
Class; % string giving class assignment of every cell
CellName; % a name for every cell, to help you remember them.
Excluded; % a GeneSet containing any
tSNE; % a 2 by nCells array giving the output of tSNE dim reduction
GeneCorrels; % nGenes x nGenes array to speed up MDS. Calculated only when needed
end
methods
function g = GeneSet(FileName, nHeaderLines)
% g = GeneSet(FileName, nHeaderLines)
% load data from CEF or loom file
% if passed a cell array of strings, will load all those files
% if FileName is a .tsv file, will load that treating
% nHeaderLines as headers
if nargin<1
return;
end
% load all in cell array
if iscell(FileName)
g = GeneSet(FileName{1});
for i=2:length(FileName)
g = g.horzcat(GeneSet(FileName{i}));
end
% give new names to ensure no duplicates
g.CellName=RandomNames(g.nCells);
return
end
% find file name extension
if ~char(FileName)
error('Was expecting either a filename or cell array of filenames');
end
LastPeriod = find(FileName=='.', 1, 'last');
Extension = FileName(LastPeriod:end);
% there are two file formats: loom and cef
% can also load a .tsv file if you insist
if strcmpi(Extension, '.loom')
fprintf('Loading loom file %s\n', FileName);
g = GeneSet;
g.GeneName = deblank(h5read(FileName, '/row_attrs/Gene'));
% for some reason, some files encase the gene name in
% "b'GName'"
% if g.GeneName{1}(1)=='b'
% for i=1:length(g.GeneName)
% g.GeneName{i} = g.GeneName{i}(3:end-1);
% end
% end
g.GeneExp = h5read(FileName, '/matrix')'; % transpose it for nGenes by nCells!
[g.nGenes, g.nCells] = size(g.GeneExp);
ColInfo = h5info(FileName, '/col_attrs');
RowInfo = h5info(FileName, '/row_attrs');
g.GeneInfo = struct;
for i=1:length(RowInfo.Datasets);
FieldName = RowInfo.Datasets(i).Name;
AttrName = FieldName;
AttrName(FieldName==' ') = '_'; % get rid of spaces
if AttrName(1)=='_'
AttrName = AttrName(2:end);
end
g.GeneInfo = setfield(g.GeneInfo, AttrName, h5read(FileName, ['/row_attrs/' FieldName]));
end
g.CellInfo = struct;
for i=1:length(ColInfo.Datasets);
FieldName = ColInfo.Datasets(i).Name;
AttrName = FieldName;
AttrName(FieldName==' ') = '_'; % get rid of spaces
if AttrName(1)=='_'
AttrName = AttrName(2:end);
end
g.CellInfo = setfield(g.CellInfo, AttrName, h5read(FileName, ['/col_attrs/' FieldName]));
g.CellInfo.Loom_Row = (1:g.nCells)';
g.CellInfo.Loom_File = repmat({FileName},[g.nCells,1]);
end
g.CellName = RandomNames(g.nCells);
elseif strcmpi(Extension, '.cef')
fprintf('Loading cef file %s\n', FileName);
%first line in cef file is info about size of each part
fid = fopen(FileName);
FirstLine = textscan(fid,'%s %d %d %d %d %d %d %*[^\r\n]', 1, 'Delimiter', '\t');
if FirstLine{1}{1}~='CEF'
error('CEF file should start with string "CEF"');
end
[nHead, nRowAttr, nColAttr, nRows, nCols, Flags] = FirstLine{2:7};
g.nGenes = nRows;
g.nCells = nCols;
% read in header
Header = textscan(fid, '%s %s %*[^\r\n]', nHead, 'Delimiter', '\t');
% read in Column Attributes
g.CellInfo = struct;
for i=1:nColAttr
% read attribute name, skipping multiple blank cells first
% ColAttrName = textscan(fid, '%s', 1, 'Delimiter', '\t', 'MultipleDelimsAsOne', 1);
% ColAttrVals = textscan(fid, '%s', nCols, 'Delimiter', '\t', 'MultipleDelimsAsOne', 0);
% g.CellInfo = setfield(g.CellInfo,ColAttrName{1}{1}, ColAttrVals{1});
textscan(fid, '%*[\r\n]'); Line = fgetl(fid); % skip blanks and read line - had to do it this way to avoid some weird file problems
[ColAttrName, pos] = textscan(Line, '%s', 1, 'Delimiter', '\t', 'MultipleDelimsAsOne', 1);
if pos<length(Line)
ColAttrVals = textscan(Line(pos+1:end), '%s', nCols, 'Delimiter', '\t', 'MultipleDelimsAsOne', 0);
g.CellInfo = setfield(g.CellInfo,ColAttrName{1}{1}, ColAttrVals{1});
end
end
% read in Row Attributes
RowAttrName = textscan(fid, '%s', nRowAttr, 'Delimiter', '\t');
RowAttrVals = textscan(fid, [repmat('%s ',[1 nRowAttr]) '%*[^\r\n]'], nRows);
g.GeneName = RowAttrVals{1};
g.GeneInfo = struct;
for i=2:nRowAttr
g.GeneInfo = setfield(g.GeneInfo, RowAttrName{1}{i}, RowAttrVals{i});
end
fclose(fid);
% now load in actual data
g.GeneExp = dlmread(FileName, '\t', 3+nColAttr, 1+nRowAttr);
% strip off blank rows and columns
g.GeneExp = g.GeneExp(1:g.nGenes, 1:g.nCells);
% give the cells some memorable names
g.CellName=RandomNames(g.nCells);
elseif strcmpi(Extension, '.tsv')
fprintf('Loading tsv file %s with %d header lines\n', FileName, nHeaderLines);
% read in actual data
g.GeneExp = dlmread(FileName, '\t', nHeaderLines,1);
g.nGenes = size(g.GeneExp,1);
% read in header lines
fid = fopen(FileName, 'r');
for i=1:nHeaderLines
Line = fgetl(fid);
SplitLine = strsplit(Line, '\t');
g.CellInfo = setfield(g.CellInfo, SplitLine{1}, SplitLine(2:end)');
if i==1
g.nCells = length(SplitLine)-1;
elseif g.nCells ~= length(SplitLine)-1
error('header lines not all same length')
end
end
% read gene names
tmp = textscan(fid, ['%s %*[^\r\n]'], g.nGenes);
g.GeneName= tmp{1};
fclose(fid);
% give them random names
g.CellName=RandomNames(g.nCells);
else
error('Unknown file extension');
end
end
function IDs = NamesToIDs(g, Names);
% GeneIDs = NamesToIDs(g, Names);
% returns numeric IDs of genes whose names are in cell array Names
% if Names is a string, will just return one matching this
% if Names is numeric, it will just return it as-is
% any non-matches are dropped with a warning
if isstr(Names)
IDs = strmatch(Names, g.GeneName, 'exact');
if isempty(IDs)
warning(sprintf('Could not find gene of name %s', Names));
end
elseif iscell(Names)
% [~, ia, IDs] = intersect(Names, g.GeneName, 'stable');
% if length(ia)<length(Names)
% str = ['Could not find gene of name ' sprintf('%s ', Names{setdiff(1:length(Names), ia)})];
% warning(str);
% end
[Good, IDs] = ismember(Names, g.GeneName);
if any(~Good)
str = ['Could not find gene of name ' sprintf('%s ', Names{~Good})];
warning(str);
end
elseif isnumeric(Names)
IDs = Names;
else
error('Names must be cell or string or numeric');
end
IDs = IDs(IDs>0);
end
function IDs = NameStartsWith(g, Root)
% IDs = NameStartsWith(Root)
%
% finds gene IDs for genes starting with Root.
% Root can be a string, or a cell array of strings
if isstr(Root)
IDs = strmatch(Root, g.GeneName);
elseif iscell(Root)
IDs = [];
for i=1:length(Root)
IDs = union(IDs, strmatch(Root{i}, g.GeneName));
end
else
error('Root should be string or cell');
end
end
function Names = IDsToNames(g, IDs);
% GeneNames = IDsToNames(g, IDs);
% returns names of genes with specified numeric IDs
% if you pass an array it returns a cell array of strings
% if you pass a number it returns a string
if isstr(IDs) | iscell(IDs)
Names = IDs;
else
Names = g.GeneName(IDs);
end
if iscell(Names) & length(Names)==1
Names = Names{1};
end
end
function IDs = MeanExceeds(g, Threshold)
% MeanExceeds(g, Threshold)
% returns IDs of all genes whose mean expression exceeds Threshold
MeanExp = mean(g.GeneExp,2);
IDs = find(MeanExp>Threshold);
end
function x= Exp(g, Gene, Cells);
% x = Exp(Gene, Cells);
% return a vector of expression levels for Gene
%
% Default for Cells is everyone; you can also pass names,
% classes, etc. (See IdentifyCells);
% Gene can be numeric, string, or cell array of strings
% any strings that don't match gene names, will try entry in
% CellInfo
if nargin<3
Cells = 1:g.nCells;
else
Cells = g.IdentifyCells(Cells);
end
if isstr(Gene)
Gene = {Gene};
end
if isnumeric(Gene)
x = g.GeneExp(Gene,Cells);
else
IsaGene = ismember(Gene, g.GeneName);
GeneID = g.NamesToIDs(Gene(IsaGene));
if isstruct(g.CellInfo)
IsaCellInfo = ismember(Gene, fieldnames(g.CellInfo));
else
IsaCellInfo = zeros(size(IsaGene));
end
x = nan(length(Gene), length(Cells));
x(IsaGene,:) = g.GeneExp(GeneID,Cells);
if any(IsaCellInfo) % because 0-by-1 matrix runs for loop
for i = find(IsaCellInfo)
x(i,:) = getfield(g.CellInfo, Gene{i});
end
end
end
end
function h = GoodExpressers(g, ThisManyCells, ExpressThisMuch)
% h = GoodExpressers(g, ThisManyCells, ExpressThisMuch)
% returns a subset structure with all genes for which at least
% ThisManyCells cells Express at least ExpressThisMuch
Sorted = sort(g.GeneExp,2, 'descend');
IDs = find(Sorted(:,ThisManyCells)>=ExpressThisMuch);
h = g.GeneSubset(IDs);
end
function h = GeneSubset(g, IDs)
% h = GeneSubset(g, GeneIDs)
% make a new array corresponding subset of genes
% if names, they will be converted
IDs = g.NamesToIDs(IDs);
h = g;
h.GeneExp = g.GeneExp(IDs,:);
h.GeneName = g.GeneName(IDs);
h.nGenes = length(IDs);
end
function h = ExcludeGenes(g, ExcludeThese)
% h = ExcludeGenes(g, ExcludeThese)
%
% removes the specified genes, and puts them in the Excluded
% field
%
% ExcludeThese can be:
% a string, in which case it has to match exactly
% a string ending in *, in which case it matches the start
% a numeric array, in which case it uses these IDs
% a cell array, in which case it takes the union of all
% members
if ~iscell(ExcludeThese)
ExcludeThese = {ExcludeThese};
end
ExcludeList = [];
for i=1:length(ExcludeThese)
e = ExcludeThese{i};
if isnumeric(e)
eIDs = e;
elseif isstr(e) & e(end)=='*'
eIDs = g.NameStartsWith(e(1:end-1));
elseif isstr(e)
eIDs = g.NamesToIDs(e);
else
error('ExcludeGenes: unexpected type');
end
ExcludeList = union(ExcludeList, eIDs);
end
h = g.GeneSubset(setdiff(1:g.nGenes, ExcludeList));
h.Excluded = g.GeneSubset(ExcludeList);
end
function h = DisexcludeGenes(g)
% h = DisexcludeGenes(g)
% puts the excluded genes back in the main structure
h1 = g;
h1.Excluded = [];
h = vertcat(h1, g.Excluded);
end
function h = ReClass(g, NewClass);
% h = ReClass(g, NewClass);
% changes the Class attribute to NewClass
%
% if a string, uses that structure of CellInfo
% if numeric, convert to strings (no space padding)
% if a containers.Map, use that to convert
% otherwise uses as-is
h = g;
if isempty(NewClass)
h.Class = repmat({''}, g.nCells,1);
elseif isstr(NewClass)
h = g.ReClass(getfield(g.CellInfo, NewClass));
elseif isnumeric(NewClass) | islogical(NewClass)
h.Class = cellstr(num2str(NewClass(:), '%-d'));
elseif isa(NewClass, 'containers.Map');
[uClass, ~, ClassNo] = unique(g.Class, 'stable');
for i=1:max(ClassNo)
h.Class(ClassNo==i) = {NewClass(uClass{i})};
end
else
h.Class = NewClass;
end
end
function h = MedianInClass(g)
% h = MedianInClass(g)
% replaces expression of every gene with the median in that class
h = g;
[ClassNames, ~, ClassNum] = unique(g.Class);
for k=1:length(g.Class);
MyCells = find(ClassNum==k);
h.GeneExp(:,MyCells) = repmat(median(g.GeneExp(:,MyCells),2), [1 length(MyCells)]);
end
end
function [h, Cells] = CellSubset(g, varargin)
% [h, CellIDs] = CellSubset(g, Cells, Exclude)
% make a new array corresponding subset of cells
% see IdentifyCells for more info on how the Cells argument is
% parsed
%
% optional output argument Cells tells you which ones were
% picked
Cells = g.IdentifyCells(varargin{:});
h = GeneSet;
h.GeneExp = g.GeneExp(:,Cells);
h.GeneName = g.GeneName;
h.nGenes = g.nGenes;
h.nCells = length(Cells);
if ~isempty(g.CellName), h.CellName = g.CellName(Cells); end
if ~isempty(g.tSNE), h.tSNE = g.tSNE(:,Cells); end
if ~isempty(g.CellInfo)
fn = fieldnames(g.CellInfo);
for i=1:length(fn)
Data = getfield(g.CellInfo, fn{i});
h.CellInfo = setfield(h.CellInfo, fn{i}, Data(Cells));
end
end
if ~isempty(g.Class)
h.Class = g.Class(Cells);
end
if ~isempty(g.Excluded)
h.Excluded = g.Excluded.CellSubset(Cells);
end
end
function h = SortByClass(g, ClassOrder)
% h = SortByClass(ClassOrder)
%
% reorders cells by their class
% ClassOrder should be a cell array of strings saying what
% order the classes should be in. Default is alphabetical
if nargin<2
ClassOrder = unique(g.Class);
end
[~, ClassNumber] = ismember(g.Class, ClassOrder);
[~, CellOrder] = sort(ClassNumber);
h = g.CellSubset(CellOrder);
end
function h = Permute(g, Cells)
% h = Permuate(g, Cells)
%
% randomizes expression of all genes, only between the cells in Cells
% (default is all of them)
% preprocessing to get cell list
if nargin<2
Cells = 1:g.nCells;
else
Cells = g.IdentifyCells(Cells);
end
% now randomize
h = g;
nCols = length(Cells);
for i=1:h.nGenes
h.GeneExp(i,Cells) = h.GeneExp(i,Cells(randperm(nCols)));
end
end
function h = Randomize(g)
% h = Randomize(g)
%
% Randomizes gene expression using Patefield's algorithm, so
% that all cells and genes have same total expression
h = g;
% find find and exclude zero genes
NonZeroGenes = find(any(h.GeneExp>0,2));
% make expression submatrix for these
Expression = h.GeneExp(NonZeroGenes,:);
% now apply Patefield's algorithm
[~,~,RandomizedExpression,Error] = Patefield(size(Expression,1), size(Expression,2), sum(Expression, 2), sum(Expression, 1), 0, 0);
if (Error); error('Patefield algorithm error'); end
h.GeneExp(NonZeroGenes,:) = RandomizedExpression;
end
function h = Power(g, p);
% Power(p);
% transform expression by raising each gene to power p (usually<1)
h = g;
h.GeneExp = g.GeneExp.^p;
end
function h = Log(g, c);
% Log(c);
% transform expression by log(x + c)
h = g;
h.GeneExp = log(g.GeneExp+c);
end
function h = Clip(g, Val, Genes);
% Clip(Val, Genes)
%
% maxes out gene expression at Val for genes in Genes (default
% all)
h = g;
if nargin<3
Genes = 1:g.nGenes;
else
Genes = g.NamesToIDs(Genes);
end
h.GeneExp(Genes,:) = min(h.GeneExp(Genes,:),Val);
end
function h = Saturate(g, Val, Genes);
% Saturate(Val, Genes)
%
% applies a Naka-Rushton function to make expression saturate
% at Val (default 50). Runs only on genes Genes.
%
% if you pass Val=inf, it won't do anything.
if nargin<2
Val = 50;
end
if ~isfinite(Val)
h = g;
return;
end
if nargin<3
Genes = 1:g.nGenes;
else
Genes = g.NamesToIDs(Genes);
end
h = g;
h.GeneExp(Genes,:) = Val*h.GeneExp(Genes,:)./(Val + h.GeneExp(Genes,:));
end
function h = ScaleGene(g, p, q);
% transform expression by dividing the expression of each gene
% by its norm raised to power p
% optional input q uses the Lq norm (default 1);
if nargin<3; q=1; end;
h = g;
Norm = mean(g.GeneExp.^q,2).^(1/q);
h.GeneExp = bsxfun(@rdivide, g.GeneExp, Norm.^p + eps);
end
function h = ScaleCell(g, p, q);
% transform expression by dividing the expression of each gene
% by its mean value raised to power p, then rescaling so total
% expression of entire set is constant.
%
% optional input q uses the Lq norm (default 1);
if nargin<3; q=1; end;
Norm = mean(g.GeneExp.^q,1).^(1/q);
Not0Norm = (Norm>0);
h = g.CellSubset(Not0Norm);
h.GeneExp = bsxfun(@rdivide, g.GeneExp(:,Not0Norm), Norm(Not0Norm).^p);
ScaleFac = (sum(g.GeneExp(:).^q)/sum(h.GeneExp(:).^q)).^(1/q);
h.GeneExp = h.GeneExp*ScaleFac;
end
function h = vertcat(varargin)
% concatenate the genes in multiple GeneSets into one
h = varargin{1};
for i=2:length(varargin)
h.GeneExp = [h.GeneExp; varargin{i}.GeneExp];
h.GeneName = [h.GeneName; varargin{i}.GeneName];
h.GeneInfo = [h.GeneInfo; varargin{i}.GeneInfo];
h.nGenes = h.nGenes + varargin{i}.nGenes;
end
end
function h = horzcat(g1, g2, varargin)
% concatenate the cells in multiple GeneSets into one
% note that unlike Merge, this DOES require the genes are in the
% same order (which it checks) But it is a lot faster.
%
% if any CellInfo fields don't match, they are discarded
if nargin>2 % recursion if more than 2 inputs
h = horzcat(horzcat(g1, g2), varargin{:});
return;
end
h = GeneSet;
h.tSNE = []; % this is meaningless when you merge datasets
if ~isequal(g1.GeneName, g2.GeneName)
error(sprintf('Gene Names mismatch'));
end
h.nGenes = g2.nGenes;
h.GeneName = g2.GeneName;
h.GeneInfo= g2.GeneInfo;
h.GeneExp = [g1.GeneExp, g2.GeneExp];
h.nCells = g1.nCells + g2.nCells;
h.Class = vertcat(g1.Class(:), g2.Class(:));
h.CellName = vertcat(g1.CellName(:), g2.CellName(:));
if ~isempty(g1.CellInfo) & ~isempty(g2.CellInfo)
% merge cell info (this is the hard part)
CellInfoFields = intersect(fieldnames(g1.CellInfo), fieldnames(g2.CellInfo));
NewCellInfo = struct;
for i=1:length(CellInfoFields(:));
f = CellInfoFields{i};
% if isfield(g2.CellInfo, f)
c1 = getfield(g1.CellInfo,f);
if length(c1)~=g1.nCells
error(sprintf('CellInfo.%s has %d entries instead of %d', ...
f, length(c1), g1.nCells));
end
c2 = getfield(g2.CellInfo,f);
if length(c2)~=g2.nCells
error(sprintf('Arg1 CellInfo.%s has %d entries instead of %d', ...
f, length(c2), g2.nCells));
end
if isnumeric(c1) & ~isnumeric(c2) % this is really annoying
c1 = cellstr(num2str(c1));
elseif isnumeric(c2) & ~isnumeric(c1) % this is really annoying
c2 = cellstr(num2str(c2));
end
NewCellInfo = setfield(NewCellInfo, f, [c1; c2]);
% else
% fprintf('Deleting CellInfo field %s\n', f);
% % h.CellInfo = rmfield(h.CellInfo, f);
% end
end
h.CellInfo = NewCellInfo;
MissingFields = setdiff(union(fieldnames(h.CellInfo), fieldnames(g2.CellInfo)), CellInfoFields);
if ~isempty(MissingFields)
wString = ['Dropping CellInfo fields ' ...
sprintf('%s ', MissingFields{:}) 'which are not in all inputs'];
warning(wString);
end
end
end
function l = Merge(g1, varargin);
% h = g1.merge(g2, ...);
% merge together the cells in two or more GeneSets
%
% note that the genes are NOT assumed to be in the same order
% use this for example to merge GEO microarray data into GeneSets
%
% for every gene in g2 that matches one in g1 by name, an entry
% is added. All other genes set to NaN
%
% optional last argument says which genes to keep:
% 'any' (default): any gene in any input; if not present, set to NaN
% 'first': keep only genes from g1
% 'all': keep only genes in all genesets
if any(strcmp(varargin(end), {'any', 'all', 'first'}))
Option = varargin(end);
varargin = varargin(1:end-1);
else
Option = 'any';
end
% get list of all genes to keep
GeneList = g1.GeneName(:);
for i=1:length(varargin)
if strcmp(Option, 'any')
GeneList = union(GeneList(:), varargin{i}.GeneName);
elseif strcmp(Option, 'all')
GeneList = intersect(GeneList(:), varargin{i}.GeneName);
end
end
% now reprocess each one
gNew{1} = g1;
gNew(2:length(varargin)+1) = varargin;
for i=1:length(gNew)
[MyGenes, MyIndices] = ismember(GeneList, gNew{i}.GeneName);
NewExp = nan(length(GeneList), gNew{i}.nCells);
NewExp(MyGenes,:) = gNew{i}.GeneExp(MyIndices(MyGenes),:);
gNew{i}.GeneExp = NewExp;
gNew{i}.GeneName = GeneList;
gNew{i}.nGenes = length(GeneList);
end
% now use horzcat
l = horzcat(gNew{:});
end
% if nargin>=3
% l = g1.Merge(g2).Merge(varargin{:});
% return;
% end
%
% h = g1;
% h.nCells = g1.nCells + g2.nCells;
% h.GeneExp = zeros(h.nGenes, h.nCells);
% h.GeneExp(:,1:g1.nCells) = g1.GeneExp;
% h.CellName = vertcat(h.CellName(:), g2.CellName(:));
% % should copy stuff for CellInfo from horzcat
%
% NewRange = (g1.nCells+1):h.nCells;
% ArrayGenes = zeros(g1.nGenes,1);
% for i=1:g1.nGenes
% Matches = find(strcmp(g1.GeneName{i}, g2.GeneName));
% if length(Matches)>=1
% h.GeneExp(i,NewRange) = sum(g2.GeneExp(Matches,:),1);
% ArrayGenes(i) = 1;
% else
% h.GeneExp(i,NewRange) = NaN;
% end
% end
%
% l = h.GeneSubset(find(ArrayGenes));
% end
function h = AddUnitGene(g)
% add a new gene containing all ones to the bottom of the list
% (for use in regression etc)
h = g;
h.nGenes = g.nGenes+1;
h.GeneExp(h.nGenes,:) = 1;
h.GeneName{h.nGenes} = 'Unit';
end
function h = AddGenes(g, Expn, Names)
% h = AddGenes(g, Expn, Names)
%
% add pseudogenes to a Geneset.
% Expn: nAddGenes x nCells matrix of expression levels
% Names: nAddGenes length cell array of gene names (strings)
h = g;
h.GeneExp = [g.GeneExp; Expn];
h.GeneName = vertcat(g.GeneName, Names(:));
end
function Scatter(g, xGene, yGene, Group, Jitter, varargin);
% Scatter(xGene, yGene, Group, Jitter, varargin);
%
% plot a scatter plot. xGene is a numeric index or name of the
% gene to plot on the x-axis, yGene same for y axis.
% or they can just be an array of length nCells.
%
% Group determines colors (see gscatter)
%
% Jitter defaults to 0.3
% varargin is passed to gscatter
if nargin<5
Jitter = 0.3;
end
if isnumeric(xGene) & length(xGene)==g.nCells
xData = xGene(:)';
xl = 'Data';
else
%xData = g.GeneExp(g.NamesToIDs(xGene),:);
xData = g.Exp(xGene);
xl = g.IDsToNames(xGene);
end
if isnumeric(yGene) & length(yGene)==g.nCells
yData = yGene(:)';
yl = 'Data';
else
%yData = g.GeneExp(g.NamesToIDs(yGene),:);
yData = g.Exp(yGene);
yl = g.IDsToNames(yGene);
end
nPoints = length(xData);
if nargin<4 | isempty(Group)
if ~isempty(g.Class)
Group = g.Class;
else
Group = ones(nPoints, 1);
end
end
% symbols: alternate between four of them to help when colors
% are similar
nGroups = length(unique(Group));
ColorMap = HsvNotYellow(ceil(nGroups*1.2)); % 1.2 is to avoid confusion of beginning and end
Sym = repmat('o+*hxsd^<v>p', [1 ceil(nGroups/12)]);
hold off
if isempty(Group) | length(Group)==1
gscatter(xData+rand(1,g.nCells)*Jitter, yData+rand(1,g.nCells)*Jitter, varargin);
else
gscatter(xData+rand(1,g.nCells)*Jitter, yData+rand(1,g.nCells)*Jitter, Group, ColorMap, Sym', varargin);%, 'interpreter', 'none');
end
xlabel(xl, 'Interpreter', 'none');
ylabel(yl, 'Interpreter', 'none');
% now fit line
if g.nCells>0
[b bint r rint stats] = regress(yData(:), [xData(:), ones(nPoints,1)]);
[rho p] = corr(yData(:), xData(:), 'type', 'Spearman');
title(sprintf('Psn: y = %.2fx + %.0f. R^2 = %.2f. p = %.3f. Spmn R=%.2f, p=%.3f.\n', b, stats([1 3]), rho, p));
hold on;
plot(xlim, xlim*b(1) + b(2),'k');
end
end
function [h, ax, bigax] = PlotMatrix(g, IDs, Group, Jitter, ColorMap, Sym, varargin);
% [h, ax, bigax] = PlotMatrix(IDs, Group, Jitter, ColorMap, Sym, varargin);
%
% makes a scatter plot matrix of genes with specified IDs
% IDs can be gene numbers or names. If it is a 2-element cell array, will do a
% scatter of one vs. the other rather than a square matrix
%
% Group says what color to plot. If it has length the number of
% cells, it means one per cell. Otherwise, it should be a cell
% array specifying a list of class branch names to highlight in color,
% on top of all others in gray. Defaults to g.Class
%
% Jitter defaults to .3
% Colors defaults to hsv for the number of classes,
% Sym defaults to alternating. If you pass a GeneSet to Colors, it will
% choose colors and symbols according to that - so do if you
% call with a subset
%
% varargin is passed to gplotmatrix - so Siz, Doleg, Dispopt, ...
if nargin<3 | isempty(Group)
if ~isempty(g.Class)
Group = g.Class;
else
Group = ones(g.nCells, 1);
end
end
if length(Group)<g.nCells
% assign groups according to input classes
GpNames = Group;
% assign all cells by default to group 0
Group = cell(g.nCells,1);
Group(1:g.nCells) = {'..'};
% assign all others
WhichWhere = zeros(g.nCells, 1);
for i=1:length(GpNames)
MyCells = strncmp(GpNames{i},g.Class, length(GpNames{i}));
Group(MyCells)=GpNames(i);
WhichWhere(MyCells) = i;
end
% now put them in the order of the classes
[~,order] = sort(WhichWhere);
g = g.CellSubset(order);
Group = Group(order);
end
if nargin<4 | isempty(Jitter)
Jitter = 0;
end
nGroups = length(unique(Group));
if nargin<5 | isempty(ColorMap);
% ColorMap = hsv(nGroups);
% TooYellow = find(ColorMap(:,1)>.7 & ColorMap(:,2)>.7);
% ColorMap(TooYellow,:) = ColorMap(TooYellow,:)*diag([.5 .5 .7]);
ColorMap = HsvNotYellow(ceil(nGroups*1.2));
end
if nargin<6 | isempty(Sym)
Sym = repmat('o+svp', [1 ceil(nGroups/6)]);
end
if strcmp(class(ColorMap), 'GeneSet')
nG0 = length(unique(ColorMap.Class));
ColorMap0 = HsvNotYellow(ceil(nG0*1.2));
Sym0 = repmat('o+svp', [1 ceil(nG0/6)]);
[~, MyClasses] = ismember(unique(Group, 'stable'), unique(ColorMap.Class,'stable'));
ColorMap = ColorMap0(MyClasses,:);
Sym = Sym0(MyClasses);
end
if length(IDs)== 2 & iscell(IDs)
% IDs1 = g.NamesToIDs(IDs{1});
% IDs2 = g.NamesToIDs(IDs{2});
IDs1 = IDs{1};
if isstr(IDs1); IDs1 = {IDs1}; end
IDs2 = IDs{2};
if isstr(IDs2); IDs2 = {IDs2}; end
nIDs1 = length(IDs1);
nIDs2 = length(IDs2);
[h, ax, bigax] = gplotmatrix(g.Exp(IDs1)' + rand(g.nCells, nIDs1)*Jitter, ...
g.Exp(IDs2)' + rand(g.nCells, nIDs2)*Jitter, Group, ColorMap, Sym, varargin{:});
set(ax, 'box', 'off');
for i=1:nIDs1
xlabel(ax(nIDs2,i), g.IDsToNames(IDs1(i)), 'Interpreter', 'none');
end
for i=1:nIDs2
ylabel(ax(i,1), g.IDsToNames(IDs2(i)), 'Interpreter', 'none');
end
elseif size(IDs,2)==1 | size(IDs,1)==1
% single vector of IDs
% IDs = g.NamesToIDs(IDs);
% nIDs = length(IDs);
%
% [h, ax, bigax] = gplotmatrix(g.GeneExp(IDs,:)' + rand(g.nCells, nIDs)*Jitter, ...
% [], Group, ColorMap, Sym, varargin{:});
nIDs = length(IDs);
[h, ax, bigax] = gplotmatrix(g.Exp(IDs)' + rand(g.nCells, nIDs)*Jitter, ...
[], Group, ColorMap, Sym, varargin{:});
set(ax, 'box', 'off');
for i=1:nIDs
xlabel(ax(nIDs,i), g.IDsToNames(IDs(i)), 'Interpreter', 'none');
ylabel(ax(i,1), g.IDsToNames(IDs(i)), 'Interpreter', 'none');
end
else
error('PlotMatrix needs a vector of IDs or a 2-element cell array');
end
end
function Ggobi(g, Genes, Group);
% GGbobi(IDs)
% launch a ggobi process to visualize specified genes
Genes = g.NamesToIDs(Genes);
GeneNames = g.IDsToNames(Genes);
nGenes = length(Genes);
if nargin<3 | isempty(Group)
if ~isempty(g.Class)
Group = g.Class;
else
Group = cellstr(num2str(ones(g.nCells,1)));
end
end