Coverage for tasks/hads.py: 56%

1"""

2 camcops_server/tasks/hads.py

3

4===============================================================================

5

6 Copyright (C) 2012, University of Cambridge, Department of Psychiatry.

7 Created by Rudolf Cardinal (rnc1001@cam.ac.uk).

8

9 This file is part of CamCOPS.

10

11 CamCOPS is free software: you can redistribute it and/or modify

12 it under the terms of the GNU General Public License as published by

13 the Free Software Foundation, either version 3 of the License, or

14 (at your option) any later version.

15

16 CamCOPS is distributed in the hope that it will be useful,

17 but WITHOUT ANY WARRANTY; without even the implied warranty of

18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

19 GNU General Public License for more details.

20

21 You should have received a copy of the GNU General Public License

22 along with CamCOPS. If not, see <https://www.gnu.org/licenses/>.

23

24===============================================================================

25

26"""

27

28 from abc import ABC

29 import logging

30 from typing import Any, cast, List, Type, Union

31

32 from cardinal_pythonlib.logs import BraceStyleAdapter

33 from cardinal_pythonlib.stringfunc import strseq

34 from sqlalchemy.sql.sqltypes import Integer

35

36 from camcops_server.cc_modules.cc_constants import (

37 CssClass,

38 DATA_COLLECTION_UNLESS_UPGRADED_DIV,

39)

40 from camcops_server.cc_modules.cc_ctvinfo import CTV_INCOMPLETE, CtvInfo

41 from camcops_server.cc_modules.cc_db import add_multiple_columns

42 from camcops_server.cc_modules.cc_html import answer, tr_qa

43 from camcops_server.cc_modules.cc_request import CamcopsRequest

44 from camcops_server.cc_modules.cc_snomed import SnomedExpression, SnomedLookup

45 from camcops_server.cc_modules.cc_string import AS

46 from camcops_server.cc_modules.cc_summaryelement import SummaryElement

47 from camcops_server.cc_modules.cc_task import (

48 Task,

49 TaskHasPatientMixin,

50 TaskHasRespondentMixin,

51)

52 from camcops_server.cc_modules.cc_trackerhelpers import TrackerInfo

53

54 log = BraceStyleAdapter(logging.getLogger(__name__))

55

56

57# =============================================================================

58# HADS (crippled unless upgraded locally) - base classes

59# =============================================================================

60

61

62 class HadsBase(TaskHasPatientMixin, Task, ABC): # type: ignore[misc]

63 """

64 Server implementation of the HADS task.

65 """

66

67 __abstract__ = True

68 provides_trackers = True

69

70 NQUESTIONS = 14

71 ANXIETY_QUESTIONS = [1, 3, 5, 7, 9, 11, 13]

72 DEPRESSION_QUESTIONS = [2, 4, 6, 8, 10, 12, 14]

73 TASK_FIELDS = strseq("q", 1, NQUESTIONS)

74 MAX_ANX_SCORE = 21

75 MAX_DEP_SCORE = 21

76

77 @classmethod

78 def extend_columns(cls: Type["HadsBase"], **kwargs: Any) -> None:

79 add_multiple_columns(

80 cls,

81 "q",

82 1,

83 cls.NQUESTIONS,

84 minimum=0,

85 maximum=3,

86 comment_fmt="Q{n}: {s} (0-3)",

87 comment_strings=[

88 "tense",

89 "enjoy usual",

90 "apprehensive",

91 "laugh",

92 "worry",

93 "cheerful",

94 "relaxed",

95 "slow",

96 "butterflies",

97 "appearance",

98 "restless",

99 "anticipate",

100 "panic",

101 "book/TV/radio",

102 ],

103 )

104

105 def is_complete(self) -> bool:

106 return self.field_contents_valid() and self.all_fields_not_none(

107 self.TASK_FIELDS

108 )

109

110 def get_trackers(self, req: CamcopsRequest) -> List[TrackerInfo]:

111 return [

112 TrackerInfo(

113 value=self.anxiety_score(),

114 plot_label="HADS anxiety score",

115 axis_label=f"Anxiety score (out of {self.MAX_ANX_SCORE})",

116 axis_min=-0.5,

117 axis_max=self.MAX_ANX_SCORE + 0.5,

118 ),

119 TrackerInfo(

120 value=self.depression_score(),

121 plot_label="HADS depression score",

122 axis_label=f"Depression score (out of {self.MAX_DEP_SCORE})",

123 axis_min=-0.5,

124 axis_max=self.MAX_DEP_SCORE + 0.5,

125 ),

126 ]

127

128 def get_clinical_text(self, req: CamcopsRequest) -> List[CtvInfo]:

129 if not self.is_complete():

130 return CTV_INCOMPLETE

