-
Notifications
You must be signed in to change notification settings - Fork 0
/
GinRibbon.cs
3596 lines (2873 loc) · 133 KB
/
GinRibbon.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;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using SysData = System.Data;
using static GINtool.ES_Extensions;
using stat_dict = System.Collections.Generic.Dictionary<string, double>;
using dataset_dict = System.Collections.Generic.Dictionary<string, GINtool.DataItem>;
using rank_dict = System.Collections.Generic.Dictionary<string, int>;
using dict_rank = System.Collections.Generic.Dictionary<int, string>;
using lib_dict = System.Collections.Generic.Dictionary<string, string[]>;
using Accord.Statistics.Distributions.Univariate;
using System.Text;
using System.Security.Cryptography;
//certificate CdF7RoqS9KXLvWtk6OZf chk
namespace GINtool
{
using gsea_dict = System.Collections.Generic.Dictionary<string, GINtool.S_GSEA>;
/// <summary>
/// The main class of the Excel Addin
/// </summary>
public partial class GinRibbon
{
/// <value>The last used folder for an input file.</value>
string gLastFolder = "";
/// <value>The flag that registers which data to update.</value>
byte gNeedsUpdate = (byte)UPDATE_FLAGS.ALL;
/// <value>The list in which the tasks are registered.</value>
readonly List<TASKS> gTasks = new List<TASKS>();
int gMaxGenesPerOperon = 1;
/// <value>The main table that contains all gene info</value>
SysData.DataTable gGenesWB = null;
/// <value>The main table containing the regulon data.</value>
SysData.DataTable gRegulonWB = null; // RegulonData .. rename later
/// <value>The main table containing the operon data</value>
SysData.DataTable gRefOperonsWB = null;
/// <value>The main table containing the category data</value>
SysData.DataTable gCategoriesWB = null;
/// <value>The main table containing the regulon info data</value>
SysData.DataTable gRegulonInfoWB = null;
/// <value>gGeneColNames contains the column names of the genes information file</value>
private string[] gGenesColNames = new string[] { };
/// <value>gRegulonColNames contains the column names of the regulon file</value>
private string[] gRegulonColNames = new string[] { };
/// <value>gCategoryColNames contains the column names of the categories file</value>
private string[] gCategoryColNames = new string[] { };
/// <value>gOperonColNames contains the columns names of the operon file</value>
private string[] gOperonColNames = new string[] { };
/// <value>gRegulonInfoColNames contains the columns names of the regulon info file</value>
private string[] gRegulonInfoColNames = new string[] { };
#region ES related variables
dataset_dict gDataSetDict = new dataset_dict();
lib_dict gCategoryDict = new Dictionary<string, string[]>();
lib_dict gRegulonDict = new Dictionary<string, string[]>();
lib_dict gCombinedDict = new Dictionary<string, string[]>();
Hashtable gFgseaHash = new Hashtable();
Hashtable gGSEAHash = new Hashtable();
Dictionary<string, string> gBSU_gene_dict = new Dictionary<string, string>();
stat_dict gES_signature = new stat_dict();
stat_dict gES_signature_ordered = new stat_dict();
dict_rank gES_map_signature = new dict_rank();
rank_dict gES_signature_map = new rank_dict();
string[] gES_signature_genes = new string[] { };
double[] gES_sigvalues = new double[] { };
double[] gES_abs_signature = new double[] { };
int gES_key;
#endregion
//readonly string gCategoryGeneColumn = "locus_tag"; // the fixed column name that refers to the genes inthe category csv file
Excel.Application gApplication = null;
Excel.Workbook gActiveWorkbook = null;
/// <value>the main list of all association types listed in the main regulon table</value>
static List<string> gAvailItems = null;
/// <value>the main list of items that the user defined as having a up-regulated association with a gene</value>
static List<string> gUpItems = null;
/// <value>the main list of items that the user defined as having a down-regulated association with a gene</value>
static List<string> gDownItems = null;
List<int> gExcelErrorValues = null;
/// <value>a string that represents the previously selected range of BSU codes</value>
string gOldRangeBSU = "";
/// <value>a string that represents the previously selected range of P-values</value>
string gOldRangeP = "";
/// <value>a string that represents the previously selected range of FC</value>
string gOldRangeFC = "";
Excel.Range gRangeBSU;
Excel.Range gRangeFC;
Excel.Range gRangeP;
List<BsuLinkedItems> gList = null;
/// <value>Contains the usage info of the regulons</value>
SysData.DataTable gRegulonTable = null;
/// <value>Contains the usage info of the categories</value>
SysData.DataTable gCategoryTable = null;
SysData.DataTable gBestTable = null;
bool gRegulonFileSelected = false;
bool gCategoryFileSelected = false;
bool gGenesFileSelected = false;
bool gOperonFileSelected = false;
bool gRegulonInfoFileSelected = false;
Properties.Settings gSettings = null;
private bool UseCategoryData()
{
return Properties.Settings.Default.useCat;
}
/// <summary>
/// Obtain the value for the property from the default settings
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
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>();
}
/// <summary>
/// Store the value or values of property to the default settings
/// </summary>
/// <param name="property"></param>
/// <param name="aValue"></param>
private void StoreValue(string property, List<string> aValue)
{
StringCollection collection = new StringCollection();
collection.AddRange(aValue.ToArray());
Properties.Settings.Default[property] = collection;
}
/// <summary>
/// From a table get the distinct records for the itmes listed in Columns
/// </summary>
/// <param name="dt"></param>
/// <param name="Columns"></param>
/// <returns></returns>
private SysData.DataTable GetDistinctRecords(SysData.DataTable dt, string[] Columns)
{
return dt.DefaultView.ToTable(true, Columns.Distinct().ToArray());
}
/// <summary>
/// Find the records in the main Regulon table where the ID (=BSU column, locus_tag) = value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private SysData.DataRow[] LookupRegulon(string value)
{
// needs to be replaced by genes table entry
SysData.DataRow[] filteredRows = gRegulonWB.Select(string.Format("[{0}] LIKE '%{1}%'", Properties.Settings.Default.referenceBSU, value));
// copy data to temporary table
SysData.DataTable dt = gRegulonWB.Clone();
foreach (SysData.DataRow dr in filteredRows)
dt.ImportRow(dr);
// return only unique values
SysData.DataTable dt_unique = GetDistinctRecords(dt, gRegulonColNames);
return dt_unique.Select();
}
/// <summary>
/// Find the records in the main Category table where the ID (=BSU column, locus tag) = value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private SysData.DataRow[] LookupCategory(string value)
{
SysData.DataRow[] filteredRows = gCategoriesWB.Select(string.Format("[locus_tag] = '{0}'", value));
// copy data to temporary table
SysData.DataTable dt = gCategoriesWB.Clone();
foreach (SysData.DataRow dr in filteredRows)
dt.ImportRow(dr);
// return only unique values
// SysData.DataTable dt_unique = GetDistinctRecords(dt, gCategoryColNames);
SysData.DataTable dt_unique = GetDistinctRecords(dt, new string[] { });
return dt_unique.Select();
}
/// <summary>
/// Find the records in the main Category table where the ID (=BSU column, locus tag) = value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private SysData.DataRow[] LookupGeneInfo(string value)
{
// needs to be replaced by genes table entry
SysData.DataRow[] filteredRows = gGenesWB.Select(string.Format("[{0}] LIKE '%{1}%'", Properties.Settings.Default.genesBSUColumn, value));
// copy data to temporary table
SysData.DataTable dt = gGenesWB.Clone();
foreach (SysData.DataRow dr in filteredRows)
dt.ImportRow(dr);
// return only unique values
SysData.DataTable dt_unique = GetDistinctRecords(dt, gGenesColNames);
return dt_unique.Select();
}
/// <summary>
/// Enable/disable the buttons and labels at the start.
/// </summary>
/// <param name="enable"></param>
private void InitFields(bool enable = false)
{
btnSelect.Enabled = enable;
btApply.Enabled = enable;
// genes items
ddGenesBSU.Enabled = enable;
ddGenesDescription.Enabled = enable;
ddGenesFunction.Enabled = enable;
ddGnsName.Enabled = enable;
// regulon items
ddBSU.Enabled = enable;
ddGene.Enabled = enable;
ddRegulon.Enabled = enable;
ddDir.Enabled = enable;
// category items
ddCatID.Enabled = enable;
ddCatName.Enabled = enable;
ddCatBSU.Enabled = enable;
// regulon info items
ddRegInfoFunction.Enabled = enable;
ddRegInfoId.Enabled = enable;
ddRegInfoSize.Enabled = enable;
btPlot.Enabled = enable;
cbUseCategories.Enabled = enable;
cbMapping.Enabled = enable;
cbSummary.Enabled = enable;
cbCombined.Enabled = enable;
cbUseOperons.Enabled = enable;
cbUsePValues.Enabled = enable;
cbUseFoldChanges.Enabled = enable;
cbNoFilter.Enabled = enable;
toggleButton1.Enabled = true;
cbAscending.Enabled = enable;
cbDescending.Enabled = enable;
cbUseRegulons.Enabled = enable;
cbUseCategories.Enabled = enable;
}
/// <summary>
/// Load the last known settings stored in the persitent default.settings
/// </summary>
private void LoadPersistentSettings()
{
btnRegulonFileName.Label = Properties.Settings.Default.referenceFile;
if (btnRegulonFileName.Label.Length > 0 & btnRegulonFileName.Label != "not defined yet")
{
try
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(btnRegulonFileName.Label);
gLastFolder = fInfo.DirectoryName;
if (LoadRegulonDataColumns())
Fill_RegulonDropDownBoxes();
}
catch (Exception ex)
{
gApplication.StatusBar.Text = ex.Message;
// show error dialog here
}
}
btnGenesFileSelected.Label = Properties.Settings.Default.genesFileName;
if (btnGenesFileSelected.Label.Length > 0)
{
try
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(btnGenesFileSelected.Label);
gLastFolder = fInfo.DirectoryName;
if (LoadGenesDataColumns())
Fill_GenesDropDownBoxes();
}
catch (Exception ex)
{
gApplication.StatusBar.Text = ex.Message;
}
}
btnOperonFile.Label = Properties.Settings.Default.operonFile;
if (btnOperonFile.Label.Length > 0)
{
try
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(btnOperonFile.Label);
gLastFolder = fInfo.DirectoryName;
//if (LoadOperonDataColumns())
// Fill_OperonDropDownBoxes();
}
catch (System.Exception ex)
{
gApplication.StatusBar.Text = ex.Message;
}
}
btnCatFile.Label = Properties.Settings.Default.categoryFile;
if (btnCatFile.Label.Length > 0)
{
try
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(btnCatFile.Label);
gLastFolder = fInfo.DirectoryName;
if (LoadCategoryDataColumns())
Fill_CategoryDropDownBoxes();
}
catch (Exception ex)
{
gApplication.StatusBar.Text = ex.Message;
}
}
//if(gSettings.operonFile.Length ==0 & gSettings.operonSheet.Length>0)
//if (Properties.Settings.Default.categoryFile.Length == 0 & Properties.Settings.Default.referenceFile.Length > 0)
//{
// cbUseCategories.Checked = false;
// cbUseRegulons.Checked = true;
// Properties.Settings.Default.useCat = false;
//}
btnRegInfoFileName.Label = gSettings.regulonInfoFIleName;
if (btnRegInfoFileName.Label.Length > 0) // check this with merge from home 17/03/2022
try
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(btnRegInfoFileName.Label);
gLastFolder = fInfo.DirectoryName;
if (LoadRegulonInfoDataColumns())
Fill_RegulonInfoDropDownBoxes();
}
catch (Exception ex)
{
gApplication.StatusBar.Text = ex.Message;
}
cbDescending.Checked = !Properties.Settings.Default.sortAscending;
cbAscending.Checked = Properties.Settings.Default.sortAscending;
cbGSEAFC.Checked = true; // Properties.Settings.Default.gseaFC;
cbGSEAP.Checked = false; // !Properties.Settings.Default.gseaFC;
cbGenesFileMapping.Checked = false; // Properties.Settings.Default.genesMappingVisible;
cbRegulonMapping.Checked = false; // Properties.Settings.Default.regulonMappingVisible;
cbCategoryMapping.Checked = false;
//operonMappingVisible
chkRegulon.Checked = Properties.Settings.Default.regPlot;
cbVolcano.Checked = Properties.Settings.Default.vcPlot;
cbMapping.Checked = Properties.Settings.Default.tblMap;
cbSummary.Checked = Properties.Settings.Default.tblSummary;
cbCombined.Checked = Properties.Settings.Default.tblCombine;
cbUseOperons.Checked = Properties.Settings.Default.useOperons;
cbClustered.Checked = Properties.Settings.Default.catPlot;
cbDistribution.Checked = Properties.Settings.Default.distPlot;
//cbUseCategories.Checked = Properties.Settings.Default.useCat;
//cbUseRegulons.Checked = !Properties.Settings.Default.useCat;
cbUsePValues.Checked = Properties.Settings.Default.use_pvalues;
cbUseFoldChanges.Checked = Properties.Settings.Default.use_foldchange;
cbNoFilter.Checked = (cbUsePValues.Checked == false) && (cbUseFoldChanges.Checked == false);
// load the up/down definitions
gAvailItems = PropertyItems("directionMapUnassigned");
gUpItems = PropertyItems("directionMapUp");
gDownItems = PropertyItems("directionMapDown");
cbUseRegulons.Checked = gSettings.useRegulons & (!gSettings.useOperons & !gSettings.useCat) & (gDownItems.Count > 0 | gUpItems.Count > 0);
cbUseCategories.Checked = gSettings.useCat & (!gSettings.useOperons & !gSettings.useRegulons);
cbUseOperons.Checked = gSettings.useOperons & (!gSettings.useRegulons & !gSettings.useCat);
AdjustFocusChecks();
}
/// <summary>
/// The initial load procedure of the Add-in. Initialize fields and labels depending on last known settings
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GinRibbon_Load(object sender, RibbonUIEventArgs e)
{
gApplication = Globals.ThisAddIn.GetExcelApplication();
// set the static application for plot routines
PlotRoutines.theApp = gApplication;
gSettings = Properties.Settings.Default;
InitFields();
// run this line to mimic first time installation 23-03
// gSettings.Reset();
LoadPersistentSettings();
EnableOutputOptions(false);
gExcelErrorValues = ((int[])Enum.GetValues(typeof(ExcelUtils.CVErrEnum))).ToList();
gCategoryFileSelected = System.IO.File.Exists(Properties.Settings.Default.categoryFile);
gRegulonFileSelected = System.IO.File.Exists(Properties.Settings.Default.referenceFile);
gGenesFileSelected = System.IO.File.Exists(Properties.Settings.Default.genesFileName);
gOperonFileSelected = System.IO.File.Exists(Properties.Settings.Default.operonFile);
gRegulonInfoFileSelected = System.IO.File.Exists(Properties.Settings.Default.regulonInfoFIleName);
btLoad.Enabled = System.IO.File.Exists(gSettings.referenceFile) | System.IO.File.Exists(gSettings.categoryFile) | System.IO.File.Exists(gSettings.genesFileName) | System.IO.File.Exists(gSettings.regulonInfoFIleName);
}
private void AdjustFocusChecks()
{
if (!cbUseCategories.Enabled)
{
cbUseCategories.Checked = false;
gSettings.useCat = false;
}
if (!cbUseOperons.Enabled)
{
cbUseOperons.Checked = false;
gSettings.useOperons = false;
}
if (!cbUseRegulons.Enabled)
{
cbUseRegulons.Checked = false;
gSettings.useRegulons = false;
}
}
/// <summary>
/// Enable/disable possible output buttons (i.e. table or charts).
/// </summary>
/// <param name="enable"></param>
private void EnableOutputOptions(bool enable)
{
ebLow.Enabled = enable;
editMinPval.Enabled = enable;
cbMapping.Enabled = enable;
cbSummary.Enabled = enable;
cbCombined.Enabled = enable;
cbClustered.Enabled = enable;
cbDistribution.Enabled = enable;
chkRegulon.Enabled = enable;
cbVolcano.Enabled = enable;
cbUseCategories.Enabled = enable && gCategoriesWB != null; //gCategoryFileSelected &&
cbUseRegulons.Enabled = enable && (gRegulonWB != null && (gDownItems.Count > 0 | gUpItems.Count > 0)); //(gRegulonFileSelected
cbUseOperons.Enabled = enable && gRefOperonsWB != null;
cbUsePValues.Enabled = enable;
cbUseFoldChanges.Enabled = enable;
cbNoFilter.Enabled = enable;
cbAscending.Enabled = enable;
cbDescending.Enabled = enable;
AdjustFocusChecks();
}
/// <summary>
/// Helper function to get the active cell from the current worksheet
/// </summary>
/// <returns></returns>
private Excel.Range GetActiveCell()
{
if (gApplication != null)
{
try { return (Excel.Range)gApplication.Selection; }
catch { return null; }
}
return null;
}
/// <summary>
/// Return the active worksheet that is selected. If the active sheet is a chart then show warning message.
/// </summary>
/// <returns></returns>
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;
}
/// <summary>
/// Determine if the cell contains an integer, else return error
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private bool IsErrorCell(object obj)
{
return (obj is Int32 @int) && gExcelErrorValues.Contains(@int);
}
/// <summary>
/// The main routine to map the data to a list of genes with their associated FC, p-values etc.. and a list of regulons
/// </summary>
/// <param name="theCells"></param>
/// <returns>A list of data genes</returns>
private List<BsuLinkedItems> AugmentWithRegulonData(List<BsuLinkedItems> theInputData)
{
AddTask(TASKS.AUGMENTING_WITH_REGULON_DATA);
// create a view and sort it to improve querying performance..
DataView _regulonView = new DataView(gRegulonWB);
_regulonView.Sort = Properties.Settings.Default.referenceBSU;
// loop of the number of rows in rangeBSU
foreach (BsuLinkedItems _it in theInputData)
{
if ((_it.BSU.Length > 0) & !(gRegulonWB is null))
{
// find the entries that are linked by the same gene
SysData.DataRow[] results = LookupRegulon(_it.BSU);
// loop over the entries (=regulons) found
for (int r = 0; r < results.Length; r++)
{
// check for existence if mapped to regulon
string item = results[r][Properties.Settings.Default.referenceRegulon].ToString();
string direction = results[r][Properties.Settings.Default.referenceDIR].ToString();
if (item.Length > 0)
{
if (gUpItems.Contains(direction))
{
_it.REGULON_UP.Add(r);
_it.Regulons.Add(new RegulonItem(item, "UP"));
}
if (gDownItems.Contains(direction))
{
_it.Regulons.Add(new RegulonItem(item, "DOWN"));
_it.REGULON_DOWN.Add(r);
}
if (!gUpItems.Contains(direction) & !gDownItems.Contains(direction))
{
_it.REGULON_UNKNOWN_DIR.Add(r);
_it.Regulons.Add(new RegulonItem(item, "NOT DEFINED"));
}
}
}
}
}
//foreach (BsuLinkedItems _it in theInputData)
//{
// if (_it.GeneName!="")
// gRegulonDict.Add(_it.GeneName, _it.Regulons.Select(r => r.Name).ToArray());
//}
RemoveTask(TASKS.AUGMENTING_WITH_REGULON_DATA);
return theInputData;
}
/// <summary>
/// The main routine to map the data to a list of genes with their associated FC, p-values etc.. and a possibly a list of categories..
/// </summary>
/// <param name="theCells"></param>
/// <returns>A list of data genes</returns>
private List<BsuLinkedItems> AugmentWithCategoryData(List<BsuLinkedItems> theInputData)
{
AddTask(TASKS.AUGMENTING_WITH_CATEGORY_DATA);
DataView _catView = new DataView(gCategoriesWB);
_catView.Sort = "locus_tag"; // Properties.Settings.Default.catBSUColum;
// loop of the number of rows in rangeBSU
foreach (BsuLinkedItems _it in theInputData)
{
if ((_it.BSU.Length > 0) & !(gCategoriesWB is null))
{
// find the entries that are linked by the same gene
SysData.DataRow[] results = LookupCategory(_it.BSU);
foreach (DataRow row in results)
{
string[] c1 = new string[] { row["cat1"].ToString(), row["cat2"].ToString(), row["cat3"].ToString(), row["cat4"].ToString(), row["cat5"].ToString() };
string catName = "";
foreach (string s in c1)
{
if (s.Length > 0)
catName = s;
}
string genID = row["locus_tag"].ToString();
string catID = row["catid_short"].ToString();
CategoryItem _lCat = new CategoryItem(catName, catID, genID);
_it.Categories.Add(_lCat);
}
}
}
//foreach (BsuLinkedItems _it in theInputData)
//{
// if (_it.GeneName != "")
// gCategoryDict.Add(_it.GeneName, _it.Categories.Select(r => r.catID).ToArray());
//}
RemoveTask(TASKS.AUGMENTING_WITH_CATEGORY_DATA);
return theInputData;
}
/// <summary>
/// Get the address in string format of a specified range
/// </summary>
/// <param name="rng"></param>
/// <returns></returns>
public string RangeAddress(Excel.Range rng)
{
return rng.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
}
/// <summary>
/// Get the addres in string format of a specified cell
/// </summary>
/// <param name="sht"></param>
/// <param name="row"></param>
/// <param name="col"></param>
/// <returns></returns>
public string CellAddress(Excel.Worksheet sht, int row, int col)
{
return RangeAddress(sht.Cells[row, col]);
}
/// <summary>
/// Get the string that should be displayed on the status bar, depending on the task that is running
/// </summary>
/// <param name="task"></param>
/// <returns></returns>
private string GetStatusTask(TASKS task)
{
return taks_strings[(int)task];
}
/// <summary>
/// Set the text of the status bar
/// </summary>
/// <param name="activeTask"></param>
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;
}
}
/// <summary>
/// Add the task to the list of tasks. The order is last in, first out (LIFO)
/// </summary>
/// <param name="newTask"></param>
private void AddTask(TASKS newTask)
{
gTasks.Add(newTask);
SetStatus(newTask);
}
/// <summary>
/// Remove the task after completion or error and set to ready if no more tasks are performed
/// </summary>
/// <param name="taskReady"></param>
private void RemoveTask(TASKS taskReady)
{
gTasks.Remove(taskReady);
if (gTasks.Count == 0 || gTasks[0] == TASKS.READY)
SetStatus(TASKS.READY);
else
SetStatus(gTasks.Last());
}
/// <summary>
/// Detemine if a selected range is different from what previously selected
/// </summary>
/// <returns></returns>
private bool InputHasChanged()
{
bool changed = false;
if (gOldRangeBSU != gRangeBSU.Address.ToString())
{
gOldRangeBSU = gRangeBSU.Address.ToString();
changed = true;
}
if (gOldRangeP != gRangeP.Address.ToString())
{
gOldRangeP = gRangeP.Address.ToString();
changed = true;
}
if (gOldRangeFC != gRangeFC.Address.ToString())
{
gOldRangeFC = gRangeFC.Address.ToString();
changed = true;
}
return changed;
}
/// <summary>
/// Copy the text in tables to a worksheet using a single assignment to an Excel.Range
/// </summary>
/// <param name="dt">data table</param>
/// <param name="sheet">existing worksheet</param>
/// <param name="firstRow">first row in worksheet</param>
/// <param name="firstCol">first column in worksheet</param>
/// <param name="lastRow">last row in worksheet</param>
/// <param name="lastCol">last column in worksheet</param>
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;
}
/// <summary>
/// Copy the cells green if value is positive and red if value in table is negative
/// </summary>
/// <param name="dt"></param>
/// <param name="sheet"></param>
/// <param name="firstRow"></param>
/// <param name="firstCol"></param>
/// <param name="lastRow"></param>
/// <param name="lastCol"></param>
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);
}
/// <summary>
/// Return a list of sheet that already exist
/// </summary>
/// <returns></returns>
private List<string> ListSheets()
{
// get a list of all sheet names
List<string> _sheets = new List<string>();
foreach (var sheet in gApplication.Sheets)
{
if (sheet is Excel.Chart _c)
_sheets.Add(_c.Name);
else
_sheets.Add(((Excel.Worksheet)sheet).Name);
}
return _sheets;
}
/// <summary>
/// Create a new non-existing sheet name that starts with a given prefix
/// </summary>
/// <param name="wsBase"></param>
/// <returns></returns>
private int NextWorksheet(string wsBase)
{
// create a sheetname starting with wsBase
List<string> currentSheets = ListSheets();
string sheetName = wsBase.Replace("Plot", "Tab");
string chartName = wsBase.Replace("Tab", "Plot");
int s = 1;
while (currentSheets.Contains(string.Format("{0}{1}", chartName, s)) || currentSheets.Contains(string.Format("{0}{1}", sheetName, s)))
s += 1;
return s;
}
/// <summary>
/// Determine fist possible suffix for a set of worksheets.
/// </summary>
/// <param name="aSheet"></param>
/// <param name="wsBase"></param>
/// <returns></returns>
private int FindSheetNames(string[] wsBase)
{
// create a sheetname starting with wsBase
List<string> currentSheets = ListSheets();
int s = 1;
while (true)
{
List<bool> aList = new List<bool>();
for (int i = 0; i < wsBase.Length; i++)
aList.Add(currentSheets.Contains(string.Format("{0}_{1}", wsBase[i], s)));
if (!aList.Contains(true))
break;
s++;
}
return s;
}
/// <summary>
/// Rename a newly created worksheet with a given prefix.
/// </summary>
/// <param name="aSheet"></param>
/// <param name="wsBase"></param>
/// <returns></returns>
private int RenameWorksheet(object aSheet, string wsBase)
{
// create a sheetname starting with wsBase
List<string> currentSheets = ListSheets();
int s = 1;
while (currentSheets.Contains(string.Format("{0}_{1}", wsBase, s)))
s += 1;
if (aSheet is Excel.Worksheet _w)
{
_w.Name = string.Format("{0}_{1}", wsBase, s);
}
return s;
}
/// <summary>
/// Return a list of genes and their FCs that are linked by a single operon
/// </summary>
/// <param name="opid"></param>
/// <param name="lLst"></param>
/// <returns></returns>
private (List<string>, List<double>) GetOperonGenesFC(/*string operon,*/ string opid, List<BsuLinkedItems> lLst)
{
SysData.DataRow[] lquery = gRefOperonsWB.Select(string.Format("op_id = '{0}'", opid));
List<string> _genes = new List<string>();
List<double> _lfcs = new List<double>();
foreach (DataRow row in lquery)
{
string lgene = row["gene"].ToString();
_genes.Add(lgene);
BsuLinkedItems result = lLst.Find(item => item.GeneName == lgene);
if (result != null)
_lfcs.Add(result.FC);
else
_lfcs.Add(Double.NaN);
}
return (_genes, _lfcs);
}
private List<BsuLinkedItems> AugmentWithGeneInfo(List<Excel.Range> theCells)
{
AddTask(TASKS.AUGMENTING_WITH_GENES_INFO);