-
Notifications
You must be signed in to change notification settings - Fork 14
/
species_model.py
executable file
·841 lines (696 loc) · 28.8 KB
/
species_model.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
# -*- coding: utf-8 -*-
#
# Copyright 2008-2010 Brett Adams
# Copyright 2012-2016 Mario Frasca <mario@anche.no>.
#
# This file is part of ghini.desktop.
#
# ghini.desktop is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ghini.desktop is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ghini.desktop. If not, see <http://www.gnu.org/licenses/>.
from itertools import chain
import logging
logger = logging.getLogger(__name__)
#logger.setLevel(logging.DEBUG)
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy import (
Column, Unicode, Integer, ForeignKey, UnicodeText, func, UniqueConstraint)
from sqlalchemy.orm import relation, backref
import bauble.db as db
import bauble.error as error
import bauble.utils as utils
import bauble.btypes as types
from bauble.i18n import _
from bauble.plugins.plants import itf2
def _remove_zws(s):
"remove_zero_width_space"
if s:
return s.replace(u'\u200b', '')
return s
class VNList(list):
"""
A Collection class for Species.vernacular_names
This makes it possible to automatically remove a
default_vernacular_name if the vernacular_name is removed from the
list.
"""
def remove(self, vn):
super(VNList, self).remove(vn)
try:
if vn.species.default_vernacular_name == vn:
del vn.species.default_vernacular_name
except Exception, e:
logger.debug(e)
infrasp_rank_values = {u'subsp.': _('subsp.'),
u'var.': _('var.'),
u'subvar.': _('subvar'),
u'f.': _('f.'),
u'subf.': _('subf.'),
u'cv.': _('cv.'),
None: ''}
# TODO: there is a trade_name column but there's no support yet for editing
# the trade_name or for using the trade_name when building the string
# for the species, for more information about trade_names see,
# http://www.hortax.org.uk/gardenplantsnames.html
# TODO: the specific epithet should not be non-nullable but instead
# make sure that at least one of the specific epithet, cultivar name
# or cultivar group is specificed
def compare_rank(rank1, rank2):
'implement the binary comparison operation needed for sorting'
ordering = [u'familia', u'subfamilia', u'tribus', u'subtribus',
u'genus', u'subgenus', u'species', None, u'subsp.',
u'var.', u'subvar.', u'f.', u'subf.', u'cv.']
return ordering.index(rank1).__cmp__(ordering.index(rank2))
class Species(db.Base, db.Serializable, db.DefiningPictures, db.WithNotes):
"""
:Table name: species
:Columns:
*epithet*:
*author*:
*cv_group*:
*trade_name*:
*label_distribution*:
UnicodeText
This field is optional and can be used for the label in case
str(self.distribution) is too long to fit on the label.
:Properties:
*accessions*:
*vernacular_names*:
*default_vernacular_name*:
*synonyms*:
*distribution*:
:Constraints:
The combination of epithet, author, hybrid, aggregate,
cv_group, trade_name, genus_id
"""
__tablename__ = 'species'
__mapper_args__ = {'order_by': ['epithet', 'author']}
rank = 'species'
link_keys = ['accepted']
# columns
epithet = Column(Unicode(64), nullable=True, index=True) # allows for `sp`
hybrid_marker = Column(types.Enum(values=dict(itf2.hybrid_marker).keys()),
default=u'')
author = Column(Unicode(255), default=u'')
aggregate = Column(types.Enum(values=dict(itf2.aggregate).keys()),
default=u'')
cv_group = Column(Unicode(50))
trade_name = Column(Unicode(64))
infrasp1 = Column(Unicode(64))
infrasp1_rank = Column(types.Enum(values=infrasp_rank_values.keys(),
translations=infrasp_rank_values))
infrasp1_author = Column(Unicode(64))
infrasp2 = Column(Unicode(64))
infrasp2_rank = Column(types.Enum(values=infrasp_rank_values.keys(),
translations=infrasp_rank_values))
infrasp2_author = Column(Unicode(64))
infrasp3 = Column(Unicode(64))
infrasp3_rank = Column(types.Enum(values=infrasp_rank_values.keys(),
translations=infrasp_rank_values))
infrasp3_author = Column(Unicode(64))
infrasp4 = Column(Unicode(64))
infrasp4_rank = Column(types.Enum(values=infrasp_rank_values.keys(),
translations=infrasp_rank_values))
infrasp4_author = Column(Unicode(64))
genus_id = Column(Integer, ForeignKey('genus.id'), nullable=False)
## the Species.genus property is defined as backref in Genus.species
label_distribution = Column(UnicodeText)
bc_distribution = Column(UnicodeText)
def search_view_markup_pair(self):
'''provide the two lines describing object for SearchView row.
'''
try:
if len(self.vernacular_names) > 0:
substring = (
'%s -- %s' %
(self.genus.family,
', '.join([str(v) for v in self.vernacular_names])))
else:
substring = '%s' % self.genus.family
trail = self.author and (' <span weight="light">%s</span>' %
utils.xml_safe(self.author)) or ''
if self.accepted:
trail += ('<span foreground="#555555" size="small" '
'weight="light"> - ' + _("synonym of %s") + "</span>"
) % self.accepted.markup(authors=True)
return self.markup(authors=False) + trail, substring
except:
return u'...', u'...'
@property
def cites(self):
'''the cites status of this taxon, or None
cites appendix number, one of I, II, or III.
not enforced by the software in v1.0.x
'''
cites_notes = [i.note for i in self.notes
if i.category and i.category.upper() == u'CITES']
if not cites_notes:
return self.genus.cites
return cites_notes[0]
@property
def conservation(self):
'''the IUCN conservation status of this taxon, or DD
one of: EX, RE, CR, EN, VU, NT, LC, DD
not enforced by the software in v1.0.x
'''
{'EX': _('Extinct (EX)'),
'EW': _('Extinct Wild (EW)'),
'RE': _('Regionally Extinct (RE)'),
'CR': _('Critically Endangered (CR)'),
'EN': _('Endangered (EN)'),
'VU': _('Vulnerable (VU)'),
'NT': _('Near Threatened (NT)'),
'LV': _('Least Concern (LC)'),
'DD': _('Data Deficient (DD)'),
'NE': _('Not Evaluated (NE)')}
notes = [i.note for i in self.notes
if i.category and i.category.upper() == u'IUCN']
return (notes + ['DD'])[0]
@property
def condition(self):
'''the condition of this taxon, or None
this is referred to what the garden conservator considers the
area of interest. it is really an interpretation, not a fact.
'''
# one of, but not forcibly so:
[_('endemic'), _('indigenous'), _('native'), _('introduced')]
notes = [i.note for i in self.notes
if i.category.lower() == u'condition']
return (notes + [None])[0]
def __lowest_infraspecific(self):
infrasp = [(self.infrasp1_rank, self.infrasp1,
self.infrasp1_author),
(self.infrasp2_rank, self.infrasp2,
self.infrasp2_author),
(self.infrasp3_rank, self.infrasp3,
self.infrasp3_author),
(self.infrasp4_rank, self.infrasp4,
self.infrasp4_author)]
infrasp = [i for i in infrasp if i[0] not in [u'cv.', '', None]]
if infrasp == []:
return (u'', u'', u'')
return sorted(infrasp, cmp=lambda a, b: compare_rank(a[0], b[0]))[-1]
@property
def infraspecific_rank(self):
return self.__lowest_infraspecific()[0] or u''
@property
def infraspecific_epithet(self):
return self.__lowest_infraspecific()[1] or u''
@property
def infraspecific_author(self):
return self.__lowest_infraspecific()[2] or u''
@property
def cultivar_epithet(self):
infrasp = ((self.infrasp1_rank, self.infrasp1,
self.infrasp1_author),
(self.infrasp2_rank, self.infrasp2,
self.infrasp2_author),
(self.infrasp3_rank, self.infrasp3,
self.infrasp3_author),
(self.infrasp4_rank, self.infrasp4,
self.infrasp4_author))
for rank, epithet, author in infrasp:
if rank == u'cv.':
return epithet
return u''
# relations
synonyms = association_proxy('_synonyms', 'synonym')
_synonyms = relation('SpeciesSynonym',
primaryjoin='Species.id==SpeciesSynonym.species_id',
cascade='all, delete-orphan', uselist=True,
backref='species')
# this is a dummy relation, it is only here to make cascading work
# correctly and to ensure that all synonyms related to this genus
# get deleted if this genus gets deleted
_syn = relation('SpeciesSynonym',
primaryjoin='Species.id==SpeciesSynonym.synonym_id',
cascade='all, delete-orphan', uselist=True)
## VernacularName.species gets defined here too.
vernacular_names = relation('VernacularName', cascade='all, delete-orphan',
collection_class=VNList,
backref=backref('species', uselist=False))
_default_vernacular_name = relation('DefaultVernacularName', uselist=False,
cascade='all, delete-orphan',
backref=backref('species',
uselist=False))
distribution = relation('SpeciesDistribution',
cascade='all, delete-orphan',
backref=backref('species', uselist=False))
habit_id = Column(Integer, ForeignKey('habit.id'), default=None)
habit = relation('Habit', uselist=False, backref='species')
flower_color_id = Column(Integer, ForeignKey('color.id'), default=None)
flower_color = relation('Color', uselist=False, backref='species')
#hardiness_zone = Column(Unicode(4))
awards = Column(UnicodeText)
def __init__(self, *args, **kwargs):
super(Species, self).__init__(*args, **kwargs)
def __str__(self):
'return the default string representation for self.'
return self.str()
def _get_default_vernacular_name(self):
if self._default_vernacular_name is None:
return None
return self._default_vernacular_name.vernacular_name
def _set_default_vernacular_name(self, vn):
if vn is None:
del self.default_vernacular_name
return
if vn not in self.vernacular_names:
self.vernacular_names.append(vn)
d = DefaultVernacularName()
d.vernacular_name = vn
self._default_vernacular_name = d
def _del_default_vernacular_name(self):
utils.delete_or_expunge(self._default_vernacular_name)
del self._default_vernacular_name
default_vernacular_name = property(_get_default_vernacular_name,
_set_default_vernacular_name,
_del_default_vernacular_name)
def distribution_str(self):
if self.distribution is None:
return ''
else:
dist = ['%s' % d for d in self.distribution]
return unicode(', ').join(sorted(dist))
def markup(self, authors=False, genus=True):
'''
returns this object as a string with markup
:param authors: flag to toggle whethe the author names should be
included
'''
return self.str(authors, markup=True, genus=genus)
# in PlantPlugins.init() we set this to 'x' for win32
hybrid_char = utils.utf8(u'×')
def str(self, authors=False, markup=False, remove_zws=False, genus=True,
qualification=None, sensu=None):
'''
returns a string for species
:param authors: flag to toggle whether authorship should be included
:param markup: flag to toggle whether the returned text is marked up
to show italics on the epithets
:param remove_zws: flag to toggle zero width spaces, helping
semantically correct lexicographic order.
:param genus: flag to toggle leading genus name.
:param qualification: pair or None. if specified, first is the
qualified rank, second is the qualification.
'''
# TODO: this method will raise an error if the session is none
# since it won't be able to look up the genus....we could
# probably try to query the genus directly with the genus_id
if genus is True:
genus = self.genus.str(author=False, use_hybrid_marker=True)
else:
genus = ''
if self.epithet and not remove_zws:
epithet = u'\u200b' + self.epithet # prepend with zero_width_space
else:
epithet = self.epithet
if markup:
escape = utils.xml_safe
italicize = lambda s: ( # all but the multiplication signs
u'<i>%s</i>' % escape(s).replace(u'×', u'</i>×<i>'))
genus = italicize(genus)
if epithet is not None:
epithet = italicize(epithet)
else:
italicize = escape = lambda x: x
author = None
if authors and self.author:
author = escape(self.author)
infrasp = ((self.infrasp1_rank, self.infrasp1,
self.infrasp1_author),
(self.infrasp2_rank, self.infrasp2,
self.infrasp2_author),
(self.infrasp3_rank, self.infrasp3,
self.infrasp3_author),
(self.infrasp4_rank, self.infrasp4,
self.infrasp4_author))
infrasp_parts = []
group_added = False
for irank, iepithet, iauthor in infrasp:
if irank == 'cv.' and iepithet:
if self.cv_group and not group_added:
group_added = True
infrasp_parts.append(_("(%(group)s Group)") %
dict(group=self.cv_group))
infrasp_parts.append("'%s'" % escape(iepithet))
else:
if irank:
infrasp_parts.append(irank)
if iepithet and irank:
infrasp_parts.append(italicize(iepithet))
elif iepithet:
infrasp_parts.append(escape(iepithet))
if authors and iauthor:
infrasp_parts.append(escape(iauthor))
if self.cv_group and not group_added:
infrasp_parts.append(_("%(group)s Group") %
dict(group=self.cv_group))
# create the binomial part
binomial = [genus, self.hybrid_marker, epithet, author]
# create the tail, ie: anything to add on to the end
tail = []
if self.aggregate != u'':
if sensu is not None:
tail.append(sensu)
else:
tail.append(u'agg.')
if qualification is None:
pass
else:
rank, qual = qualification
print binomial, qualification
if qual in ['incorrect']:
rank = None
if rank == 'sp':
binomial.insert(2, qual)
elif not rank:
binomial[2] += ' (' + qual + ')'
elif rank == 'genus':
binomial.insert(0, qual)
elif rank == 'infrasp':
if infrasp_parts:
infrasp_parts.insert(0, qual)
else:
for r, e, a in infrasp:
if r == 'cv.':
e = "'%s'" % e
if rank == r:
pos = infrasp_parts.index(e)
infrasp_parts.insert(pos, qual)
else:
logger.info('cannot find specified rank %s' % e)
parts = chain(binomial, infrasp_parts, tail)
s = utils.utf8(' '.join(i for i in parts if i))
return s
@property
def accepted(self):
'Name that should be used if name of self should be rejected'
from sqlalchemy.orm.session import object_session
session = object_session(self)
if not session:
logger.warn('species:accepted - object not in session')
return None
syn = session.query(SpeciesSynonym).filter(
SpeciesSynonym.synonym_id == self.id).first()
accepted = syn and syn.species
return accepted
@accepted.setter
def accepted(self, value):
'Name that should be used if name of self should be rejected'
logger.debug("Accepted taxon: %s %s" % (type(value), value))
assert isinstance(value, self.__class__)
if self in value.synonyms:
return
# remove any previous `accepted` link
from sqlalchemy.orm.session import object_session
session = object_session(self)
if not session:
logger.warn('species:accepted.setter - object not in session')
return
session.query(SpeciesSynonym).filter(
SpeciesSynonym.synonym_id == self.id).delete()
session.commit()
value.synonyms.append(self)
def has_accessions(self):
'''true if species is linked to at least one accession
'''
return False
infrasp_attr = {1: {'rank': 'infrasp1_rank',
'epithet': 'infrasp1',
'author': 'infrasp1_author'},
2: {'rank': 'infrasp2_rank',
'epithet': 'infrasp2',
'author': 'infrasp2_author'},
3: {'rank': 'infrasp3_rank',
'epithet': 'infrasp3',
'author': 'infrasp3_author'},
4: {'rank': 'infrasp4_rank',
'epithet': 'infrasp4',
'author': 'infrasp4_author'}}
def get_infrasp(self, level):
"""
level should be 1-4
"""
return getattr(self, self.infrasp_attr[level]['rank']), \
getattr(self, self.infrasp_attr[level]['epithet']), \
getattr(self, self.infrasp_attr[level]['author'])
def set_infrasp(self, level, rank, epithet, author=None):
"""
level should be 1-4
"""
setattr(self, self.infrasp_attr[level]['rank'], rank)
setattr(self, self.infrasp_attr[level]['epithet'], epithet)
setattr(self, self.infrasp_attr[level]['author'], author)
def as_dict(self, recurse=True):
result = dict((col, getattr(self, col))
for col in self.__table__.columns.keys()
if col not in ['id', 'epithet']
and col[0] != '_'
and getattr(self, col) is not None
and not col.endswith('_id'))
result['object'] = 'taxon'
result['rank'] = 'species'
result['epithet'] = self.epithet
result['ht-rank'] = 'genus'
result['ht-epithet'] = self.genus.epithet
if recurse and self.accepted is not None:
result['accepted'] = self.accepted.as_dict(recurse=False)
return result
@classmethod
def retrieve(cls, session, keys):
from genus import Genus
try:
return session.query(cls).filter(
cls.epithet == keys['epithet']).join(Genus).filter(
Genus.epithet == keys['ht-epithet']).one()
except:
return None
@classmethod
def correct_field_names(cls, keys):
for internal, exchange in [('genus', 'ht-epithet')]:
if exchange in keys:
keys[internal] = keys[exchange]
del keys[exchange]
@classmethod
def compute_serializable_fields(cls, session, keys):
from genus import Genus
result = {'genus': None}
## retrieve genus object
specifies_family = keys.get('familia')
result['genus'] = Genus.retrieve_or_create(
session, {'epithet': keys['ht-epithet'],
'ht-epithet': specifies_family},
create=(specifies_family is not None))
if result['genus'] is None:
raise error.NoResultException()
return result
def top_level_count(self):
plants = [p for a in self.accessions for p in a.plants]
return {(1, 'Species'): 1,
(2, 'Genera'): set([self.genus.id]),
(3, 'Families'): set([self.genus.family.id]),
(4, 'Accessions'): len(self.accessions),
(5, 'Plantings'): len(plants),
(6, 'Living plants'): sum(p.quantity for p in plants),
(7, 'Locations'): set(p.location.id for p in plants),
(8, 'Sources'): set([a.source.source_detail.id
for a in self.accessions
if a.source and a.source.source_detail])}
class SpeciesNote(db.Base, db.Serializable):
"""
Notes for the species table
"""
__tablename__ = 'species_note'
__mapper_args__ = {'order_by': 'species_note.date'}
date = Column(types.Date, default=func.now())
user = Column(Unicode(64))
category = Column(Unicode(32))
note = Column(UnicodeText, nullable=False)
species_id = Column(Integer, ForeignKey('species.id'), nullable=False)
species = relation('Species', uselist=False,
backref=backref('notes', cascade='all, delete-orphan'))
def as_dict(self):
result = db.Serializable.as_dict(self)
result['species'] = self.species.str(remove_zws=True)
return result
@classmethod
def compute_serializable_fields(cls, session, keys):
logger.debug('compute_serializable_fields(session, %s)' % keys)
result = {}
genus_name, epithet = keys['species'].split(' ', 1)
sp_dict = {'ht-epithet': genus_name,
'epithet': epithet}
result['species'] = Species.retrieve_or_create(
session, sp_dict, create=False)
return result
@classmethod
def retrieve(cls, session, keys):
from genus import Genus
genus, epithet = keys['species'].split(' ', 1)
try:
return session.query(cls).filter(
cls.category == keys['category']).join(Species).filter(
Species.epithet == epithet).join(Genus).filter(
Genus.epithet == genus).one()
except:
return None
class SpeciesSynonym(db.Base):
"""
:Table name: species_synonym
"""
__tablename__ = 'species_synonym'
# columns
species_id = Column(Integer, ForeignKey('species.id'),
nullable=False)
synonym_id = Column(Integer, ForeignKey('species.id'),
nullable=False, unique=True)
# relations
synonym = relation('Species', uselist=False,
primaryjoin='SpeciesSynonym.synonym_id==Species.id')
def __init__(self, synonym=None, **kwargs):
# it is necessary that the first argument here be synonym for
# the Species.synonyms association_proxy to work
self.synonym = synonym
super(SpeciesSynonym, self).__init__(**kwargs)
def __str__(self):
return str(self.synonym)
class VernacularName(db.Base, db.Serializable):
"""
:Table name: vernacular_name
:Columns:
*name*:
the vernacular name
*language*:
language is free text and could include something like UK
or US to identify the origin of the name
*species_id*:
key to the species this vernacular name refers to
:Properties:
:Constraints:
"""
__tablename__ = 'vernacular_name'
name = Column(Unicode(128), nullable=False)
language = Column(Unicode(128))
species_id = Column(Integer, ForeignKey('species.id'), nullable=False)
__table_args__ = (UniqueConstraint('name', 'language',
'species_id', name='vn_index'), {})
def search_view_markup_pair(self):
"""provide the two lines describing object for SearchView row.
"""
return str(self), self.species.markup(authors=False)
def __str__(self):
if self.name:
return self.name
else:
return ''
def replacement(self):
'user wants the species, not just the name'
return self.species
def as_dict(self):
result = db.Serializable.as_dict(self)
result['species'] = self.species.str(remove_zws=True)
return result
@classmethod
def compute_serializable_fields(cls, session, keys):
logger.debug('compute_serializable_fields(session, %s)' % keys)
result = {'species': None}
if 'species' in keys:
## now we must connect the name to the species it refers to
genus_name, epithet = keys['species'].split(' ', 1)
sp_dict = {'ht-epithet': genus_name,
'epithet': epithet}
result['species'] = Species.retrieve_or_create(
session, sp_dict, create=False)
return result
@classmethod
def retrieve(cls, session, keys):
from genus import Genus
g_epithet, s_epithet = keys['species'].split(' ', 1)
sp = session.query(Species).filter(
Species.epithet == s_epithet).join(Genus).filter(
Genus.epithet == g_epithet).first()
try:
return session.query(cls).filter(
cls.species == sp,
cls.language == keys['language']).one()
except:
return None
@property
def pictures(self):
return self.species.pictures
class DefaultVernacularName(db.Base):
"""
:Table name: default_vernacular_name
DefaultVernacularName is not meant to be instantiated directly.
Usually the default vernacular name is set on a species by setting
the default_vernacular_name property on Species to a
VernacularName instance
:Columns:
*id*:
Integer, primary_key
*species_id*:
foreign key to species.id, nullable=False
*vernacular_name_id*:
:Properties:
:Constraints:
"""
__tablename__ = 'default_vernacular_name'
__table_args__ = (UniqueConstraint('species_id', 'vernacular_name_id',
name='default_vn_index'), {})
# columns
species_id = Column(Integer, ForeignKey('species.id'), nullable=False)
vernacular_name_id = Column(Integer, ForeignKey('vernacular_name.id'),
nullable=False)
# relations
vernacular_name = relation(VernacularName, uselist=False)
def __str__(self):
return str(self.vernacular_name)
class SpeciesDistribution(db.Base):
"""
:Table name: species_distribution
:Columns:
:Properties:
:Constraints:
"""
__tablename__ = 'species_distribution'
# columns
geography_id = Column(Integer, ForeignKey('gheography.id'), nullable=False)
species_id = Column(Integer, ForeignKey('species.id'), nullable=False)
def __str__(self):
return str(self.geography)
# late bindings
SpeciesDistribution.geography = relation(
'Geography',
primaryjoin='SpeciesDistribution.geography_id==Geography.id',
uselist=False)
class Habit(db.Base):
__tablename__ = 'habit'
name = Column(Unicode(64))
code = Column(Unicode(8), unique=True)
def __str__(self):
if self.name:
return '%s (%s)' % (self.name, self.code)
else:
return str(self.code)
class Color(db.Base):
__tablename__ = 'color'
name = Column(Unicode(32))
code = Column(Unicode(8), unique=True)
def __str__(self):
if self.name:
return '%s (%s)' % (self.name, self.code)
else:
return str(self.code)
db.Species = Species
db.SpeciesNote = SpeciesNote
db.VernacularName = VernacularName