-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScans.cs
403 lines (381 loc) · 13.5 KB
/
Scans.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
using org.COPASI;
using Microsoft.VisualBasic.FileIO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
namespace CopasiApi
{
public class Scans
{
private string SOURCE_FOLDER = "scans";
private string SOURCE_MODEL = "Model.cps";
private string TARGET_MODEL = "Model-scan.cps";
private string SOURCE_SCANS = "fit.csv";
private string TARGET_SCAN = "scan.csv";
private string TARGET_SCANS = "scans.csv";
private string TARGET_MATRIX = "matrix.csv";
private string TARGET_FOLDER = "results";
private string[] CNVS = { "CNV_MIR335", "CNV_MIR16-2" };
private string[] SPECIES = new string[] { "PLAUR", "MIR335", "MIR16-2" , "JUND", "FOXP2", "TFAP2C", "FOSL1" };
private string MAIN = "PLAUR";
private uint STEPS = 4;
private double MIN = 1.0;
private double MAX = 5.0;
private List<string> lines;
private List<string> list;
private Dictionary<string, List<double>> dict;
public Scans()
{
ProcessData();
ProcessModel();
// ProcessScans();
Process3dScans();
}
private void ProcessData()
{
dict = new Dictionary<string, List<double>>();
try
{
var path = SOURCE_FOLDER + "/" + SOURCE_SCANS;
using (var parser = new TextFieldParser(path))
{
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
var row = parser.ReadFields();
if (row[0] == "LINE")
{
lines = new List<string>();
list = new List<string>(row.Skip(1));
}
else
{
var line = row[0];
lines.Add(line);
var list = new List<double>(row.Skip(1).Select((val) => Double.Parse(val)));
dict.Add(line, new List<double>(list));
}
}
}
}
catch (Exception exception)
{
printError(exception, "ProcessData");
}
}
private void ProcessModel()
{
var modelPath = Path.GetFullPath(SOURCE_FOLDER + "/" + SOURCE_MODEL);
var dataModel = CRootContainer.addDatamodel();
dataModel.addModel(modelPath);
var model = dataModel.getModel();
var reports = dataModel.getReportDefinitionList();
var report = reports.createReportDefinition("PS", "3 dimensional table");
report.setTaskType(CTaskEnum.Task_scan);
report.setIsTable(true);
report.setPrecision(6);
report.setSeparator(new CCopasiReportSeparator(","));
var scanTask = (CScanTask)dataModel.getTask("Scan");
scanTask.setUpdateModel(false);
scanTask.setScheduled(false);
scanTask.getReport().setReportDefinition(report);
scanTask.getReport().setAppend(false);
var scanProblem = (CScanProblem)scanTask.getProblem();
scanProblem.setModel(dataModel.getModel());
scanProblem.setSubtask(CTaskEnum.Task_steadyState);
var table = report.getTableAddr();
var numModelValues = model.getNumModelValues();
var count = 0;
for (var i = 0; CNVS.Length != count && i < numModelValues; ++i)
{
var modelValue = model.getModelValue((uint)i);
var initialValueRef = modelValue.getInitialValueReference();
var cn = initialValueRef.getCN();
var cnStr = cn.getString();
var cnv = CNVS.ToList().Find((item) => cnStr.Contains(item));
if (cnv != null)
{
var cnvCn = new CRegisteredCommonName(initialValueRef.getCN().getString());
table.Add(cnvCn);
var scanItem = scanProblem.addScanItem(CScanProblem.SCAN_LINEAR, STEPS);
scanProblem.setContinueFromCurrentState(false);
scanProblem.setOutputInSubtask(false);
scanProblem.setContinueOnError(false);
scanItem.getParameter("Object").setCNValue(cnvCn);
scanItem.getParameter("Minimum").setDblValue(MIN);
scanItem.getParameter("Maximum").setDblValue(MAX);
scanItem.getParameter("log").setBoolValue(false);
scanItem.getParameter("Values").setStringValue("");
scanItem.getParameter("Use Values").setBoolValue(false);
++count;
}
}
if (MAIN != null && MAIN != "")
{
table.Add(new CRegisteredCommonName(model.getMetabolite(MAIN).getConcentrationReference().getCN().getString()));
}
else
{
SPECIES.ToList().ForEach((specie) =>
{
table.Add(new CRegisteredCommonName(model.getMetabolite(specie).getConcentrationReference().getCN().getString()));
});
}
var success = true;
for (var l = 0; success && l < lines.Count; ++l)
{
success &= ProcessTask(dataModel, model, scanTask, numModelValues, lines[l]);
}
}
private bool ProcessTask(CDataModel dataModel, CModel model, CScanTask scanTask, uint numModelValues, string line)
{
var results = SOURCE_FOLDER + "/" + TARGET_FOLDER + "/" + line;
if (!Directory.Exists(results))
{
Directory.CreateDirectory(results);
}
var targetModel = Path.GetFullPath(results + "/" + TARGET_MODEL);
var targetFile = Path.GetFullPath(results + "/" + TARGET_SCAN);
var regex = new Regex("Values\\[([^\\\\]+)\\\\");
for (var i = 0; i < numModelValues; ++i)
{
var modelValue = model.getModelValue((uint)i);
var initialValueRef = modelValue.getInitialValueReference();
var cn = initialValueRef.getCN();
var cnStr = cn.getString();
var name = regex.Match(cnStr).Groups[1].Value;
var index = list.IndexOf(name);
if (index > -1)
{
modelValue.setInitialValue(dict[line][index]);
}
else if (name.StartsWith("T0_"))
{
var parts = name.Split("_");
index = list.IndexOf(parts[1]);
if (index > -1)
{
modelValue.setInitialValue(dict[line][index]);
}
}
}
model.compile();
scanTask.getReport().setTarget(targetFile);
var saved = dataModel.saveModel(targetModel, true);
Console.WriteLine("\t|-> Model Saved (" + saved + "): " + targetModel);
var processed = scanTask.process(true);
Console.WriteLine("\t|\t|-> Scan Processed (" + processed + "): " + targetFile);
return saved && processed;
}
private void ProcessScans()
{
try
{
var table = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
var path = SOURCE_FOLDER + "/" + TARGET_FOLDER;
var directoryInfo = new DirectoryInfo(path);
var directories = directoryInfo.GetDirectories();
var names = directories.OrderBy(file => file.CreationTime).Select((dir) => dir.Name);
List<string> prefixes = null;
List<string> suffixes = null;
List<string> headers = new List<string>() { "LINE" };
var first = true;
var lines = names.ToList();
lines.ForEach((line) =>
{
table.Add(line, new Dictionary<string, Dictionary<string, string>>());
var file = path + "/" + line + "/" + TARGET_SCAN;
using (var parser = new TextFieldParser(file))
{
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
var row = parser.ReadFields();
if (row[0].Contains("Values"))
{
if (first)
{
prefixes = new List<string>();
suffixes = new List<string>();
var regex = new Regex("Values\\[([^\\[]+)");
var match = regex.Match(row[0]);
var value = match.Groups[1].Value;
prefixes.Add(value);
table[line].Add(value, new Dictionary<string, string>());
regex = new Regex("\\[([^\\[]+)\\]");
row.Skip(1).ToList().ForEach((pre) =>
{
match = regex.Match(pre);
value = match.Groups[1].Value;
prefixes.Add(value);
table[line].Add(value, new Dictionary<string, string>());
});
}
}
else
{
var suffix = row[0];
if (first)
{
suffixes.Add(suffix);
}
prefixes.ForEach((pre) =>
{
if (!table[line].ContainsKey(pre))
{
table[line][pre] = new Dictionary<string, string>();
}
});
var rowInd = 0;
row.ToList().ForEach((val) =>
{
var preInd = 0;
prefixes.ForEach((pre) =>
{
if (rowInd == preInd)
{
table[line][pre].Add(suffix, val);
}
++preInd;
});
++rowInd;
});
}
}
}
if (first)
{
prefixes.ForEach((pre) =>
{
suffixes.ForEach((suf) =>
{
headers.Add(pre + "_" + suf);
});
});
first = false;
}
});
var csv = new StringBuilder();
csv.AppendLine(String.Join(",", headers));
lines.ForEach((line) =>
{
Console.WriteLine("\t|-> Scan Parsing: " + line);
var row = new List<string>() { line };
prefixes.ForEach((pre) =>
{
suffixes.ForEach((suf) =>
{
if (table.ContainsKey(line) && table[line].ContainsKey(pre) && table[line][pre].ContainsKey(suf))
{
row.Add(table[line][pre][suf]);
}
else
{
row.Add("nan");
}
});
});
csv.AppendLine(String.Join(",", row));
});
File.WriteAllText(SOURCE_FOLDER + "/" + TARGET_FOLDER + "/" + TARGET_SCANS, csv.ToString());
}
catch (Exception exception)
{
printError(exception, "ProcessScans");
}
}
private void Process3dScans()
{
try
{
var table = new Dictionary<string, Dictionary<double, Dictionary<double, Dictionary<bool, double>>>>();
var path = SOURCE_FOLDER + "/" + TARGET_FOLDER;
var directoryInfo = new DirectoryInfo(path);
var directories = directoryInfo.GetDirectories();
var names = directories.OrderBy(file => file.CreationTime).Select((dir) => dir.Name);
var lines = names.ToList();
var isHeader = true;
var header = new List<string>();
header.Add("Line");
lines.ForEach((line) =>
{
Console.WriteLine("\t|-> Scan Parsing: " + line);
table.Add(line, new Dictionary<double, Dictionary<double, Dictionary<bool, double>>>());
var file = path + "/" + line + "/" + TARGET_SCAN;
var isFirst = true;
var div = 0.0;
using (var parser = new TextFieldParser(file))
{
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
var row = parser.ReadFields();
if (row[0].Contains("Values"))
{
if (isHeader)
{
isHeader = false;
var regexInitial = new Regex(@"\[(.+)\[");
var regexSpecies = new Regex(@"\[(.+)\]");
var x = regexInitial.Match(row[0]).Groups[1].Value;
var y = regexInitial.Match(row[1]).Groups[1].Value;
var z = regexSpecies.Match(row[2]).Groups[1].Value;
header.Add(x);
header.Add(y);
header.Add(z);
header.Add("NOR_" + z);
}
}
else
{
var x = Double.Parse(row[0]);
var y = Double.Parse(row[1]);
var z = Double.Parse(row[2]);
if (isFirst)
{
isFirst = false;
div = z;
}
if (!table[line].ContainsKey(x))
{
table[line].Add(x, new Dictionary<double, Dictionary<bool, double>>());
}
if (!table[line][x].ContainsKey(y))
{
table[line][x].Add(y, new Dictionary<bool, double>());
}
table[line][x][y].Add(false, z);
table[line][x][y].Add(true, z / div);
}
}
}
});
var csv = new StringBuilder();
csv.AppendLine(String.Join(",", header));
lines.ForEach((line) =>
{
table[line].Keys.ToList().ForEach((x) => {
table[line][x].Keys.ToList().ForEach((y) => {
var z = table[line][x][y][false];
var n = table[line][x][y][true];
csv.AppendLine(line + "," + x + "," + y + "," + z + "," + n);
});
});
});
File.WriteAllText(SOURCE_FOLDER + "/" + TARGET_FOLDER + "/" + TARGET_MATRIX, csv.ToString());
}
catch (Exception exception)
{
printError(exception, "Process3dScans");
}
}
private void printError(Exception exception, string source)
{
Console.Error.WriteLine("ERROR (" + source + "): " + exception);
Environment.Exit(1);
}
}
}