source: trunk/grails-app/services/dbnp/studycapturing/AssayService.groovy @ 1864

Last change on this file since 1864 was 1864, checked in by s.h.sikkema@…, 13 years ago

in exporter: module error display improvements (ie. display on screen but still able to export); removed changes to simplewizard; removed unnecessary imports; should handle 'null' parent subject from samples correctly; should handle non number values from modules correctly; deselects module measurements in case of module error/no measurements; removed obsolete entry in topnav

  • Property svn:keywords set to Rev Author Date
File size: 21.6 KB
Line 
1/**
2 * AssayService Service
3 *
4 * @author  s.h.sikkema@gmail.com
5 * @since       20101216
6 * @package     dbnp.studycapturing
7 *
8 * Revision information:
9 * $Rev: 1864 $
10 * $Author: s.h.sikkema@gmail.com $
11 * $Date: 2011-05-23 14:36:00 +0000 (ma, 23 mei 2011) $
12 */
13package dbnp.studycapturing
14
15import org.apache.poi.ss.usermodel.*
16import org.apache.poi.xssf.usermodel.XSSFWorkbook
17import org.apache.poi.hssf.usermodel.HSSFWorkbook
18import org.codehaus.groovy.grails.web.json.JSONObject
19import org.dbnp.gdt.RelTime
20import org.dbnp.gdt.TemplateFieldType
21import java.text.DecimalFormat
22import java.text.NumberFormat
23import org.dbnp.gdt.Template
24import org.dbnp.gdt.TemplateField
25
26class AssayService {
27
28        boolean transactional = false
29        def authenticationService
30        def moduleCommunicationService
31
32        /**
33         * Collects the assay field names per category in a map as well as the
34         * module's measurements.
35         *
36         * @param assay the assay for which to collect the fields
37         * @return a map of categories as keys and field names or measurements as
38         *  values
39         */
40        def collectAssayTemplateFields(assay) throws Exception {
41
42                def getUsedTemplateFields = { templateEntities ->
43
44                        // gather all unique and non null template fields that haves values
45                        templateEntities*.giveFields().flatten().unique().findAll{ field ->
46
47                                field && templateEntities.any { it?.fieldExists(field.name) && it.getFieldValue(field.name) != null }
48
49                        }.collect{[name: it.name, comment: it.comment, displayName: it.name + (it.unit ? " ($it.unit)" : '')]}
50                }
51
52        def moduleError = '', moduleMeasurements = []
53
54        try {
55            moduleMeasurements = requestModuleMeasurementNames(assay)
56        } catch (e) {
57            moduleError = e.message
58        }
59
60                def samples = assay.samples
61                [               'Subject Data' :            getUsedTemplateFields( samples*."parentSubject".unique() ),
62                                        'Sampling Event Data' :     getUsedTemplateFields( samples*."parentEvent".unique() ),
63                                        'Sample Data' :             getUsedTemplateFields( samples ),
64                                        'Event Group' :             [[name: 'name', comment: 'Name of Event Group', displayName: 'name']],
65                                        'Module Measurement Data':  moduleMeasurements,
66                    'ModuleError':              moduleError
67                ]
68
69        }
70
71        /**
72         * Gathers all assay related data, including measurements from the module,
73         * into 1 hash map containing: Subject Data, Sampling Event Data, Sample
74         * Data, and module specific measurement data.
75         * Data from each of the 4 hash map entries are themselves hash maps
76         * representing a descriptive header (field name) as key and the data as
77         * value.
78         *
79         * @param assay                                 the assay to collect data for
80         * @param fieldMap                              map with categories as keys and fields as values
81         * @param measurementTokens     selection of measurementTokens
82         * @return                              The assay data structure as described above.
83         */
84        def collectAssayData(assay, fieldMap, measurementTokens) throws Exception {
85
86                def collectFieldValuesForTemplateEntities = { headerFields, templateEntities ->
87
88                        // return a hash map with for each field name all values from the
89                        // template entity list
90                        headerFields.inject([:]) { map, headerField ->
91
92                                map + [(headerField.displayName): templateEntities.collect { entity ->
93
94                    // default to an empty string
95                    def val = ''
96
97                    if (entity) {
98                        def field
99                        try {
100
101                            val = entity.getFieldValue(headerField.name)
102
103                            // Convert RelTime fields to human readable strings
104                            field = entity.getField(headerField.name)
105                            if (field.type == TemplateFieldType.RELTIME)
106                                val = new RelTime( val as long )
107
108                        } catch (NoSuchFieldException e) { /* pass */ }
109                    }
110
111                    (val instanceof Number) ? val : val.toString()}]
112                        }
113                }
114
115                def getFieldValues = { templateEntities, headerFields, propertyName = '' ->
116
117                        def returnValue
118
119                        // if no property name is given, simply collect the fields and
120                        // values of the template entities themselves
121                        if (propertyName == '') {
122
123                                returnValue = collectFieldValuesForTemplateEntities(headerFields, templateEntities)
124
125                        } else {
126
127                                // if a property name is given, we'll have to do a bit more work
128                                // to ensure efficiency. The reason for this is that for a list
129                                // of template entities, the properties referred to by
130                                // propertyName can include duplicates. For example, for 10
131                                // samples, there may be less than 10 parent subjects. Maybe
132                                // there's only 1 parent subject. We don't want to collect field
133                                // values for this single subject 10 times ...
134                                def fieldValues
135
136                                // we'll get the unique list of properties to make sure we're
137                                // not getting the field values for identical template entity
138                                // properties more then once.
139                                def uniqueProperties = templateEntities*."$propertyName".unique()
140
141                                fieldValues = collectFieldValuesForTemplateEntities(headerFields, uniqueProperties)
142
143                                // prepare a lookup hashMap to be able to map an entities'
144                                // property (e.g. a sample's parent subject) to an index value
145                                // from the field values list
146                                int i = 0
147                                def propertyToFieldValueIndexMap = uniqueProperties.inject([:]) { map, item -> map + [(item):i++]}
148
149                                // prepare the return value so that it has an entry for field
150                                // name. This will be the column name (second header line).
151                                returnValue = headerFields*.displayName.inject([:]) { map, item -> map + [(item):[]] }
152
153                                // finally, fill map the unique field values to the (possibly
154                                // not unique) template entity properties. In our example with
155                                // 1 unique parent subject, this means copying that subject's
156                                // field values to all 10 samples.
157                                templateEntities.each{ te ->
158
159                                        headerFields*.displayName.each{
160
161                                                returnValue[it] << fieldValues[it][propertyToFieldValueIndexMap[te[propertyName]]]
162
163                                        }
164
165                                }
166
167                        }
168
169                        returnValue
170
171                }
172
173                // Find samples and sort by name
174                def samples = assay.samples.toList().sort { it.name }
175
176                def eventFieldMap = [:]
177
178                // check whether event group data was requested
179                if (fieldMap['Event Group']) {
180
181                        def names = samples*.parentEventGroup*.name.flatten()
182
183                        // only set name field when there's actual data
184                        if (!names.every {!it}) eventFieldMap['name'] = names
185
186                }
187
188                def moduleError = '', moduleMeasurementData = [:]
189
190                if (measurementTokens) {
191
192            try {
193                moduleMeasurementData = requestModuleMeasurements(assay, measurementTokens, samples)
194            } catch (e) {
195                moduleMeasurementData = ['error' : ['Module error, module not available or unknown assay'] * samples.size() ]
196                moduleError =  e.message
197            }
198
199                }
200
201                [       'Subject Data' :            getFieldValues(samples, fieldMap['Subject Data'], 'parentSubject'),
202                                'Sampling Event Data' :     getFieldValues(samples, fieldMap['Sampling Event Data'], 'parentEvent'),
203                'Sample Data' :             getFieldValues(samples, fieldMap['Sample Data']),
204                'Event Group' :             eventFieldMap,
205                'Module Measurement Data' : moduleMeasurementData,
206                'ModuleError' :             moduleError
207                                ]
208        }
209
210        /**
211         * Prepend data from study to the data structure
212         * @param assayData             Column wise data structure of samples
213         * @param assay                 Assay object the data should be selected from
214         * @param numValues             Number of values for this assay
215         * @return                              Extended column wise data structure
216         */
217        def prependStudyData( inputData, Assay assay, numValues ) {
218                if( !assay )
219                        return inputData;
220
221                // Retrieve study data
222                def studyData =[:]
223                assay.parent?.giveFields().each {
224                        def value = assay.parent.getFieldValue( it.name )
225                        if( value )
226                                studyData[ it.name ] = [value] * numValues
227                }
228
229                return [
230                        'Study Data': studyData
231                ] + inputData
232        }
233
234        /**
235         * Prepend data from assay to the data structure
236         * @param assayData             Column wise data structure of samples
237         * @param assay                 Assay object the data should be selected from
238         * @param numValues             Number of values for this assay
239         * @return                              Extended column wise data structure
240         */
241        def prependAssayData( inputData, Assay assay, numValues ) {
242                if( !assay )
243                        return inputData;
244
245                // Retrieve assay data
246                def assayData = [:]
247                assay.giveFields().each {
248                        def value = assay.getFieldValue( it.name )
249                        if( value )
250                                assayData[ it.name ] = [value] * numValues
251                }
252
253                return [
254                        'Assay Data': assayData
255                ] + inputData
256        }
257
258        /**
259         * Retrieves measurement names from the module through a rest call
260         *
261         * @param consumer the url of the module
262         * @param path path of the rest call to the module
263         * @return
264         */
265        def requestModuleMeasurementNames(assay) {
266
267                def moduleUrl = assay.module.url
268
269                def path = moduleUrl + "/rest/getMeasurements/query"
270        def query = "assayToken=${assay.giveUUID()}"
271        def jsonArray
272
273        try {
274            jsonArray = moduleCommunicationService.callModuleMethod(moduleUrl, path, query, "POST")
275        } catch (e) {
276            throw new Exception("An error occured while trying to get the measurement tokens from the $assay.module.name. \
277             This means the module containing the measurement data is not available right now. Please try again \
278             later or notify the system administrator if the problem persists. URL: $path?$query.")
279        }
280
281                jsonArray.collect {
282                        if( it == JSONObject.NULL )
283                                return ""
284                        else
285                                return it.toString()
286                }
287
288        }
289
290        /**
291         * Retrieves module measurement data through a rest call to the module
292         *
293         * @param assay                         Assay for which the module measurements should be retrieved
294         * @param measurementTokens     List with the names of the fields to be retrieved. Format: [ 'measurementName1', 'measurementName2' ]
295         * @param samples                       Samples to collect measurements for
296         * @return
297         */
298        def requestModuleMeasurements(assay, inputMeasurementTokens, samples) {
299
300                def moduleUrl = assay.module.url
301
302                def tokenString = ''
303
304                inputMeasurementTokens.each{
305                        tokenString+="&measurementToken=${it.encodeAsURL()}"
306                }
307
308                def path = moduleUrl + "/rest/getMeasurementData/query"
309
310        def query = "assayToken=$assay.assayUUID$tokenString"
311
312                def sampleTokens = [], measurementTokens = [], moduleData = []
313
314        try {
315            (sampleTokens, measurementTokens, moduleData) = moduleCommunicationService.callModuleMethod(moduleUrl, path, query, "POST")
316        } catch (e) {
317            throw new Exception("An error occured while trying to get the measurement data from the $assay.module.name. \
318             This means the module containing the measurement data is not available right now. Please try again \
319             later or notify the system administrator if the problem persists. URL: $path?$query.")
320        }
321
322                if (!sampleTokens?.size()) return []
323
324                // Convert the three different maps into a map like:
325                //
326                // [ "measurement 1": [ value1, value2, value3 ],
327                //   "measurement 2": [ value4, value5, value6 ] ]
328                //
329                // The returned values should be in the same order as the given samples-list
330                def map = [:]
331                def numSampleTokens = sampleTokens.size();
332
333                measurementTokens.eachWithIndex { measurementToken, measurementIndex ->
334                        def measurements = [];
335                        samples.each { sample ->
336
337                                // Do measurements for this sample exist? If not, a null value is returned
338                                // for this sample. Otherwise, the measurement is looked up in the list with
339                                // measurements, based on the sample token
340                                if( sampleTokens.collect{ it.toString() }.contains( sample.giveUUID() ) ) {
341                                        def tokenIndex = sampleTokens.indexOf( sample.giveUUID() );
342                                        def valueIndex = measurementIndex * numSampleTokens + tokenIndex;
343
344                                        // If the module data is in the wrong format, show an error in the log file
345                                        // and return a null value for this measurement.
346                                        if( valueIndex >= moduleData.size() ) {
347                                                log.error "Module measurements given by module " + assay.module.name + " are not in the right format: " + measurementTokens?.size() + " measurements, " + sampleTokens?.size() + " samples, " + moduleData?.size() + " values"
348                                                measurements << null
349                                        }  else {
350
351                        def val
352                        def measurement = moduleData[ valueIndex ]
353
354                        if          (measurement == JSONObject.NULL)    val = ""
355                        else if     (measurement instanceof Number)     val = measurement
356                        else if     (measurement.isDouble())            val = measurement.toDouble()
357                        else val =   measurement.toString()
358                                                measurements << val
359                                        }
360                                } else {
361                                        measurements << null
362                                }
363                        }
364                        map[ measurementToken.toString() ] = measurements
365                }
366
367                return map;
368        }
369
370        /**
371         * Merges the data from multiple studies into a structure that can be exported to an excel file. The format for each assay is
372         *
373         *      [Category1:
374         *      [Column1: [1,2,3], Column2: [4,5,6]],
375         *   Category2:
376         *      [Column3: [7,8,9], Column4: [10,11,12], Column5: [13,14,15]]]
377         *
378         * Where the category describes the category of data that is presented (e.g. subject, sample etc.) and the column names describe
379         * the fields that are present. Each entry in the lists shows the value for that column for an entity. In this case, 3 entities are described.
380         * Each field should give values for all entities, so the length of all value-lists should be the same.
381         *
382         * Example: If the following input is given (2 assays)
383         *
384         *      [
385         *    [Category1:
386         *      [Column1: [1,2,3], Column2: [4,5,6]],
387         *     Category2:
388         *      [Column3: [7,8,9], Column4: [10,11,12], Column5: [13,14,15]]],
389         *    [Category1:
390         *      [Column1: [16,17], Column6: [18,19]],
391         *     Category3:
392         *      [Column3: [20,21], Column8: [22,23]]]
393         * ]
394         *
395         * the output will be (5 entries for each column, empty values for fields that don't exist in some assays)
396         *
397         *      [
398         *    [Category1:
399         *      [Column1: [1,2,3,16,17], Column2: [4,5,6,,], Column6: [,,,18,19]],
400         *     Category2:
401         *      [Column3: [7,8,9,,], Column4: [10,11,12,,], Column5: [13,14,15,,]],
402         *     Category3:
403         *      [Column3: [,,,20,21], Column8: [,,,22,23]]
404         * ]
405         *
406         *
407         * @param columnWiseAssayData   List with each entry being the column wise data of an assay. The format for each
408         *                                                              entry is described above
409         * @return      Hashmap                         Combined assay data, in the same structure as each input entry. Empty values are given as an empty string.
410         *                                                              So for input entries
411         */
412        def mergeColumnWiseDataOfMultipleStudies(def columnWiseAssayData) {
413                // Compute the number of values that is expected for each assay. This number is
414                // used later on to determine the number of empty fields to add if a field is not present in this
415                // assay
416                def numValues = columnWiseAssayData.collect { assay ->
417                        for( cat in assay ) {
418                                if( cat ) {
419                                        for( field in cat.value ) {
420                                                if( field?.value?.size() > 0 ) {
421                                                        return field.value.size();
422                                                }
423                                        }
424                                }
425                        }
426
427                        return 0;
428                }
429
430                // Merge categories from all assays. Create a list for all categories
431                def categories = columnWiseAssayData*.keySet().toList().flatten().unique();
432                def mergedColumnWiseData = [:]
433                categories.each { category ->
434                        // Only work with this category for all assays
435                        def categoryData = columnWiseAssayData*.getAt( category );
436
437                        // Find the different fields in all assays
438                        def categoryFields = categoryData.findAll{ it }*.keySet().toList().flatten().unique();
439
440                        // Find data for all assays for these fields. If the fields do not exist, return an empty string
441                        def categoryValues = [:]
442                        categoryFields.each { field ->
443                                categoryValues[ field ] = [];
444
445                                // Loop through all assays
446                                categoryData.eachWithIndex { assayValues, idx ->
447                                        if( assayValues && assayValues.containsKey( field ) ) {
448                                                // Append the values if they exist
449                                                categoryValues[ field ] += assayValues[ field ];
450                                        } else {
451                                                // Append empty string for each entity if the field doesn't exist
452                                                categoryValues[ field ] += [""] * numValues[ idx ]
453                                        }
454                                }
455                        }
456
457                        mergedColumnWiseData[ category ] = categoryValues
458                }
459
460                return mergedColumnWiseData;
461        }
462
463        /**
464         * Converts column
465         * @param columnData multidimensional map containing column data.
466         * On the top level, the data must be grouped by category. Each key is the
467         * category title and the values are maps representing the columns. Each
468         * column also has a title (its key) and a list of values. Columns must be
469         * equally sized.
470         *
471         * For example, consider the following map:
472         * [Category1:
473         *      [Column1: [1,2,3], Column2: [4,5,6]],
474         *  Category2:
475         *      [Column3: [7,8,9], Column4: [10,11,12], Column5: [13,14,15]]]
476         *
477         * which will be written as:
478         *
479         * | Category1  |           | Category2 |           |           |
480         * | Column1    | Column2   | Column3   | Column4   | Column5   |
481         * | 1          | 4         | 7         | 10        | 13        |
482         * | 2          | 5         | 8         | 11        | 14        |
483         * | 3          | 6         | 9         | 12        | 15        |
484         *
485         * @return row wise data
486         */
487        def convertColumnToRowStructure(columnData) {
488
489                // check if all columns have the dimensionality 2
490                if (columnData.every { it.value.every { it.value instanceof ArrayList } }) {
491
492                        def headers = [[],[]]
493
494                        columnData.each { category ->
495
496                                if (category.value.size()) {
497
498                                        // put category keys into first row separated by null values
499                                        // wherever there are > 1 columns per category
500                                        headers[0] += [category.key] + [null] * (category.value.size() - 1)
501
502                                        // put non-category column headers into 2nd row
503                                        headers[1] += category.value.collect{it.key}
504
505                                }
506
507                        }
508
509                        def d = []
510
511                        // add all column wise data into 'd'
512                        columnData.each { it.value.each { d << it.value } }
513
514                        // transpose d into row wise data and combine with header rows
515                        headers + d.transpose()
516                } else []
517
518        }
519
520        /**
521         * Export column wise data in Excel format to a stream.
522         *
523         * @param columnData Multidimensional map containing column data
524         * @param outputStream Stream to write to
525         * @param useOfficeOpenXML Flag to specify xlsx (standard) or xls output
526         * @return
527         */
528        def exportColumnWiseDataToExcelFile(columnData, outputStream, useOfficeOpenXML = true) {
529
530                // transform data into row based structure for easy writing
531                def rows = convertColumnToRowStructure(columnData)
532
533                if (rows) {
534
535                        exportRowWiseDataToExcelFile(rows, outputStream, useOfficeOpenXML)
536
537                } else {
538
539                        throw new Exception('Wrong column data format.')
540
541                }
542
543        }
544
545        /**
546         * Export row wise data in Excel format to a stream
547         *
548         * @param rowData List of lists containing for each row all cell values
549         * @param outputStream Stream to write to
550         * @param useOfficeOpenXML Flag to specify xlsx (standard) or xls output
551         * @return
552         */
553        def exportRowWiseDataToExcelFile(rowData, outputStream, useOfficeOpenXML = true) {
554                Workbook wb = useOfficeOpenXML ? new XSSFWorkbook() : new HSSFWorkbook()
555                Sheet sheet = wb.createSheet()
556
557                exportRowWiseDataToExcelSheet( rowData, sheet );
558
559                wb.write(outputStream)
560                outputStream.close()
561        }
562
563        /**
564         * Export row wise data in CSV to a stream. All values are surrounded with
565     * double quotes (" ").
566         *
567         * @param rowData List of lists containing for each row all cell values
568         * @param outputStream Stream to write to
569         * @return
570         */
571        def exportRowWiseDataToCSVFile(rowData, outputStream, outputDelimiter = '\t', locale = java.util.Locale.US) {
572
573        def formatter = NumberFormat.getNumberInstance(locale)
574        formatter.setGroupingUsed false // we don't want grouping (thousands) separators
575
576        outputStream << rowData.collect { row ->
577          row.collect{
578
579              // omit quotes in case of numeric values and format using chosen locale
580              if (it instanceof Number) return formatter.format(it)
581
582              def s = it?.toString() ?: ''
583
584              def addQuotes = false
585
586              // escape double quotes with double quotes if they exist and
587              // enable surround with quotes
588              if (s.contains('"')) {
589                  addQuotes = true
590                  s = s.replaceAll('"','""')
591              } else {
592                  // enable surround with quotes in case of comma's
593                  if (s.contains(',') || s.contains('\n')) addQuotes = true
594              }
595
596              addQuotes ? "\"$s\"" : s
597
598          }.join(outputDelimiter)
599        }.join('\n')
600
601                outputStream.close()
602        }
603
604        /**
605         * Export row wise data for multiple assays in Excel format (separate sheets) to a stream
606         *
607         * @param rowData       List of structures with rowwise data for each assay
608         * @param outputStream Stream to write to
609         * @param useOfficeOpenXML Flag to specify xlsx (standard) or xls output
610         * @return
611         */
612        def exportRowWiseDataForMultipleAssaysToExcelFile(assayData, outputStream, useOfficeOpenXML = true) {
613                Workbook wb = useOfficeOpenXML ? new XSSFWorkbook() : new HSSFWorkbook()
614
615                assayData.each { rowData ->
616                        Sheet sheet = wb.createSheet()
617
618                        exportRowWiseDataToExcelSheet( rowData, sheet );
619                }
620
621                wb.write(outputStream)
622                outputStream.close()
623        }
624
625        /**
626         * Export row wise data in Excel format to a given sheet in an excel workbook
627         *
628         * @param rowData       List of lists containing for each row all cell values
629         * @param sheet         Excel sheet to append the
630         * @return
631         */
632        def exportRowWiseDataToExcelSheet(rowData, Sheet sheet) {
633                // create all rows
634                rowData.size().times { sheet.createRow it }
635
636                sheet.eachWithIndex { Row row, ri ->
637                        if( rowData[ ri ] ) {
638                                // create appropriate number of cells for this row
639                                rowData[ri].size().times { row.createCell it }
640
641                                row.eachWithIndex { Cell cell, ci ->
642
643                                        // Numbers and values of type boolean, String, and Date can be
644                                        // written as is, other types need converting to String
645                                        def value = rowData[ri][ci]
646
647                                        value = (value instanceof Number | value?.class in [boolean.class, String.class, Date.class]) ? value : value?.toString()
648
649                                        // write the value (or an empty String if null) to the cell
650                                        cell.setCellValue(value ?: '')
651
652                                }
653                        }
654                }
655        }
656}
Note: See TracBrowser for help on using the repository browser.