forked from rafelafrance/traiter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvn_utils.py
3351 lines (2930 loc) · 111 KB
/
vn_utils.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The line above is to signify that the script contains utf-8 encoded characters.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Adapted from https://github.com/VertNet/dwc-indexer
# Adapted from https://github.com/kurator-org/kurator-validation
# This file contains common utility functions for dealing with the content of VertNet
# harvested text files. It is built with unit tests that can be invoked by running the
# script without any command line parameters. Test data are expected to be in
# ./tests/data.
#
# Example:
#
# python vn_utils.py
__author__ = "John Wieczorek"
__contributors__ = "Aaron Steele, John Wieczorek"
__copyright__ = "Copyright 2018 vertnet.org"
__version__ = "vn_utils.py 2018-04-07T10:43-3:00"
import csv
import os
import re
import logging
import unittest
import arrow # used for format_date_as_w3c()
from slugify import slugify
from datetime import datetime
# need to install arrow for this to be used (better support of date time)
# pip install arrow
def record_level_resolution(rec):
""" Create a dictionary of completed, corrected record-level fields from data in
a dictionary. Also make a keynam for the index.
parameters:
rec - dictionary to search for record_level input (required)
returns:
dictionary of completed, corrected record_level fields
"""
### KEYNAME ###
keyname = None
# rec must contain icode
if rec.has_key('icode') == False or len(rec['icode']) == 0:
print 'missing icode in %s' % rec
return None
# rec must contain either collectioncode or gbifdatasetid
if rec.has_key('collectioncode') == False or len(rec['collectioncode']) == 0:
if rec.has_key('gbifdatasetid') == False or len(rec['gbifdatasetid']) == 0:
print 'missing collectioncode AND gbifdatasetid in %s' % rec
return None
# rec must contain either catalognumber or id
if rec.has_key('catalognumber') == False or len(rec['catalognumber']) == 0:
if rec.has_key('id') == False or len(rec['id']) == 0:
if rec.has_key('occurrenceid') == False or len(rec['occurrenceid']) == 0:
print 'missing catalognumber AND id in %s' % rec
return None
# Create a condensed version of the icode from the VertNet registry as an
# institution identifier
icode_slug = slugify(rec['icode'])
# Create a condensed version of the collectioncode as a collection identifier
# If the collectioncode has content, use it for the collection identifier
# otherwise, use the slugged version of the resource identifier
if rec.has_key('collectioncode') and len(rec['collectioncode']) > 0:
# coll_id = re.sub(' ','-', re.sub("\'",'',repr(rec['collectioncode'])).lower())
coll_id = slugify(rec['collectioncode'])
else:
coll_id = rec['gbifdatasetid']
# Create a condensed version of the occurrence identifier
# If the catalognumber has content, use it for the occurrence identifier
# otherwise, use the id field
bestid = None
if rec.has_key('occurrenceid') and len(rec['occurrenceid'].strip()) > 0:
bestid = rec['occurrenceid'].strip()
elif rec.has_key('id') and len(rec['id'].strip()) > 0:
bestid = rec['id'].strip()
elif rec.has_key('catalognumber') and len(rec['catalognumber'].strip()) > 0:
bestid = rec['catalognumber'].strip()
else:
bestid = 'noid'
occ_id = slugify(bestid)
# Make a unique, potentially persistent record (datastore document) identifier
keyname ='%s/%s/%s' % (icode_slug, coll_id, occ_id)
keyname = keyname.replace('//','/')
### REFERENCES ###
# VertNet migrator must construct the references field using this same pattern for
# records that do not already have a references value.
references = None
if rec.has_key('references') == False or len(rec['references']) == 0 or \
'portal.vertnet.org' in rec['references'].lower():
references = 'http://portal.vertnet.org/o/%s/%s?id=%s' % \
(icode_slug, coll_id, occ_id)
else:
references = rec['references']
### BASISOFRECORD ###
# Standardize basisOfRecord
basisofrecord = 'Occurrence'
if rec.has_key('basisofrecord'):
s = rec['basisofrecord'].strip().lower()
if len(s) > 0:
if 'preserv' in s:
basisofrecord = 'PreservedSpecimen'
elif 'material' in s:
basisofrecord = 'MaterialSample'
elif s == 'specimen':
basisofrecord = 'PreservedSpecimen'
elif 'machine' in s:
basisofrecord = 'MachineObservation'
elif 'human' in s:
basisofrecord = 'HumanObservation'
elif 'zoo' in s:
basisofrecord = 'ZooarchaeologicalSpecimen'
# Requires is_fossil() to have been used to set rec['isfossil']
if rec.has_key('isfossil') and rec['isfossil'] == 1:
basisofrecord = 'FossilSpecimen'
### DCTYPE ###
# Standardize dc:type
dctype = 'Event'
if 'specimen' in basisofrecord.lower():
dctype = 'PhysicalObject'
elif 'material' in basisofrecord.lower():
dctype = 'PhysicalObject'
elif rec.has_key('dctype'):
s = rec['dctype'].strip().lower()
if 'moving' in s:
dctype = 'MovingImage'
basisofrecord = 'MachineObservation'
elif 'still' in s:
dctype = 'StillImage'
basisofrecord = 'MachineObservation'
elif s == 'sound':
dctype = 'Sound'
basisofrecord = 'MachineObservation'
elif 'obj' in s:
if 'obs' not in basisofrecord.lower():
dctype = 'PhysicalObject'
### CITATION ###
# Construct a standardized citation following the formula from the VertNet norms.
citation = None
title = None
publisher = None
link = None
doi = None
pubdate = None
if rec.has_key('title') and len(rec['title'].strip()) > 0:
title = rec['title'].strip()
elif rec.has_key('collectioncode') and len(rec['collectioncode'].strip()) > 0:
title = rec['collectioncode'].strip()
else:
title = rec['gbifdatasetid']
if rec.has_key('orgname') and len(rec['orgname'].strip()) > 0:
publisher = rec['orgname'].strip()
else:
publisher = rec['icode']
if rec.has_key('source_url') and len(rec['source_url'].strip()) > 0:
link = rec['source_url'].strip()
if rec.has_key('doi') and len(rec['doi'].strip()) > 0:
doi = rec['doi'].strip()
if rec.has_key('pubdate') and len(rec['pubdate'].strip()) > 0:
pubdate = rec['pubdate'].strip()
datasetpart = ''
if publisher is not None:
datasetpart += '%s. ' % publisher
if title is not None:
datasetpart += '%s. ' % title
if doi is not None:
datasetpart += 'Dataset DOI: %s.' % doi
datasetpart = datasetpart.strip()
sourcepart = ''
if link is not None:
sourcepart += 'Source: %s ' % link
if pubdate is not None:
sourcepart += '(source published on %s)' % pubdate
# Citation format
# [orgname]. [dataset title]. Dataset DOI: [data set doi]. Source: [source URL] (source published on [source published date]; accessed from VertNet on [today in YYYY-MM-DD format])
citation = '%s %s' % (datasetpart, sourcepart)
### BIBLIOGRAPHICCITATION ###
# Construct a standardized bibliographic citation following the formula from the
# VertNet norms.
# Citation format
# [orgname]. [dataset title]. Dataset DOI: [data set doi]. Record ID: [occurrenceID]. Source: [source URL] (source published on [source published date]; accessed from VertNet on [today in YYYY-MM-DD format])
recordidpart = 'Record ID: %s.' % bestid
bib = '%s %s %s' % (datasetpart, recordidpart, sourcepart)
d = {}
d['keyname'] = keyname
d['references'] = references
d['citation'] = citation
d['bibliographiccitation'] = bib
d['basisofrecord'] = basisofrecord
d['dctype'] = dctype
return d
def license_resolution(rec):
""" Create a dictionary of completed, corrected license fields from data in
a dictionary.
parameters:
rec - dictionary to search for georeference input (required)
returns:
dictionary of completed, corrected georeference fields
"""
license = None
haslicense = None
if rec.has_key('license') == False or len(rec['license']) == 0:
if rec.has_key('iptlicense') and len(rec['iptlicense']) > 0:
license = rec['iptlicense']
else:
license = rec['license']
if license is not None:
haslicense = 1
else:
haslicense = 0
d = {}
d['license'] = license
d['haslicense'] = haslicense
return d
def dynamicproperties_resolution(rec):
""" Create a clean version of the dynamicproperties in a dictionary.
parameters:
rec - dictionary to search for dynamicproperties (required)
returns:
cleaned version of dynamicproperties
"""
if rec.has_key('dynamicproperties') == False or len(rec['dynamicproperties']) == 0:
return None
c = rec['dynamicproperties'].replace('"{','{').replace('}"','}').replace('""','"')
return c
def occurrence_resolution(rec):
""" Create a clean version of the occurrence fields in a dictionary. Depends on
rec['wascaptive'] having been populated.
parameters:
rec - dictionary to search for occurrence fields (required)
returns:
cleaned version of occurrence fields
"""
occremarks = None
emeans = None
recordedby = None
if rec.has_key('recordedby') and rec['recordedby'] is not None and \
len(rec['recordedby']) > 0:
recordedby = strip_quote(rec['recordedby'])
if rec.has_key('occurrenceremarks') and rec['occurrenceremarks'] is not None and \
len(rec['occurrenceremarks']) > 0:
occremarks = strip_quote(rec['occurrenceremarks'])
if rec.has_key('wascaptive') and rec['wascaptive'] == 1:
emeans = 'managed'
d = {}
d['occurrenceremarks'] = occremarks
d['recordedby'] = recordedby
d['establishmentmeans'] = emeans
return d
def sex_resolution(sex):
""" Standardize the value of the sex field.
parameters:
sex - the string to standardize (required)
returns:
cleaned version of sex field
"""
if sex is None or len(sex.strip())==0:
return None
s = strip_quote(sex).lower()
if s == 'm' or s == 'mâle' or s == 'macho':
s = 'male'
elif s == 'f' or s == 'femelle' or s == 'hembra':
s = 'female'
elif 'un' in s:
s = 'undetermined'
elif s == 'u' or s == 'not recorded' or s == 'indéterminé':
s = 'undetermined'
return s
def location_resolution(rec):
""" Create a clean version of the location fields in a dictionary.
parameters:
rec - dictionary to search for location fields (required)
returns:
cleaned version of location fields
"""
loc = None
locremarks = None
if rec.has_key('locality') and len(rec['locality']) > 0:
loc = strip_quote(rec['locality'])
if rec.has_key('locationremarks') and len(rec['locationremarks']) > 0:
locremarks = strip_quote(rec['locationremarks'])
d = {}
d['locality'] = loc
d['locationremarks'] = locremarks
return d
def georef_resolution(rec):
""" Create a dictionary of completed, corrected georeference fields from data in
a dictionary.
parameters:
rec - dictionary to search for georeference input (required)
returns:
dictionary of completed, corrected georeference fields
"""
lat = None
lng = None
datum = None
unc = None
gdate = None
gsources = None
if rec.has_key('decimallatitude') and rec.has_key('decimallongitude'):
if valid_latlng(rec['decimallatitude'], rec['decimallongitude']):
lat = rec['decimallatitude']
lng = rec['decimallongitude']
if rec.has_key('geodeticdatum') and len(rec['geodeticdatum']) > 0:
datum = rec['geodeticdatum']
else:
datum = 'not recorded'
if rec.has_key('coordinateuncertaintyinmeters'):
unc = _coordinateuncertaintyinmeters(rec['coordinateuncertaintyinmeters'])
# Try to clean dateidentified
if rec.has_key('georeferenceddate') and len(rec['georeferenceddate']) > 0:
gdate = rec['georeferenceddate'].strip(' 00:00:00.0').strip(' 0:00:00')
cleandate = w3c_datestring(gdate)
if cleandate is not None:
gdate = cleandate
if rec.has_key('georeferencesources') and len(rec['georeferencesources']) > 0:
gsources = rec['georeferencesources'].replace('""','"').replace('""','"')
d = {}
d['decimallatitude'] = lat
d['decimallongitude'] = lng
d['coordinateuncertaintyinmeters'] = unc
d['geodeticdatum'] = datum
d['georeferenceddate'] = gdate
d['georeferencesources'] = gsources
return d
def event_resolution(rec):
""" Create a dictionary of completed, corrected event fields from data in
a dictionary.
parameters:
rec - dictionary to search for event input (required)
returns:
dictionary of completed, corrected event fields
"""
year = None
month = None
day = None
begindate = None
beginyear = None
beginmonth = None
beginday = None
enddate = None
endyear = None
endmonth = None
endday = None
begindayofyear = None
enddayofyear = None
isoeventdate = None
verbatimeventdate = None
eventremarks = None
if rec.has_key('year') and len(str(rec['year']).strip())>0:
year = rec['year']
if rec.has_key('month') and len(str(rec['month']).strip())>0:
month = rec['month']
if rec.has_key('day') and len(str(rec['day']).strip())>0:
day = rec['day']
if rec.has_key('verbatimeventdate') and len(rec['verbatimeventdate'].strip())>0:
if rec.has_key('eventdate') == False or len(rec['eventdate'].strip())==0:
rec['eventdate'] = rec['verbatimeventdate']
if rec.has_key('eventdate') and len(rec['eventdate'].strip())>0:
ed = rec['eventdate']
# Set the verbatimeventdate from event date if verbatimeventdate is empty
if rec.has_key('verbatimeventdate') and len(rec['verbatimeventdate']) > 0:
verbatimeventdate = rec['verbatimeventdate']
else:
verbatimeventdate = ed
# Get begin and end dates from eventdate
ds = ed.replace('//','/').split('/')
if len(ds) == 1:
begindate = ds[0]
if len(ds) > 1:
enddate = ds[1]
else:
enddate = begindate
else:
begindate = ed
enddate = ed
# Try to clean begin date
cleaned = w3c_datestring(begindate)
if cleaned is not None:
begindate = cleaned
# Try to clean end date
cleaned = w3c_datestring(enddate)
if cleaned is not None:
enddate = cleaned
# If there still is no begin date, try to get it from year, month, day
if begindate is None:
begindate = iso_datestring_from_ymd(year, month, day)
if enddate is None:
enddate = begindate
beginyear, beginmonth, beginday = ymd_from_iso_datestring(begindate)
endyear, endmonth, endday = ymd_from_iso_datestring(enddate)
# Set the year, month, and day if they are not already populated and can be
# unambiguously determined.
if year is None and beginyear == endyear:
year = beginyear
if month is None and beginmonth == endmonth:
month = beginmonth
if day is None and beginday == endday:
day = beginday
# Set the begin and end days of year from begin and end dates
begindayofyear = day_of_year(begindate)
if begindate == enddate:
enddayofyear = begindayofyear
else:
enddayofyear = day_of_year(enddate)
# Set the isodate from the begin and end dates
if begindate is None:
begindate = ''
if enddate is None:
enddate = ''
if begindate == enddate:
isodate = begindate
else:
isodate = '%s/%s' % (begindate, enddate)
if isodate == '/' or isodate == '':
isodate = None
if rec.has_key('eventremarks') and len(rec['eventremarks']) > 0:
eventremarks = rec['eventremarks'].replace('""','"').replace('""','"')
d = {}
d['year'] = year
d['month'] = month
d['day'] = day
d['startdayofyear'] = begindayofyear
d['enddayofyear'] = enddayofyear
d['eventdate'] = isodate
d['verbatimeventdate'] = verbatimeventdate
d['eventremarks'] = eventremarks
return d
def identification_resolution(rec):
""" Create a clean version of the identification fields in a dictionary.
parameters:
rec - dictionary to search for identification fields (required)
returns:
cleaned version of identification fields
"""
previds = None
idrefs = None
idremarks = None
typestatus = None
iddate = None
if rec.has_key('previousidentifications') and len(rec['previousidentifications']) > 0:
previds = strip_quote(rec['previousidentifications'])
if rec.has_key('identificationreferences') and \
len(rec['identificationreferences']) > 0:
idrefs = strip_quote(rec['identificationreferences'])
if rec.has_key('identificationremarks') and len(rec['identificationremarks']) > 0:
idremarks = strip_quote(rec['identificationremarks'])
if rec.has_key('typestatus') and len(rec['typestatus']) > 0:
typestatus = strip_quote(rec['typestatus'])
# Try to clean dateidentified
if rec.has_key('dateidentified') and len(rec['dateidentified']) > 0:
iddate = w3c_datestring(rec['dateidentified'])
if iddate is None:
iddate = rec['dateidentified']
d = {}
d['previousidentifications'] = previds
d['identificationreferences'] = idrefs
d['identificationremarks'] = idremarks
d['dateidentified'] = iddate
d['typestatus'] = typestatus
return d
def strip_quote(str):
""" Remove excessive quoting.
parameters:
str - string (required)
returns:
string with the excessive quoting removed
"""
try:
return str.replace('""','"').replace('""','"')
except:
return None
def as_float(str):
""" Convert a string into a float, if possible.
parameters:
str - string (required)
returns:
a float equivalent of the string, or None
"""
try:
return float(str)
except:
return None
def as_int(str):
""" Convert a string into an int, if possible.
parameters:
str - string (required)
returns:
an int equivalent of the string, or None
"""
try:
return int(str)
except:
return None
def valid_year(year):
""" Determine if a value can be interpreted as a year.
parameters:
year - string, int or float (required)
returns:
True if the value can be interpreted as a valid year, otherwise False
"""
fyear = as_int(year)
if fyear is None:
return False
if fyear < 1:
return False
if fyear > datetime.now().year:
return False
return True
def valid_month(month):
""" Determine if a value can be interpreted as a month.
parameters:
month - string, int or float (required)
returns:
True if the value can be interpreted as a valid month, otherwise False
"""
fmonth = as_int(month)
if fmonth is None:
return False
if fmonth < 1:
return False
if fmonth > 12:
return False
return True
def valid_day(day, month=None, year=None):
""" Determine if a value can be interpreted as a valid day of a month.
parameters:
day - string, int or float (required)
month - string, int or float (optional)
year - string, int or float (optional)
returns:
True if the value can be interpreted as a valid day in the given month
and year, otherwise False
"""
fday = as_int(day)
if fday is None:
return False
if fday < 1:
return False
if fday > 31:
return False
# now look at month dependencies
fmonth = as_int(month)
if fmonth is None:
return True
if fmonth in (1,3,5,7,8,10,12):
return True
if fday > 30:
return False
if fmonth in (4,6,9,11):
return True
if fday < 29:
return True
if fday == 30:
return False
fyear = as_int(year)
if fyear is None:
return True
if leap(year) == 1:
return True
return False
def leap(year):
""" Determine if the year is a leap year.
parameters:
year - string, int or float (required)
returns:
True if the value can be interpreted as a valid leap year, otherwise False
"""
leap = 0
fyear = as_int(year)
if fyear is None:
return 0
if fyear < 1582:
return 0
# If the year is evenly divisible by 4
if fyear % 4 == 0:
# If the year is a century year
if fyear % 100 == 0:
# If the century year is evenly divisible by 400
if fyear % 400 == 0:
leap = 1
else:
leap = 1
return leap
def day_of_year(datestring):
""" Determine the day of the year from a W3C date string.
parameters:
datestring - string (required)
returns:
an integer for the ordinal day of the year matching the given date, or None.
"""
try:
y, m, d = datestring.split('-')
except:
return None
if y is None or m is None or d is None:
return None
if valid_year(y):
year = as_int(y)
if year is None:
return None
else:
return None
if valid_month(m):
month = as_int(m)
if month is None:
return None
else:
return None
if valid_day(d, m, y):
day = as_int(d)
if day is None:
return None
else:
return None
dayofyearforfirst = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
doy = dayofyearforfirst[month-1] + day
if month >2 and leap(year):
doy += 1
return doy
def iso_datestring_from_ymd(year, month, day):
""" Construct an ISO8601 date string from year, month and day.
parameters:
year - int, float or string (required)
month - int, float or string (optional)
day - int, float or string (optional)
returns:
a date in ISO8601 date format, or None.
"""
if year is None or len(str(year)) == 0:
# Can't make an ISO date without a year
return None
if valid_year(year) is False:
# Shouldn't make an ISO date if the year is not valid
return None
hasmonth = valid_month(month)
hasday = valid_day(day, month, year)
isodate = str(year)
if hasmonth == True:
m = as_int(month)
if m is not None:
if m > 9:
isodate += '-'+str(m)
else:
isodate += '-0'+str(m)
if hasday == True:
d = as_int(day)
if d is not None:
if d > 9:
isodate += '-'+str(d)
else:
isodate += '-0'+str(d)
return isodate
def ymd_from_iso_datestring(datestring):
""" Get the year, month and day from a string in W3C-formatted datetime (yyyy-mm-dd).
parameters:
datestring - string (required)
returns:
(year, month, day) - a tuple with the three derived values.
"""
if datestring is None or len(datestring)==0:
return (None, None, None)
d = datestring.split('-')
year = as_int(d[0])
month = None
day = None
if len(d)>1:
month = as_int(d[1])
if len(d)>2:
day = as_int(d[2])
return (year, month, day)
def w3c_datestring(datestring):
""" Create a W3C date as a string given an input date as a string.
parameters:
datestring - string (required)
returns:
a W3C-formatted date string, or None
"""
# Try date as YYYY-MM-DD or DD MMM YYYY
d = format_date_as_w3c(['YYYY-M-D', 'D MMM YYYY'], datestring)
if d is not None:
return d
# Try date as MM/DD/YYYY
d = format_date_as_w3c(['D/M/YYYY'], datestring)
# Try date as DD/MM/YYYY
a = format_date_as_w3c(['M/D/YYYY'], datestring)
if a is None:
if d is not None:
# Date fits DD/MM/YYYY only
return d
# Date doesn't fit either remaining format
return None
# Date matches MM/DD/YYYY
if d is None:
# Date fits MM/DD/YYYY only
return a
# Date matches both MM/DD/YYYY and DD/MM/YYYY
if a==d:
return a
return None
def format_date_as_w3c(formats, datestring):
""" Construct an W3C date string from a date string in one of the given formats.
parameters:
formats - a list of date formats to try (required)
datestring - date to convert, as string (required)
returns:
a W3C-formatted date string, or None
"""
try:
d = arrow.get(datestring, formats).format('YYYY-MM-DD')
return d
except:
return None
def valid_latlng(lat,lng):
""" Test the validity of lat and lng as geographic coordinates in decimal degrees.
parameters:
lat - latitude as numeric or string (required)
lng - longitude as numeric or string (required)
returns:
True if valid otherwise False
"""
flat = as_float(lat)
if flat is None:
return False
if flat < -90 or flat > 90:
return False
flng = as_float(lng)
if flng is None:
return False
if flng < -180 or flng > 180:
return False
if flat == 0 and flng == 0:
return False
return True
def valid_coords(rec):
""" Test the validity of the geographic coordinates in a dictionary.
parameters:
rec - dictionary to search for geographic coordinates
in decimal degrees (required)
returns:
True if decimallatitude and decimallongitude in rec are in valid ranges,
otherwise False
"""
if rec is None:
return False
if rec.has_key('decimallatitude') == False:
return False
if rec.has_key('decimallongitude') == False:
return False
return valid_latlng(rec['decimallatitude'],rec['decimallongitude'])
def _coordinateuncertaintyinmeters(unc):
""" Round the value of unc up to an integer if it is a number greater than zero,
otherwise return None
parameters:
unc - the value to make into a valid coordinateuncertaintyinmeters (required)
returns:
the valid coordinateuncertaintyinmeters as an integer, or None
"""
uncertaintyinmeters = as_float(unc)
if uncertaintyinmeters is None:
return None
# Check to see if uncertaintyinmeters is less than one. Zero is not a legal
# value. Less than one is an error in concept.
if uncertaintyinmeters < 1:
return None
# Return the nearest rounded up meter.
i_unc = as_int(uncertaintyinmeters)
if uncertaintyinmeters == i_unc:
return i_unc
return int( round(uncertaintyinmeters + 0.5) )
def valid_georef(rec):
""" Test the validity of the georeference in a dictionary.
parameters:
rec - dictionary to search for georeference (required)
returns:
True if georeference is complete and valid, otherwise False
"""
# If any of the fields that make up a valid georeference are missing, return False
if rec.has_key('coordinateuncertaintyinmeters') == False:
return False
if _coordinateuncertaintyinmeters(rec['coordinateuncertaintyinmeters']) is None:
return False
if rec.has_key('geodeticdatum') == False:
return False
if rec.has_key('decimallatitude') == False:
return False
if rec.has_key('decimallongitude') == False:
return False
# Otherwise, base validity on the validity of the coordinates and uncertainty
unc = as_float(rec['coordinateuncertaintyinmeters'])
if unc < 1:
return False
valid = valid_latlng(rec['decimallatitude'],rec['decimallongitude'])
return valid
def read_header(fullpath, dialect = None):
""" Get the header line of a CSV or TXT data file.
parameters:
fullpath - full path to the input file (required)
dialect - csv.dialect object with the attributes of the input file (default None)
returns:
header - a list containing the fields in the original header
"""
if fullpath is None or len(fullpath)==0:
logging.debug('No file given in read_header().')
return None
# Cannot function without an actual file where the full path points
if os.path.isfile(fullpath) == False:
logging.debug('File %s not found in read_header().' % fullpath)
return None
header = None
# If no explicit dialect for the file is given, figure it out from the file
if dialect is None:
dialect = csv_file_dialect(fullpath)
# Open up the file for processing
with open(fullpath, 'rU') as csvfile:
reader = csv.DictReader(csvfile, dialect=dialect)
# header is the list as returned by the reader
header=reader.fieldnames
return header
def tsv_dialect():
""" Get a dialect object with TSV properties.
parameters:
None
returns:
dialect - a csv.dialect object with TSV attributes"""
dialect = csv.excel_tab
dialect.lineterminator='\n'
dialect.delimiter='\t'
dialect.escapechar=''
dialect.doublequote=True
dialect.quotechar=''
dialect.quoting=csv.QUOTE_NONE
dialect.skipinitialspace=True
dialect.strict=False
return dialect
def csv_file_dialect(fullpath):
"""Detect the dialect of a CSV or TXT data file.
parameters:
fullpath - full path to the file to process (required)
returns:
dialect - a csv.dialect object with the detected attributes
"""
if fullpath is None or len(fullpath) == 0:
logging.debug('No file given in csv_file_dialect().')
return False
# Cannot function without an actual file where full path points
if os.path.isfile(fullpath) == False:
logging.debug('File %s not found in csv_file_dialect().' % fullpath)
return None
# Let's look at up to readto bytes from the file
readto = 4096
filesize = os.path.getsize(fullpath)
if filesize < readto:
readto = filesize
found_doublequotes = False
with open(fullpath, 'rb') as file:
# Try to read the specified part of the file
try:
buf = file.read(readto)
# s = 'csv_file_dialect()'
# s += ' buf:\n%s' % buf
# logging.debug(s)
# See if the buffer has any doubled double quotes in it. If so, infer that the
# dialect doublequote value should be true.
if buf.find('""')>0:
found_doublequotes = True
# Make a determination based on existence of tabs in the buffer, as the
# Sniffer is not particularly good at detecting TSV file formats. So, if the
# buffer has a tab in it, let's treat it as a TSV file
if buf.find('\t')>0:
return tsv_dialect()
# dialect = csv.Sniffer().sniff(file.read(readto))
# Otherwise let's see what we can find invoking the Sniffer.
logging.debug('Forced to use csv.Sniffer()')
dialect = csv.Sniffer().sniff(buf,delimiters=',\t|')
except csv.Error:
# Something went wrong, so let's try to read a few lines from the beginning of
# the file
try:
file.seek(0)
s = 'csv_file_dialect()'
s += ' Re-sniffing with tab to %s' % (readto)
logging.debug(s)
sample_text = ''.join(file.readline() for x in xrange(2,4,1))
# See if the buffer has any doubled double quotes in it. If so, infer that the
# dialect doublequote value should be true.
if sample_text.find('""')>0:
found_doublequotes = True
dialect = csv.Sniffer().sniff(sample_text)
# Sorry, couldn't figure it out
except csv.Error:
logging.debug('Unable to determine csv dialect')
return None
# Fill in some standard values for the remaining dialect attributes
if dialect.escapechar is None:
dialect.escapechar='\\'
dialect.skipinitialspace=True
dialect.strict=False
dialect.doublequote = found_doublequotes
return dialect
def dialect_attributes(dialect):
""" Show the attributes of a csv dialect.
parameters:
dialect - a csv.dialect object (required)
returns:
string showing the csv dialect attributes
"""
if dialect is None:
return 'No dialect given in dialect_attributes().'