131 return [

132 CtvInfo(

133 content=(

134 f"anxiety score "

135 f"{self.anxiety_score()}/{self.MAX_ANX_SCORE}, "

136 f"depression score "

137 f"{self.depression_score()}/{self.MAX_DEP_SCORE}"

138 )

139 )

140 ]

141

142 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:

143 return self.standard_task_summary_fields() + [

144 SummaryElement(

145 name="anxiety",

146 coltype=Integer(),

147 value=self.anxiety_score(),

148 comment=f"Anxiety score (/{self.MAX_ANX_SCORE})",

149 ),

150 SummaryElement(

151 name="depression",

152 coltype=Integer(),

153 value=self.depression_score(),

154 comment=f"Depression score (/{self.MAX_DEP_SCORE})",

155 ),

156 ]

157

158 def score(self, questions: List[int]) -> int:

159 fields = self.fieldnames_from_list("q", questions)

160 return cast(int, self.sum_fields(fields))

161

162 def anxiety_score(self) -> Union[int, float]:

163 return self.score(self.ANXIETY_QUESTIONS)

164

165 def depression_score(self) -> Union[int, float]:

166 return self.score(self.DEPRESSION_QUESTIONS)

167

168 def get_task_html(self, req: CamcopsRequest) -> str:

169 min_score = 0

170 max_score = 3

171 crippled = not self.extrastrings_exist(req)

172 a = self.anxiety_score()

173 d = self.depression_score()

174 h = f"""

175 <div class="{CssClass.SUMMARY}">

176 <table class="{CssClass.SUMMARY}">

177 {self.get_is_complete_tr(req)}

178 <tr>

179 <td>{req.wappstring(AS.HADS_ANXIETY_SCORE)}</td>

180 <td>{answer(a)} / {self.MAX_ANX_SCORE}</td>

181 </tr>

182 <tr>

183 <td>{req.wappstring(AS.HADS_DEPRESSION_SCORE)}</td>

184 <td>{answer(d)} / 21</td>

185 </tr>

186 </table>

187 </div>

188 <div class="{CssClass.EXPLANATION}">

189 All questions are scored from 0–3

190 (0 least symptomatic, 3 most symptomatic).

191 </div>

192 <table class="{CssClass.TASKDETAIL}">

193 <tr>

194 <th width="50%">Question</th>

195 <th width="50%">Answer</th>

196 </tr>

197 """

198 for n in range(1, self.NQUESTIONS + 1):

199 if crippled:

200 q = f"HADS: Q{n}"

201 else:

202 q = f"Q{n}. {self.wxstring(req, f'q{n}_stem')}"

203 if n in self.ANXIETY_QUESTIONS:

204 q += " (A)"

205 if n in self.DEPRESSION_QUESTIONS:

206 q += " (D)"

207 v = getattr(self, "q" + str(n))

208 if crippled or v is None or v < min_score or v > max_score:

209 a = v

210 else:

211 a = f"{v}: {self.wxstring(req, f'q{n}_a{v}')}" # type: ignore[assignment] # noqa: E501

212 h += tr_qa(q, a)

213 h += (

214 """

215 </table>

216 """

217 + DATA_COLLECTION_UNLESS_UPGRADED_DIV

218 )

219 return h

220

221

222# =============================================================================

223# Hads

224# =============================================================================

225

226

227 class Hads(HadsBase):

228 __tablename__ = "hads"

229 shortname = "HADS"

230

231 @staticmethod

232 def longname(req: "CamcopsRequest") -> str:

233 _ = req.gettext

234 return _(

235 "Hospital Anxiety and Depression Scale (data collection only)"

236 )

237

238 def get_snomed_codes(self, req: CamcopsRequest) -> List[SnomedExpression]:

239 codes = [

240 SnomedExpression(

241 req.snomed(SnomedLookup.HADS_PROCEDURE_ASSESSMENT)

242 )

243 ]

244 if self.is_complete():

245 codes.append(

246 SnomedExpression(

247 req.snomed(SnomedLookup.HADS_SCALE),

248 {

249 req.snomed(

250 SnomedLookup.HADS_ANXIETY_SCORE

251 ): self.anxiety_score(),

252 req.snomed(

253 SnomedLookup.HADS_DEPRESSION_SCORE

254 ): self.depression_score(),

255 },

256 )

257 )

258 return codes

259

260

261# =============================================================================

262# HadsRespondent

263# =============================================================================

264

265

266 class HadsRespondent(TaskHasRespondentMixin, HadsBase): # type: ignore[misc]

267 __tablename__ = "hads_respondent"

268 shortname = "HADS-Respondent"

269 extrastring_taskname = "hads"

270 info_filename_stem = extrastring_taskname

271

272 @staticmethod

273 def longname(req: "CamcopsRequest") -> str:

274 _ = req.gettext

275 return _(

276 "Hospital Anxiety and Depression Scale (data collection "

277 "only), non-patient respondent version"

278 )

279

280 # No SNOMED codes; not for the patient!