Passed
Pull Request — devel (#72)
by Paolo
06:50
created

excel.helpers.fill_uid.fill_uid_animals()   B

Complexity

Conditions 4

Size

Total Lines 94
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 57
dl 0
loc 94
rs 8.4072
c 0
b 0
f 0
cc 4
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
"""
4
Created on Fri Jul  5 16:37:48 2019
5
6
@author: Paolo Cozzi <[email protected]>
7
"""
8
9
import logging
10
11
from common.constants import (
12
    ERROR, LOADED, ACCURACIES, SAMPLE_STORAGE, SAMPLE_STORAGE_PROCESSING)
13
from common.helpers import image_timedelta, parse_image_timedelta
14
from uid.helpers import get_or_create_obj, update_or_create_obj
15
from uid.models import (
16
    DictBreed, DictCountry, DictSpecie, DictSex, DictUberon, Animal,
17
    Sample, DictDevelStage, DictPhysioStage)
18
from submissions.helpers import send_message
19
from validation.helpers import construct_validation_message
20
from validation.models import ValidationSummary
21
22
from .exceptions import ExcelImportError
23
from .exceltemplate import ExcelTemplateReader
24
25
# Get an instance of a logger
26
logger = logging.getLogger(__name__)
27
28
29
def fill_uid_breeds(submission_obj, template):
30
    """Fill DictBreed from a excel record"""
31
32
    logger.info("fill_uid_breeds() started")
33
34
    # ok get languages from submission (useful for translation)
35
    language = submission_obj.gene_bank_country.label
36
37
    # iterate among excel template
38
    for record in template.get_breed_records():
39
        # get a DictSpecie object. Species are in latin names, but I can
40
        # find also a common name in translation tables
41
        specie = DictSpecie.get_specie_check_synonyms(
42
            species_label=record.species,
43
            language=language)
44
45
        # get country for breeds. Ideally will be the same of submission,
46
        # however, it could be possible to store data from other contries
47
        country = DictCountry.objects.get(label=record.efabis_breed_country)
48
49
        get_or_create_obj(
50
            DictBreed,
51
            supplied_breed=record.supplied_breed,
52
            specie=specie,
53
            country=country)
54
55
    logger.info("fill_uid_breeds() completed")
56
57
58
def fill_uid_animals(submission_obj, template):
59
    # debug
60
    logger.info("called fill_uid_animals()")
61
62
    # get language
63
    language = submission_obj.gene_bank_country.label
64
65
    # iterate among excel template
66
    for record in template.get_animal_records():
67
        # determine sex. Check for values
68
        sex = DictSex.objects.get(label__iexact=record.sex)
69
70
        # get specie (mind synonyms)
71
        specie = DictSpecie.get_specie_check_synonyms(
72
            species_label=record.species, language=language)
73
74
        logger.debug("Found '%s' as specie" % (specie))
75
76
        # how I can get breed from my data?
77
        breed_record = template.get_breed_from_animal(record)
78
79
        # get a country for this breed
80
        country = DictCountry.objects.get(
81
            label=breed_record.efabis_breed_country)
82
83
        # ok get a real dictbreed object
84
        breed = DictBreed.objects.get(
85
            supplied_breed=breed_record.supplied_breed,
86
            specie=specie,
87
            country=country)
88
89
        logger.debug("Selected breed is %s" % (breed))
90
91
        # define mother and father
92
        mother, father = None, None
93
94
        # get name for this animal and for mother and father
95
        if record.father_id_in_data_source:
96
            logger.debug("Getting %s as father" % (
97
                record.father_id_in_data_source))
98
99
            father = Animal.objects.get(
100
                name=record.father_id_in_data_source,
101
                breed=breed,
102
                owner=submission_obj.owner)
103
104
        if record.mother_id_in_data_source:
105
            logger.debug("Getting %s as mother" % (
106
                record.mother_id_in_data_source))
107
108
            mother = Animal.objects.get(
109
                name=record.mother_id_in_data_source,
110
                breed=breed,
111
                owner=submission_obj.owner)
112
113
        # now get accuracy
114
        accuracy = ACCURACIES.get_value_by_desc(
115
            record.birth_location_accuracy)
116
117
        # create a new object. Using defaults to avoid collisions when
118
        # updating data
119
        defaults = {
120
            'alternative_id': record.alternative_animal_id,
121
            'description': record.animal_description,
122
            'sex': sex,
123
            'father': father,
124
            'mother': mother,
125
            'birth_date': record.birth_date,
126
            'birth_location': record.birth_location,
127
            'birth_location_latitude': record.birth_location_latitude,
128
            'birth_location_longitude': record.birth_location_longitude,
129
            'birth_location_accuracy': accuracy,
130
        }
131
132
        # creating or updating an object
133
        update_or_create_obj(
134
            Animal,
135
            name=record.animal_id_in_data_source,
136
            breed=breed,
137
            owner=submission_obj.owner,
138
            submission=submission_obj,
139
            defaults=defaults)
140
141
    # create a validation summary object and set all_count
142
    validation_summary = get_or_create_obj(
143
        ValidationSummary,
144
        submission=submission_obj,
145
        type="animal")
146
147
    # reset counts
148
    validation_summary.reset_all_count()
149
150
    # debug
151
    logger.info("fill_uid_animals() completed")
152
153
154
def fill_uid_samples(submission_obj, template):
155
    # debug
156
    logger.info("called fill_uid_samples()")
157
158
    # get language
159
    language = submission_obj.gene_bank_country.label
160
161
    # iterate among excel template
162
    for record in template.get_sample_records():
163
        # get animal by reading record
164
        animal_record = template.get_animal_from_sample(record)
165
166
        # get specie (mind synonyms)
167
        specie = DictSpecie.get_specie_check_synonyms(
168
            species_label=animal_record.species,
169
            language=language)
170
171
        logger.debug("Found '%s' as specie" % (specie))
172
173
        # get breed from animal record
174
        breed_record = template.get_breed_from_animal(animal_record)
175
176
        # get a country for this breed
177
        country = DictCountry.objects.get(
178
            label=breed_record.efabis_breed_country)
179
180
        # ok get a real dictbreed object
181
        breed = DictBreed.objects.get(
182
            supplied_breed=breed_record.supplied_breed,
183
            specie=specie,
184
            country=country)
185
186
        logger.debug("Selected breed is %s" % (breed))
187
188
        animal = Animal.objects.get(
189
            name=animal_record.animal_id_in_data_source,
190
            breed=breed,
191
            owner=submission_obj.owner)
192
193
        logger.debug("Selected animal is %s" % (animal))
194
195
        # get a organism part. Organism parts need to be in lowercases
196
        organism_part = get_or_create_obj(
197
            DictUberon,
198
            label=record.organism_part
199
        )
200
201
        # get developmental_stage and physiological_stage terms
202
        # they are not mandatory
203
        devel_stage, physio_stage = None, None
204
205
        if record.developmental_stage:
206
            devel_stage = get_or_create_obj(
207
                DictDevelStage,
208
                label=record.developmental_stage
209
            )
210
211
        if record.physiological_stage:
212
            physio_stage = get_or_create_obj(
213
                DictPhysioStage,
214
                label=record.physiological_stage
215
            )
216
217
        # animal age could be present or not
218
        if record.animal_age_at_collection:
219
            animal_age_at_collection, time_units = parse_image_timedelta(
220
                record.animal_age_at_collection)
221
222
        else:
223
            # derive animal age at collection
224
            animal_age_at_collection, time_units = image_timedelta(
225
                record.collection_date, animal.birth_date)
226
227
        # another time column
228
        preparation_interval, preparation_interval_units = None, None
229
230
        if record.sampling_to_preparation_interval:
231
            preparation_interval, preparation_interval_units = \
232
                parse_image_timedelta(record.sampling_to_preparation_interval)
233
234
        # now get accuracy
235
        accuracy = ACCURACIES.get_value_by_desc(
236
            record.collection_place_accuracy)
237
238
        # now get storage and storage processing
239
        # TODO; check those values in excel columns
240
        storage = SAMPLE_STORAGE.get_value_by_desc(
241
            record.sample_storage)
242
243
        storage_processing = SAMPLE_STORAGE_PROCESSING.get_value_by_desc(
244
            record.sample_storage_processing)
245
246
        # create a new object. Using defaults to avoid collisions when
247
        # updating data
248
        defaults = {
249
            'alternative_id': record.alternative_sample_id,
250
            'description': record.sample_description,
251
            'protocol': record.specimen_collection_protocol,
252
            'collection_date': record.collection_date,
253
            'collection_place_latitude': record.collection_place_latitude,
254
            'collection_place_longitude': record.collection_place_longitude,
255
            'collection_place': record.collection_place,
256
            'collection_place_accuracy': accuracy,
257
            'organism_part': organism_part,
258
            'developmental_stage': devel_stage,
259
            'physiological_stage': physio_stage,
260
            'animal_age_at_collection': animal_age_at_collection,
261
            'animal_age_at_collection_units': time_units,
262
            'availability': record.availability,
263
            'storage': storage,
264
            'storage_processing': storage_processing,
265
            'preparation_interval': preparation_interval,
266
            'preparation_interval_units': preparation_interval_units,
267
        }
268
269
        update_or_create_obj(
270
            Sample,
271
            name=record.sample_id_in_data_source,
272
            animal=animal,
273
            owner=submission_obj.owner,
274
            submission=submission_obj,
275
            defaults=defaults)
276
277
    # create a validation summary object and set all_count
278
    validation_summary = get_or_create_obj(
279
        ValidationSummary,
280
        submission=submission_obj,
281
        type="sample")
282
283
    # reset counts
284
    validation_summary.reset_all_count()
285
286
    # debug
287
    logger.info("fill_uid_samples() completed")
288
289
290
def check_UID(submission_obj, reader):
291
    # check for species and sex in a similar way as cryoweb does
292
    # TODO: identical to CRBanim. Move to a mixin
293
    check, not_found = reader.check_sex()
294
295
    # check sex
296
    if not check:
297
        message = (
298
            "Not all Sex terms are loaded into database: "
299
            "check for '%s' in your dataset" % (not_found))
300
301
        raise ExcelImportError(message)
302
303
    check, not_found = reader.check_species(
304
        submission_obj.gene_bank_country)
305
306
    # check species and related
307
    if not check:
308
        raise ExcelImportError(
309
            "Some species are not loaded into database: "
310
            "check for '%s' in your dataset" % (not_found))
311
312
    check, not_found = reader.check_species_in_animal_sheet()
313
314
    if not check:
315
        raise ExcelImportError(
316
            "Some species are not defined in breed sheet: "
317
            "check for '%s' in your dataset" % (not_found))
318
319
    # check countries
320
    check, not_found = reader.check_countries()
321
322
    if not check:
323
        raise ExcelImportError(
324
            "Those countries are not loaded in database: "
325
            "check for '%s' in your dataset" % (not_found))
326
327
    # check accuracies
328
    check, not_found = reader.check_accuracies()
329
330
    if not check:
331
        message = (
332
            "Not all accuracy levels are defined in database: "
333
            "check for '%s' in your dataset" % (not_found))
334
335
        raise ExcelImportError(message)
336
337
338
def upload_template(submission_obj):
339
    # debug
340
    logger.info("Importing from Excel template file")
341
342
    # this is the full path in docker container
343
    fullpath = submission_obj.get_uploaded_file_path()
344
345
    # read submission data
346
    reader = ExcelTemplateReader()
347
    reader.read_file(fullpath)
348
349
    # start data loading
350
    try:
351
        # check UID data like cryoweb does
352
        check_UID(submission_obj, reader)
353
354
        # BREEDS
355
        fill_uid_breeds(submission_obj, reader)
356
357
        # ANIMALS
358
        fill_uid_animals(submission_obj, reader)
359
360
        # SAMPLES
361
        fill_uid_samples(submission_obj, reader)
362
363
    except Exception as exc:
364
        # set message:
365
        message = "Error in importing data: %s" % (str(exc))
366
367
        # save a message in database
368
        submission_obj.status = ERROR
369
        submission_obj.message = message
370
        submission_obj.save()
371
372
        # send async message
373
        send_message(submission_obj)
374
375
        # debug
376
        logger.error("Error in importing from Template: %s" % (exc))
377
        logger.exception(exc)
378
379
        return False
380
381
    else:
382
        message = "Template import completed for submission: %s" % (
383
            submission_obj.id)
384
385
        submission_obj.message = message
386
        submission_obj.status = LOADED
387
        submission_obj.save()
388
389
        # send async message
390
        send_message(
391
            submission_obj,
392
            validation_message=construct_validation_message(submission_obj))
393
394
    logger.info("Import from Template is complete")
395
396
    return True
397