Repository navigation
Expand file tree
/
Copy pathdat.cpp
More file actions
2164 lines (1931 loc) · 74 KB
/
Copy pathdat.cpp
File metadata and controls
2164 lines (1931 loc) · 74 KB
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
/*****************************************************************************
* This file is provided under the Creative Commons Attribution 3.0 license.
*
* You are free to share, copy, distribute, transmit, or adapt this work
* PROVIDED THAT you attribute the work to the authors listed below.
* For more information, please see the following web page:
* http://creativecommons.org/licenses/by/3.0/
*
* This file is a component of the Sleipnir library for functional genomics,
* authored by:
* Curtis Huttenhower ([email protected])
* Mark Schroeder
* Maria D. Chikina
* Olga G. Troyanskaya ([email protected], primary contact)
*
* If you use this library, the included executable tools, or any related
* code in your work, please cite the following publication:
* Curtis Huttenhower, Mark Schroeder, Maria D. Chikina, and
* Olga G. Troyanskaya.
* "The Sleipnir library for computational functional genomics"
*****************************************************************************/
#include "stdafx.h"
#include "dat.h"
#include "genome.h"
#include "statistics.h"
#include "annotation.h"
#include "color.h"
#include "meta.h"
namespace Sleipnir {
const char CDatImpl::c_acComment[] = "#";
const CColor &CDatImpl::c_ColorMax = CColor::c_Red;
const CColor &CDatImpl::c_ColorMin = CColor::c_Green;
const CColor &CDatImpl::c_ColorMid = CColor::c_Black;
static const struct {
const char *m_szExtension;
const CDat::EFormat m_eFormat;
} c_asFormats[] = {
{"dat", CDat::EFormatText},
{"das", CDat::EFormatSparse},
{"pcl", CDat::EFormatPCL},
{"qdab", CDat::EFormatQdab},
{NULL, CDat::EFormatBinary}
};
size_t CDatImpl::MapGene(TMapStrI &mapGenes, TVecStr &vecGenes, const std::string &strToken) {
TMapStrI::iterator iterGenes;
size_t iRet;
if ((iterGenes = mapGenes.find(strToken)) == mapGenes.end()) {
iRet = mapGenes.size();
mapGenes[strToken] = iRet;
vecGenes.push_back(strToken);
} else
iRet = iterGenes->second;
return iRet;
}
void CDatImpl::ResizeNaN(TAF &vecf, size_t iLast) {
size_t i;
if ((i = vecf.size()) > iLast)
return;
vecf.resize(iLast + 1);
for (; i < vecf.size(); ++i)
vecf[i] = CMeta::GetNaN();
}
void CDatImpl::DabGene(std::istream &istm, char *acBuffer) {
size_t i;
i = 0;
do
istm.seekg(1, ios_base::cur);
while ((acBuffer[i++] = istm.get()));
}
CDatImpl::~CDatImpl() {
Reset();
}
void CDatImpl::Reset() {
m_Data.Reset();
m_vecstrGenes.clear();
if (m_pPCL && m_fPCLMemory)
delete m_pPCL;
m_pPCL = NULL;
if (m_pMeasure && m_fMeasureMemory)
delete m_pMeasure;
m_pMeasure = NULL;
CMeta::Unmap(m_abData, m_hndlData, m_iData);
m_abData = NULL;
m_hndlData = 0;
m_iData = 0;
if (m_aadData)
delete[] m_aadData;
m_aadData = NULL;
}
void CDatImpl::SlimCache(const CSlim &Slim, vector <vector<size_t>> &vecveciGenes) const {
size_t iS, iG;
vecveciGenes.resize(Slim.GetSlims());
for (iS = 0; iS < vecveciGenes.size(); ++iS) {
vecveciGenes[iS].resize(Slim.GetGenes(iS));
for (iG = 0; iG < vecveciGenes[iS].size(); ++iG)
vecveciGenes[iS][iG] = GetGene(Slim.GetGene(iS, iG).GetName());
}
}
/*!
* \brief
* Construct a CDat from the given ontology slim.
*
* \param Slim
* Set of ontology terms from which to generate a CDat.
*
* \returns
* True if CDat was generated successfully.
*
* Generates a CDat over all genes within the given slim. Gene pairs coannotated to at least one slim term
* are given a value of 1; all other gene pairs are given a value of 0. This is useful for rapidly generating
* gold standards from functional catalogs.
*
* \see
* IOntology
*/
bool CDat::Open(const CSlim &Slim) {
vector <string> vecstrGenes;
size_t iS1, iS2, iG1, iG2, iGene1, iGene2;
vector <vector<size_t>> vecveciGenes;
Reset();
Slim.GetGeneNames(vecstrGenes);
if (!Open(vecstrGenes))
return false;
SlimCache(Slim, vecveciGenes);
for (iS1 = 0; iS1 < Slim.GetSlims(); ++iS1) {
g_CatSleipnir().info("CDat::Open( ) processing slim: %s",
Slim.GetSlim(iS1).c_str());
for (iG1 = 0; iG1 < Slim.GetGenes(iS1); ++iG1) {
iGene1 = vecveciGenes[iS1][iG1];
for (iG2 = (iG1 + 1); iG2 < Slim.GetGenes(iS1); ++iG2)
Set(iGene1, vecveciGenes[iS1][iG2], 1);
for (iS2 = (iS1 + 1); iS2 < Slim.GetSlims(); ++iS2)
for (iG2 = 0; iG2 < Slim.GetGenes(iS2); ++iG2) {
iGene2 = vecveciGenes[iS2][iG2];
if (CMeta::IsNaN(Get(iGene1, iGene2)))
Set(iGene1, iGene2, 0);
}
}
}
return true;
}
/*!
* \brief
* Construct a CDat from the given ontology slims.
*
* \param SlimPositives
* Set of ontology terms from which to generate related gene pairs.
*
* \param SlimNonnegatives
* Set of ontology terms from which to generate agnostic gene pairs (neither related nor unrelated).
*
* \returns
* True if CDat was generated successfully.
*
* Generates a CDat over all genes within the given slims. Gene pairs coannotated to at least one positive
* slim term are given a value of 1, other gene pairs coannotated to at least one nonnegative slim term are
* given no value (NaN), and all other gene pairs are given a value of 0. This is useful for rapidly
* generating gold standards from functional catalogs.
*
* \see
* IOntology
*/
bool CDat::Open(const CSlim &SlimPositives, const CSlim &SlimNonnegatives) {
set <string> setstrGenes;
vector <string> vecstrGenes;
size_t iS1, iS2, iG1, iG2, iGene1, iGene2;
vector <vector<size_t>> vecveciGenes;
Reset();
SlimPositives.GetGeneNames(vecstrGenes);
setstrGenes.insert(vecstrGenes.begin(), vecstrGenes.end());
vecstrGenes.clear();
SlimNonnegatives.GetGeneNames(vecstrGenes);
setstrGenes.insert(vecstrGenes.begin(), vecstrGenes.end());
vecstrGenes.clear();
vecstrGenes.resize(setstrGenes.size());
copy(setstrGenes.begin(), setstrGenes.end(), vecstrGenes.begin());
if (!Open(vecstrGenes))
return false;
SlimCache(SlimPositives, vecveciGenes);
for (iS1 = 0; iS1 < SlimPositives.GetSlims(); ++iS1) {
g_CatSleipnir().info("CDat::Open( ) processing slim: %s",
SlimPositives.GetSlim(iS1).c_str());
for (iG1 = 0; iG1 < SlimPositives.GetGenes(iS1); ++iG1) {
iGene1 = vecveciGenes[iS1][iG1];
for (iG2 = (iG1 + 1); iG2 < SlimPositives.GetGenes(iS1); ++iG2)
Set(iGene1, vecveciGenes[iS1][iG2], 1);
}
}
vecveciGenes.clear();
SlimCache(SlimNonnegatives, vecveciGenes);
for (iS1 = 0; iS1 < SlimNonnegatives.GetSlims(); ++iS1) {
g_CatSleipnir().info("CDat::Open( ) processing slim: %s",
SlimNonnegatives.GetSlim(iS1).c_str());
for (iG1 = 0; iG1 < SlimNonnegatives.GetGenes(iS1); ++iG1) {
iGene1 = vecveciGenes[iS1][iG1];
for (iS2 = (iS1 + 1); iS2 < SlimNonnegatives.GetSlims(); ++iS2)
for (iG2 = 0; iG2 < SlimNonnegatives.GetGenes(iS2); ++iG2) {
iGene2 = vecveciGenes[iS2][iG2];
if (CMeta::IsNaN(Get(iGene1, iGene2)))
Set(iGene1, iGene2, 0);
}
}
}
return true;
}
/*!
* \brief
* Construct a CDat from the given known gene relationships and gene sets.
*
* \param DatKnown
* Known pairwise scores, either positive or negative as indicated.
*
* \param vecpOther
* Gene sets, either positive or nonnegative as indicated (possibly empty).
*
* \param Genome
* Genome containing all genes of interest.
*
* \param fKnownNegatives
* If true, DatKnown contains known negative gene pairs (0 scores); if false, it contains known related
* gene pairs (1 scores). In the former case, positives are generated from pairs coannotated to the
* given gene sets; in the latter, negatives are generated from pairs not coannotated to the given gene
* sets.
*
* \param fIncident
* If true, only allow negative pairs incident to at least one agnostic gene set. Otherwise,
* negative gene pairs can include any non-co-annotated genes.
*
* \returns
* True if CDat was generated successfully.
*
* Constructs a CDat by copying either the positive (1) or negative (0) values from DatKnown and calculating
* negatives or positives from vecpOther. In either case, values are calculated for all genes in the given
* genome.
* - If fKnownNegatives is true, negative (0) gene pairs are first copied from DatKnown. Then any other
* gene pair coannotated to at least one of the given gene sets is given a positive (1) score. Remaining
* gene pairs are given no value (NaN).
* - If fKnownNegatives is false, positive (1) gene pairs are first copied from DatKnown. Then any other
* gene pair coannotated to at least one of the given gene sets is given a missing (NaN) value. Remaining
* gene pairs are given a negative (0) score.
*/
bool CDat::Open(const CDat &DatKnown, const vector<CGenes *> &vecpOther, const CGenome &Genome,
bool fKnownNegatives, bool fIncident) {
size_t i, j, iOne, iTwo;
vector <size_t> veciGenes;
float d;
Reset();
Open(Genome.GetGeneNames());
for (i = 0; i < vecpOther.size(); ++i)
OpenHelper(vecpOther[i], 1);
if (!fKnownNegatives)
for (i = 0; i < GetGenes(); ++i)
for (j = (i + 1); j < GetGenes(); ++j)
Set(i, j, CMeta::IsNaN(Get(i, j)) ? 0 : CMeta::GetNaN());
veciGenes.resize(DatKnown.GetGenes());
for (i = 0; i < veciGenes.size(); ++i)
veciGenes[i] = GetGene(DatKnown.GetGene(i));
for (i = 0; i < DatKnown.GetGenes(); ++i) {
iOne = veciGenes[i];
for (j = (i + 1); j < DatKnown.GetGenes(); ++j) {
iTwo = veciGenes[j];
if (CMeta::IsNaN(d = DatKnown.Get(i, j))) {
if (fKnownNegatives && CMeta::IsNaN(Get(iOne, iTwo)))
Set(iOne, iTwo, 0);
} else if (fKnownNegatives == !d)
Set(iOne, iTwo, d);
}
}
if (fIncident) {
vector<float> vecfNegatives;
vecfNegatives.resize(GetGenes());
fill(vecfNegatives.begin(), vecfNegatives.end(), false);
for (i = 0; i < vecfNegatives.size(); ++i)
for (j = 0; j < vecpOther.size(); ++j)
if (vecpOther[j]->IsGene(GetGene(i))) {
vecfNegatives[i] = true;
break;
}
for (i = 0; i < vecfNegatives.size(); ++i)
if (DatKnown.GetGene(GetGene(i)) != -1)
vecfNegatives[i] = true;
for (i = 0; i < GetGenes(); ++i) {
if (vecfNegatives[i])
continue;
for (j = (i + 1); j < GetGenes(); ++j)
if (!(vecfNegatives[j] || Get(i, j))) {
Set(i, j, CMeta::GetNaN());
//cerr << "setting to NaN" << endl;
}
}
}
return true;
}
/*!
* \brief
* Construct a copy of the given CDat.
*
* \param Dat
* Data to be copied.
*
* \returns
* True if the copy was successful.
*/
bool CDat::Open(const CDat &Dat) {
size_t i;
if (!Open(Dat.GetGeneNames()))
return false;
for (i = 0; i < GetGenes(); ++i)
memcpy(Get(i), Dat.Get(i), (GetGenes() - i - 1) * sizeof(*Get(i)));
return true;
}
/*!
* \brief
* Construct a CDat from the given gene sets.
*
* \param vecpPositives
* Set of gene sets from which to generate related gene pairs.
*
* \param vecpNonnegatives
* Set of ontology terms from which to generate agnostic gene pairs (neither related nor unrelated),
* possibly empty.
*
* \param dPValue
* Hypergeometric p-value of overlap below which nonnegative gene set pairs are considered agnostic rather
* than negative.
*
* \param Genome
* Genome containing all genes of interest.
*
* \param fIncident
* If true, only allow negative pairs incident to at least one agnostic gene set. Otherwise,
* negative gene pairs can include any non-co-annotated genes.
*
* \returns
* True if CDat was generated successfully.
*
* Generates a CDat over all genes in the given genome in which:
* - Any gene pair coannotated to at least one positive gene set is assigned value 1.
* - Any other gene pair coannotated to at least one nonnegative gene set is assigned no value (NaN).
* - Any other gene pair annotated to nonnegative gene sets with hypergeometric p-value of overlap less than
* the given cutoff is assigned no value (NaN).
* - Any other gene pair is assigned value 0.
* This is useful for rapidly generating gold standards from gene sets of interest: any gene pair known to
* participate in some function of interest will be marked as related, any gene pair known to participate
* in two unrelated functions will be marked as unrelated, and other gene pairs will be left unmarked.
*/
bool CDat::Open(const vector<CGenes *> &vecpPositives, const vector<CGenes *> &vecpNonnegatives,
float dPValue, const CGenome &Genome, bool fIncident) {
size_t i, j, k, iOne, iTwo, iOverlap;
float d;
const CGenes *pBig;
const CGenes *pSmall;
Reset();
Open(Genome.GetGeneNames());
for (i = 0; i < vecpPositives.size(); ++i)
OpenHelper(vecpPositives[i], 1);
if (vecpNonnegatives.size()) {
for (i = 0; i < vecpNonnegatives.size(); ++i)
OpenHelper(vecpNonnegatives[i], 0);
if (dPValue > 0)
for (i = 0; i < vecpPositives.size(); ++i) {
iOne = vecpPositives[i]->GetGenes();
for (j = (i + 1); j < vecpPositives.size(); ++j) {
iTwo = vecpPositives[j]->GetGenes();
if (iOne < iTwo) {
pSmall = vecpPositives[i];
pBig = vecpPositives[j];
} else {
pSmall = vecpPositives[j];
pBig = vecpPositives[i];
}
for (iOverlap = k = 0; k < pSmall->GetGenes(); ++k)
if (pBig->IsGene(pSmall->GetGene(k).GetName()))
iOverlap++;
if (CStatistics::HypergeometricCDF(iOverlap, iOne, iTwo, GetGenes()) < dPValue)
OpenHelper(pBig, pSmall, 0);
}
}
for (i = 0; i < GetGenes(); ++i)
for (j = (i + 1); j < GetGenes(); ++j)
if (CMeta::IsNaN(d = Get(i, j)))
Set(i, j, 0);
else if (!d)
Set(i, j, CMeta::GetNaN());
if (fIncident) {
vector<float> vecfNegatives;
vecfNegatives.resize(GetGenes());
fill(vecfNegatives.begin(), vecfNegatives.end(), false);
for (i = 0; i < vecfNegatives.size(); ++i)
for (j = 0; j < vecpNonnegatives.size(); ++j)
if (vecpNonnegatives[j]->IsGene(GetGene(i))) {
vecfNegatives[i] = true;
break;
}
for (i = 0; i < GetGenes(); ++i) {
if (vecfNegatives[i])
continue;
for (j = (i + 1); j < GetGenes(); ++j)
if (!(vecfNegatives[j] || Get(i, j)))
Set(i, j, CMeta::GetNaN());
}
}
}
return true;
}
void CDatImpl::OpenHelper(const CGenes *pGenes, float dValue) {
vector <size_t> veciGenes;
size_t i, j, iOne, iTwo;
veciGenes.resize(pGenes->GetGenes());
for (i = 0; i < veciGenes.size(); ++i)
veciGenes[i] = GetGene(pGenes->GetGene(i).GetName());
for (i = 0; i < veciGenes.size(); ++i) {
iOne = veciGenes[i];
for (j = (i + 1); j < veciGenes.size(); ++j) {
iTwo = veciGenes[j];
if (CMeta::IsNaN(Get(iOne, iTwo)))
Set(iOne, iTwo, dValue);
}
}
}
void CDatImpl::OpenHelper(const CGenes *pOne, const CGenes *pTwo, float dValue) {
vector <size_t> veciOne, veciTwo;
size_t i, j, iOne, iTwo;
veciOne.resize(pOne->GetGenes());
for (i = 0; i < veciOne.size(); ++i)
veciOne[i] = GetGene(pOne->GetGene(i).GetName());
veciTwo.resize(pTwo->GetGenes());
for (i = 0; i < veciTwo.size(); ++i)
veciTwo[i] = GetGene(pTwo->GetGene(i).GetName());
for (i = 0; i < veciOne.size(); ++i) {
iOne = veciOne[i];
for (j = 0; j < veciTwo.size(); ++j) {
iTwo = veciTwo[j];
if (CMeta::IsNaN(Get(iOne, iTwo)))
Set(iOne, iTwo, dValue);
}
}
}
/*!
* \brief
* Open a CDat stored in the given stream with the given format, processing missing values and duplicates as
* specified.
*
* \param istm
* Stream from which CDat is loaded.
*
* \param eFormat
* Format in which the stream should be parsed.
*
* \param dDefault
* Default value inserted for missing pairs (DAT format only).
*
* \param fDuplicates
* If true, allow duplicates (DAT format only), ignoring all but the last value for each gene pair.
*
* \param iSkip
* If the given stream contains a PCL, the number of columns to skip between the ID and experiments.
*
* \param fZScore
* If true and the given stream contains a PCL, z-score similarity measures after pairwise calculation.
*
* \param fSeek
* If true, read by seeking in the file, particularly useful if reading a few values, since there is no
* need to read the entire file. (for binary format only)
*
* \returns
* True if CDat was successfully opened.
*
* Opens a CDat from the given stream with the given format.
*
* \remarks
* dDefault and fDuplicates are ignored for non-DAT formats; iSkip and fZScore are ignored for non-PCL formats.
* Specifying the format incorrectly will generally cause Bad Things.
*
* \see
* Save | CPCL
*/
bool CDat::Open(std::istream &istm, EFormat eFormat, float dDefault, bool fDuplicates, size_t iSkip,
bool fZScore, bool fSeek) {
switch (eFormat) {
case EFormatText:
return OpenText(istm, dDefault, fDuplicates);
case EFormatPCL:
return OpenPCL(istm, iSkip, fZScore);
case EFormatSparse:
return OpenSparse(istm);
case EFormatQdab:
return OpenQdab(istm);
default:
break;
}
if (fSeek) {
m_fSeek = true;
}
return OpenBinary(istm, fSeek);
}
bool CDatImpl::OpenPCL(std::istream &istm, size_t iSkip, bool fZScore) {
Reset();
m_pPCL = new CPCL();
if (!m_pPCL->Open(istm, iSkip))
return false;
m_pMeasure = new CMeasurePearNorm();
m_fMeasureMemory = true;
if (fZScore) {
size_t iN;
double dAve, dStd;
AveStd(dAve, dStd, iN);
delete m_pMeasure;
m_pMeasure = new CMeasurePearNorm(dAve, dStd);
}
return true;
}
/*!
* \brief
* Construct a new CDat backed by the given PCL and similarity measure.
*
* \param PCL
* PCL from which CDat genes and pairwise values are drawn.
*
* \param pMeasure
* Similarity measure used to calculate pairwise scores between genes.
*
* \param fMeasureMemory
* If true, the CDat is responsible for freeing the given similarity measure.
*
* \returns
* True if CDat was generated successfully.
*
* This opens a new CDat without precalculated similarity scores; the CDat retains a reference to the given
* PCL and similarity measure and calculates pairwise scores as needed. This can greatly reduce the amount
* of memory required by the CDat, but it can increase runtime when specific pairwise values are requested
* repeatedly.
*
* \remarks
* fMeasureMemory should be false if a static or stack-based similarity measure object is used; it can be
* set to true for cloned/new allocated similarity measure objects that should be cleaned up with the CDat.
* The given PCL is not copied and should thus not be destroyed before the current CDat.
*/
bool CDat::Open(const CPCL &PCL, const IMeasure *pMeasure, bool fMeasureMemory) {
Reset();
m_pPCL = (CPCL *) &PCL;
m_fPCLMemory = false;
m_pMeasure = pMeasure;
m_fMeasureMemory = fMeasureMemory;
return true;
}
bool CDatImpl::OpenText(std::istream &istm, float dDefault, bool fDuplicates) {
const char *pc;
char *pcTail;
char *acBuf;
string strToken, strCache, strValue;
TMapStrI mapGenes;
size_t iOne, iTwo, i;
float dScore;
TAAF vecvecfScores;
Reset();
acBuf = new char[c_iBufferSize];
while (istm.peek() != EOF) {
istm.getline(acBuf, c_iBufferSize - 1);
strToken = OpenToken(acBuf, &pc);
if (!strToken.length())
break;
if (strToken == c_acComment)
continue;
if (strToken != strCache) {
strCache = strToken;
iOne = MapGene(mapGenes, m_vecstrGenes, strToken);
}
strToken = OpenToken(pc, &pc);
if (!strToken.length()) {
Reset();
delete[] acBuf;
return false;
}
iTwo = MapGene(mapGenes, m_vecstrGenes, strToken);
strValue = OpenToken(pc);
if (!strValue.length()) {
if (CMeta::IsNaN(dScore = dDefault)) {
Reset();
delete[] acBuf;
return false;
}
} else if (!(dScore = (float) strtod(strValue.c_str(), &pcTail)) &&
(pcTail != (strValue.c_str() + strValue.length()))) {
Reset();
delete[] acBuf;
return false;
}
i = ((iOne > iTwo) ? iOne : iTwo);
if (vecvecfScores.size() <= i)
vecvecfScores.resize(i + 1);
ResizeNaN(vecvecfScores[iOne], i);
ResizeNaN(vecvecfScores[iTwo], i);
if (!CMeta::IsNaN(vecvecfScores[iOne][iTwo]) && (vecvecfScores[iOne][iTwo] != dScore)) {
g_CatSleipnir().error("CDatImpl::OpenText( ) duplicate genes %s, %s (%g:%g)",
strCache.c_str(), strToken.c_str(), vecvecfScores[iOne][iTwo],
dScore);
if (!fDuplicates) {
Reset();
delete[] acBuf;
return false;
}
}
vecvecfScores[iOne][iTwo] = vecvecfScores[iTwo][iOne] = dScore;
}
delete[] acBuf;
m_Data.Initialize(GetGenes());
for (iOne = 0; iOne < GetGenes(); ++iOne)
for (iTwo = (iOne + 1); iTwo < GetGenes(); ++iTwo)
Set(iOne, iTwo, ((iTwo < vecvecfScores[iOne].size()) ?
vecvecfScores[iOne][iTwo] : CMeta::GetNaN()));
return true;
}
bool CDatImpl::OpenBinary(std::istream &istm, bool fSeek) {
size_t i;
float *adScores;
if (fSeek) {
if (!OpenHeader(istm)) {
cerr << "Error opening header" << endl;
return false;
}
return true;
}
if (!OpenGenes(istm, true, false))
return false;
g_CatSleipnir().debug("Reading genes");
m_Data.Initialize(GetGenes());
adScores = new float[GetGenes() - 1];
for (i = 0; (i + 1) < GetGenes(); ++i) {
istm.read((char *) adScores, sizeof(*adScores) * (GetGenes() - i - 1));
Set(i, adScores);
}
delete[] adScores;
return true;
}
/* still to be tested
* used for BINARY mode, and DAB file only, ie Float matrix
*/
bool CDatImpl::OpenHeader(std::istream &istm) {
if (!m_fSeek) {
cerr << "Don't know how you got here" << endl;
}
if (!OpenGenes(istm, true, false)) {
return false;
}
EstimateSeekPositions(istm);
return true;
}
/* still to be tested
* used for BINARY mode, and DAB file only, ie Float matrix
*/
float *CDatImpl::GetRowSeek(std::istream &istm, const size_t &ind) const {
if (!m_fSeek) {
cerr << "Don't know how you got here" << endl;
}
size_t iRow, iColumn;
size_t i, iNumGenes;
iNumGenes = GetGenes();
float *adScores = (float *) malloc(iNumGenes * sizeof(float));
size_t j;
for (i = 0; i < ind; i++) {
iRow = i;
iColumn = ind - 1;
size_t offset1 = m_iHeader + m_veciSeekPos[iRow] + iColumn * sizeof(float);
istm.seekg(offset1, ios_base::beg);
float v;
char *p = (char *) &v;
istm.read(p, sizeof(float));
adScores[i] = v;
}
adScores[ind] = CMeta::GetNaN();
int iSize = iNumGenes - (ind + 1);
if (iSize == 0) {
return adScores;
}
float *v = (float *) malloc(iSize * sizeof(float));
char *p = (char *) v;
istm.seekg(m_iHeader + m_veciSeekPos[ind], ios_base::beg);
istm.read(p, iSize * sizeof(float));
for (i = 0; i < iSize; i++) {
adScores[i + ind + 1] = v[i];
}
free(v);
return adScores;
}
/* still to be tested
* used for BINARY mode, and DAB file only, ie Float matrix
*/
float *CDatImpl::GetRowSeek(std::istream &istm, const std::string &strGene) const {
if (!m_fSeek) {
cerr << "Don't know how you got here" << endl;
}
size_t i;
size_t iNumGenes = GetGenes();
size_t ind;
if ((ind = GetGeneIndex(strGene)) == -1) {
return NULL; //missing gene
}
return GetRowSeek(istm, ind);
}
bool CDatImpl::OpenQdab(std::istream &istm) {
size_t iTotal, i, j, num_bins, num_bits, iPos;
float *adScores;
unsigned char tmp;
float *bounds;
unsigned char btmpf;
unsigned char btmpb;
unsigned char bufferA;
unsigned char bufferB;
float nan_val;
if (!OpenGenes(istm, true, false))
return false;
m_Data.Initialize(GetGenes());
// read the number of bins
istm.read((char *) &tmp, sizeof(char));
num_bins = (size_t) tmp;
//read the bin boundaries
bounds = new float[num_bins];
istm.read((char *) bounds, sizeof(float) * num_bins);
// number of bits required for each bin representation
num_bits = (size_t) ceil(log(num_bins) / log(2.0));
// add one more bit for NaN case
if (pow(2, num_bits) == num_bins)
++num_bits;
// set nan value
nan_val = pow(2, num_bits) - 1;
// read the data
adScores = new float[GetGenes() - 1];
istm.read((char *) &bufferA, sizeof(bufferA));
istm.read((char *) &bufferB, sizeof(bufferB));
for (iTotal = i = 0; (i + 1) < GetGenes(); ++i) {
for (j = 0; j < (GetGenes() - i - 1); ++j) {
iPos = (iTotal * num_bits) % 8;
// check bit data overflow??
if (iPos + num_bits > 8) {
btmpb = (bufferA << iPos);
btmpf = (bufferB >> (16 - num_bits - iPos)) << (8 - num_bits);
adScores[j] = ((btmpb | btmpf) >> (8 - num_bits));
++iTotal;
bufferA = bufferB;
istm.read((char *) &bufferB, sizeof(bufferB));
} else {
adScores[j] = (((bufferA << iPos) & 0xFF) >> (8 - num_bits));
++iTotal;
if (iPos + num_bits == 8) {
bufferA = bufferB;
istm.read((char *) &bufferB, sizeof(bufferB));
}
}
// check if value added was promised 2^#bits -1 (NaN value)
if (adScores[j] == nan_val)
adScores[j] = CMeta::GetNaN();
}
Set(i, adScores);
}
delete[] adScores;
delete[] bounds;
return true;
}
bool CDatImpl::OpenSparse(std::istream &istm) {
size_t i;
uint32_t j;
float d;
if (!OpenGenes(istm, true, false))
return false;
m_Data.Initialize(GetGenes());
for (i = 0; (i + 1) < GetGenes(); ++i) {
for (j = (i + 1); j < GetGenes(); ++j)
Set(i, j, CMeta::GetNaN());
while (true) {
istm.read((char *) &j, sizeof(j));
if (j == -1)
break;
istm.read((char *) &d, sizeof(d));
Set(i, j, d);
}
}
return true;
}
/*!
* \brief
* Open the genes from a CDat stored in the given file, guessing the format from the file's extension.
*
* \param szFile
* Filename from which CDat genes are loaded.
*
* \param iSkip
* If the given file is a PCL, the number of columns to skip between the ID and experiments.
*
* \returns
* True if genes were successfully loaded.
*
* Like Open, OpenGenes will guess the appropriate file format from the given filename's extension, but it
* will load only a CDat's size and gene list from the file. This is useful for rapidly obtaining gene
* lists and counts from large CDats without incurring the memory/time penalty of loading or memory mapping
* the whole file.
*
* \remarks
* Attempting to access a CDat's data after opening only its genes is a poor idea. If the extension is not
* recognized, DAB format is assumed.
*/
bool CDat::OpenGenes(const char *szFile, size_t iSkip) {
ifstream ifsm;
bool fBinary;
size_t i;
EFormat eFormat;
for (i = 0; c_asFormats[i].m_szExtension; ++i)
if (!strcmp(szFile + strlen(szFile) - strlen(c_asFormats[i].m_szExtension),
c_asFormats[i].m_szExtension))
break;
eFormat = c_asFormats[i].m_eFormat;
fBinary = (eFormat != EFormatText) && (eFormat != EFormatPCL);
ifsm.open(szFile, fBinary ? ios_base::binary : ios_base::in);
return OpenGenes(ifsm, fBinary, (eFormat == EFormatPCL));
}
/*!
* \brief
* Open the genes from a CDat stored in the stream with the given format.
*
* \param istm
* Stream from which genes are loaded.
*
* \param fBinary
* If true, assume DAB format.
*
* \param fPCL
* If true, assume PCL format.
*
* \returns
* True if genes were successfully loaded.
*
* Like Open, OpenGenes will load a CDat from the stream in the requested format, but it will load only the
* CDat's size and gene list from the stream. This is useful for rapidly obtaining gene lists and counts
* from large CDats without incurring the memory/time penalty of loading or memory mapping the whole file.
*
* \remarks
* Attempting to access a CDat's data after opening only its genes is a poor idea.
*
* \see
* CPCL
*/
bool CDat::OpenGenes(std::istream &istm, bool fBinary, bool fPCL) {
return CDatImpl::OpenGenes(istm, fBinary, fPCL);
}
bool CDatImpl::OpenGenes(std::istream &istm, bool fBinary, bool fPCL) {
size_t i, iToken;
uint32_t iCount;
string strToken, strCache;
float d;
const char *pc;
char *acBuf;
Reset();
if (fPCL) {
m_pPCL = new CPCL();
if (m_pPCL->Open(istm)) {
m_pMeasure = (IMeasure *) 1;
m_fMeasureMemory = false;
return true;
}
return false;
}
acBuf = new char[c_iBufferSize];
if (fBinary) {
istm.read((char *) &iCount, sizeof(iCount));
if (iCount > c_iGeneLimit) {
delete[] acBuf;
return false;
}
m_vecstrGenes.resize(iCount);
for (i = 0; i < iCount; ++i) {
DabGene(istm, acBuf);
m_vecstrGenes[i] = acBuf;
m_mapstrGenes[acBuf] = i;
}
} else {
set <string> setstrGenes;
set<string>::const_iterator iterGenes;
while (istm.peek() != EOF) {
istm.getline(acBuf, c_iBufferSize - 1);
for (iToken = 0; iToken < 3; ++iToken) {
strToken = OpenToken(acBuf, &pc);
if (!strToken.length())
break;
if (strToken != strCache) {
strCache = strToken;