-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrdml.py
executable file
·17836 lines (15734 loc) · 796 KB
/
rdml.py
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
#!/usr/bin/python
from __future__ import division
from __future__ import print_function
import sys
import io
import os
import re
import datetime
import zipfile
import tempfile
import argparse
import math
import warnings
import json
import csv
import numpy as np
import scipy.stats as scp
from matplotlib.backends.backend_svg import FigureCanvasSVG as figSVG
from matplotlib.figure import Figure as plt_fig
from lxml import etree as et
def get_rdml_lib_version():
"""Return the version string of the RDML library.
Returns:
The version string of the RDML library.
"""
return "3.0.0"
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.bool_):
return bool(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NpEncoder, self).default(obj)
class RdmlError(Exception):
"""Basic exception for errors raised by the RDML-Python library"""
def __init__(self, message):
Exception.__init__(self, message)
pass
class secondError(RdmlError):
"""Just to have, not used yet"""
def __init__(self, message):
RdmlError.__init__(self, message)
pass
def _add_err(err, sep, text):
"""Get the var as float or "".
Args:
err: The error string to append to.
sep: The seperator used if the string is not empty.
text: The text to append.
Returns:
The error string.
"""
if err == "":
return text
else:
return err + sep + text
def _save_float(var):
"""Get the var as float or "".
Args:
var: The value as float.
Returns:
The float or "" on error.
"""
if var == "":
return ""
try:
vFloat = float(var)
except ValueError:
return ""
else:
if math.isfinite(vFloat):
return vFloat
else:
return ""
def _get_copies_threshold():
"""Get the number of copies at threshold (rule of thumb).
Returns:
The number of copies at threshold as float.
"""
copies = 10 * pow(1.9, 35.0) * 20.0 / 50.0
return copies
def _get_first_child(base, tag):
"""Get a child element of the base node with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
The first child lxml node element found or None.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
return node
return None
def _get_first_child_text(base, tag):
"""Get a child element of the base node with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
The text of first child node element found or an empty string.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
return node.text
return ""
def _get_first_child_bool(base, tag, triple=True):
"""Get a child element of the base node with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
triple: If True, None is returned if not found, if False, False
Returns:
The a bool value of tag or if triple is True None.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
return _string_to_bool(node.text, triple)
if triple is False:
return False
else:
return None
def _get_step_sort_nr(elem):
"""Get the number of the step eg. for sorting.
Args:
elem: The node element. (lxml node)
Returns:
The a int value of the step node nr.
"""
if elem is None:
raise RdmlError('A step element must be provided for sorting.')
ret = _get_first_child_text(elem, "nr")
if ret == "":
raise RdmlError('A step element must have a \"nr\" element for sorting.')
return int(ret)
def _sort_list_int(elem):
"""Get the first element of the array as int. for sorting.
Args:
elem: The 2d list
Returns:
The a int value of the first list element.
"""
return int(elem[0])
def _sort_list_float(elem):
"""Get the first element of the array as float. for sorting.
Args:
elem: The 2d list
Returns:
The a float value of the first list element.
"""
return float(elem[0])
def _sort_list_digital_PCR(elem):
"""Get the first column of the list as int. for sorting.
Args:
elem: The list
Returns:
The a int value of the first list element.
"""
arr = elem.split("\t")
return int(arr[0]), arr[4]
def _string_to_bool(value, triple=True):
"""Translates a string into bool value or None.
Args:
value: The string value to evaluate. (string)
triple: If True, None is returned if not found, if False, False
Returns:
The a bool value of tag or if triple is True None.
"""
if value is None or value == "":
if triple is True:
return None
else:
return False
if type(value) is bool:
return value
if type(value) is int:
if value != 0:
return True
else:
return False
if type(value) is str:
if value.lower() in ['false', '0', 'f', '-', 'n', 'no']:
return False
else:
return True
return
def _value_to_booldic(value):
"""Translates a string, list or dic to a dictionary with true/false.
Args:
value: The string value to evaluate. (string)
Returns:
The a bool value of tag or if triple is True None.
"""
ret = {}
if type(value) is str:
ret[value] = True
if type(value) is list:
for ele in value:
ret[ele] = True
if type(value) is dict:
for key, val in value.items():
ret[key] = _string_to_bool(val, triple=False)
return ret
def _get_first_child_by_pos_or_id(base, tag, by_id, by_pos):
"""Get a child element of the base node with a given tag and position or id.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
by_id: The unique id to search for. (string)
by_pos: The position of the element in the list (int)
Returns:
The child node element found or raise error.
"""
if by_id is None and by_pos is None:
raise RdmlError('Either an ' + tag + ' id or a position must be provided.')
if by_id is not None and by_pos is not None:
raise RdmlError('Only an ' + tag + ' id or a position can be provided.')
allChildren = _get_all_children(base, tag)
if by_id is not None:
for node in allChildren:
if node.get('id') == by_id:
return node
raise RdmlError('The ' + tag + ' id: ' + by_id + ' was not found in RDML file.')
if by_pos is not None:
if by_pos < 0 or by_pos > len(allChildren) - 1:
raise RdmlError('The ' + tag + ' position ' + by_pos + ' is out of range.')
return allChildren[by_pos]
def _add_first_child_to_dic(base, dic, opt, tag):
"""Adds the first child element with a given tag to a dictionary.
Args:
base: The base node element. (lxml node)
dic: The dictionary to add the element to (dictionary)
opt: If false and id is not found in base, the element is added with an empty string (Bool)
tag: Child elements group tag used to select the elements. (string)
Returns:
The dictionary with the added element.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
dic[tag] = node.text
return dic
if not opt:
dic[tag] = ""
return dic
def _get_all_children(base, tag):
"""Get a list of all child elements with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
A list with all child node elements found or an empty list.
"""
ret = []
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
ret.append(node)
return ret
def _get_all_children_id(base, tag):
"""Get a list of ids of all child elements with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
A list with all child id strings found or an empty list.
"""
ret = []
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
ret.append(node.get('id'))
return ret
def _get_number_of_children(base, tag):
"""Count all child elements with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
A int number of the found child elements with the id.
"""
counter = 0
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
counter += 1
return counter
def _check_unique_id(base, tag, id):
"""Find all child elements with a given group and check if the id is already used.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
id: The unique id to search for. (string)
Returns:
False if the id is already used, True if not.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
if node.get('id') == id:
return False
return True
def _create_new_element(base, tag, id):
"""Create a new element with a given tag and id.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag. (string)
id: The unique id of the new element. (string)
Returns:
False if the id is already used, True if not.
"""
if id is None or id == "":
raise RdmlError('An ' + tag + ' id must be provided.')
if not _check_unique_id(base, tag, id):
raise RdmlError('The ' + tag + ' id "' + id + '" must be unique.')
return et.Element(tag, id=id)
def _add_new_subelement(base, basetag, tag, text, opt):
"""Create a new element with a given tag and id.
Args:
base: The base node element. (lxml node)
basetag: Child elements group tag. (string)
tag: Child elements own tag, to be created. (string)
text: The text content of the new element. (string)
opt: If true, the element is optional (Bool)
Returns:
Nothing, the base lxml element is modified.
"""
if opt is False:
if text is None or text == "":
raise RdmlError('An ' + basetag + ' ' + tag + ' must be provided.')
et.SubElement(base, tag).text = text
else:
if text is not None and text != "":
et.SubElement(base, tag).text = text
def _change_subelement(base, tag, xmlkeys, value, opt, vtype, id_as_element=False):
"""Change the value of the element with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements own tag, to be created. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
value: The text content of the new element.
opt: If true, the element is optional (Bool)
vtype: If true, the element is optional ("string", "int", "float")
id_as_element: If true, handle tag "id" as element, else as attribute
Returns:
Nothing, the base lxml element is modified.
"""
# Todo validate values with vtype
goodVal = value
if vtype == "bool":
ev = _string_to_bool(value, triple=True)
if ev is None or ev == "":
goodVal = ""
else:
if ev:
goodVal = "true"
else:
goodVal = "false"
if opt is False:
if goodVal is None or goodVal == "":
raise RdmlError('A value for ' + tag + ' must be provided.')
if tag == "id" and id_as_element is False:
if base.get('id') != goodVal:
par = base.getparent()
groupTag = base.tag.replace("{http://www.rdml.org}", "")
if not _check_unique_id(par, groupTag, goodVal):
raise RdmlError('The ' + groupTag + ' id "' + goodVal + '" is not unique.')
base.attrib['id'] = goodVal
return
# Check if the tag already excists
elem = _get_first_child(base, tag)
if elem is not None:
if goodVal is None or goodVal == "":
base.remove(elem)
else:
elem.text = goodVal
else:
if goodVal is not None and goodVal != "":
new_node = et.Element(tag)
new_node.text = goodVal
place = _get_tag_pos(base, tag, xmlkeys, 0)
base.insert(place, new_node)
def _get_or_create_subelement(base, tag, xmlkeys):
"""Get element with a given tag, if not present, create it.
Args:
base: The base node element. (lxml node)
tag: Child elements own tag, to be created. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
Returns:
The node element with the tag.
"""
# Check if the tag already excists
if _get_first_child(base, tag) is None:
new_node = et.Element(tag)
place = _get_tag_pos(base, tag, xmlkeys, 0)
base.insert(place, new_node)
return _get_first_child(base, tag)
def _remove_irrelevant_subelement(base, tag):
"""If element with a given tag has no children, remove it.
Args:
base: The base node element. (lxml node)
tag: Child elements own tag, to be created. (string)
Returns:
The node element with the tag.
"""
# Check if the tag already excists
elem = _get_first_child(base, tag)
if elem is None:
return
if len(elem) == 0:
base.remove(elem)
def _move_subelement(base, tag, id, xmlkeys, position):
"""Change the value of the element with a given tag.
Args:
base: The base node element. (lxml node)
tag: The id to search for. (string)
id: The unique id of the new element. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
position: the new position of the element (int)
Returns:
Nothing, the base lxml element is modified.
"""
pos = _get_tag_pos(base, tag, xmlkeys, position)
ele = _get_first_child_by_pos_or_id(base, tag, id, None)
base.insert(pos, ele)
def _move_subelement_pos(base, tag, oldpos, xmlkeys, position):
"""Change the value of the element with a given tag.
Args:
base: The base node element. (lxml node)
tag: The id to search for. (string)
oldpos: The unique id of the new element. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
position: the new position of the element (int)
Returns:
Nothing, the base lxml element is modified.
"""
pos = _get_tag_pos(base, tag, xmlkeys, position)
ele = _get_first_child_by_pos_or_id(base, tag, None, oldpos)
base.insert(pos, ele)
def _get_tag_pos(base, tag, xmlkeys, pos):
"""Returns a position were to add a subelement with the given tag inc. pos offset.
Args:
base: The base node element. (lxml node)
tag: The id to search for. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
pos: The position relative to the tag elements (int)
Returns:
The int number of were to add the element with the tag.
"""
count = _get_number_of_children(base, tag)
offset = pos
if pos is None or pos < 0:
offset = 0
pos = 0
if pos > count:
offset = count
return _get_first_tag_pos(base, tag, xmlkeys) + offset
def _get_first_tag_pos(base, tag, xmlkeys):
"""Returns a position were to add a subelement with the given tag.
Args:
base: The base node element. (lxml node)
tag: The id to search for. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
Returns:
The int number of were to add the element with the tag.
"""
listrest = xmlkeys[xmlkeys.index(tag):]
counter = 0
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") in listrest:
return counter
counter += 1
return counter
def _writeFileInRDML(rdmlName, fileName, data):
"""Writes a file in the RDML zip, even if it existed before.
Args:
rdmlName: The name of the RDML zip file
fileName: The name of the file to write into the zip
data: The data string of the file
Returns:
Nothing, modifies the RDML file.
"""
needRewrite = False
if os.path.isfile(rdmlName):
try:
with zipfile.ZipFile(rdmlName, 'r') as RDMLin:
for item in RDMLin.infolist():
if item.filename == fileName:
needRewrite = True
except zipfile.BadZipFile as e:
needRewrite = False
if needRewrite:
tempFolder, tempName = tempfile.mkstemp(dir=os.path.dirname(rdmlName))
os.close(tempFolder)
# copy everything except the filename
with zipfile.ZipFile(rdmlName, 'r') as RDMLin:
with zipfile.ZipFile(tempName, mode='w', compression=zipfile.ZIP_DEFLATED) as RDMLout:
RDMLout.comment = RDMLin.comment
for item in RDMLin.infolist():
if item.filename != fileName:
RDMLout.writestr(item, RDMLin.read(item.filename))
if data != "":
RDMLout.writestr(fileName, data)
os.remove(rdmlName)
os.rename(tempName, rdmlName)
else:
with zipfile.ZipFile(rdmlName, mode='a', compression=zipfile.ZIP_DEFLATED) as RDMLout:
RDMLout.writestr(fileName, data)
def _niceQuantityType(txt):
if txt == "cop":
return "copies per microliter"
if txt == "fold":
return "fold change"
if txt == "dil":
return "dilution"
if txt == "nMol":
return "nanomol per microliter"
if txt == "ng":
return "nanogram per microliter"
if txt == "other":
return "other unit"
return txt
def _niceQuantityTypeReact(txt):
if txt == "cop":
return "copies per reaction"
if txt == "fold":
return "fold change"
if txt == "dil":
return "dilution"
if txt == "nMol":
return "nanomol per reaction"
if txt == "ng":
return "nanogram per reaction"
if txt == "other":
return "other unit"
return txt
def _wellRangeToList(wells, columns):
"""Translates a range like "B2-C3" to list ["B2","B3","C2","C3"].
Args:
wells: The range like "B2-C3"
columns: Number of colums in a plate
Returns:
returns a list like ["B2","B3","C2","C3"].
"""
res = []
wellList = []
re_found_comp = re.search(r"(\D)(\d+)-(\D)(\d+)\s*", wells)
if re_found_comp:
letter_s = ord(re_found_comp.group(1).upper())
letter_e = ord(re_found_comp.group(3).upper())
numb_s = int(re_found_comp.group(2))
numb_e = int(re_found_comp.group(4))
if letter_e < letter_s:
temp_num = letter_s
letter_s = letter_e
letter_e = temp_num
if numb_e < numb_s:
temp_num = numb_s
numb_s = numb_e
numb_e = temp_num
for letter in range(letter_s, letter_e + 1):
for numb in range(numb_s, numb_e + 1):
wellList.append(chr(letter) + str(numb))
else:
re_found_simp = re.search(r"(\D)(\d+)\s*", wells)
if re_found_simp:
wellList.append(re_found_simp.group(1) + re_found_simp.group(2))
for well in wellList:
re_found_simp = re.search(r"(\D)(\d+)\s*", well)
if re_found_simp:
letter = ord(re_found_simp.group(1).upper()) - ord("A")
numb = int(re_found_simp.group(2))
fin_id = numb + letter * int(columns)
res.append(str(fin_id))
return res
def _sampleTypeToDics(rootEl):
"""Translates all ele in samples to dic {sample Id}{target Id} with ele value.
Args:
rootEl: The root node of the rdml file
Returns:
returns a dictionary {sample Id}{target Id} with ele value.
"""
tar = []
ret = {}
# Get all targets
targets = _get_all_children(rootEl, "target")
for node in targets:
if 'id' in node.attrib:
tar.append(node.attrib['id'])
samples = _get_all_children(rootEl, "sample")
for node in samples:
if 'id' in node.attrib:
currSam = node.attrib['id']
ret[currSam] = {}
for currTar in tar:
ret[currSam][currTar] = "unkn"
subEles = _get_all_children(node, "type")
for subNode in subEles:
if 'targetId' not in subNode.attrib:
for currTar in tar:
ret[currSam][currTar] = subNode.text
for subNode in subEles:
if 'targetId' in subNode.attrib:
ret[currSam][subNode.attrib['targetId']] = subNode.text
return ret
def _lrp_linReg(adp_cyc_min, fluor):
"""A function which calculates the slope or the intercept by linear regression.
Args:
xIn: The numpy array of the cycles
yUse: The numpy array that contains the fluorescence
Returns:
An array with the slope and intercept.
"""
# Create a matrix with the cycle for each rawFluor value
spFl = fluor.shape
cycles = np.arange(adp_cyc_min, (adp_cyc_min + spFl[1]))
cyclesSqared = cycles * cycles
cyclesSum = np.sum(cycles)
cyclesSqaredSum = np.sum(cyclesSqared)
cycFluor = cycles * fluor
sumFluor = np.nansum(fluor, axis=1)
sumCycFluor = np.nansum(cycFluor, axis=1)
ssx = cyclesSqaredSum - (cyclesSum * cyclesSum) / spFl[1]
sxy = sumCycFluor - (cyclesSum * sumFluor) / spFl[1]
return sxy / ssx
# slope = sxy / ssx
# intercept = (sumFluor / n) - slope * (sumCyc / n)
# return [slope, intercept]
def _lrp_findStopCyc(fluor, aRow):
"""Find the stop cycle of the log lin phase in fluor.
Args:
fluor: The array with the fluorescence values
aRow: The row to work on
Returns:
An int with the stop cycle.
"""
# Take care of nan values
validTwoLessCyc = 3 # Cycles so +1 to array
while (validTwoLessCyc <= fluor.shape[1] and
(np.isnan(fluor[aRow, validTwoLessCyc - 1]) or
np.isnan(fluor[aRow, validTwoLessCyc - 2]) or
np.isnan(fluor[aRow, validTwoLessCyc - 3]))):
validTwoLessCyc += 1
# First and Second Derivative values calculation
fluorShift = np.roll(fluor[aRow], 1, axis=0) # Shift to right - real position is -0.5
fluorShift[0] = np.nan
firstDerivative = fluor[aRow] - fluorShift
if np.isfinite(firstDerivative).any():
FDMaxCyc = np.nanargmax(firstDerivative, axis=0) + 1 # Cycles so +1 to array
else:
return fluor.shape[1]
firstDerivativeShift = np.roll(firstDerivative, -1, axis=0) # Shift to left
firstDerivativeShift[-1] = np.nan
secondDerivative = firstDerivativeShift - firstDerivative
if FDMaxCyc + 2 <= fluor.shape[1]:
# Only add two cycles if there is an increase without nan
if (not np.isnan(fluor[aRow, FDMaxCyc - 1]) and
not np.isnan(fluor[aRow, FDMaxCyc]) and
not np.isnan(fluor[aRow, FDMaxCyc + 1]) and
fluor[aRow, FDMaxCyc + 1] > fluor[aRow, FDMaxCyc] > fluor[aRow, FDMaxCyc - 1]):
FDMaxCyc += 2
else:
FDMaxCyc = fluor.shape[1]
maxMeanSD = 0.0
stopCyc = fluor.shape[1]
for cycInRange in range(validTwoLessCyc, FDMaxCyc):
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
tempMeanSD = np.mean(secondDerivative[cycInRange - 2: cycInRange + 1], axis=0)
# The > 0.000000000001 is to avoid float differences to the pascal version
if not np.isnan(tempMeanSD) and (tempMeanSD - maxMeanSD) > 0.000000000001:
maxMeanSD = tempMeanSD
stopCyc = cycInRange
if stopCyc + 2 >= fluor.shape[1]:
stopCyc = fluor.shape[1]
return stopCyc
def _lrp_findStartCyc(fluor, row, stopCyc):
"""A function which finds the start cycle of the log lin phase in fluor.
Args:
fluor: The array with the fluorescence values
aRow: The row to work on
stopCyc: The stop cycle
Returns:
An array [int, int] with the start cycle and the fixed start cycle.
"""
startCyc = stopCyc - 1
if startCyc < 1 or np.isnan(fluor[row, startCyc - 1]):
return [startCyc, startCyc]
# As long as there are no NaN and new values are increasing
while (startCyc > 1 and
stopCyc - startCyc < 11 and
not np.isnan(fluor[row, startCyc - 2]) and
fluor[row, startCyc - 2] < fluor[row, startCyc - 1]):
startCyc -= 1
startCycFix = startCyc
startStep = np.log10(fluor[row, startCyc]) - np.log10(fluor[row, startCyc - 1])
stopStep = np.log10(fluor[row, stopCyc - 1]) - np.log10(fluor[row, stopCyc - 2])
if startStep > 1.1 * stopStep:
startCycFix += 1
return [startCyc, startCycFix]
def _lrp_findStartCyc2(fluor, row, stopCyc):
"""A function which finds the start cycle of the log lin phase in fluor.
Args:
fluor: The array with the fluorescence values
aRow: The row to work on
stopCyc: The stop cycle
Returns:
An array [int, int] with the start cycle and the fixed start cycle.
"""
startCyc = stopCyc
if (startCyc < 1 or
np.isnan(fluor[row, startCyc - 1]) or
fluor[row, startCyc - 1] <= 0.0):
return [startCyc, startCyc]
# As long as there are no NaN and new values are increasing
while (startCyc > 1 and
stopCyc - startCyc < 11 and # TODO set to 6!
not np.isnan(fluor[row, startCyc - 2]) and
fluor[row, startCyc - 2] > 0.0 and
fluor[row, startCyc - 2] < fluor[row, startCyc - 1]):
startCyc -= 1
startCycFix = startCyc
if startCyc < stopCyc:
startStep = np.log10(fluor[row, startCyc]) - np.log10(fluor[row, startCyc - 1])
stopStep = np.log10(fluor[row, stopCyc - 1]) - np.log10(fluor[row, stopCyc - 2])
if startStep > 1.1 * stopStep:
startCycFix += 1
return [startCyc, startCycFix]
def _lrp_testSlopes(fluor, aRow, stopCyc, startCycFix):
"""Splits the values and calculates a slope for the upper and the lower half.
Args:
fluor: The array with the fluorescence values
aRow: The row to work on
stopCyc: The stop cycle
startCycFix: The start cycle
Returns:
An array with [slopelow, slopehigh].
"""
# Both start with full range
center = (stopCyc[aRow] + startCycFix[aRow]) / 2.0
loopStart = [startCycFix[aRow], int(center + 0.6)]
loopStop = [int(center), stopCyc[aRow]]
# basic regression per group
ssx = [0, 0]
sxy = [0, 0]
slope = [0, 0]
for j in range(0, 2):
sumx = 0.0
sumy = 0.0
sumx2 = 0.0
sumxy = 0.0
nincl = 0.0
for i in range(loopStart[j], loopStop[j] + 1):
sumx += i
sumy += np.log10(fluor[aRow, i - 1])
sumx2 += i * i
sumxy += i * np.log10(fluor[aRow, i - 1])
nincl += 1
if nincl != 0.0:
ssx[j] = sumx2 - sumx * sumx / nincl
sxy[j] = sumxy - sumx * sumy / nincl
slope[j] = sxy[j] / ssx[j]
else:
slope[j] = -999.9
return [slope[0], slope[1]]
def _lrp_testSlopes2(fluor):
"""Splits the values and calculates a slope for the upper and the lower half.
Args:
fluor: The array with the fluorescence values
Returns:
An array with [slopelow, slopehigh].
"""
# Split the list
center = len(fluor) / 2.0
loopStart = [0, int(center)]
loopStop = [int(center - 0.4), len(fluor) - 1]
# basic regression per section
ssx = [0, 0]