-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconcept.go
366 lines (321 loc) · 13.4 KB
/
concept.go
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
package controllers
import (
"bytes"
"encoding/csv"
"fmt"
"log"
"net/http"
"sort"
"strconv"
"github.com/gin-gonic/gin"
"github.com/uc-cdis/cohort-middleware/middlewares"
"github.com/uc-cdis/cohort-middleware/models"
"github.com/uc-cdis/cohort-middleware/utils"
)
type ConceptController struct {
conceptModel models.ConceptI
cohortDefinitionModel models.CohortDefinitionI
teamProjectAuthz middlewares.TeamProjectAuthzI
}
func NewConceptController(conceptModel models.ConceptI, cohortDefinitionModel models.CohortDefinitionI, teamProjectAuthz middlewares.TeamProjectAuthzI) ConceptController {
return ConceptController{
conceptModel: conceptModel,
cohortDefinitionModel: cohortDefinitionModel,
teamProjectAuthz: teamProjectAuthz,
}
}
func (u ConceptController) RetriveAllBySourceId(c *gin.Context) {
sourceId := c.Param("sourceid")
if sourceId != "" {
sourceId, _ := strconv.Atoi(sourceId)
concepts, err := u.conceptModel.RetriveAllBySourceId(sourceId)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error retrieving concept details", "error": err.Error()})
c.Abort()
return
}
c.JSON(http.StatusOK, gin.H{"concepts": concepts})
return
}
log.Printf("Error: bad request")
c.JSON(http.StatusBadRequest, gin.H{"message": "bad request"})
c.Abort()
}
func (u ConceptController) RetrieveInfoBySourceIdAndConceptIds(c *gin.Context) {
sourceId, conceptIds, err := utils.ParseSourceIdAndConceptIds(c)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
c.Abort()
return
}
// call model method:
conceptInfo, err := u.conceptModel.RetrieveInfoBySourceIdAndConceptIds(sourceId, conceptIds)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error retrieving concept details", "error": err.Error()})
c.Abort()
return
}
c.JSON(http.StatusOK, gin.H{"concepts": conceptInfo})
}
func (u ConceptController) RetrieveInfoBySourceIdAndConceptTypes(c *gin.Context) {
sourceId, conceptTypes, err := utils.ParseSourceIdAndConceptTypes(c)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
c.Abort()
return
}
// call model method:
conceptInfo, err := u.conceptModel.RetrieveInfoBySourceIdAndConceptTypes(sourceId, conceptTypes)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error retrieving concept details", "error": err.Error()})
c.Abort()
return
}
c.JSON(http.StatusOK, gin.H{"concepts": conceptInfo})
}
func (u ConceptController) RetrieveBreakdownStatsBySourceIdAndCohortId(c *gin.Context) {
sourceId, cohortId, err := utils.ParseSourceAndCohortId(c)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"message": "bad request", "error": err.Error()})
c.Abort()
return
}
validAccessRequest := u.teamProjectAuthz.TeamProjectValidationForCohort(c, cohortId)
if !validAccessRequest {
log.Printf("Error: invalid request")
c.JSON(http.StatusForbidden, gin.H{"message": "access denied"})
c.Abort()
return
}
breakdownConceptId, err := utils.ParseBigNumericArg(c, "breakdownconceptid")
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"message": "bad request", "error": err.Error()})
c.Abort()
return
}
breakdownStats, err := u.conceptModel.RetrieveBreakdownStatsBySourceIdAndCohortId(sourceId, cohortId, breakdownConceptId)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error retrieving stats", "error": err.Error()})
c.Abort()
return
}
c.JSON(http.StatusOK, gin.H{"concept_breakdown": breakdownStats})
}
func (u ConceptController) RetrieveBreakdownStatsBySourceIdAndCohortIdAndVariables(c *gin.Context) {
sourceId, cohortId, conceptDefsAndCohortPairs, err := utils.ParseSourceIdAndCohortIdAndVariablesAsSingleList(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "bad request", "error": err.Error()})
c.Abort()
return
}
// parse cohortPairs separately as well, so we can validate permissions
_, cohortPairs := utils.GetConceptDefsAndValuesAndCohortPairsAsSeparateLists(conceptDefsAndCohortPairs)
validAccessRequest := u.teamProjectAuthz.TeamProjectValidation(c, []int{cohortId}, cohortPairs)
if !validAccessRequest {
log.Printf("Error: invalid request")
c.JSON(http.StatusForbidden, gin.H{"message": "access denied"})
c.Abort()
return
}
breakdownConceptId, err := utils.ParseBigNumericArg(c, "breakdownconceptid")
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"message": "bad request", "error": err.Error()})
c.Abort()
return
}
breakdownStats, err := u.conceptModel.RetrieveBreakdownStatsBySourceIdAndCohortIdAndConceptDefsPlusCohortPairs(sourceId, cohortId, conceptDefsAndCohortPairs, breakdownConceptId)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error retrieving stats", "error": err.Error()})
c.Abort()
return
}
c.JSON(http.StatusOK, gin.H{"concept_breakdown": breakdownStats})
}
func getConceptValueToPeopleCount(breakdownStats []*models.ConceptBreakdown) map[string]int {
conceptValuesToPeopleCount := make(map[string]int)
for _, breakdownStat := range breakdownStats {
concept_value := breakdownStat.ConceptValue
if concept_value == "" {
concept_value = "empty string"
}
conceptValuesToPeopleCount[concept_value] = breakdownStat.NpersonsInCohortWithValue
}
return conceptValuesToPeopleCount
}
func generateRowForVariable(variableName string, breakdownConceptValuesToPeopleCount map[string]int, sortedBreakdownConceptValues []string) []string {
// validate:
if variableName == "" {
panic("unexpected error: variableName should be set!")
}
cohortSize := 0
for _, peopleCount := range breakdownConceptValuesToPeopleCount {
cohortSize += peopleCount
}
row := []string{variableName, strconv.Itoa(cohortSize)}
// make sure the numbers are printed out in the right order:
for _, concept := range sortedBreakdownConceptValues {
row = append(row, strconv.Itoa(breakdownConceptValuesToPeopleCount[concept]))
}
return row
}
func (u ConceptController) RetrieveAttritionTable(c *gin.Context) {
sourceId, cohortId, conceptDefsAndCohortPairs, err := utils.ParseSourceIdAndCohortIdAndVariablesAsSingleList(c)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"message": "bad request", "error": err.Error()})
c.Abort()
return
}
_, cohortPairs := utils.GetConceptDefsAndValuesAndCohortPairsAsSeparateLists(conceptDefsAndCohortPairs)
validAccessRequest := u.teamProjectAuthz.TeamProjectValidation(c, []int{cohortId}, cohortPairs)
if !validAccessRequest {
log.Printf("Error: invalid request")
c.JSON(http.StatusForbidden, gin.H{"message": "access denied"})
c.Abort()
return
}
breakdownConceptId, err := utils.ParseBigNumericArg(c, "breakdownconceptid")
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"message": "bad request", "error": err.Error()})
c.Abort()
return
}
cohortName, err := u.cohortDefinitionModel.GetCohortName(cohortId)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error retrieving cohort name", "error": err.Error()})
c.Abort()
return
}
breakdownStats, err := u.conceptModel.RetrieveBreakdownStatsBySourceIdAndCohortId(sourceId, cohortId, breakdownConceptId)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error retrieving concept breakdown for given cohortId", "error": err.Error()})
c.Abort()
return
}
sortedConceptValues := getSortedConceptValues(breakdownStats)
headerAndNonFilteredRow, err := u.GenerateHeaderAndNonFilteredRow(breakdownStats, sortedConceptValues, cohortName)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error generating concept breakdown header and cohort rows", "error": err.Error()})
c.Abort()
return
}
otherAttritionRows, err := u.GetAttritionRowForConceptDefsAndCohortPairs(sourceId, cohortId, conceptDefsAndCohortPairs, breakdownConceptId, sortedConceptValues)
if err != nil {
log.Printf("Error: %s", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error retrieving concept breakdown rows for filter conceptIds and cohortPairs", "error": err.Error()})
c.Abort()
return
}
b := GenerateAttritionCSV(headerAndNonFilteredRow, otherAttritionRows)
c.String(http.StatusOK, b.String())
}
func (u ConceptController) GetAttritionRowForConceptDefsAndCohortPairs(sourceId int, cohortId int, conceptDefsAndCohortPairs []interface{}, breakdownConceptId int64, sortedConceptValues []string) ([][]string, error) {
var otherAttritionRows [][]string
for idx, conceptIdOrCohortPair := range conceptDefsAndCohortPairs {
// attrition filter: run each query with an increasingly longer list of filterConceptDefsAndCohortPairs, until the last query is run with them all:
filterConceptDefsAndCohortPairs := conceptDefsAndCohortPairs[0 : idx+1]
attritionRow, err := u.GetAttritionRowForConceptDefOrCohortPair(sourceId, cohortId, conceptIdOrCohortPair, filterConceptDefsAndCohortPairs, breakdownConceptId, sortedConceptValues)
if err != nil {
log.Printf("Error: %s", err.Error())
return nil, err
}
otherAttritionRows = append(otherAttritionRows, attritionRow)
}
return otherAttritionRows, nil
}
func (u ConceptController) GetAttritionRowForConceptDefOrCohortPair(sourceId int, cohortId int, conceptIdOrCohortPair interface{}, filterConceptDefsAndCohortPairs []interface{}, breakdownConceptId int64, sortedConceptValues []string) ([]string, error) {
filterConceptDefsAndValues, filterCohortPairs := utils.GetConceptDefsAndValuesAndCohortPairsAsSeparateLists(filterConceptDefsAndCohortPairs)
filterConceptIds := utils.ExtractConceptIdsFromCustomConceptVariablesDef(filterConceptDefsAndValues)
breakdownStats, err := u.conceptModel.RetrieveBreakdownStatsBySourceIdAndCohortIdAndConceptDefsPlusCohortPairs(sourceId, cohortId, filterConceptDefsAndCohortPairs, breakdownConceptId)
if err != nil {
return nil, fmt.Errorf("could not retrieve concept Breakdown for concepts %v dichotomous variables %v due to error: %s", filterConceptIds, filterCohortPairs, err.Error())
}
conceptValuesToPeopleCount := getConceptValueToPeopleCount(breakdownStats)
variableName := ""
switch convertedItem := conceptIdOrCohortPair.(type) {
case utils.CustomConceptVariableDef:
conceptInformation, err := u.conceptModel.RetrieveInfoBySourceIdAndConceptId(sourceId, convertedItem.ConceptId)
if err != nil {
return nil, fmt.Errorf("could not retrieve concept details for %v due to error: %s", convertedItem, err.Error())
}
variableName = conceptInformation.ConceptName
case utils.CustomDichotomousVariableDef:
variableName = convertedItem.ProvidedName
}
log.Printf("Generating row for variable with name %s", variableName)
generatedRow := generateRowForVariable(variableName, conceptValuesToPeopleCount, sortedConceptValues)
return generatedRow, nil
}
func getSortedConceptValues(breakdownStats []*models.ConceptBreakdown) []string {
concepts := []string{}
for _, breakdownStat := range breakdownStats {
concepts = append(concepts, breakdownStat.ConceptValue)
}
sort.Strings(concepts)
return concepts
}
func getConceptValueToConceptName(breakdownStats []*models.ConceptBreakdown) map[string]string {
conceptValuesToConceptName := make(map[string]string)
for _, breakdownStat := range breakdownStats {
conceptValue := breakdownStat.ConceptValue
conceptName := breakdownStat.ValueName
if conceptValue == "" {
conceptValue = "empty string"
conceptName = "empty string"
}
conceptValuesToConceptName[conceptValue] = conceptName
}
return conceptValuesToConceptName
}
func getConceptNamesFromConceptValues(conceptValues []string, conceptValuesToConceptName map[string]string) []string {
conceptNames := []string{}
for _, conceptValue := range conceptValues {
conceptNames = append(conceptNames, conceptValuesToConceptName[conceptValue])
}
return conceptNames
}
func (u ConceptController) GenerateHeaderAndNonFilteredRow(breakdownStats []*models.ConceptBreakdown, sortedConceptValues []string, cohortName string) ([][]string, error) {
conceptValuesToPeopleCount := getConceptValueToPeopleCount(breakdownStats)
conceptValuesToConceptName := getConceptValueToConceptName(breakdownStats)
cohortSize := 0
for _, peopleCount := range conceptValuesToPeopleCount {
cohortSize += peopleCount
}
conceptNames := getConceptNamesFromConceptValues(sortedConceptValues, conceptValuesToConceptName)
header := append([]string{"Cohort", "Size"}, conceptNames...)
row := []string{cohortName, strconv.Itoa(cohortSize)}
for _, concept := range sortedConceptValues {
row = append(row, strconv.Itoa(conceptValuesToPeopleCount[concept]))
}
return [][]string{
header,
row,
}, nil
}
func GenerateAttritionCSV(headerAndNonFilteredRow [][]string, filteredRows [][]string) *bytes.Buffer {
var rows [][]string
rows = append(rows, headerAndNonFilteredRow...)
rows = append(rows, filteredRows...)
b := new(bytes.Buffer)
w := csv.NewWriter(b)
w.Comma = ',' // CSV
err := w.WriteAll(rows)
if err != nil {
log.Fatal(err)
}
return b
}