-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGinRibbon_old.cs
3414 lines (2589 loc) · 128 KB
/
GinRibbon_old.cs
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
#undef CLICK_CHART // check to include clickable chart and events.. only if object storage is an option.
using Microsoft.Office.Tools.Ribbon;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Drawing.Imaging;
using System.Linq;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using SysData = System.Data;
namespace GINtool
{
public partial class GinRibbon
{
#region inits
bool gOperonOutput = false;
bool gCatOutput = false;
//bool gpValueUpdate = true;
//bool gRegulonPlot = true;
#if CLICK_CHART
List<chart_info> gCharts = new List<chart_info>();
#endif
byte gNeedsUpdate = (byte)UPDATE_FLAGS.ALL;
List<TASKS> gTasks = new List<TASKS>();
// int[] updateFlags = new int[3] { 1, 1, 1 };
//bool SummaryTableNeedsUpdating = true;
//bool CombinedTableNeedsUpdating = true;
//bool OperonTableNeedsUpdating = true;
//bool MappedTableNeedsUpdating = true;
//bool RegulonPlotsNeedsUpdating = true;
//bool CategoryPlotNeedsUpdating = true;
//bool DistributionPlotNeedsUpdating = true;
//bool RegulonPlotNeedsUpdating = true;
int maxGenesPerOperon = 1;
SysData.DataTable gRefWB = null; // RegulonData .. rename later
SysData.DataTable gRefStats = null;
SysData.DataTable gRefOperons = null;
SysData.DataTable gCategories = null;
string[] gColNames = null;
string gCategoryGeneColumn = "locus_tag"; // the fixed column name that refers to the genes inthe category csv file
Excel.Application gApplication = null;
//bool gGeneratePlots = false;
//bool gQPlot = false;
//bool gNeedsUpdating = true;
//bool gOrderAscending = true;
bool gSortResults = false;
//bool gUseCatOutput = false;
static List<string> gAvailItems = null;
static List<string> gUpItems = null;
static List<string> gDownItems = null;
List<int> gExcelErrorValues = null;
string gInputRange = "";
List<FC_BSU> gOutput = null;
SysData.DataTable gSummary = null;
List<BsuRegulons> gList = null;
SysData.DataTable gCombineInfo = null;
//int gDDcatLevel = 1;
// private bool gPlotDistribution = false;
// private bool gPlotClustered = false; // is category plot
//PlotRoutines gEnrichmentAnalysis;
#endregion
#region database_utils
private List<string> propertyItems(string property)
{
StringCollection myCol = (StringCollection)Properties.Settings.Default[property];
if (myCol != null)
return myCol.Cast<string>().ToList();
return new List<string>();
}
private void storeValue(string property, List<string> aValue)
{
StringCollection collection = new StringCollection();
collection.AddRange(aValue.ToArray());
Properties.Settings.Default[property] = collection;
}
private SysData.DataTable GetDistinctRecords(SysData.DataTable dt, string[] Columns)
{
return dt.DefaultView.ToTable(true, Columns);
}
private SysData.DataRow[] Lookup(string value)
{
SysData.DataRow[] filteredRows = gRefWB.Select(string.Format("[{0}] LIKE '%{1}%'", Properties.Settings.Default.referenceBSU, value));
// copy data to temporary table
SysData.DataTable dt = gRefWB.Clone();
foreach (SysData.DataRow dr in filteredRows)
dt.ImportRow(dr);
// return only unique values
SysData.DataTable dt_unique = GetDistinctRecords(dt, gColNames);
return dt_unique.Select();
}
#endregion
private bool LoadCategoryData()
{
if (Properties.Settings.Default.categoryFile.Length == 0 || Properties.Settings.Default.catSheet.Length == 0)
return false;
//gApplication.StatusBar = "Load category data";
//gApplication.EnableEvents = false;
AddTask(TASKS.LOAD_CATEGORY_DATA);
SysData.DataTable _tmp = ExcelUtils.ReadExcelToDatable(gApplication, Properties.Settings.Default.catSheet, Properties.Settings.Default.categoryFile, 1, 1);
gCategories = new SysData.DataTable("Categories");
gCategories.CaseSensitive = false;
gCategories.Columns.Add("catid", Type.GetType("System.String"));
gCategories.Columns.Add("catid_short", Type.GetType("System.String"));
gCategories.Columns.Add("gene", Type.GetType("System.String"));
gCategories.Columns.Add("locus_tag", Type.GetType("System.String"));
gCategories.Columns.Add("cat1", Type.GetType("System.String"));
gCategories.Columns.Add("cat2", Type.GetType("System.String"));
gCategories.Columns.Add("cat3", Type.GetType("System.String"));
gCategories.Columns.Add("cat4", Type.GetType("System.String"));
gCategories.Columns.Add("cat5", Type.GetType("System.String"));
gCategories.Columns.Add("cat1_int", Type.GetType("System.Int32"));
gCategories.Columns.Add("cat2_int", Type.GetType("System.Int32"));
gCategories.Columns.Add("cat3_int", Type.GetType("System.Int32"));
gCategories.Columns.Add("cat4_int", Type.GetType("System.Int32"));
gCategories.Columns.Add("cat5_int", Type.GetType("System.Int32"));
gCategories.Columns.Add("ucat1_int", Type.GetType("System.Int32"));
gCategories.Columns.Add("ucat2_int", Type.GetType("System.Int32"));
gCategories.Columns.Add("ucat3_int", Type.GetType("System.Int32"));
gCategories.Columns.Add("ucat4_int", Type.GetType("System.Int32"));
gCategories.Columns.Add("ucat5_int", Type.GetType("System.Int32"));
string[] lcols = new string [] {"cat1_int","cat2_int","cat3_int","cat4_int","cat5_int"};
string[] ulcols = new string[] { "ucat1_int", "ucat2_int", "ucat3_int", "ucat4_int", "ucat5_int" };
foreach (SysData.DataRow lRow in _tmp.Rows)
{
object[] lItems = lRow.ItemArray;
SysData.DataRow lNewRow = gCategories.Rows.Add();
for (int i = 0; i < lItems.Length; i++)
{
lNewRow["catid"] = lItems[0];
string[] splits = lItems[0].ToString().Split(' ');
lNewRow["catid_short"] = splits[splits.Count()-1];
lNewRow["Gene"] = lItems[1];
lNewRow["locus_tag"] = lItems[2];
lNewRow["cat1"] = lItems[3];
lNewRow["cat2"] = lItems[4];
lNewRow["cat3"] = lItems[5];
lNewRow["cat4"] = lItems[6];
lNewRow["cat5"] = lItems[7];
string[] llItems = lItems[0].ToString().Split(' ')[1].Split('.');
for (int j = 0; j < llItems.Length; j++)
{
lNewRow[lcols[j]] = Int32.Parse(llItems[j]);
}
for (int j = llItems.Length; j < 5; j++)
{
//lNewRow[lcols[j]] = 0;
//lNewRow[ulcols[j]] = 0;
}
int offset = 0;
for (int j = 0; j < llItems.Length; j++)
{
lNewRow[ulcols[j]] = offset + ((Int32)lNewRow[lcols[j]]) * Math.Pow(10, 5 - j);
offset = (Int32)lNewRow[ulcols[j]];
}
}
}
//gApplication.EnableEvents = true;
//gApplication.StatusBar = "Ready";
RemoveTask(TASKS.LOAD_CATEGORY_DATA);
return gCategories.Rows.Count > 0;
}
private bool LoadOperonData()
{
if (Properties.Settings.Default.operonFile.Length == 0 || Properties.Settings.Default.operonSheet.Length == 0)
return false;
AddTask(TASKS.LOAD_OPERON_DATA);
//gApplication.EnableEvents = false;
//gApplication.StatusBar = "Load operon data";
SysData.DataTable _tmp = ExcelUtils.ReadExcelToDatable(gApplication, Properties.Settings.Default.operonSheet, Properties.Settings.Default.operonFile, 1, 1);
gRefOperons = new SysData.DataTable("OPERONS");
gRefOperons.CaseSensitive = false;
gRefOperons.Columns.Add("operon", Type.GetType("System.String"));
gRefOperons.Columns.Add("gene", Type.GetType("System.String"));
foreach(SysData.DataRow lRow in _tmp.Rows)
{
string[] lItems = lRow.ItemArray[0].ToString().Split('-');
if (maxGenesPerOperon < lItems.Length)
maxGenesPerOperon = lItems.Length;
for (int i = 0; i < lItems.Length; i++)
{
SysData.DataRow lNewRow = gRefOperons.Rows.Add();
lNewRow["operon"] = lItems[0];
lNewRow["gene"] = lItems[i];
}
}
//gApplication.EnableEvents = true;
//gApplication.StatusBar = "Ready";
RemoveTask(TASKS.LOAD_OPERON_DATA);
return gRefOperons.Rows.Count>0;
}
private bool LoadData()
{
//gApplication.StatusBar = "Load regulon/gene mappings";
//gApplication.EnableEvents = false;
AddTask(TASKS.LOAD_REGULON_DATA);
gRefWB = ExcelUtils.ReadExcelToDatable(gApplication, Properties.Settings.Default.referenceSheetName, Properties.Settings.Default.referenceFile, 1, 1);
if (gRefWB != null)
{
gColNames = new string[gRefWB.Columns.Count];
int i = 0;
foreach (SysData.DataColumn col in gRefWB.Columns)
{
gColNames[i++] = col.ColumnName;
}
// generate database frequency table
CreateTableStatistics();
}
//gApplication.EnableEvents = true;
//gApplication.StatusBar = "Ready";
RemoveTask(TASKS.LOAD_REGULON_DATA);
return gRefWB != null ? true : false;
}
private void CreateTableStatistics()
{
List<string> lString = new List<string> { Properties.Settings.Default.referenceRegulon };
SysData.DataTable lUnique = GetDistinctRecords(gRefWB, lString.ToArray());
// initialize the global datatable
gRefStats = new SysData.DataTable("tblstat");
int totNrRows = gRefWB.Rows.Count;
SysData.DataColumn regColumn = new SysData.DataColumn("Regulon", Type.GetType("System.String"));
SysData.DataColumn countColumn = new SysData.DataColumn("Count", Type.GetType("System.Int16"));
SysData.DataColumn avgColumn = new SysData.DataColumn("Average", Type.GetType("System.Double"));
gRefStats.Columns.Add(regColumn);
gRefStats.Columns.Add(countColumn);
gRefStats.Columns.Add(avgColumn);
foreach (SysData.DataRow lRow in lUnique.Rows)
{
string lVal = lRow[Properties.Settings.Default.referenceRegulon].ToString();
int cnt = gRefWB.Select(string.Format("{0}='{1}'", Properties.Settings.Default.referenceRegulon, lVal)).Length;
SysData.DataRow nRow = gRefStats.Rows.Add();
nRow["Regulon"] = lVal;
nRow["Count"] = cnt;
nRow["Average"] = ((double)cnt) / totNrRows;
}
}
private void GinRibbon_Load(object sender, RibbonUIEventArgs e)
{
gApplication = Globals.ThisAddIn.GetExcelApplication();
btnRegulonFileName.Label = Properties.Settings.Default.referenceFile;
btnOperonFile.Label = Properties.Settings.Default.operonFile;
btnCatFile.Label = Properties.Settings.Default.categoryFile;
cbOrderFC.Checked = Properties.Settings.Default.useSort;
cbDescending.Checked = !Properties.Settings.Default.sortAscending;
cbAscending.Checked = Properties.Settings.Default.sortAscending;
chkRegulon.Checked = Properties.Settings.Default.regPlot;
cbMapping.Checked = Properties.Settings.Default.tblMap;
cbSummary.Checked = Properties.Settings.Default.tblSummary;
cbCombined.Checked = Properties.Settings.Default.tblCombine;
cbOperon.Checked = Properties.Settings.Default.tblOperon;
cbClustered.Checked = Properties.Settings.Default.catPlot;
cbDistribution.Checked = Properties.Settings.Default.distPlot;
//chkRegulon.Checked = Properties.Settings.Default.regPlot;
//cbOrderFC.Checked = Properties.Settings.Default.useFCorder;
cbUseCategories.Checked = Properties.Settings.Default.useCat;
cbUsePValues.Checked = Properties.Settings.Default.use_pvalues;
cbUseFoldChanges.Checked = !Properties.Settings.Default.use_pvalues;
if (Properties.Settings.Default.operonFile.Length == 0)
btnOperonFile.Label = "No file selected";
gAvailItems = propertyItems("directionMapUnassigned");
gUpItems = propertyItems("directionMapUp");
gDownItems = propertyItems("directionMapDown");
btnSelect.Enabled = false;
btApply.Enabled = false;
ddBSU.Enabled = false;
ddGene.Enabled = false;
ddRegulon.Enabled = false;
ddDir.Enabled = false;
btPlot.Enabled = false;
cbUseCategories.Enabled = false;
cbMapping.Enabled = false;
cbSummary.Enabled = false;
cbCombined.Enabled = false;
cbOperon.Enabled = false;
cbOrderFC.Enabled = false;
cbUsePValues.Enabled = false;
cbUseFoldChanges.Enabled = false;
toggleButton1.Enabled = true;
cbAscending.Enabled = false;
cbDescending.Enabled = false;
//grpDirection.Visible = false;
//gOrderAscending = cbOrderFC.Checked;
//edtMaxGroups.Enabled = false;
//btnPalette.Enabled = false;
//cbGenPlots.Checked = Properties.Settings.Default.generatePlots;
//cbQplot.Checked = Properties.Settings.Default.qPlot;
//gCompositPlot = cbGenPlots.Checked;
//gQPlot = cbQplot.Enabled;
//if (cbGenPlots.Checked )
//if (gEnrichmentAnalysis == null)
//{
// gEnrichmentAnalysis = new PlotRoutines(gApplication);
//}
PlotRoutines.theApp = gApplication;
EnableOutputOptions(false);
gExcelErrorValues = ((int[])Enum.GetValues(typeof(ExcelUtils.CVErrEnum))).ToList();
//if (Properties.Settings.Default.use_pvalues)
//{
// splitButton3.Label = but_pvalues.Label;
// splitButton3.Image = but_pvalues.Image;
//}
//else
//{
// splitButton3.Label = but_fc.Label;
// splitButton3.Image = but_pvalues.Image;
//}
btLoad.Enabled = System.IO.File.Exists(Properties.Settings.Default.referenceFile);
}
private Excel.Range GetActiveCell()
{
if (gApplication != null)
{
try { return (Excel.Range)gApplication.Selection; }
catch (Exception e) { return null; }
}
return null;
}
private void EnableOutputOptions(bool enable)
{
ebLow.Enabled = enable;
ebMid.Enabled = enable;
ebHigh.Enabled = enable;
editMinPval.Enabled = enable;
//splitButton3.Enabled = enable;
//cbUseCategories.Enabled = enable;
cbMapping.Enabled = enable;
cbSummary.Enabled = enable;
cbCombined.Enabled = enable;
cbClustered.Enabled = enable;
cbDistribution.Enabled = enable;
chkRegulon.Enabled= enable;
cbOrderFC.Enabled = enable;
cbUseCategories.Enabled = enable && gCatOutput;
cbOperon.Enabled = enable && gOperonOutput;
cbUsePValues.Enabled = enable;
cbUseFoldChanges.Enabled = enable;
cbAscending.Enabled = enable;
cbDescending.Enabled = enable;
//splitbtnEA.Enabled = enable;
}
private Excel.Worksheet GetActiveSheet()
{
if (gApplication != null)
{
if (gApplication.ActiveSheet is Excel.Chart)
{
MessageBox.Show("Please activate data sheet and select columns with data");
return null;
}
try
{
return (Excel.Worksheet)gApplication.ActiveSheet;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
return null;
}
private void ConditionFormatRange(Excel.Range columnRange)
{
Excel.FormatConditions fcs = columnRange.FormatConditions;
var formatCondition = fcs.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType.xlDatabar);
formatCondition.MinPoint.Modify(Microsoft.Office.Interop.Excel.XlConditionValueTypes.xlConditionValueAutomaticMin);
formatCondition.MaxPoint.Modify(Microsoft.Office.Interop.Excel.XlConditionValueTypes.xlConditionValueAutomaticMax);
formatCondition.BarFillType = Microsoft.Office.Interop.Excel.XlGradientFillType.xlGradientFillPath;
formatCondition.Direction = Microsoft.Office.Interop.Excel.Constants.xlContext;
formatCondition.NegativeBarFormat.ColorType = Microsoft.Office.Interop.Excel.XlDataBarNegativeColorType.xlDataBarColor;
formatCondition.BarColor.Color = 8700771; // System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);
formatCondition.BarColor.TintAndShade = 0; // System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);
formatCondition.BarBorder.Color.Color = 8700771; // System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);
formatCondition.BarBorder.Type = Microsoft.Office.Interop.Excel.XlDataBarBorderType.xlDataBarBorderSolid;
formatCondition.NegativeBarFormat.BorderColorType = Microsoft.Office.Interop.Excel.XlDataBarNegativeColorType.xlDataBarColor;
formatCondition.NegativeBarFormat.Parent.BarBorder.Type = Microsoft.Office.Interop.Excel.XlDataBarBorderType.xlDataBarBorderSolid;
formatCondition.AxisPosition = Microsoft.Office.Interop.Excel.XlDataBarAxisPosition.xlDataBarAxisAutomatic;
formatCondition.AxisColor.Color = 0; // System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
formatCondition.AxisColor.TintAndShade = 0;
formatCondition.NegativeBarFormat.Color.Color = 255; // System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSalmon);
formatCondition.NegativeBarFormat.Color.TintAndShade = 0;
formatCondition.NegativeBarFormat.BorderColor.Color = 255; // System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSalmon);
formatCondition.NegativeBarFormat.BorderColor.TintAndShade = 0;
}
private bool iserrorCell(object obj)
{
return (obj is Int32) && gExcelErrorValues.Contains((Int32)obj);
}
private List<BsuRegulons> QueryResultTable(Excel.Range theCells)
{
AddTask(TASKS.MAPPING_GENES_TO_REGULONS);
List<BsuRegulons> lList = new List<BsuRegulons>();
foreach (Excel.Range c in theCells.Rows)
{
string lBSU;
double lFC = 0;
double lPvalue = 1;
BsuRegulons lMap = null;
if (c.Columns.Count == 3)
{
object[,] value = c.Value2;
// first check if the cell contains an erroneous value, if not then try to parse the value or reset to default
if (!iserrorCell(value[1, 1]))
if (!Double.TryParse(value[1, 1].ToString(), out lPvalue))
lPvalue = 1;
if (!iserrorCell(value[1, 2]))
if (!Double.TryParse(value[1, 2].ToString(), out lFC))
lFC = 0;
lBSU = value[1, 3].ToString();
lMap = new BsuRegulons(lFC, lPvalue, lBSU);
}
if (lMap.BSU.Length > 0)
{
SysData.DataRow[] results = Lookup(lMap.BSU);
if (results.Length > 0)
{
string gene = results[0][Properties.Settings.Default.referenceGene].ToString();
lMap.GENE = gene;
for (int r = 0; r < results.Length; r++)
{
string item = results[r][Properties.Settings.Default.referenceRegulon].ToString();
string direction = results[r][Properties.Settings.Default.referenceDIR].ToString();
if (item.Length > 0) // loop over found regulons
{
lMap.REGULONS.Add(item);
if (gUpItems.Contains(direction))
lMap.UP.Add(r);
if (gDownItems.Contains(direction))
lMap.DOWN.Add(r);
}
}
}
}
lList.Add(lMap);
}
RemoveTask(TASKS.MAPPING_GENES_TO_REGULONS);
return lList;
}
(SysData.DataTable, SysData.DataTable) PrepareResultTable(List<BsuRegulons> lResults)
{
SysData.DataTable myTable = new System.Data.DataTable("mytable");
SysData.DataTable clrTable = new System.Data.DataTable("colortable");
int maxcol = lResults[0].REGULONS.Count;
// count max number of columns neccesary
for (int r = 1; r < lResults.Count; r++)
if (maxcol < lResults[r].REGULONS.Count)
maxcol = lResults[r].REGULONS.Count;
// add BSU/gene/p-value/fc columns
SysData.DataColumn bsuCol = new SysData.DataColumn("bsu", Type.GetType("System.String"));
myTable.Columns.Add(bsuCol);
SysData.DataColumn geneCol = new SysData.DataColumn("gene", Type.GetType("System.String"));
myTable.Columns.Add(geneCol);
SysData.DataColumn fcCol = new SysData.DataColumn("fc", Type.GetType("System.Double"));
myTable.Columns.Add(fcCol);
SysData.DataColumn pValCol = new SysData.DataColumn("pval", Type.GetType("System.Double"));
myTable.Columns.Add(pValCol);
// add count column
SysData.DataColumn countCol = new SysData.DataColumn("count_col", Type.GetType("System.Int16"));
myTable.Columns.Add(countCol);
// add variable columns
for (int c = 0; c < maxcol; c++)
{
SysData.DataColumn newCol = new SysData.DataColumn(string.Format("col_{0}", c + 1));
myTable.Columns.Add(newCol);
SysData.DataColumn clrCol = new SysData.DataColumn(string.Format("col_{0}", c + 1), Type.GetType("System.Int16"));
clrTable.Columns.Add(clrCol);
}
// fill data
for (int r = 0; r < lResults.Count; r++)
{
SysData.DataRow newRow = myTable.Rows.Add();
newRow["bsu"] = lResults[r].BSU;
newRow["gene"] = lResults[r].GENE;
newRow["fc"] = lResults[r].FC;
newRow["pval"] = lResults[r].PVALUE;
newRow["count_col"] = lResults[r].TOT;
SysData.DataRow clrRow = clrTable.Rows.Add();
for (int c = 0; c < lResults[r].REGULONS.Count; c++)
newRow[string.Format("col_{0}", c + 1)] = lResults[r].REGULONS[c];
for (int c = 0; c < lResults[r].UP.Count; c++)
clrRow[lResults[r].UP[c]] = 1;
for (int c = 0; c < lResults[r].DOWN.Count; c++)
clrRow[lResults[r].DOWN[c]] = -1;
}
return (myTable, clrTable);
}
public string RangeAddress(Excel.Range rng)
{
return rng.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1,Type.Missing, Type.Missing);
}
public string CellAddress(Excel.Worksheet sht, int row, int col)
{
return RangeAddress(sht.Cells[row, col]);
}
private string GetStatusTask(TASKS task)
{
return taks_strings[(int)task];
}
private void SetStatus(TASKS activeTask)
{
gApplication.StatusBar = GetStatusTask(activeTask);
if (activeTask != TASKS.READY)
{
gApplication.ScreenUpdating = false;
gApplication.DisplayAlerts = false;
gApplication.EnableEvents = false;
}
else
{
gApplication.ScreenUpdating = true;
gApplication.DisplayAlerts = true;
gApplication.EnableEvents = true;
}
}
private void AddTask(TASKS newTask)
{
gTasks.Add(newTask);
SetStatus(newTask);
}
private void RemoveTask(TASKS taskReady)
{
gTasks.Remove(taskReady);
if (gTasks.Count == 0 || gTasks[0] == TASKS.READY)
SetStatus(TASKS.READY);
else
SetStatus(gTasks.Last());
}
// the main routine after mouse selection update // generates mapping output.. should be de-coupled (update data & mapping output)
private (List<FC_BSU>, List<BsuRegulons>) GenerateOutput(bool suppressOutput=false)
{
AddTask(TASKS.READ_SHEET_DATA);
Excel.Range theInputCells = GetActiveCell();
Excel.Worksheet theSheet = GetActiveSheet();
if (theSheet == null)
{
MessageBox.Show("Please select a worksheet with data first");
RemoveTask(TASKS.READ_SHEET_DATA);
return (null, null);
}
if (theSheet.Name.Contains("Plot_") || theSheet.Name.Contains("CongruenceData_") || theSheet.Name.Contains("CongruencePlot_") || theSheet.Name.Contains("Summary_") ||
theSheet.Name.Contains("Combined_") || theSheet.Name.Contains("Mapped_") || theInputCells.Columns.Count != 3 )
{
MessageBox.Show("Please select 3 columns (first P-Value, second FC, third BSU)");
RemoveTask(TASKS.READ_SHEET_DATA);
return (null, null);
}
if (RangeAddress(theInputCells) != gInputRange || (gOutput == null || gList == null))
{
gInputRange = RangeAddress(theInputCells);
gNeedsUpdate = (byte)UPDATE_FLAGS.ALL;
}
else
{
RemoveTask(TASKS.READ_SHEET_DATA);
return (gOutput, gList);
}
int nrRows = theInputCells.Rows.Count;
int startC = theInputCells.Column;
int startR = theInputCells.Row;
// from now always assume 3 columns.. p-value, fc, bsu
// generate the results for outputting the data and summary
List<BsuRegulons> lResults = QueryResultTable(theInputCells);
List<FC_BSU> lOutput = new List<FC_BSU>();
for (int r = 0; r < nrRows; r++)
for (int c = 0; c < lResults[r].REGULONS.Count; c++)
{
int val = 0;
if (lResults[r].UP.Contains(c))
val = 1;
if (lResults[r].DOWN.Contains(c))
val = -1;
lOutput.Add(new FC_BSU(lResults[r].FC, lResults[r].REGULONS[c], val, lResults[r].PVALUE,lResults[r].GENE));
}
RemoveTask(TASKS.READ_SHEET_DATA);
return (lOutput, lResults);
}
private void CreateMappingSheet(List<BsuRegulons> bsuRegulons)
{
var lOut = PrepareResultTable(bsuRegulons);
SysData.DataTable lTable = lOut.Item1;
SysData.DataTable clrTbl;
AddTask(TASKS.UPDATE_MAPPED_TABLE);
//gApplication.StatusBar = "Creating mapping sheet";
int nrRows = lTable.Rows.Count;
//int startC = 1;
int startR = 2;
// from now always assume 3 columns.. p-value, fc, bsu
int offsetColumn = 1;
Excel.Worksheet lNewSheet = gApplication.Worksheets.Add();
renameWorksheet(lNewSheet, "Mapped_");
lNewSheet.Cells[1, 1] = "BSU";
lNewSheet.Cells[1, 2] = "GENE";
lNewSheet.Cells[1, 3] = "FC";
lNewSheet.Cells[1, 4] = "PVALUE";
lNewSheet.Cells[1, 5] = "TOT REGULONS";
string lastColumn = lTable.Columns[lTable.Columns.Count - 1].ColumnName;
lastColumn = lastColumn.Replace("col_", "");
int maxreg = Int16.Parse(lastColumn);
for (int i = 0; i < maxreg; i++)
lNewSheet.Cells[1, i + 6] = string.Format("Regulon_{0}", i + 1);
FastDtToExcel(lTable, lNewSheet, startR, offsetColumn, startR + nrRows - 1, offsetColumn + lTable.Columns.Count - 1);
Excel.Range top = lNewSheet.Cells[1, 1];
Excel.Range bottom = lNewSheet.Cells[lTable.Rows.Count + 1, lTable.Columns.Count];
Excel.Range all = (Excel.Range)lNewSheet.get_Range(top, bottom);
all.Columns.AutoFit();
clrTbl = lOut.Item2;
ColorCells(clrTbl, lNewSheet, startR, offsetColumn + 5, startR + nrRows - 1, offsetColumn + lTable.Columns.Count - 1);
RemoveTask(TASKS.UPDATE_MAPPED_TABLE);
}
private void FastDtToExcel(System.Data.DataTable dt, Excel.Worksheet sheet, int firstRow, int firstCol, int lastRow, int lastCol)
{
Excel.Range top = sheet.Cells[firstRow, firstCol];
Excel.Range bottom = sheet.Cells[lastRow, lastCol];
Excel.Range all = (Excel.Range)sheet.get_Range(top, bottom);
object[,] arrayDT = new object[dt.Rows.Count, dt.Columns.Count];
for (int i = 0; i < dt.Rows.Count; i++)
for (int j = 0; j < dt.Columns.Count; j++)
arrayDT[i, j] = dt.Rows[i][j];
all.Value = arrayDT;
}
private void ColorCells(System.Data.DataTable dt, Excel.Worksheet sheet, int firstRow, int firstCol, int lastRow, int lastCol)
{
AddTask(TASKS.COLOR_CELLS);
Excel.Range top = sheet.Cells[firstRow, firstCol];
Excel.Range bottom = sheet.Cells[lastRow, lastCol];
Excel.Range all = (Excel.Range)sheet.get_Range(top, bottom);
for (int r = 0; r < dt.Rows.Count; r++)
{
SysData.DataRow clrRow = dt.Rows[r];
for (int c = 0; c < clrRow.ItemArray.Length; c++)
{
Excel.Range lR = all.Cells[r + 1, c + 1];
if (Int32.TryParse(clrRow[c].ToString(), out int val))
{
if (val == 1)
lR.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);
if (val == -1)
lR.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSalmon);
}
}
}
RemoveTask(TASKS.COLOR_CELLS);
}
private void CreateSummarySheet(SysData.DataTable theTable)
{
AddTask(TASKS.UPDATE_SUMMARY_TABLE);
Excel.Worksheet lNewSheet = gApplication.Worksheets.Add();
renameWorksheet(lNewSheet, "Summary_");
int col = 1;
Excel.Range top = lNewSheet.Cells[1, 4];
Excel.Range bottom = lNewSheet.Cells[1, 11];
Excel.Range all = (Excel.Range)lNewSheet.get_Range(top, bottom);
all.Merge();
all.Value = "Observed Counts and directions";
all.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
top = lNewSheet.Cells[1, 13];
bottom = lNewSheet.Cells[1, 20];
all = (Excel.Range)lNewSheet.get_Range(top, bottom);
all.Merge();
all.Value = "Percentage";
all.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
top = lNewSheet.Cells[1, 21];
bottom = lNewSheet.Cells[1, 22];
all = (Excel.Range)lNewSheet.get_Range(top, bottom);
all.Merge();
all.Value = "Logical direction";
all.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
lNewSheet.Cells[2, col++] = "Regulon";
lNewSheet.Cells[2, col++] = "Total number in database";
lNewSheet.Cells[2, col++] = "Total number in dataset";
lNewSheet.Cells[2, col++] = string.Format("UP >{0}", Properties.Settings.Default.fcHIGH);
lNewSheet.Cells[2, col++] = string.Format("UP <={0} & >{1}", Properties.Settings.Default.fcHIGH, Properties.Settings.Default.fcMID);
lNewSheet.Cells[2, col++] = string.Format("UP <={0} & >{1}", Properties.Settings.Default.fcMID, Properties.Settings.Default.fcLOW);
lNewSheet.Cells[2, col++] = string.Format("UP <={0} & >0", Properties.Settings.Default.fcLOW);
lNewSheet.Cells[2, col++] = string.Format("DOWN <0 & >=-{0}", Properties.Settings.Default.fcLOW);
lNewSheet.Cells[2, col++] = string.Format("DOWN <-{0} & >=-{1}", Properties.Settings.Default.fcMID, Properties.Settings.Default.fcLOW);
lNewSheet.Cells[2, col++] = string.Format("DOWN <=-{0} & >=-{1}", Properties.Settings.Default.fcHIGH, Properties.Settings.Default.fcMID);
lNewSheet.Cells[2, col++] = string.Format("DOWN <-{0}", Properties.Settings.Default.fcHIGH);
lNewSheet.Cells[2, col++] = "Total Relevant";
int colGreen = col;
lNewSheet.Cells[2, col++] = string.Format("UP >{0}", Properties.Settings.Default.fcHIGH);
lNewSheet.Cells[2, col++] = string.Format("UP <={0} & >{1}", Properties.Settings.Default.fcHIGH, Properties.Settings.Default.fcMID);
lNewSheet.Cells[2, col++] = string.Format("UP <={0} & >{1}", Properties.Settings.Default.fcMID, Properties.Settings.Default.fcLOW);
lNewSheet.Cells[2, col++] = string.Format("UP <={0} & >0", Properties.Settings.Default.fcLOW);
lNewSheet.Cells[2, col++] = string.Format("DOWN <0 & >=-{0}", Properties.Settings.Default.fcLOW);
lNewSheet.Cells[2, col++] = string.Format("DOWN <-{0} & >=-{1}", Properties.Settings.Default.fcMID, Properties.Settings.Default.fcLOW);
lNewSheet.Cells[2, col++] = string.Format("DOWN <=-{0} & >=-{1}", Properties.Settings.Default.fcHIGH, Properties.Settings.Default.fcMID);
lNewSheet.Cells[2, col++] = string.Format("DOWN <-{0}", Properties.Settings.Default.fcHIGH);
lNewSheet.Cells[2, col++] = "DOWN";
lNewSheet.Cells[2, col++] = "UP";
// starting from row 3
FastDtToExcel(theTable, lNewSheet, 3, 1, theTable.Rows.Count + 2, theTable.Columns.Count);
// color cells here
top = lNewSheet.Cells[3, colGreen];
bottom = lNewSheet.Cells[theTable.Rows.Count + 2, colGreen+4];
all = (Excel.Range)lNewSheet.get_Range(top, bottom);
all.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);
top = lNewSheet.Cells[3, colGreen+4];
bottom = lNewSheet.Cells[theTable.Rows.Count + 2, colGreen + 4+3];
all = (Excel.Range)lNewSheet.get_Range(top, bottom);
all.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSalmon);
// set number format
top = lNewSheet.Cells[3, 13];
bottom = lNewSheet.Cells[2 + theTable.Rows.Count, 22];
all = (Excel.Range)lNewSheet.get_Range(top, bottom);
all.NumberFormat = "###%";
// fit the width of the columns
top = lNewSheet.Cells[1, 1];
bottom = lNewSheet.Cells[theTable.Rows.Count+2, theTable.Columns.Count];
all = (Excel.Range)lNewSheet.get_Range(top, bottom);
all.Columns.AutoFit();
RemoveTask(TASKS.UPDATE_SUMMARY_TABLE);
}
private SysData.DataTable ReformatResults(List<FC_BSU> aList)
{
// find unique regulons
SysData.DataTable lTable = new SysData.DataTable("FC_BSU");
SysData.DataColumn regColumn = new SysData.DataColumn("Regulon", Type.GetType("System.String"));
SysData.DataColumn geneColumn = new SysData.DataColumn("Gene", Type.GetType("System.String"));
SysData.DataColumn pvalColumn = new SysData.DataColumn("Pvalue", Type.GetType("System.Single"));
SysData.DataColumn fcColumn = new SysData.DataColumn("FC", Type.GetType("System.Single"));
SysData.DataColumn dirColumn = new SysData.DataColumn("DIR", Type.GetType("System.Int32"));
lTable.Columns.Add(regColumn);
lTable.Columns.Add(geneColumn);
lTable.Columns.Add(fcColumn);
lTable.Columns.Add(pvalColumn);
lTable.Columns.Add(dirColumn);
for (int r = 0; r < aList.Count; r++)
{
SysData.DataRow lRow = lTable.Rows.Add();
lRow["Regulon"] = aList[r].BSU;
lRow["FC"] = aList[r].FC;
lRow["DIR"] = aList[r].DIR;
lRow["Pvalue"] = aList[r].PVALUE;
lRow["Gene"] = aList[r].GENE;
}
return lTable;
}
private (int,int, int) CalculateFPRatio(SysData.DataRow[] aRow)
{
int nrUP=0, nrDOWN = 0, nrTot=0;
// aRow from an FC_BSU table
for (int i = 0; i < aRow.Length; i++)
{
float fcGene = (float)aRow[i]["FC"];
int dirBSU = (int)aRow[i]["DIR"];
float lowValue = Properties.Settings.Default.fcLOW;
// if upregulated
if (dirBSU < 0)
{
if (fcGene < -lowValue)