forked from bikalims/bika.lims
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathabstractanalysis.py
1781 lines (1621 loc) · 70.1 KB
/
abstractanalysis.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
# -*- coding: utf-8 -*-
# This file is part of Bika LIMS
#
# Copyright 2011-2016 by it's authors.
# Some rights reserved. See LICENSE.txt, AUTHORS.txt.
import cgi
import math
from decimal import Decimal
from AccessControl import ClassSecurityInfo
from DateTime import DateTime
from Products.Archetypes.Field import BooleanField, DateTimeField, \
FixedPointField, IntegerField, StringField
from Products.Archetypes.Schema import Schema
from Products.Archetypes.references import HoldingReference
from Products.CMFCore.WorkflowCore import WorkflowException
from bika.lims import bikaMessageFactory as _, deprecated
from bika.lims import logger
from bika.lims.browser.fields import HistoryAwareReferenceField
from bika.lims.browser.fields import UIDReferenceField
from bika.lims.browser.widgets import DateTimeWidget
from bika.lims.content.abstractbaseanalysis import AbstractBaseAnalysis
from bika.lims.content.abstractbaseanalysis import schema
from bika.lims.content.reflexrule import doReflexRuleAction
from bika.lims.interfaces import ISamplePrepWorkflow, IDuplicateAnalysis
from bika.lims.permissions import *
from bika.lims.permissions import Verify as VerifyPermission
from bika.lims.utils import changeWorkflowState, formatDecimalMark
from bika.lims.utils import drop_trailing_zeros_decimal
from bika.lims.utils.analysis import create_analysis, format_numeric_result
from bika.lims.utils.analysis import get_significant_digits
from bika.lims.workflow import skip
from plone.api.portal import get_tool
from plone.api.user import has_permission
from zope.interface import implements
# A link directly to the AnalysisService object used to create the analysis
AnalysisService = UIDReferenceField(
'AnalysisService'
)
# Overrides the AbstractBaseAnalysis. Analyses have a versioned link to the
# calculation as it was when created.
Calculation = HistoryAwareReferenceField(
'Calculation',
allowed_types=('Calculation',),
relationship='AnalysisCalculation',
referenceClass=HoldingReference
)
# Attachments which are added manually in the UI, or automatically when
# results are imported from a file supplied by an instrument.
Attachment = UIDReferenceField(
'Attachment',
multiValued=1,
allowed_types=('Attachment',)
)
# The final result of the analysis is stored here. The field contains a
# String value, but the result itself is required to be numeric. If
# a non-numeric result is needed, ResultOptions can be used.
Result = StringField(
'Result'
)
# When the result is changed, this value is updated to the current time.
# Only the most recent result capture date is recorded here and used to
# populate catalog values, however the workflow review_history can be
# used to get all dates of result capture
ResultCaptureDate = DateTimeField(
'ResultCaptureDate'
)
# If ReportDryMatter is True in the AnalysisService, the adjusted result
# is stored here.
ResultDM = StringField(
'ResultDM'
)
# If the analysis has previously been retracted, this flag is set True
# to indicate that this is a re-test.
Retested = BooleanField(
'Retested',
default=False
)
# When the AR is published, the date of publication is recorded here.
# It's used to populate catalog values.
DateAnalysisPublished = DateTimeField(
'DateAnalysisPublished',
widget=DateTimeWidget(
label=_("Date Published")
)
)
# If the result is outside of the detection limits of the method or instrument,
# the operand (< or >) is stored here. For routine analyses this is taken
# from the Result, if the result entered explicitly startswith "<" or ">"
DetectionLimitOperand = StringField(
'DetectionLimitOperand'
)
# This is used to calculate turnaround time reports.
# The value is set when the Analysis is published.
Duration = IntegerField(
'Duration',
)
# This is used to calculate turnaround time reports. The value is set when the
# Analysis is published.
Earliness = IntegerField(
'Earliness',
)
# The ID of the logged in user who submitted the result for this Analysis.
Analyst = StringField(
'Analyst'
)
# The actual uncertainty for this analysis' result, populated from the ranges
# specified in the analysis service when the result is submitted.
Uncertainty = FixedPointField(
'Uncertainty',
precision=10,
)
# transitioned to a 'verified' state. This value is set automatically
# when the analysis is created, based on the value set for the property
# NumberOfRequiredVerifications from the Analysis Service
NumberOfRequiredVerifications = IntegerField(
'NumberOfRequiredVerifications',
default=1
)
# This field keeps the user_ids of members who verified this analysis.
# After each verification, user_id will be added end of this string
# seperated by comma- ',' .
Verificators = StringField(
'Verificators',
default=''
)
schema = schema.copy() + Schema((
AnalysisService,
Analyst,
Attachment,
# Calculation overrides AbstractBaseClass
Calculation,
DateAnalysisPublished,
DetectionLimitOperand,
Duration,
Earliness,
# NumberOfRequiredVerifications overrides AbstractBaseClass
NumberOfRequiredVerifications,
Result,
ResultCaptureDate,
ResultDM,
Retested,
Uncertainty,
Verificators
))
class AbstractAnalysis(AbstractBaseAnalysis):
implements(ISamplePrepWorkflow)
security = ClassSecurityInfo()
displayContentsTab = False
schema = schema
@deprecated("Currently returns the Analysis object itself. If you really "
"need to get the service, use getAnalysisService instead.")
@security.public
def getService(self):
return self
def getServiceUID(self):
"""Return the UID of the associated service.
"""
service = self.getAnalysisService()
if service:
return service.UID()
logger.error("Cannot get ServiceUID for %s"%self)
@security.public
def getNumberOfVerifications(self):
verificators = self.getVerificators()
if not verificators:
return 0
return len(verificators.split(','))
@security.public
def addVerificator(self, username):
verificators = self.getVerificators()
if not verificators:
self.setVerificators(username)
else:
self.setVerificators(verificators + "," + username)
@security.public
def deleteLastVerificator(self):
verificators = self.getVerificators().split(',')
del verificators[-1]
self.setVerificators(",".join(verificators))
@security.public
def wasVerifiedByUser(self, username):
verificators = self.getVerificators().split(',')
return username in verificators
@security.public
def getLastVerificator(self):
return self.getVerificators().split(',')[-1]
@deprecated("You should use the Analysis Title.")
@security.public
def getServiceTitle(self):
"""Returns the Title of the associated service. Analysis titles are
always the same as the title of the service from which they are derived.
"""
return self.Title()
@security.public
def getDefaultUncertainty(self, result=None):
"""Return the uncertainty value, if the result falls within
specified ranges for the service from which this analysis was derived.
"""
if result is None:
result = self.getResult()
uncertainties = self.getUncertainties()
if uncertainties:
try:
res = float(result)
except (TypeError, ValueError):
# if analysis result is not a number, then we assume in range
return None
for d in uncertainties:
_min = float(d['intercept_min'])
_max = float(d['intercept_max'])
if _min <= res and res <= _max:
if str(d['errorvalue']).strip().endswith('%'):
try:
percvalue = float(d['errorvalue'].replace('%', ''))
except ValueError:
return None
uncertainty = res / 100 * percvalue
else:
uncertainty = float(d['errorvalue'])
return uncertainty
return None
@security.public
def getUncertainty(self, result=None):
"""Returns the uncertainty for this analysis and result.
Returns the value from Schema's Uncertainty field if the Service has
the option 'Allow manual uncertainty'. Otherwise, do a callback to
getDefaultUncertainty(). Returns None if no result specified and the
current result for this analysis is below or above detections limits.
"""
uncertainty = self.getField('Uncertainty').get(self)
if result is None and (self.isAboveUpperDetectionLimit() or
self.isBelowLowerDetectionLimit()):
return None
if uncertainty and self.getAllowManualUncertainty() is True:
try:
uncertainty = float(uncertainty)
return uncertainty
except (TypeError, ValueError):
# if uncertainty is not a number, return default value
pass
return self.getDefaultUncertainty(result)
@security.public
def setUncertainty(self, unc):
"""Sets the uncertainty for this analysis. If the result is a
Detection Limit or the value is below LDL or upper UDL, sets the
uncertainty value to 0
"""
# Uncertainty calculation on DL
# https://jira.bikalabs.com/browse/LIMS-1808
if self.isAboveUpperDetectionLimit() or \
self.isBelowLowerDetectionLimit():
self.getField('Uncertainty').set(self, None)
else:
self.getField('Uncertainty').set(self, unc)
@security.public
def setDetectionLimitOperand(self, value):
"""Sets the detection limit operand for this analysis, so the result
will be interpreted as a detection limit. The value will only be set
if the Service has 'DetectionLimitSelector' field set to True,
otherwise, the detection limit operand will be set to None. See
LIMS-1775 for further information about the relation amongst
'DetectionLimitSelector' and 'AllowManualDetectionLimit'.
https://jira.bikalabs.com/browse/LIMS-1775
"""
md = self.getDetectionLimitSelector()
val = value if (md and value in '<>') else None
self.getField('DetectionLimitOperand').set(self, val)
# Method getLowerDetectionLimit overrides method of class BaseAnalysis
@security.public
def getLowerDetectionLimit(self):
"""Returns the Lower Detection Limit (LDL) that applies to this
analysis in particular. If no value set or the analysis service
doesn't allow manual input of detection limits, returns the value set
by default in the Analysis Service
"""
operand = self.getDetectionLimitOperand()
if operand and operand == '<':
result = self.getResult()
try:
# in this case, the result itself is the LDL.
return float(result)
except (TypeError, ValueError):
logger.warn("The result for the analysis %s is a lower "
"detection limit, but not floatable: '%s'. "
"Returnig AS's default LDL." %
(self.id, result))
return AbstractBaseAnalysis.getLowerDetectionLimit(self)
# Method getUpperDetectionLimit overrides method of class BaseAnalysis
@security.public
def getUpperDetectionLimit(self):
"""Returns the Upper Detection Limit (UDL) that applies to this
analysis in particular. If no value set or the analysis service
doesn't allow manual input of detection limits, returns the value set
by default in the Analysis Service
"""
operand = self.getDetectionLimitOperand()
if operand and operand == '>':
result = self.getResult()
try:
# in this case, the result itself is the LDL.
return float(result)
except (TypeError, ValueError):
logger.warn("The result for the analysis %s is a lower "
"detection limit, but not floatable: '%s'. "
"Returnig AS's default LDL." %
(self.id, result))
return AbstractBaseAnalysis.getUpperDetectionLimit(self)
@security.public
def isBelowLowerDetectionLimit(self):
"""Returns True if the result is below the Lower Detection Limit or
if Lower Detection Limit has been manually set
"""
dl = self.getDetectionLimitOperand()
if dl and dl == '<':
return True
result = self.getResult()
if result and str(result).strip().startswith('<'):
return True
elif result:
ldl = self.getLowerDetectionLimit()
try:
result = float(result)
return result < ldl
except (TypeError, ValueError):
pass
return False
@security.public
def isAboveUpperDetectionLimit(self):
"""Returns True if the result is above the Upper Detection Limit or
if Upper Detection Limit has been manually set
"""
dl = self.getDetectionLimitOperand()
if dl and dl == '>':
return True
result = self.getResult()
if result and str(result).strip().startswith('>'):
return True
elif result:
udl = self.getUpperDetectionLimit()
try:
result = float(result)
return result > udl
except (TypeError, ValueError):
pass
return False
@security.public
def getDetectionLimits(self):
"""Returns a two-value array with the limits of detection (LDL and
UDL) that applies to this analysis in particular. If no value set or
the analysis service doesn't allow manual input of detection limits,
returns the value set by default in the Analysis Service
"""
return [self.getLowerDetectionLimit(), self.getUpperDetectionLimit()]
@security.public
def isLowerDetectionLimit(self):
"""Returns True if the result for this analysis represents a Lower
Detection Limit. Otherwise, returns False
"""
if self.isBelowLowerDetectionLimit():
if self.getDetectionLimitOperand() == '<':
return True
@security.public
def isUpperDetectionLimit(self):
"""Returns True if the result for this analysis represents an Upper
Detection Limit. Otherwise, returns False
"""
if self.isAboveUpperDetectionLimit():
if self.getDetectionLimitOperand() == '>':
return True
@security.public
def getDependents(self):
"""Return a list of analyses who depend on us to calculate their result
"""
dependents = []
ar = self.aq_parent
for sibling in ar.getAnalyses(full_objects=True):
if sibling == self:
continue
calculation = sibling.getCalculation()
if not calculation:
continue
depservices = calculation.getDependentServices()
dep_keywords = [x.getKeyword() for x in depservices]
if self.getKeyword() in dep_keywords:
dependents.append(sibling)
return dependents
@security.public
def getDependencies(self):
"""Return a list of analyses who we depend on to calculate our result.
"""
siblings = self.aq_parent.getAnalyses(full_objects=True)
calculation = self.getCalculation()
if not calculation:
return []
dep_services = [d.UID() for d in calculation.getDependentServices()]
dep_analyses = [a for a in siblings if
a.getServiceUID() in dep_services]
return dep_analyses
@security.public
def setResult(self, value):
"""Validate and set a value into the Result field, taking into
account the Detection Limits.
:param value: is expected to be a string.
"""
# Always update ResultCapture date when this field is modified
self.setResultCaptureDate(DateTime())
# Only allow DL if manually enabled in AS
val = str(value).strip()
if val and val[0] in '<>':
self.setDetectionLimitOperand(None)
oper = val[0]
val = val.replace(oper, '', 1)
# Check if the value is indeterminate / non-floatable
try:
str(float(val))
except (ValueError, TypeError):
val = value
if self.getDetectionLimitSelector():
if self.getAllowManualDetectionLimit():
# DL allowed, try to remove the operator and set the
# result as a detection limit
self.setDetectionLimitOperand(oper)
else:
# Trying to set a result with an '<,>' operator,
# but manual DL not allowed, so override the
# value with the service's default LDL or UDL
# according to the operator, but only if the value
# is not an indeterminate.
if oper == '<':
val = self.getLowerDetectionLimit()
else:
val = self.getUpperDetectionLimit()
self.setDetectionLimitOperand(oper)
elif val is '':
# Reset DL
self.setDetectionLimitOperand(None)
self.getField('Result').set(self, val)
# Uncertainty calculation on DL
# https://jira.bikalabs.com/browse/LIMS-1808
if self.isAboveUpperDetectionLimit() or \
self.isBelowLowerDetectionLimit():
self.getField('Uncertainty').set(self, None)
@security.public
def getAnalysisSpecs(self, specification=None):
"""Retrieves the analysis specs to be applied to this analysis.
Allowed values for specification= 'client', 'lab', None If
specification is None, client specification gets priority from lab
specification. If no specification available for this analysis,
returns None
"""
sample = self.getSample()
sampletype = sample.getSampleType()
sampletype_uid = sampletype and sampletype.UID() or ''
bsc = get_tool('bika_setup_catalog')
# retrieves the desired specs if None specs defined
if not specification:
proxies = bsc(portal_type='AnalysisSpec',
getClientUID=self.getClientUID(),
getSampleTypeUID=sampletype_uid)
if len(proxies) == 0:
# No client specs available, retrieve lab specs
proxies = bsc(portal_type='AnalysisSpec',
getSampleTypeUID=sampletype_uid)
else:
specuid = specification == "client" and self.getClientUID() or \
self.bika_setup.bika_analysisspecs.UID()
proxies = bsc(portal_type='AnalysisSpec',
getSampleTypeUID=sampletype_uid,
getClientUID=specuid)
outspecs = None
for spec in (p.getObject() for p in proxies):
if self.getKeyword() in spec.getResultsRangeDict():
outspecs = spec
break
return outspecs
@security.public
def getResultsRange(self, specification=None):
"""Returns the valid results range for this analysis, a dictionary
with the following keys: 'keyword', 'uid', 'min', 'max ', 'error',
'hidemin', 'hidemax', 'rangecomment' Allowed values for
specification='ar', 'client', 'lab', None If specification is None,
the following is the priority to get the results range: AR > Client >
Lab If no specification available for this analysis, returns {}
"""
rr = {}
an = self
if specification == 'ar' or specification is None:
if an.aq_parent and an.aq_parent.portal_type == 'AnalysisRequest':
rr = an.aq_parent.getResultsRange()
rr = [r for r in rr if r.get('keyword', '') == an.getKeyword()]
rr = rr[0] if rr and len(rr) > 0 else {}
if rr:
rr['uid'] = self.UID()
if not rr:
# Let's try to retrieve the specs from client and/or lab
specs = an.getAnalysisSpecs(specification)
rr = specs.getResultsRangeDict() if specs else {}
rr = rr.get(an.getKeyword(), {}) if rr else {}
if rr:
rr['uid'] = self.UID()
return rr
@security.public
def getResultsRangeNoSpecs(self):
"""This method is used to populate catalog values
"""
return self.getResultsRange()
@security.public
def calculateResult(self, override=False, cascade=False):
"""Calculates the result for the current analysis if it depends of
other analysis/interim fields. Otherwise, do nothing
"""
if self.getResult() and override is False:
return False
calc = self.getCalculation()
if not calc:
return False
mapping = {}
# Interims' priority order (from low to high):
# Calculation < Analysis
interims = calc.getInterimFields() + self.getInterimFields()
# Add interims to mapping
for i in interims:
if 'keyword' not in i:
continue
try:
ivalue = float(i['value'])
mapping[i['keyword']] = ivalue
except (TypeError, ValueError):
# Interim not float, abort
return False
# Add dependencies results to mapping
dependencies = self.getDependencies()
for dependency in dependencies:
result = dependency.getResult()
if not result:
# Dependency without results found
if cascade:
# Try to calculate the dependency result
dependency.calculateResult(override, cascade)
result = dependency.getResult()
else:
return False
if result:
try:
result = float(str(result))
key = dependency.getKeyword()
ldl = dependency.getLowerDetectionLimit()
udl = dependency.getUpperDetectionLimit()
bdl = dependency.isBelowLowerDetectionLimit()
adl = dependency.isAboveUpperDetectionLimit()
mapping[key] = result
mapping['%s.%s' % (key, 'RESULT')] = result
mapping['%s.%s' % (key, 'LDL')] = ldl
mapping['%s.%s' % (key, 'UDL')] = udl
mapping['%s.%s' % (key, 'BELOWLDL')] = int(bdl)
mapping['%s.%s' % (key, 'ABOVEUDL')] = int(adl)
except (TypeError, ValueError):
return False
# Calculate
formula = calc.getMinifiedFormula()
formula = formula.replace('[', '%(').replace(']', ')f')
try:
formula = eval("'%s'%%mapping" % formula,
{"__builtins__": None,
'math': math,
'context': self},
{'mapping': mapping})
result = eval(formula)
except TypeError:
self.setResult("NA")
return True
except ZeroDivisionError:
self.setResult('0/0')
return True
except KeyError:
self.setResult("NA")
return True
self.setResult(str(result))
return True
@security.public
def getPriority(self):
"""get priority from AR
"""
# this analysis could be in a worksheet or instrument, careful
if hasattr(self.aq_parent, 'getPriority'):
return self.aq_parent.getPriority()
@security.public
def getPrice(self):
"""The function obtains the analysis' price without VAT and without
member discount
:return: the price (without VAT or Member Discount) in decimal format
"""
analysis_request = self.aq_parent
client = analysis_request.aq_parent
if client.getBulkDiscount():
price = self.getBulkPrice()
else:
price = self.getPrice()
priority = self.getPriority()
if priority and priority.getPricePremium() > 0:
price = Decimal(price) + \
(Decimal(price) * Decimal(priority.getPricePremium()) / 100)
return price
@security.public
def getVATAmount(self):
"""Compute the VAT amount without member discount.
:return: the result as a float
"""
vat = self.getVAT()
price = self.getPrice()
return Decimal(price) * Decimal(vat) / 100
@security.public
def getTotalPrice(self):
"""Obtain the total price without client's member discount. The function
keeps in mind the client's bulk discount.
:return: the result as a float
"""
return Decimal(self.getPrice()) + Decimal(self.getVATAmount())
@security.public
def isInstrumentValid(self):
"""Checks if the instrument selected for this analysis is valid.
Returns false if an out-of-date or uncalibrated instrument is
assigned. Returns true if the Analysis has no instrument assigned or
is valid.
"""
if self.getInstrument():
return self.getInstrument().isValid()
return True
@security.public
def isInstrumentAllowed(self, instrument):
"""Checks if the specified instrument can be set for this analysis,
according to the Method and Analysis Service. If the Analysis Service
hasn't set 'Allows instrument entry' of results, returns always
False. Otherwise, checks if the method assigned is supported by the
instrument specified. Returns false, If the analysis hasn't any
method assigned. NP: The methods allowed for selection are defined at
Analysis Service level. instrument param can be either an uid or an
object
"""
if isinstance(instrument, str):
uid = instrument
else:
uid = instrument.UID()
return uid in self.getAllowedInstruments()
@security.public
def isMethodAllowed(self, method):
"""Checks if the analysis can follow the method specified. Looks for
manually selected methods when AllowManualEntry is set and
instruments methods when AllowInstrumentResultsEntry is set. method
param can be either a uid or an object
"""
if isinstance(method, str):
uid = method
else:
uid = method.UID()
return uid in self.getAllowedMethods()
@security.public
def getAllowedMethods(self):
"""Returns the allowed methods for this analysis. If manual entry of
results is set, only returns the methods set manually. Otherwise (if
Instrument Entry Of Results is set) returns the methods assigned to
the instruments allowed for this Analysis
"""
service = self.getAnalysisService()
if not service:
return []
methods = []
if self.getInstrumentEntryOfResults():
for instrument in service.getInstruments():
methods.extend(instrument.getMethods())
else:
# Get only the methods set manually
methods = service.getMethods()
return list(set(methods))
@security.public
def getAllowedMethodUIDs(self):
"""Used to populate getAllowedMethodUIDs metadata
"""
return [m.UID() for m in self.getAllowedMethods()]
@security.public
def getAllowedInstruments(self):
"""Returns the allowed instruments for this Analysis Service. Gets the
instruments assigned to the allowed methods.
"""
service = self.getAnalysisService()
if not service:
return []
instruments = []
if self.getInstrumentEntryOfResults():
instruments = service.getInstruments()
elif self.getManualEntryOfResults():
for meth in self.getAllowedMethods():
instruments += meth.getInstruments()
return list(set(instruments))
@security.public
def getAllowedInstrumentUIDs(self):
"""Used to populate getAllowedInstrumentUIDs metadata
"""
return [i.UID() for i in self.getAllowedInstruments()]
@security.public
def getDefaultMethod(self):
"""Returns the default method for this Analysis according to its
current instrument. If the Analysis hasn't set yet an Instrument,
looks to the Service
"""
instr = self.getInstrument() \
if self.getInstrument() else self.getDefaultInstrument()
return instr.getMethod() if instr else None
@security.public
def getExponentialFormatPrecision(self, result=None):
""" Returns the precision for the Analysis Service and result
provided. Results with a precision value above this exponential
format precision should be formatted as scientific notation.
If the Calculate Precision according to Uncertainty is not set,
the method will return the exponential precision value set in the
Schema. Otherwise, will calculate the precision value according to
the Uncertainty and the result.
If Calculate Precision from the Uncertainty is set but no result
provided neither uncertainty values are set, returns the fixed
exponential precision.
Will return positive values if the result is below 0 and will return
0 or positive values if the result is above 0.
Given an analysis service with fixed exponential format
precision of 4:
Result Uncertainty Returns
5.234 0.22 0
13.5 1.34 1
0.0077 0.008 -3
32092 0.81 4
456021 423 5
For further details, visit https://jira.bikalabs.com/browse/LIMS-1334
:param result: if provided and "Calculate Precision according to the
Uncertainty" is set, the result will be used to retrieve the
uncertainty from which the precision must be calculated. Otherwise,
the fixed-precision will be used.
:returns: the precision
"""
field = self.getField('ExponentialFormatPrecision')
if not result or self.getPrecisionFromUncertainty() is False:
return field.get(self)
else:
uncertainty = self.getUncertainty(result)
if uncertainty is None:
return field.get(self)
try:
float(result)
except ValueError:
# if analysis result is not a number, then we assume in range
return field.get(self)
return get_significant_digits(uncertainty)
@security.public
def getFormattedResult(self, specs=None, decimalmark='.', sciformat=1,
html=True):
"""Formatted result:
1. If the result is a detection limit, returns '< LDL' or '> UDL'
2. Print ResultText of matching ResultOptions
3. If the result is not floatable, return it without being formatted
4. If the analysis specs has hidemin or hidemax enabled and the
result is out of range, render result as '<min' or '>max'
5. If the result is below Lower Detection Limit, show '<LDL'
6. If the result is above Upper Detecion Limit, show '>UDL'
7. Otherwise, render numerical value
:param specs: Optional result specifications, a dictionary as follows:
{'min': <min_val>,
'max': <max_val>,
'error': <error>,
'hidemin': <hidemin_val>,
'hidemax': <hidemax_val>}
:param decimalmark: The string to be used as a decimal separator.
default is '.'
:param sciformat: 1. The sci notation has to be formatted as aE^+b
2. The sci notation has to be formatted as a·10^b
3. As 2, but with super html entity for exp
4. The sci notation has to be formatted as a·10^b
5. As 4, but with super html entity for exp
By default 1
:param html: if true, returns an string with the special characters
escaped: e.g: '<' and '>' (LDL and UDL for results like < 23.4).
"""
result = self.getResult()
# 1. The result is a detection limit, return '< LDL' or '> UDL'
dl = self.getDetectionLimitOperand()
if dl:
try:
res = float(result) # required, check if floatable
res = drop_trailing_zeros_decimal(res)
fdm = formatDecimalMark(res, decimalmark)
hdl = cgi.escape(dl) if html else dl
return '%s %s' % (hdl, fdm)
except (TypeError, ValueError):
logger.warn(
"The result for the analysis %s is a detection limit, "
"but not floatable: %s" % (self.id, result))
return formatDecimalMark(result, decimalmark=decimalmark)
choices = self.getResultOptions()
# 2. Print ResultText of matching ResulOptions
match = [x['ResultText'] for x in choices
if str(x['ResultValue']) == str(result)]
if match:
return match[0]
# 3. If the result is not floatable, return it without being formatted
try:
result = float(result)
except (TypeError, ValueError):
return formatDecimalMark(result, decimalmark=decimalmark)
# 4. If the analysis specs has enabled hidemin or hidemax and the
# result is out of range, render result as '<min' or '>max'
specs = specs if specs else self.getResultsRange()
hidemin = specs.get('hidemin', '')
hidemax = specs.get('hidemax', '')
try:
belowmin = hidemin and result < float(hidemin) or False
except (TypeError, ValueError):
belowmin = False
try:
abovemax = hidemax and result > float(hidemax) or False
except (TypeError, ValueError):
abovemax = False
# 4.1. If result is below min and hidemin enabled, return '<min'
if belowmin:
fdm = formatDecimalMark('< %s' % hidemin, decimalmark)
return fdm.replace('< ', '< ', 1) if html else fdm
# 4.2. If result is above max and hidemax enabled, return '>max'
if abovemax:
fdm = formatDecimalMark('> %s' % hidemax, decimalmark)
return fdm.replace('> ', '> ', 1) if html else fdm
# Below Lower Detection Limit (LDL)?
ldl = self.getLowerDetectionLimit()
if result < ldl:
# LDL must not be formatted according to precision, etc.
# Drop trailing zeros from decimal
ldl = drop_trailing_zeros_decimal(ldl)
fdm = formatDecimalMark('< %s' % ldl, decimalmark)
return fdm.replace('< ', '< ', 1) if html else fdm
# Above Upper Detection Limit (UDL)?
udl = self.getUpperDetectionLimit()
if result > udl:
# UDL must not be formatted according to precision, etc.
# Drop trailing zeros from decimal
udl = drop_trailing_zeros_decimal(udl)
fdm = formatDecimalMark('> %s' % udl, decimalmark)
return fdm.replace('> ', '> ', 1) if html else fdm
# Render numerical values
return format_numeric_result(self, self.getResult(),
decimalmark=decimalmark,
sciformat=sciformat)
@security.public
def getPrecision(self, result=None):
"""Returns the precision for the Analysis.
- ManualUncertainty not set: returns the precision from the
AnalysisService.
- ManualUncertainty set and Calculate Precision from Uncertainty
is also set in Analysis Service: calculates the precision of the
result according to the manual uncertainty set.
- ManualUncertainty set and Calculatet Precision from Uncertainty
not set in Analysis Service: returns the result as-is.
Further information at AbstractBaseAnalysis.getPrecision()
"""
schu = self.getField('Uncertainty').get(self)
if all([schu,
self.getAllowManualUncertainty(),
self.getPrecisionFromUncertainty()]):
uncertainty = self.getUncertainty(result)
if uncertainty == 0:
return 1
return get_significant_digits(uncertainty)
return self.getField('Precision').get(self)
@security.public
def getAnalyst(self):
"""Returns the identifier of the assigned analyst. If there is no
analyst assigned, and this analysis is attached to a worksheet,
retrieves the analyst assigned to the parent worksheet
"""
field = self.getField('Analyst')
analyst = field and field.get(self) or ''
if not analyst:
# Is assigned to a worksheet?
wss = self.getBackReferences('WorksheetAnalysis')
if len(wss) > 0:
analyst = wss[0].getAnalyst()
field.set(self, analyst)
return analyst if analyst else ''
@security.public
def getAnalystName(self):
"""Returns the name of the currently assigned analyst
"""
mtool = get_tool('portal_membership')
analyst = self.getAnalyst().strip()