Class: TaxonName
- Inherits:
-
ApplicationRecord
- Object
- ActiveRecord::Base
- ApplicationRecord
- TaxonName
- Includes:
- Housekeeping, Shared::AlternateValues, Shared::Citations, Shared::Confidences, Shared::DataAttributes, Shared::Depictions, Shared::DwcOccurrenceHooks, Shared::HasPapertrail, Shared::Identifiers, Shared::IsData, Shared::Labels, Shared::MatrixHooks::Dynamic, Shared::MatrixHooks::Member, Shared::Notes, Shared::QueryBatchUpdate, Shared::Tags, SoftValidation, Hierarchy, MatrixHooks, OtuSyncronization
- Defined in:
- app/models/taxon_name.rb
Overview
A taxon name (nomenclature only). See also NOMEN (github.com/SpeciesFileGroup/nomen).
rubocop:disable Metrics/ClassLength
TODO: Refactor into
* methods that set new state (new values
* verbosely touches database
* methods that set fixed state (cached, exports)
* once state is loaded, it is never reloaded or hit again
* sensu TaxonomyObjects
* methods that get/check state
* sparesly touches database
In general there is too much interplay between the our current variables, they should not (probably) cross boundaries.
Direct Known Subclasses
Defined Under Namespace
Modules: Hierarchy, MatrixHooks, OtuSyncronization
Constant Summary collapse
- ALTERNATE_VALUES_FOR =
Allows users to provide arbitrary annotations that “over-ride” rank string
[:rank_class].freeze
- COMBINATION_ELEMENTS =
[:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze
- SPECIES_EPITHET_RANKS =
%w{species subspecies variety subvariety form subform}.freeze
- NOT_LATIN =
Dash is allowed?
Regexp.new(/[^a-zA-Z|\-]/).freeze
- NO_CACHED_MESSAGE =
'REBUILD PROJECT TAXON NAME CACHE'.freeze
- ROOT_NAME =
'Root'
- NOMEN_VALID =
{ icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze
Constants included from SoftValidation
SoftValidation::ANCESTORS_WITH_SOFT_VALIDATIONS
Instance Attribute Summary collapse
-
#also_create_otu ⇒ Boolean
When true, also creates an OTU that is tied to this taxon name.
-
#cached ⇒ String
Genus-species combination for genus and lower, monominal for higher.
-
#cached_author ⇒ String?
Author string without parentheses.
-
#cached_author_year ⇒ String?
Author and year string with parentheses where necessary, i.e.
-
#cached_classified_as ⇒ String
if the name was classified in different group (e.g. a genus placed in wrong family).
-
#cached_html ⇒ String
As in ‘cached` but with tags.
-
#cached_misspelling ⇒ Boolean
if the name is a misspelling, stores True.
-
#cached_original_combination ⇒ String
Name as formed in original combination, no author/year, without HTML.
-
#cached_original_combination_html ⇒ String
As cached_original_combination but with HTML.
-
#cached_primary_homonym ⇒ String
original genus and species name.
-
#cached_primary_homonym_alternative_spelling ⇒ String
Original genus and species name in alternative spelling.
-
#cached_secondary_homonym ⇒ String
current genus and species name.
-
#cached_secondary_homonym_alternative_spelling ⇒ String
Current genus and species name in alternative spelling.
-
#classifications(rebuild = false) ⇒ Object
Array of all taxon_name_classifications, memoizable.
-
#etymology ⇒ String
the derivation and history of the name in written form.
-
#feminine_name ⇒ String
Species name which are adjective or participle change depending on the gender of the genus.
-
#masculine_name ⇒ String
Species name which are adjective or participle change depending on the gender of the genus.
-
#name ⇒ String?
the fully latinized string (monominal) of a code governed taxonomic biological name not applicable for Combinations, they are derived from their pieces.
-
#neuter_name ⇒ String
Species name which are adjective or participle change depending on the gender of the genus.
-
#no_cached ⇒ Boolean
When true cached values are not built.
-
#parent_id ⇒ Integer
The id of the parent taxon.
-
#project_id ⇒ Integer
the project ID.
-
#rank_class ⇒ NomenclaturalRank class
Rank as a NomenclaturalRank class, like NomenclaturalRank::Iczn::SpeciesGroup::Species.
-
#related_relationships(rebuild = false) ⇒ Object
!! Memoized attributes are not reset when related objects reload them.
-
#taxonomy(rebuild = false) ⇒ Object
readonly
See attr_reader.
-
#type ⇒ String
The subclass of this taxon name, e.g.
-
#verbatim_author ⇒ String
the verbatim author string as provided ? is not post-filled in when Source is referenced !?.
-
#verbatim_name ⇒ String
a representation of what the Combination (fully spelled out) or Protonym (monominal) *looked like* in its originating publication.
-
#year_of_publication ⇒ Integer
Sensu ICZN - the 4 digit year when this name was published, i.e.
Class Method Summary collapse
- .calculated_invalid ⇒ Object
- .calculated_valid ⇒ Object
-
.not_leaves ⇒ Object
TODO: belongs in lib/queries/filter.rb likely.
-
.out_of_scope_combinations(taxon_name_id) ⇒ Scope
!! When :cached_valid_taxon_name_id is properly set then this method is not required rather you should use :historical_taxon_names.
- .select_optimized(user_id, project_id, target: nil) ⇒ Hash
-
.sort_by_rank(taxon_names) ⇒ Array of TaxonName
Ordered by rank, a scope-like hack.
- .used_recently(user_id, project_id, target: nil) ⇒ Array
-
.used_recently_in_classifications(user_id, project_id) ⇒ Scope
All taxon names attached to relationships recently created by user.
-
.used_recently_in_relationships(user_id, project_id) ⇒ Scope
All taxon names attached to relationships recently created by user.
- .with_taxon_name_relationship(relationship) ⇒ Object
Instance Method Summary collapse
-
#all_taxon_name_relationships ⇒ Array
All TaxonNameRelationships where this taxon is an object or subject.
-
#ancestor_at_rank(rank, include_self = false) ⇒ TaxonName?
TODO: replace with @taxonomy.
-
#ancestor_hash ⇒ Object
Hash { ‘family’ => ‘Aidae’, …}.
-
#ancestor_protonyms ⇒ Array of TaxonName
Ancestors of type ‘Protonym’.
-
#ancestors_through_parents(result = [self], start = self) ⇒ Array
Of TaxonName same as self.ancestors.to_a, but also works for new records when parents specified.
-
#author_string ⇒ String?
Important, string format priority is 1) as provided verbatim 2) as generated from People 3) as taken from the Source Source People (Authors) Source Verbatim authors.
-
#cached_html_name_and_author_year ⇒ String
TODO: helper/render?.
-
#cached_html_original_name_and_author_year ⇒ String
Combination of cached_original_combination_html and original_author_year.
-
#cached_name_and_author_year ⇒ String
Combination of cached and cached_author_year.
- #check_for_children ⇒ Object protected
-
#check_new_parent_class ⇒ Object
protected
TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already.
-
#check_new_rank_class ⇒ Object
protected
Note- prior version prevented groups from moving when set in error, and was far too strict.
-
#classification_invalid_or_unavailable? ⇒ Boolean
Whether this name has any classification asserting that this the name is NOT valid or that it is unavailable.
-
#classification_unavailable? ⇒ Boolean
Whether this name has any classification asserting that this the name is unavailable.
-
#classification_valid? ⇒ Boolean
True if this name has any classification asserting that it is valid.
- #clear_cached(update: false) ⇒ Object
-
#combination_list_all ⇒ Array of Protonym
All of the names this name has been in combination with.
-
#combination_list_self ⇒ Array of Protonym
For all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?).
-
#combined_statuses ⇒ Array of String
The unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships.
- #create_otu ⇒ Object
-
#descendant_protonyms ⇒ Array of TaxonName
Descendants of type ‘Protonym’.
- #dwc_occurrences ⇒ Object
-
#first_possible_invalid_taxan_name_relationship ⇒ Object
TODO: Write test.
-
#first_possible_valid_taxon_name ⇒ TaxonName
Returns the youngest #object_taxon_name from the youngest taxon name relationship.
-
#first_possible_valid_taxon_name_relationship ⇒ TaxonNameRelationship
TODO: write test.
-
#full_name ⇒ String?
Returns nil for Higher names.
-
#full_name_array ⇒ rank, ...
“section”=>[“sect.”, “Aus”], “series”=>[“ser.”, “Aus”], “species”=>[nil, “aaa”], “subspecies”=>[nil, “bbb”], “variety”=>[“var.”, “ccc”]}.
-
#full_name_hash ⇒ Object
!! TODO: Higher classification does not follow the same pattern !! TODO: when name is a subgenus will not grab genus (still true?).
- #gbif_status_array ⇒ Object
-
#gender_class ⇒ Class?
Gender of a genus as class.
-
#gender_instance ⇒ TaxonNameClassification instance?
The gender classification of this name, if provided.
-
#gender_name ⇒ String?
Gender as a string (only applicable to Genera).
- #genderized_name(gender = nil) ⇒ String?
-
#get_author ⇒ Object
TODO: cleanly isolate getters, setters, and cached builders TODO: remove, this is only used for a strange call in sv_checked cached.
-
#get_author_and_year ⇒ Object
return [String] the author and year of the name, adds parenthesis where asserted.
- #get_cached_classified_as ⇒ String?
-
#get_cached_misspelling ⇒ Object
verbatim_name should not have downstream factual consequences.
-
#get_full_name ⇒ String?
A monominal if names is above genus, or a full epithet if below.
-
#get_full_name_html(name = nil) ⇒ Object
String.
-
#get_genus_species(genus_option, self_option) ⇒ Object
return [String, nil, false] # TODO: fix.
-
#get_original_combination ⇒ Object
Stub, see subclasses TaxonNameRelationships call it for Combinations.
-
#get_original_combination_html ⇒ Object
Stub, see subclasses only Protonym, but TaxonNameRelationships call it for Combinations.
-
#get_valid_taxon_name ⇒ TaxonName
A valid taxon_name for an invalid name or self for valid name.
- #icn_author_and_year(taxon) ⇒ Object
-
#iczn_author_and_year(taxon) ⇒ String?
The authors, and year, with parentheses as inferred by the data.
-
#is_ambiguously_invalid? ⇒ Boolean
Has Classification, but no relationship describing why.
-
#is_candidatus? ⇒ True|False
True if this name has a TaxonNameClassification of candidatus.
- #is_combination? ⇒ Boolean
-
#is_fossil? ⇒ True|False
True if this name has a TaxonNameClassification of Fossil.
-
#is_genus_or_species_rank? ⇒ Boolean
See subclasses.
-
#is_hybrid? ⇒ Boolean
TODO: ultimately deprecate for type Hybrid names.
-
#is_italicized? ⇒ Boolean
Whether this name needs italics applied.
- #is_protonym? ⇒ Boolean
-
#is_valid? ⇒ Boolean
After all inference on the validity of a name, the result is stored in cached_valid_taxon_name_id, #is_valid checks that result.
-
#list_of_invalid_taxon_names ⇒ Array of TaxonName
Can’t we just use #valid_id now? DD: no this is used for validation of multiple conflicting relationships this list does not return Combinations.
-
#matrix_row_item ⇒ {"matrix_row_item": matrix_column_item, "object": object}, false
See Shared::MatrixHooks the hash corresponding to the keyword used in this tag if it exists !! Assumes it can only be in one matrix, this is wrong !!.
-
#merge_to(to_taxon_name, kind) ⇒ Object
TODO: Deprecate/remove for .unify().
- #minimum_invalidating_year ⇒ Object
- #minimum_years_valid ⇒ Object
-
#name_in_gender(gender = nil) ⇒ Object
String, nil then name according to the gender requested.
-
#name_is_misapplied?(relationships = nil) ⇒ Boolean
TODO: needs test return [Boolean] whether there is an ICZN missapplication relationship present on this name.
-
#name_with_misspelling(gender) ⇒ String
TODO: does this form of the name contain parens for subgenus? TODO: provide a default to gender (but do NOT eliminate param) TODO: on third thought- eliminate this mess.
-
#next_sibling ⇒ Object
TODO: this should be paginated, not all IDs!.
-
#nomeclatural_history ⇒ array
returns array of hashes for history of taxon.
-
#nomenclature_date ⇒ Time
!! Overrides and references Shared::Citations#nomenclature_date.
-
#normalized_genus ⇒ Object
Protonym.
-
#not_binominal? ⇒ True|False
True if this name has a TaxonNameClassification of not_binominal.
-
#original_author_year ⇒ String?
Derived from cached_author_year The intent is to remove outer parens for an original combination.
- #out_of_scope_combinations ⇒ Object
-
#part_of_speech_class ⇒ Class
Part of speech of a species as class.
- #part_of_speech_instance ⇒ Object
-
#part_of_speech_name ⇒ String
Part of speech of a species as string.
-
#previous_sibling ⇒ Object
TODO: this should be paginated, not all IDs!.
-
#rank ⇒ String
Rank as human readable short-form, like ‘genus’ or ‘species’.
-
#rank_string ⇒ String
Rank (Kindom, Phylum…) as a string, like NomenclaturalRank::Iczn::SpeciesGroup::Species.
-
#reified_id ⇒ Object
a reified ID is used when the original combination, which does not yet have it’s own ID, is not the same as the current classification Some observations: - reified ids are only for original combinations (for which we have no ID) - reified ids never reference gender changes because they are always in context of original combination, i.e.
-
#related_taxon_names ⇒ Array of TaxonName
All taxon_names which have relationships to this taxon as an object or subject.
-
#relationship_invalid? ⇒ Boolean
True if there is a relationship where then name is asserted to be invalid.
- #relationships(rebuild = false) ⇒ Object
-
#reload ⇒ Object
NOT USED attr_accessor :relationships.
-
#safe_self_and_ancestors ⇒ Array of TaxonName
TODO: Integrate with Taxonomy? Taxonomy.values.
-
#set_cached ⇒ Object
TODO: We need to isolate this into 2 subclasses, 1 - cached methods that touch author/year 2 - cached methods that do not.
- #set_cached_author ⇒ Object
-
#set_cached_author_columns ⇒ Object
See TaxonNameAuthor.
- #set_cached_author_year ⇒ Object
- #set_cached_classified_as ⇒ Object
- #set_cached_is_valid ⇒ Object
- #set_cached_nomenclature_date ⇒ Object
- #set_cached_valid_taxon_name_id ⇒ Object
- #set_cached_warnings ⇒ Object
-
#statuses_from_classifications ⇒ Array of String
The unique string labels (human readable) derived from TaxonNameClassifications.
-
#statuses_from_relationships ⇒ Array of String
The unique string labels derived from and TaxonNameRelationships.
- #sv_cached_names ⇒ Object protected
- #sv_combination_duplicates ⇒ Object protected
- #sv_conflicting_subordinate_taxa ⇒ Object protected
-
#sv_fix_cached_names ⇒ Object
protected
TODO: This can be made more specific, we don’t need to call some of the methods in set_cached It also should never be required.
- #sv_fix_parent_is_valid_name ⇒ Object protected
- #sv_homotypic_synonyms ⇒ Object protected
- #sv_hybrid_name_relationships ⇒ Object protected
- #sv_incomplete_combination ⇒ Object protected
- #sv_missing_classifications ⇒ Object protected
-
#sv_missing_confidence_level ⇒ Object
protected
TODO: this needs to go.
-
#sv_missing_etymology ⇒ Object
protected
def sv_missing_author true # see Protonym end.
- #sv_missing_original_publication ⇒ Object protected
- #sv_missing_relationships ⇒ Object protected
-
#sv_not_synonym_of_self ⇒ Object
protected
Required for synonyms of synomyms.
- #sv_parent_is_valid_name ⇒ Object protected
- #sv_parent_priority ⇒ Object protected
- #sv_potential_homonyms ⇒ Object protected
- #sv_primary_types ⇒ Object protected
- #sv_single_sub_taxon ⇒ Object protected
- #sv_species_gender_agreement ⇒ Object protected
- #sv_two_unresolved_alternative_synonyms ⇒ Object protected
- #sv_type_placement ⇒ Object protected
- #sv_validate_coordinated_names ⇒ Object protected
- #sv_validate_name ⇒ Object protected
- #sv_validate_parent_rank ⇒ Object protected
-
#synonyms ⇒ Scope
Protonym(s) the **broad sense** synonyms of this name.
-
#taxon_name_classification_minimum_invalidating_year ⇒ Object
TODO: @proceps write test please).
- #taxon_name_classifications_for_statuses ⇒ Scope
-
#taxon_name_relationship_minimum_invalidating_year ⇒ Object
Year,nil based on TaxonNameRelationships only at present.
-
#unavailable_or_invalid? ⇒ Boolean
@return [Boolean] return true if name is unavailable OR invalid, else false, checks both classifications and relationships !! Should only be referenced when building cached values, all other uses should rather be ‘!is_valid?`.
- #validate_parent_from_the_same_project ⇒ Object protected
-
#validate_rank_class_class ⇒ Object
protected
See subclasses.
- #validate_root_name_is_root ⇒ Object protected
- #validate_source_type ⇒ Object protected
-
#year_integer ⇒ Integer
A 4 digit integer representing year of publication, like 1974.
Methods included from Shared::IsData
#errors_excepting, #full_error_messages_excepting, #identical, #is_community?, #is_destroyable?, #is_editable?, #is_in_use?, #is_in_users_projects?, #metamorphosize, #similar
Methods included from MatrixHooks
#coordinate_observation_matrix_row_items, #in_scope_observation_matrix_row_items, #out_of_scope_observation_matrix_row_items
Methods included from Shared::MatrixHooks::Dynamic
#dynamic_add_to_matrix_column_items, #dynamic_add_to_matrix_row_items, #dynamic_cleanup_in_scope_column_items, #dynamic_cleanup_in_scope_row_items, #dynamic_cleanup_out_of_scope_column_items, #dynamic_cleanup_out_of_scope_row_items, #dynamic_column_items_in, #dynamic_column_items_out, #dynamic_inspect_matrices, #dynamic_remove_from_matrix_column_items, #dynamic_remove_from_matrix_row_items, #dynamic_row_items_in, #dynamic_row_items_out, #dynamic_synchronize_matrices, #dynamic_update_matrix_column_items?, #dynamic_update_matrix_row_items?, #in_scope_observation_matrix_column_items, #in_scope_observation_matrix_row_items, #out_of_scope_observation_matrix_column_items, #out_of_scope_observation_matrix_row_items, #prepare_matrix_items
Methods included from Shared::MatrixHooks::Member
#member_add_matrix_columns, #member_add_matrix_rows, #member_add_to_matrix_items, #member_of_new_matrix_column_items, #member_of_new_matrix_row_items, #member_of_old_matrix_column_items, #member_of_old_matrix_row_items, #member_remove_from_matrix_items, #member_remove_matrix_columns, #member_remove_matrix_rows, #member_synchronize_matrices, #member_update_matrix_items?
Methods included from Shared::QueryBatchUpdate
Methods included from SoftValidation
#clear_soft_validations, #fix_for, #fix_soft_validations, #soft_fixed?, #soft_valid?, #soft_validate, #soft_validated?, #soft_validations, #soft_validators
Methods included from Shared::Labels
Methods included from Shared::HasPapertrail
#attribute_updated, #attribute_updater, #detect_version
Methods included from Shared::AlternateValues
#all_values_for, #alternate_valued?
Methods included from Shared::Confidences
Methods included from Shared::Citations
#cited?, #mark_citations_for_destruction, #origin_citation_source_id, #reject_citations, #requires_citation?, #sources_by_topic_id
Methods included from Shared::Depictions
#has_depictions?, #image_array=, #reject_depictions, #reject_images
Methods included from Shared::Notes
#concatenated_notes_string, #reject_notes
Methods included from Shared::Identifiers
#dwc_occurrence_id, #identified?, #next_by_identifier, #previous_by_identifier, #reject_identifiers, #uri, #uuid
Methods included from Shared::Tags
#reject_tags, #tag_with, #tagged?, #tagged_with?
Methods included from Shared::DataAttributes
#import_attributes, #internal_attributes, #keyword_value_hash, #reject_data_attributes
Methods included from Housekeeping
#has_polymorphic_relationship?
Methods inherited from ApplicationRecord
Instance Attribute Details
#also_create_otu ⇒ Boolean
Returns When true, also creates an OTU that is tied to this taxon name.
232 233 234 |
# File 'app/models/taxon_name.rb', line 232 def also_create_otu @also_create_otu end |
#cached ⇒ String
Genus-species combination for genus and lower, monominal for higher. The string has NO html, and no author/year.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_author ⇒ String?
Returns author string without parentheses.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_author_year ⇒ String?
Returns author and year string with parentheses where necessary, i.e. with context of present placement for ICZN.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_classified_as ⇒ String
if the name was classified in different group (e.g. a genus placed in wrong family).
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_html ⇒ String
As in ‘cached` but with tags.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_misspelling ⇒ Boolean
if the name is a misspelling, stores True.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_original_combination ⇒ String
Returns name as formed in original combination, no author/year, without HTML.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_original_combination_html ⇒ String
Returns as cached_original_combination but with HTML.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_primary_homonym ⇒ String
original genus and species name. Used to find and validate primary homonyms.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_primary_homonym_alternative_spelling ⇒ String
Original genus and species name in alternative spelling. Used to find and validate primary homonyms.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_secondary_homonym ⇒ String
current genus and species name. Used to find and validate secondary homonyms.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#cached_secondary_homonym_alternative_spelling ⇒ String
Current genus and species name in alternative spelling. Used to find and validate secondary homonyms.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#classifications(rebuild = false) ⇒ Object
Returns array of all taxon_name_classifications, memoizable.
228 229 230 |
# File 'app/models/taxon_name.rb', line 228 def classifications @classifications end |
#etymology ⇒ String
the derivation and history of the name in written form
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#feminine_name ⇒ String
Species name which are adjective or participle change depending on the gender of the genus. 3 fields provide alternative species spelling. The part_of_speech is designated as a taxon_name_classification. The gender of a genus also designated as a taxon_name_classification.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#masculine_name ⇒ String
Species name which are adjective or participle change depending on the gender of the genus. 3 fields provide alternative species spelling. The part_of_speech is designated as a taxon_name_classification. The gender of a genus also designated as a taxon_name_classification.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#name ⇒ String?
the fully latinized string (monominal) of a code governed taxonomic biological name not applicable for Combinations, they are derived from their pieces
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#neuter_name ⇒ String
Species name which are adjective or participle change depending on the gender of the genus. 3 fields provide alternative species spelling. The part_of_speech is designated as a taxon_name_classification. The gender of a genus also designated as a taxon_name_classification.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#no_cached ⇒ Boolean
Returns When true cached values are not built.
236 237 238 |
# File 'app/models/taxon_name.rb', line 236 def no_cached @no_cached end |
#parent_id ⇒ Integer
The id of the parent taxon. The parent child relationship is exclusively organizational. All statuses and relationships of a taxon name must be explicitly defined via taxon name relationships or classifications. The parent of a taxon name can be thought of as “the place where you’d find this name in a hierarchy if you knew literally nothing else about that name.” In practice read each monominal in the name (protonym or combination) from right to left, the parent is the parent of the last monominal read. There are 3 simple rules for determining the parent of a Protonym or Combination:
1) the parent must always be at least one rank higher than the target names rank
2) the parent of a synonym (any sense) is the parent of the synonym's valid name
3) the parent of a combination is the parent of the highest ranked monominal in the epithet (almost always the parent of the genus)
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#project_id ⇒ Integer
the project ID
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#rank_class ⇒ NomenclaturalRank class
Returns rank as a NomenclaturalRank class, like NomenclaturalRank::Iczn::SpeciesGroup::Species.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#related_relationships(rebuild = false) ⇒ Object
!! Memoized attributes are not reset when related objects reload them. !! For example if species = subject_taxon_name. of a = TaxonNameRelationship !! then a.subject_taxon_name.reload is not the same as species.reload
225 226 227 |
# File 'app/models/taxon_name.rb', line 225 def @related_relationships end |
#taxonomy(rebuild = false) ⇒ Object (readonly)
See attr_reader.
206 207 208 |
# File 'app/models/taxon_name.rb', line 206 def taxonomy @taxonomy end |
#type ⇒ String
The subclass of this taxon name, e.g. Protonym or Combination
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#verbatim_author ⇒ String
the verbatim author string as provided ? is not post-filled in when Source is referenced !?
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#verbatim_name ⇒ String
a representation of what the Combination (fully spelled out) or Protonym (monominal) *looked like* in its originating publication. The sole purpose of this string is to represent visual differences from what is recorded in the latinized version of the name (Protonym#name, Combination#cached) from what was originally transcribed. This string should NOT include the author year (see verbatim_author and year_of_publication for those data).
If at all possible this field SHOULD NOT be used, it has very little downstream inference use.
If a subgenus it should __TODO____ (not?) contain parens.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
#year_of_publication ⇒ Integer
Returns sensu ICZN - the 4 digit year when this name was published, i.e. made available. Not the publishers date stamped on the title page, but the actual date of publication. Precidence for taxon name publication year is TaxonName#year_of_publication, Source#year, Source#stated_year.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'app/models/taxon_name.rb', line 146 class TaxonName < ApplicationRecord # @return class # this method calls Module#module_parent # TODO: This method can be placed elsewhere inside this class (or even removed if not used) # when https://github.com/ClosureTree/closure_tree/issues/346 is fixed. # The issue is closed # def self.parent # self.module_parent # end # Must be before various of these includes, in particular MatrixHooks has_closure_tree include Housekeeping include Shared::DataAttributes include Shared::Tags include Shared::Identifiers include Shared::Notes include Shared::Depictions include Shared::Citations include Shared::Confidences include Shared::AlternateValues include Shared::HasPapertrail include Shared::Labels include SoftValidation include Shared::QueryBatchUpdate include TaxonName::OtuSyncronization include TaxonName::Hierarchy include Shared::MatrixHooks::Member include Shared::MatrixHooks::Dynamic include TaxonName::MatrixHooks include Shared::DwcOccurrenceHooks include Shared::IsData # Allows users to provide arbitrary annotations that "over-ride" rank string ALTERNATE_VALUES_FOR = [:rank_class].freeze # !! Don't even think about putting this on `name` COMBINATION_ELEMENTS = [:genus, :subgenus, :species, :subspecies, :variety, :subvariety, :form, :subform].freeze SPECIES_EPITHET_RANKS = %w{species subspecies variety subvariety form subform}.freeze NOT_LATIN = Regexp.new(/[^a-zA-Z|\-]/).freeze # Dash is allowed? NO_CACHED_MESSAGE = 'REBUILD PROJECT TAXON NAME CACHE'.freeze ROOT_NAME = 'Root' NOMEN_VALID = { icn: 'http://purl.obolibrary.org/obo/NOMEN_0000383', icnp: 'http://purl.obolibrary.org/obo/NOMEN_0000081', icvcn: 'http://purl.obolibrary.org/obo/NOMEN_0000125', iczn: 'http://purl.obolibrary.org/obo/NOMEN_0000224' }.freeze # See related concept in concerns/shared/taxonomy, this may belong there. # # @return [Hash] attr_reader :taxonomy # @return array of all taxon_name_relationships (name is subject), memoized # NOT USED # attr_accessor :relationships def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end # @return Array # all taxon_name_relationships (name is object), memoized # !! Memoized attributes are not reset when related objects reload them. # !! For example if species = subject_taxon_name. of a = TaxonNameRelationship # !! then a.subject_taxon_name.reload is not the same as species.reload attr_accessor :related_relationships # @return array of all taxon_name_classifications, memoizable attr_accessor :classifications # @return [Boolean] # When true, also creates an OTU that is tied to this taxon name attr_accessor :also_create_otu # @return [Boolean] # When true cached values are not built attr_accessor :no_cached delegate :nomenclatural_code, to: :rank_class, allow_nil: true delegate :rank_name, to: :rank_class, allow_nil: true # TODO: this was not implemented and tested properly # I think the intent is *before* save, i.e. the name will change # to a new cached value, so let's record the old one # after_save :create_new_combination_if_absent after_create :create_otu, if: :also_create_otu before_destroy :check_for_children, prepend: true # With this @taxonomy can more or less replace full_name_hash # after_save :reset_taxonomy # def reset_taxonomy # @taxonomy = nil # end # Rails 7 experiments have after_commit creating a whack-a-mole situation # (though leave after_commit on TaxonNameRelationship) after_commit :set_cached, unless: Proc.new {|n| n.no_cached || errors.any? } after_commit :set_cached_warnings, if: Proc.new {|n| n.no_cached } # Should definitely be after commit validate :validate_rank_class_class validate :check_new_rank_class validate :check_new_parent_class validate :validate_source_type validate :validate_parent_from_the_same_project, unless: Proc.new {|n| n.name == ROOT_NAME } # Root validations validate :validate_root_name_is_root, if: Proc.new {|n| n.name == ROOT_NAME } validates_presence_of :parent, unless: Proc.new {|m| self.name == ROOT_NAME} validates_uniqueness_of :name, scope: [:project_id], if: Proc.new {|n| n.name == ROOT_NAME} # TODO: remove, this is handled natively, and in DB validates_presence_of :type, message: 'is not specified' validates :year_of_publication, date_year: {min_year: 1000, max_year: Time.now.year + 5}, allow_nil: true # TODO: move some of these down to Protonym when they don't apply to Combination belongs_to :valid_taxon_name, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_one :source_classified_as_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::SourceClassifiedAs'}) }, class_name: 'TaxonNameRelationship::SourceClassifiedAs', foreign_key: :subject_taxon_name_id has_one :family_group_name_form_relationship, -> { where(taxon_name_relationships: {type: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm'}) }, class_name: 'TaxonNameRelationship::Iczn::Invalidating::Usage::FamilyGroupNameForm', foreign_key: :subject_taxon_name_id, inverse_of: :subject_taxon_name has_one :source_classified_as, through: :source_classified_as_relationship, source: :object_taxon_name # TODO: think of a different name, and test has_many :historical_taxon_names, class_name: 'TaxonName', foreign_key: :cached_valid_taxon_name_id has_many :observation_matrix_row_items, as: :observation_object, inverse_of: :observation_object, class_name: 'ObservationMatrixRowItem::Dynamic::TaxonName', dependent: :destroy # was delete_all has_many :observation_matrices, through: :observation_matrix_row_items has_many :otus, inverse_of: :taxon_name, dependent: :restrict_with_error has_many :taxon_determinations, through: :otus has_many :collection_objects, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'CollectionObject' has_many :field_occurrences, through: :taxon_determinations, source: :taxon_determination_object, source_type: 'FieldOccurrence' # TODO: check class_name constraints. has_many :related_taxon_name_relationships, class_name: 'TaxonNameRelationship', foreign_key: :object_taxon_name_id, dependent: :restrict_with_error, inverse_of: :object_taxon_name has_many :taxon_name_author_roles, class_name: 'TaxonNameAuthor', as: :role_object, dependent: :destroy, inverse_of: :role_object has_many :taxon_name_authors, -> { order('roles.position ASC') }, through: :taxon_name_author_roles, source: :person # TODO: Combinations shouldn't have classifications or relationships? Move to Protonym? has_many :taxon_name_classifications, dependent: :destroy, inverse_of: :taxon_name has_many :taxon_name_relationships, foreign_key: :subject_taxon_name_id, dependent: :restrict_with_error, inverse_of: :subject_taxon_name # NOTE: Protonym subclassed methods might not be nicely tracked here, we'll have to see. Placement is after has_many relationships. (?) accepts_nested_attributes_for :related_taxon_name_relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? || attributes['subject_taxon_name_id'].blank? } accepts_nested_attributes_for :family_group_name_form_relationship, allow_destroy: true, reject_if: proc { |attributes| attributes['object_taxon_name_id'].blank? } accepts_nested_attributes_for :taxon_name_authors, :taxon_name_author_roles, allow_destroy: true accepts_nested_attributes_for :taxon_name_classifications, allow_destroy: true, reject_if: proc { |attributes| attributes['type'].blank? } has_many :classified_as_unavailable_or_invalid, -> { where type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }, class_name: 'TaxonNameClassification' # Combinations are rankless, but we need this scope here for generic returns scope :order_by_rank, -> (code) {order(Arel.sql("position(taxon_names.rank_class in '#{code}')"))} scope :with_same_cached_valid_id, -> { where(arel_table[:id].eq(arel_table[:cached_valid_taxon_name_id])) } scope :with_different_cached_valid_id, -> { where(arel_table[:id].not_eq(arel_table[:cached_valid_taxon_name_id])) } # This doesn't catch all invalid names. Those with classifications only are missed !$#!@# scope :that_is_valid, -> {where(cached_is_valid: true) } scope :that_is_invalid, -> {where(cached_is_valid: false) } def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end scope :with_type, -> (type) {where(type:)} scope :descendants_of, -> (taxon_name) { with_ancestor(taxon_name )} scope :ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) .where('taxon_name_hierarchies.ancestor_id != ?', taxon_name.id) .order('taxon_name_hierarchies.generations DESC') # root is at index 0 } # LEAVE UNORDERED, if you want order: # .order('taxon_name_hierarchies.generations DESC') scope :self_and_ancestors_of, -> (taxon_name) { joins(:descendant_hierarchies) .where(taxon_name_hierarchies: {descendant_id: taxon_name.id}) } # Includes taxon_name, doesn't order result scope :ancestors_and_descendants_of, -> (taxon_name) do scoping do a = TaxonName.self_and_ancestors_of(taxon_name) b = TaxonName.descendants_of(taxon_name) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end end # TODO: remove scope :with_rank_class, -> (rank_class_name) { where(rank_class: rank_class_name) } # TODO: remove scope :with_parent_taxon_name, -> (parent) { where(parent_id: parent) } scope :with_base_of_rank_class, -> (rank_class) { where('rank_class LIKE ?', "#{rank_class}%") } scope :with_rank_class_including, -> (include_string) { where('rank_class LIKE ?', "%#{include_string}%") } # A specific relationship scope :as_subject_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_subject_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT LIKE ?) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_without_taxon_name_relationship_array, -> (taxon_name_relationship_name_array) { includes(:taxon_name_relationships).where('(taxon_name_relationships.type NOT IN (?)) OR (taxon_name_relationships.subject_taxon_name_id IS NULL)', "#{taxon_name_relationship_name_array}%").references(:taxon_name_relationships) } scope :as_subject_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:taxon_name_relationships) } scope :as_object_with_taxon_name_relationship, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {type: taxon_name_relationship}) } scope :as_object_with_taxon_name_relationship_base, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } scope :as_object_with_taxon_name_relationship_containing, -> (taxon_name_relationship) { includes(:related_taxon_name_relationships).where('taxon_name_relationships.type LIKE ?', "%#{taxon_name_relationship}%").references(:related_taxon_name_relationships) } # @param relationship [Array, String] def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end scope :with_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NOT NULL OR tnr2.object_taxon_name_id IS NOT NULL') } # *Any* relationship where there IS a relationship for a subject/object/both scope :with_taxon_name_relationships_as_subject, -> { joins(:taxon_name_relationships) } scope :with_taxon_name_relationships_as_object, -> { joins(:related_taxon_name_relationships) } # *Any* relationship where there is NOT a relationship for a subject/object/both scope :without_subject_taxon_name_relationships, -> { includes(:taxon_name_relationships).where(taxon_name_relationships: {subject_taxon_name_id: nil}) } scope :without_object_taxon_name_relationships, -> { includes(:related_taxon_name_relationships).where(taxon_name_relationships: {object_taxon_name_id: nil}) } scope :without_taxon_name_relationships, -> { joins('LEFT OUTER JOIN taxon_name_relationships tnr1 ON taxon_names.id = tnr1.subject_taxon_name_id'). joins('LEFT OUTER JOIN taxon_name_relationships tnr2 ON taxon_names.id = tnr2.object_taxon_name_id'). where('tnr1.subject_taxon_name_id IS NULL AND tnr2.object_taxon_name_id IS NULL') } # TODO: deprecate all of these for where() scope :with_parent_id, -> (parent_id) {where(parent_id:)} scope :with_cached_valid_taxon_name_id, -> (cached_valid_taxon_name_id) {where(cached_valid_taxon_name_id:)} scope :with_cached_original_combination, -> (original_combination) { where(cached_original_combination: original_combination) } scope :without_otus, -> { includes(:otus).where(otus: {id: nil}) } scope :with_otus, -> { includes(:otus).where.not(otus: {id: nil}) } # @return [Scope] # Combinations that are composed of children of this taxon name # when those children are not currently descendants of this taxon name # # !! When :cached_valid_taxon_name_id is properly set then this method is not required # rather you should use :historical_taxon_names. # def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end # @return Scope # names that are not leaves # TODO: belongs in lib/queries/filter.rb likely def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end soft_validate( :sv_missing_confidence_level, set: :missing_fields, name: 'Missing confidence level', description: 'To remaind that the taxon spelling have to be compared to the original source' ) soft_validate( :sv_missing_original_publication, set: :missing_fields, name: 'Missing original source', description: 'Original source is not selected' ) soft_validate( :sv_parent_is_valid_name, set: :parent_is_valid_name, fix: :sv_fix_parent_is_valid_name, name: 'Parent should be a valid taxon', description: 'When the parent taxon (for example a genus) is treated as a synonym, all subordinate taxa from this taxon should be transferred to the valid taxon' ) soft_validate( :sv_conflicting_subordinate_taxa, set: :parent_is_valid_name, name: 'Conflicting subordinate taxa', description: 'Unavailable or invalid taxon should not have subordinate taxa' ) soft_validate( :sv_cached_names, set: :cached_names, fix: :sv_fix_cached_names, name: 'Cached names', description: 'Check if cached values need to be updated' ) # TODO: move to protonym spec? soft_validate( :sv_not_synonym_of_self, set: :not_synonym_of_self, name: 'Not synonym of self', description: 'Taxon has two conflicting relationships (invalidating and validating).' ) # TODO: move to protonym spec? soft_validate( :sv_two_unresolved_alternative_synonyms, set: :two_unresolved_alternative_synonyms, name: 'Two conflicting relationships', description: 'Taxon has two conflicting relationships.' ) # TODO: move to combination spec? soft_validate( :sv_incomplete_combination, set: :incomplete_combination, name: 'Incomplete combination', description: 'Intermediate ranks are missing in combination (either original or subsequent)' ) # @return [Array of TaxonName] # ordered by rank, a scope-like hack def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end # TODO: what is this:!? :) # def self.foo(rank_classes) # from <<-SQL.strip_heredoc # ( SELECT *, rank() # OVER ( # PARTITION BY rank_class, parent_id # ORDER BY generations asc, name # ) AS rn # FROM taxon_names # INNER JOIN "taxon_name_hierarchies" ON "taxon_names"."id" = "taxon_name_hierarchies"."descendant_id" # WHERE #{rank_classes.collect{|c| "rank_class = '#{c}'" }.join(' OR ')} # ) as taxon_names # SQL # end # See attr_reader. def taxonomy(rebuild = false) if rebuild @taxonomy = full_name_hash else @taxonomy ||= full_name_hash end end def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end def (rebuild = false) if rebuild @related_relationships = .eager_load(:subject_taxon_name, :object_taxon_name).to_a else @related_relationships ||= .eager_load(:subject_taxon_name, :object_taxon_name).to_a end @related_relationships end def classifications(rebuild = false) if rebuild @classifications = taxon_name_classifications.to_a else @classifications ||= taxon_name_classifications.to_a end end # @return [Scope] Protonym(s) the **broad sense** synonyms of this name def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end # @return [String] # rank as human readable short-form, like 'genus' or 'species' def rank ::RANKS.include?(rank_string) ? rank_name : nil end # @return [String] # rank (Kindom, Phylum...) as a string, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_string read_attribute(:rank_class) end def rank_class=(value) write_attribute(:rank_class, value.to_s) end # @return [NomenclaturalRank class] # rank as a {NomenclaturalRank} class, like {NomenclaturalRank::Iczn::SpeciesGroup::Species} def rank_class r = read_attribute(:rank_class) Ranks.valid?(r) ? r.safe_constantize : r end # @see .out_of_scope_combinations def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end # TODO: replace with @taxonomy # @return [TaxonName, nil] an ancestor at the specified rank # @param rank [symbol|string| # like :species or 'genus' # @param include_self [Boolean] # if true then self will also be returned def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end # Unused # @return scope [TaxonName, nil] an ancestor at the specified rank # @params rank [symbol|string| # like :species or 'genus' # def descendants_at_rank(rank) # return TaxonName.none if nomenclatural_code.blank? # Root names # descendants.with_rank_class( # Ranks.lookup(nomenclatural_code, rank) # ) # end # @return [Array] # all TaxonNameRelationships where this taxon is an object or subject. def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end # @return [Array of TaxonName] # all taxon_names which have relationships to this taxon as an object or subject. def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end # @return [String, nil] # the baseline means of displaying name authorship, i.e. the author for this taxon, last name only. # Important, string format priority is # 1) as provided verbatim # 2) as generated from People # 3) as taken from the Source # Source People (Authors) # Source Verbatim authors def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end # @return [Integer] # a 4 digit integer representing year of publication, like 1974 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end # @return Year,nil # based on TaxonNameRelationships only at present def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end # TODO: @proceps write test please) def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end # TODO: cleanly isolate getters, setters, and cached builders # TODO: remove, this is only used for a strange call in sv_checked cached. # # @return String, nil # virtual attribute, to ultimately be fixed in db def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end # @return [Time] # effective date of publication, used to determine nomenclatural priority # # !! Overrides *and* references Shared::Citations#nomenclature_date def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end # @return [array] # returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end # @return [Class, nil] # gender of a genus as class def gender_class gender_instance.try(:type_class) end # @return [TaxonNameClassification instance, nil] # the gender classification of this name, if provided def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end # @return [String, nil] # gender as a string (only applicable to Genera) def gender_name gender_instance.try(:classification_label).try(:downcase) end # @return [Class] # part of speech of a species as class. def part_of_speech_class part_of_speech_instance.try(:type_class) end def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end # @return [String] # part of speech of a species as string. def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end # @return [Array of String] # the unique string labels (human readable) derived from TaxonNameClassifications def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end # @return [Scope] def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end # @return [Array of String] # the unique string labels derived from and TaxonNameRelationships def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end # @return [Array of String] # the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end # @return [Array of Protonym] # All of the names this name has been in combination with def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end # @return [Array of Protonym] # for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?) def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end # TODO: should be moved to helpers # and referenced in models with helper. # TODO: in refactor these are often just helper methods , # though variously used in soft_validations # (and various are only used in helpers already) # TODO: helper/render? # @return [String] # combination of cached_html and cached_author_year. def [cached_html, ].compact.join(' ') end # @return [String] # combination of cached_original_combination_html and original_author_year. def [cached_original_combination_html, ].compact.join(' ') end # @return [String] combination of cached and cached_author_year. def [cached, ].compact.join(' ') end # @return [String, nil] # Derived from cached_author_year # The intent is to remove outer parens for an original combination. # # !! DO NOT USE IN BUILDING CACHED !! # # See also app/helpers/taxon_names_helper # !! TODO: needs tests badly # !? TODO: cached_author_year should not include `non` likely # !! i.e. it currently differs from cached_author + cached_nomenclature_date.year def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end # @return [Array of TaxonName] ancestors of type 'Protonym' def ancestor_protonyms Protonym.ancestors_of(self) end # @return [Array of TaxonName] descendants of type 'Protonym' def descendant_protonyms Protonym.descendants_of(self) end # @return [Boolean] # true if there is a relationship where then name is asserted to be invalid def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end # @return [Boolean] # true if this name has any classification asserting that it is valid def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end # @return [Boolean] # whether this name has any classification asserting that this the name is NOT valid or that it is unavailable def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end # @return [Boolean] # whether this name has any classification asserting that this the name is unavailable def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end # @return [Boolean] # return true if name is unavailable OR invalid, else false, checks both classifications and relationships # !! Should only be referenced when building cached values, all other uses should rather be `!is_valid?` def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end # @return [Boolean] # after all inference on the validity of a name, the result is stored # in cached_valid_taxon_name_id, #is_valid checks that result def is_valid? cached_is_valid end # Has Classification, but no relationship describing why def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end # @return [Boolean] # whether this name needs italics applied def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end def is_protonym? type == 'Protonym' end def is_combination? type == 'Combination' end # @return [True|False] # true if this name has a TaxonNameClassification of Fossil def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end # TODO: ultimately deprecate for type Hybrid names. # @return [Boolean] # true if this name has a TaxonNameClassification of hybrid def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end # @return [True|False] # true if this name has a TaxonNameClassification of candidatus def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end # @return [True|False] # true if this name has a TaxonNameClassification of not_binominal def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end # @return [Boolean] # see subclasses def is_genus_or_species_rank? false end # @return [TaxonName] # a valid taxon_name for an invalid name or self for valid name. # a stub here - See Protonym and Combination def get_valid_taxon_name nil end # TODO: write test # @return [TaxonNameRelationship] # returns youngest taxon name relationship where self is the subject. def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end # TODO: Write test def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end # @return [TaxonName] # returns the youngest #object_taxon_name from the youngest taxon name relationship. def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end # @return [Array of TaxonName] # returns list of invalid names for a given taxon. # Can't we just use #valid_id now? # DD: no this is used for validation of multiple conflicting relationships # this list does not return Combinations def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end # @param gender, String # @return String, nil # then name according to the gender requested def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end # TODO: We need to isolate this into 2 subclasses, # 1 - cached methods that touch author/year # 2 - cached methods that do not def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end # See TaxonNameAuthor def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end def update_column(:cached_author_year, ) end def update_column(:cached_author, ) end def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end # @proceps I feel this needs to go away. If you want to define misspelling you can not use a verbatim_name. In general # verbatim_name should not have downstream factual consequences. # # TODO: Missing specs def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end # Stub, see subclasses # TaxonNameRelationships call it for Combinations def get_original_combination nil end # Stub, see subclasses # only Protonym, but TaxonNameRelationships call it for Combinations def get_original_combination_html nil end # @return [Array] # of TaxonName # same as self.ancestors.to_a, but also works # for new records when parents specified def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end # TODO: Integrate with Taxonomy? # Taxonomy.values # # @return [Array of TaxonName] # an list of ancestors, Root first # # Uses parent recursion when record is new and awesome_nested_set # index is not yet usable. # def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end # @return [ rank, prefix, name], ...] for genus and below # @taxon_name.full_name_array # => # [ ["genus", [nil, "Aus"]], # ["subgenus", [nil, "Aus"]], # "section"=>["sect.", "Aus"], "series"=>["ser.", "Aus"], "species"=>[nil, "aaa"], "subspecies"=>[nil, "bbb"], "variety"=>["var.", "ccc"]\} def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end # @return Hash # { 'family' => 'Aidae', ...} def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end # !! TODO: Higher classification does not follow the same pattern # !! TODO: when name is a subgenus will not grab genus (still true?) # # # Conceptually there are 2 objects required to build @taxonomy, # one for the scientific name, the other for the higher taxa. # These need to be kept seperately in terms of optimizing # queries, or at least isolatable if combined. # # This method covers scientific name, gathering all string # elements, including 'sic' etc., and pointing to them # by rank. It therefor sits between model/helper. # # @!return [ { rank => [prefix, name] } ] # for genus and below: # # @taxon_name.full_name_hash # => # { "family' => 'Gidae', # "genus" => [nil, "Aus"], # Note Array! # "subgenus" => [nil, "Aus"], # "section" => ["sect.", "Aus"], # "series" => ["ser.", "Aus"], # "species" => [nil, "aaa"], # "subspecies" => [nil, "bbb"], # "variety" => ["var.", "ccc"]} # def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end # @return [String, nil] # A monominal if names is above genus, or a full epithet if below. # Does not include author_year. Does not include HTML. # # !! Combination has its own version now. # def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end # @return [String, nil] # returns nil for Higher names def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end # @return String def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end # @return [String] # TODO: does this form of the name contain parens for subgenus? # TODO: provide a default to gender (but do NOT eliminate param) # TODO: on third thought- eliminate this mess def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end # @return [String, nil] def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end # return [String, nil, false] # TODO: fix def get_genus_species(genus_option, self_option) # see Protonym true end # TODO: needs test # return [Boolean] # whether there is an ICZN missapplication relationship present on this name def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end # return [String] # the author and year of the name, adds parenthesis where asserted def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end # @return [String, nil] # the authors, and year, with parentheses as inferred by the data def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end # @return Protonym def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end # @return [String, nil] def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end # TODO: this should be paginated, not all IDs! def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end # TODO: this should be paginated, not all IDs! def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end # @return [Scope] # All taxon names attached to relationships recently created by user def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end # @return [Array] def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end # @return [Hash] def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end # See Shared::MatrixHooks # @return [{"matrix_row_item": matrix_column_item, "object": object}, false] # the hash corresponding to the keyword used in this tag if it exists # !! Assumes it can only be in one matrix, this is wrong !! def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end # a reified ID is used when the original combination, which does not yet have it's own ID, is not the same as the current classification # Some observations: # - reified ids are only for original combinations (for which we have no ID) # - reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change # Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) # Duplicated in COLDP export code def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end # TODO: Deprecate/remove for .unify() def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end protected def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end # TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end # See subclasses def validate_rank_class_class true end # Note- prior version prevented groups from moving when set in error, and was far too strict def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end # TODO: this needs to go. def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end # def sv_missing_author # true # see Protonym # end # # def sv_missing_year # true # see Protonym # end def sv_missing_etymology true # see Protonym end def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end # TODO: This can be made more specific, we don't need to call some of the methods in set_cached # It also should never be required. def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end # Required for synonyms of synomyms def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end def sv_cached_names true # see validation in subclasses end def sv_validate_parent_rank true # see validation in Protonym.rb end def sv_missing_relationships true # see validation in Protonym.rb end def sv_validate_name true # see validation in Protonym.rb end def sv_missing_classifications true # see validation in Protonym.rb end def sv_species_gender_agreement true # see validation in Protonym.rb end def sv_primary_types true # see validation in Protonym.rb end def sv_validate_coordinated_names true # see validation in Protonym.rb end def sv_type_placement true # see validation in Protonym.rb end def sv_single_sub_taxon true # see validation in Protonym.rb end def sv_parent_priority true # see validation in Protonym.rb end def sv_homotypic_synonyms true # see validation in Protonym.rb end def sv_potential_homonyms true # see validation in Protonym.rb end def sv_combination_duplicates true # see validation in Combination.rb end def sv_hybrid_name_relationships true # see validation in Hybrid.rb end end |
Class Method Details
.calculated_invalid ⇒ Object
330 331 332 333 334 |
# File 'app/models/taxon_name.rb', line 330 def self.calculated_invalid a = TaxonName.with_different_cached_valid_id # that_is_invalid b = TaxonName.joins(:taxon_name_classifications).where(taxon_name_classifications: {type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID }) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end |
.calculated_valid ⇒ Object
336 337 338 339 340 341 342 343 |
# File 'app/models/taxon_name.rb', line 336 def self.calculated_valid # Alt format: TaxonName.that_is_valid.left_joins(:classified_as_unavailable_or_invalid).merge(TaxonNameClassification.where(id: nil)) TaxonName .with_same_cached_valid_id .where.not( id: TaxonNameClassification.select(:taxon_name_id).where(type: TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID) ) end |
.not_leaves ⇒ Object
TODO: belongs in lib/queries/filter.rb likely
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 |
# File 'app/models/taxon_name.rb', line 466 def self.not_leaves t = self.arel_table h = ::TaxonNameHierarchy.arel_table a = t.alias('a_') b = t.project(a[Arel.star]).from(a) c = h.alias('h1') b = b.join(c, Arel::Nodes::OuterJoin) .on( a[:id].eq(c[:ancestor_id]) ) e = c[:generations].not_eq(0) f = c[:ancestor_id].not_eq(c[:descendant_id]) b = b.where(e.and(f)) b = b.group(a[:id]) b = b.as('tnh_') ::TaxonName.joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['id'].eq(t['id'])))) end |
.out_of_scope_combinations(taxon_name_id) ⇒ Scope
!! When :cached_valid_taxon_name_id is properly set then this method is not required rather you should use :historical_taxon_names.
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 |
# File 'app/models/taxon_name.rb', line 432 def self.out_of_scope_combinations(taxon_name_id) t = ::TaxonName.arel_table h = ::TaxonNameHierarchy.arel_table r = ::TaxonNameRelationship.arel_table h1 = h.alias('osch_') h2 = h.alias('oschh_') b = h.project( h1[:descendant_id].as('b'), h2[:ancestor_id].as('c'), ).from([h]) b = b.join(r, Arel::Nodes::InnerJoin).on(h[:descendant_id].eq(r[:subject_taxon_name_id]).and(h[:ancestor_id].eq(taxon_name_id))) .join(h1, Arel::Nodes::InnerJoin).on(r[:object_taxon_name_id].eq(h1[:descendant_id]).and(h1[:ancestor_id].not_eq(h1[:descendant_id]))) .join(h2, Arel::Nodes::OuterJoin).on( h1[:ancestor_id].eq(h2[:ancestor_id]). and(h2[:descendant_id].eq(taxon_name_id)) ) # This was particularly useful in debugging the join chain: # ap TaxonNameHierarchy.connection.execute(b.to_sql).collect{|a| a} b = b.as('abc') ::Combination .joins(Arel::Nodes::InnerJoin.new(b, Arel::Nodes::On.new(b['b'].eq(t[:id])))) .where(b['c'].eq(nil)) .distinct end |
.select_optimized(user_id, project_id, target: nil) ⇒ Hash
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 |
# File 'app/models/taxon_name.rb', line 1699 def self.select_optimized(user_id, project_id, target: nil) klass = (target == 'TypeMaterial' ? Protonym : TaxonName) h = { recent: klass.used_recently(user_id, project_id, target: klass.name), pinboard: klass.pinned_by(user_id).pinned_in_project(project_id).to_a } h[:quick] = (klass.pinned_by(user_id).pinboard_inserted.pinned_in_project(project_id).to_a + h[:recent][0..3]).uniq h end |
.sort_by_rank(taxon_names) ⇒ Array of TaxonName
Returns ordered by rank, a scope-like hack.
545 546 547 |
# File 'app/models/taxon_name.rb', line 545 def self.sort_by_rank(taxon_names) taxon_names.sort!{|a, b| RANKS.index(a.rank_string) <=> RANKS.index(b.rank_string)} end |
.used_recently(user_id, project_id, target: nil) ⇒ Array
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 |
# File 'app/models/taxon_name.rb', line 1681 def self.used_recently(user_id, project_id, target: nil) klass, a,b,c = nil, nil, nil, nil if target == 'TypeMaterial' klass = Protonym a = klass.is_species_group.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).is_species_group.where(type: klass.name).limit(6).to_a else klass = TaxonName a = klass.touched_by(user_id).where(project_id:).order(updated_at: :desc).limit(6).to_a b = used_recently_in_classifications(user_id, project_id).where(type: klass.name).limit(6).to_a c = used_recently_in_relationships(user_id, project_id).where(type: klass.name).limit(6).to_a end d = [ a,b,c ].flatten.compact.uniq.sort{|e,f| e.cached <=> f.cached} end |
.used_recently_in_classifications(user_id, project_id) ⇒ Scope
Returns All taxon names attached to relationships recently created by user.
1651 1652 1653 1654 1655 1656 1657 |
# File 'app/models/taxon_name.rb', line 1651 def self.used_recently_in_classifications(user_id, project_id) TaxonName.where(project_id:, updated_by_id: user_id) .joins(:taxon_name_classifications) .includes(:taxon_name_classifications) .where(taxon_name_classifications: { updated_at: 1.week.ago..Time.now } ) .order('taxon_name_classifications.updated_at DESC') end |
.used_recently_in_relationships(user_id, project_id) ⇒ Scope
Returns All taxon names attached to relationships recently created by user.
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 |
# File 'app/models/taxon_name.rb', line 1661 def self.used_recently_in_relationships(user_id, project_id) t = TaxonNameRelationship.arel_table t1 = t.alias('tnr1') t2 = t.alias('tnr2') sql = t1[:updated_by_id].eq(user_id).or(t1[:created_by_id].eq(user_id)) .or(t2[:updated_by_id].eq(user_id).or(t2[:created_by_id].eq(user_id)) ).to_sql sql2 = t1[:updated_at].between( 1.week.ago..Time.now ) .or( t2[:updated_at].between( 1.week.ago..Time.now ) ).to_sql TaxonName.with_taxon_name_relationships .where(taxon_names: {project_id:}) .where(sql2) .where(sql) .order('taxon_names.updated_at DESC') ## needs optimisation. Does not sort by TNR date end |
.with_taxon_name_relationship(relationship) ⇒ Object
392 393 394 395 396 |
# File 'app/models/taxon_name.rb', line 392 def self.with_taxon_name_relationship(relationship) a = TaxonName.joins(:taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) b = TaxonName.joins(:related_taxon_name_relationships).where(taxon_name_relationships: {type: relationship}) TaxonName.from("((#{a.to_sql}) UNION (#{b.to_sql})) as taxon_names") end |
Instance Method Details
#all_taxon_name_relationships ⇒ Array
Returns all TaxonNameRelationships where this taxon is an object or subject.
664 665 666 667 668 669 670 671 672 673 674 |
# File 'app/models/taxon_name.rb', line 664 def all_taxon_name_relationships # !! If self relationships are ever made possible this needs a DISTINCT clause TaxonNameRelationship.find_by_sql( "SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.subject_taxon_name_id = #{self.id} UNION SELECT taxon_name_relationships.* FROM taxon_name_relationships WHERE taxon_name_relationships.object_taxon_name_id = #{self.id}") end |
#ancestor_at_rank(rank, include_self = false) ⇒ TaxonName?
TODO: replace with @taxonomy
640 641 642 643 644 645 646 647 648 649 |
# File 'app/models/taxon_name.rb', line 640 def ancestor_at_rank(rank, include_self = false) if target_code = (is_combination? ? combination_taxon_names.first.nomenclatural_code : nomenclatural_code) r = Ranks.lookup(target_code, rank) return self if include_self && (rank_class.to_s == r) ancestors.with_rank_class( r ).first # @taxonomy here else # Root has no nomenclature code return nil end end |
#ancestor_hash ⇒ Object
Returns Hash { ‘family’ => ‘Aidae’, …}.
1320 1321 1322 1323 1324 1325 1326 |
# File 'app/models/taxon_name.rb', line 1320 def ancestor_hash h = {} safe_self_and_ancestors.each do |n| h[n.rank] = n.name end h end |
#ancestor_protonyms ⇒ Array of TaxonName
Returns ancestors of type ‘Protonym’.
946 947 948 |
# File 'app/models/taxon_name.rb', line 946 def ancestor_protonyms Protonym.ancestors_of(self) end |
#ancestors_through_parents(result = [self], start = self) ⇒ Array
Returns of TaxonName same as self.ancestors.to_a, but also works
for new records when parents specified.
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 |
# File 'app/models/taxon_name.rb', line 1270 def ancestors_through_parents(result = [self], start = self) if start.parent.nil? return result.reverse elsif result.include?(start.parent) raise TaxonWorks::Error, 'parents contain infinfinte loop' else result << start.parent ancestors_through_parents(result, start.parent) end end |
#author_string ⇒ String?
Important, string format priority is
1) as provided verbatim
2) as generated from People
3) as taken from the Source
Source People (Authors)
Source Verbatim authors
694 695 696 697 698 699 700 701 702 |
# File 'app/models/taxon_name.rb', line 694 def return if !.nil? if .any? return Utilities::Strings.( .pluck(:last_name) ) end return source. if !source.nil? nil end |
#cached_html_name_and_author_year ⇒ String
TODO: helper/render?
893 894 895 |
# File 'app/models/taxon_name.rb', line 893 def [cached_html, ].compact.join(' ') end |
#cached_html_original_name_and_author_year ⇒ String
Returns combination of cached_original_combination_html and original_author_year.
899 900 901 |
# File 'app/models/taxon_name.rb', line 899 def [cached_original_combination_html, ].compact.join(' ') end |
#cached_name_and_author_year ⇒ String
Returns combination of cached and cached_author_year.
904 905 906 |
# File 'app/models/taxon_name.rb', line 904 def [cached, ].compact.join(' ') end |
#check_for_children ⇒ Object (protected)
1768 1769 1770 1771 1772 1773 1774 1775 |
# File 'app/models/taxon_name.rb', line 1768 def check_for_children if leaf? true else errors.add(:base, 'This taxon has children names attached, delete those first.') throw :abort end end |
#check_new_parent_class ⇒ Object (protected)
TODO: deprecate here we eliminate TaxonName.new() (is present in Protonym already
1788 1789 1790 1791 1792 1793 1794 1795 1796 |
# File 'app/models/taxon_name.rb', line 1788 def check_new_parent_class if is_protonym? && parent_id != parent_id_was && !parent_id_was.nil? && nomenclatural_code == :iczn if old_parent = TaxonName.find_by(id: parent_id_was) if (rank_name == 'subgenus' || rank_name == 'subspecies') && old_parent.name == name errors.add(:parent_id, "The nominotypical #{rank_name} #{name} can not be moved out of the nominal #{old_parent.rank_name}") end end end end |
#check_new_rank_class ⇒ Object (protected)
Note- prior version prevented groups from moving when set in error, and was far too strict
1806 1807 1808 1809 1810 1811 1812 1813 1814 |
# File 'app/models/taxon_name.rb', line 1806 def check_new_rank_class if (rank_class != rank_class_was) && !rank_class_was.nil? if rank_class_was == 'NomenclaturalRank' && rank_class_changed? errors.add(:rank_class, 'Root can not have a new rank') return end end end |
#classification_invalid_or_unavailable? ⇒ Boolean
Returns whether this name has any classification asserting that this the name is NOT valid or that it is unavailable.
969 970 971 |
# File 'app/models/taxon_name.rb', line 969 def classification_invalid_or_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).any? end |
#classification_unavailable? ⇒ Boolean
Returns whether this name has any classification asserting that this the name is unavailable.
975 976 977 |
# File 'app/models/taxon_name.rb', line 975 def classification_unavailable? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE).any? end |
#classification_valid? ⇒ Boolean
Returns true if this name has any classification asserting that it is valid.
963 964 965 |
# File 'app/models/taxon_name.rb', line 963 def classification_valid? taxon_name_classifications.with_type_array(TAXON_NAME_CLASS_NAMES_VALID).any? # !TaxonNameClassification.where_taxon_name(self).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? end |
#clear_cached(update: false) ⇒ Object
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 |
# File 'app/models/taxon_name.rb', line 1140 def clear_cached(update: false) assign_attributes( cached_html: nil, cached_author_year: nil, cached_author: nil, cached_original_combination_html: nil, cached_secondary_homonym: nil, cached_primary_homonym: nil, cached_secondary_homonym_alternative_spelling: nil, cached_primary_homonym_alternative_spelling: nil, cached_misspelling: nil, cached_classified_as: nil, cached: nil, cached_valid_taxon_name_id: nil, cached_is_valid: nil, cached_original_combination: nil, cached_nomenclature_date: nil ) save if update end |
#combination_list_all ⇒ Array of Protonym
Returns All of the names this name has been in combination with.
873 874 875 |
# File 'app/models/taxon_name.rb', line 873 def combination_list_all taxon_name_relationships.with_type_base('TaxonNameRelationship::Combination').collect {|r| r.object_taxon_name}.uniq end |
#combination_list_self ⇒ Array of Protonym
Returns for all names this name has been in combination with, select those names that are of the same rank (!! CONFIRM?).
879 880 881 |
# File 'app/models/taxon_name.rb', line 879 def combination_list_self combination_list_all.select{|c| c.protonyms_by_rank[c.protonyms_by_rank.keys.last] == self} end |
#combined_statuses ⇒ Array of String
Returns the unique string labels derived from both TaxonNameClassifications and TaxonNameRelationships.
867 868 869 |
# File 'app/models/taxon_name.rb', line 867 def combined_statuses (statuses_from_classifications + statuses_from_relationships).uniq.sort end |
#create_otu ⇒ Object
1645 1646 1647 |
# File 'app/models/taxon_name.rb', line 1645 def create_otu Otu.create(by: creator, project_id:, taxon_name_id: id) end |
#descendant_protonyms ⇒ Array of TaxonName
Returns descendants of type ‘Protonym’.
951 952 953 |
# File 'app/models/taxon_name.rb', line 951 def descendant_protonyms Protonym.descendants_of(self) end |
#dwc_occurrences ⇒ Object
1136 1137 1138 |
# File 'app/models/taxon_name.rb', line 1136 def dwc_occurrences ::Queries::DwcOccurrence::Filter.new(taxon_name_id: id).all end |
#first_possible_invalid_taxan_name_relationship ⇒ Object
TODO: Write test
1063 1064 1065 1066 |
# File 'app/models/taxon_name.rb', line 1063 def first_possible_invalid_taxan_name_relationship # TaxonNameRelationship.youngest(taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID)) # .reload taxon_name_relationships.reload.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_INVALID).youngest_by_citation end |
#first_possible_valid_taxon_name ⇒ TaxonName
Returns the youngest #object_taxon_name from the youngest taxon name relationship.
1070 1071 1072 1073 1074 |
# File 'app/models/taxon_name.rb', line 1070 def first_possible_valid_taxon_name return self if !unavailable_or_invalid? # catches all cases where no Classifications or Relationships are provided relationship = first_possible_valid_taxon_name_relationship relationship.nil? ? self : relationship.object_taxon_name # ?! probably the if is caught by unavailable_or_invalid already end |
#first_possible_valid_taxon_name_relationship ⇒ TaxonNameRelationship
TODO: write test
1055 1056 1057 1058 1059 1060 |
# File 'app/models/taxon_name.rb', line 1055 def first_possible_valid_taxon_name_relationship # TaxonNameRelationship.youngest( # taxon_name_relationships.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) # .reload # ) taxon_name_relationships.reload.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).youngest_by_citation end |
#full_name ⇒ String?
Returns nil for Higher names
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 |
# File 'app/models/taxon_name.rb', line 1414 def full_name d = full_name_hash # @taxonomy ? elements = [] elements.push(d['genus']) unless (not_binominal? && d['genus'][1] == '[GENUS NOT SPECIFIED]') elements.push ['(', d['subgenus'], ')'] elements.push ['(', d['infragenus'], ')'] if rank_name == 'infragenus' elements.push ['(', d['supergenus'], ')'] if rank_name == 'supergenus' elements.push ['(', d['supersubgenus'], ')'] if rank_name == 'supersubgenus' elements.push ['(', d['supersupersubgenus'], ')'] if rank_name == 'supersupersubgenus' elements.push [d['supersuperspecies']] if rank_name == 'supersuperspecies' elements.push [d['superspecies']] if rank_name == 'superspecies' elements.push [d['subsuperspecies']] if rank_name == 'subsuperspecies' elements.push(d['species'], d['subspecies'], d['variety'], d['subvariety'], d['form'], d['subform']) elements = elements.flatten.compact.join(' ').gsub(/\(\s*\)/, '').gsub(/\(\s/, '(').gsub(/\s\)/, ')').squish elements.presence end |
#full_name_array ⇒ rank, ...
“section”=>[“sect.”, “Aus”], “series”=>[“ser.”, “Aus”], “species”=>[nil, “aaa”], “subspecies”=>[nil, “bbb”], “variety”=>[“var.”, “ccc”]}
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 |
# File 'app/models/taxon_name.rb', line 1306 def full_name_array gender = nil data = [] safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' method = "#{rank.gsub(/\s/, '_')}_name_elements" data.push([rank] + send(method, i, gender)) if self.respond_to?(method) end data end |
#full_name_hash ⇒ Object
!! TODO: Higher classification does not follow the same pattern !! TODO: when name is a subgenus will not grab genus (still true?)
Conceptually there are 2 objects required to build @taxonomy, one for the scientific name, the other for the higher taxa. These need to be kept seperately in terms of optimizing queries, or at least isolatable if combined.
This method covers scientific name, gathering all string elements, including ‘sic’ etc., and pointing to them by rank. It therefor sits between model/helper.
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 |
# File 'app/models/taxon_name.rb', line 1354 def full_name_hash gender = nil data = {} safe_self_and_ancestors.each do |i| rank = i.rank gender = i.gender_name if rank == 'genus' if i.is_genus_or_species_rank? if ['genus', 'subgenus', 'species', 'subspecies'].include?(rank) && rank_string =~ /Iczn/ data[rank] = [nil, i.name_with_misspelling(gender)] elsif ['genus', 'subgenus', 'species'].include?(rank) data[rank] = [nil, i.name_with_misspelling(gender)] else data[rank] = [i.rank_class.abbreviation, i.name_with_misspelling(gender)] end else data[rank] = i.name end end # Only check for these ranks if COMBINATION_ELEMENTS.include?(rank.to_sym) if data['genus'].nil? if original_genus data['genus'] = [nil, "[#{original_genus&.name}]"] else data['genus'] = [nil, '[GENUS NOT SPECIFIED]'] end end if data['species'].nil? && (!data['subspecies'].nil? || !data['variety'].nil? || !data['subvariety'].nil? || !data['form'].nil? || !data['subform'].nil?) data['species'] = [nil, '[SPECIES NOT SPECIFIED]'] end if !data['subvariety'].nil? && data['variety'].nil? data['variety'] = [nil, '[VARIETY NOT SPECIFIED]'] end if !data['subform'].nil? && data['form'].nil? data['form'] = [nil, '[FORM NOT SPECIFIED]'] end end data end |
#gbif_status_array ⇒ Object
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 |
# File 'app/models/taxon_name.rb', line 1105 def gbif_status_array return nil if self.class.nil? return ['combination'] if self.class == 'Combination' s1 = taxon_name_classifications.collect{|c| c.class.gbif_status}.compact return s1 unless s1.empty? s2 = taxon_name_relationships.collect{|r| r.class.gbif_status_of_subject} s3 = .collect{|r| r.class.gbif_status_of_object} s = s2 + s3 s.compact! return ['valid'] if s.empty? s end |
#gender_class ⇒ Class?
Returns gender of a genus as class.
810 811 812 |
# File 'app/models/taxon_name.rb', line 810 def gender_class gender_instance.try(:type_class) end |
#gender_instance ⇒ TaxonNameClassification instance?
Returns the gender classification of this name, if provided.
816 817 818 |
# File 'app/models/taxon_name.rb', line 816 def gender_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::Gender').first end |
#gender_name ⇒ String?
Returns gender as a string (only applicable to Genera).
822 823 824 |
# File 'app/models/taxon_name.rb', line 822 def gender_name gender_instance.try(:classification_label).try(:downcase) end |
#genderized_name(gender = nil) ⇒ String?
1471 1472 1473 1474 1475 1476 1477 |
# File 'app/models/taxon_name.rb', line 1471 def genderized_name(gender = nil) if gender.nil? || is_genus_rank? name else name_in_gender(gender) end end |
#get_author ⇒ Object
TODO: cleanly isolate getters, setters, and cached builders TODO: remove, this is only used for a strange call in sv_checked cached.
761 762 763 |
# File 'app/models/taxon_name.rb', line 761 def .to_s.gsub(/,\s\(?\d+\)?\s\[\d+\]|,\s\(?\d+\)?/, '').gsub(') ', ', ').gsub('(', '').gsub(')', '') end |
#get_author_and_year ⇒ Object
return [String]
the author and year of the name, adds parenthesis where asserted
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 |
# File 'app/models/taxon_name.rb', line 1496 def if self.type == 'Combination' c = protonyms_by_rank return nil if c.empty? taxon = c[c.keys.last] else taxon = self end case taxon.rank_class.try(:nomenclatural_code) when :iczn ay = (taxon) when :icvcn ay = (taxon) when :icnp ay = (taxon) when :icn ay = (taxon) else ay = ([] + [cached_nomenclature_date&.year]).compact.join(' ') end (ay.presence) end |
#get_cached_classified_as ⇒ String?
1614 1615 1616 1617 1618 1619 1620 |
# File 'app/models/taxon_name.rb', line 1614 def get_cached_classified_as return nil unless is_protonym? || is_combination? # source_classified_as is a method generated through relationships r = reload_source_classified_as return " (as #{r.name})" if r.present? nil end |
#get_cached_misspelling ⇒ Object
verbatim_name should not have downstream factual consequences.
TODO: Missing specs
1244 1245 1246 1247 1248 1249 1250 1251 1252 |
# File 'app/models/taxon_name.rb', line 1244 def get_cached_misspelling misspelling = taxon_name_relationships.with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_ONLY).first unless misspelling.nil? n1 = verbatim_name? ? verbatim_name : name n2 = misspelling.object_taxon_name.verbatim_name? ? misspelling.object_taxon_name.verbatim_name : misspelling.object_taxon_name.name return true if n1 != n2 end nil end |
#get_full_name ⇒ String?
Returns A monominal if names is above genus, or a full epithet if below. Does not include author_year. Does not include HTML.
!! Combination has its own version now.
1406 1407 1408 1409 1410 |
# File 'app/models/taxon_name.rb', line 1406 def get_full_name return name_with_misspelling(nil) if !is_genus_or_species_rank? return name if rank_class.to_s =~ /Icvcn/ full_name end |
#get_full_name_html(name = nil) ⇒ Object
Returns String.
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 |
# File 'app/models/taxon_name.rb', line 1437 def get_full_name_html(name = nil) name = get_full_name if name.nil? return "\"<i>Candidatus</i> #{name}\"" if is_candidatus? if name.present? && is_hybrid? w = name.split(' ') w[-1] = ('×' + w[-1]).gsub('×(', '(×') name = w.join(' ') end m = name m = Utilities::Italicize.taxon_name(name) if is_italicized? m = '† ' + m if is_fossil? m end |
#get_genus_species(genus_option, self_option) ⇒ Object
return [String, nil, false] # TODO: fix
1480 1481 1482 1483 |
# File 'app/models/taxon_name.rb', line 1480 def get_genus_species(genus_option, self_option) # see Protonym true end |
#get_original_combination ⇒ Object
Stub, see subclasses TaxonNameRelationships call it for Combinations
1256 1257 1258 |
# File 'app/models/taxon_name.rb', line 1256 def get_original_combination nil end |
#get_original_combination_html ⇒ Object
Stub, see subclasses
only Protonym, but TaxonNameRelationships call it for Combinations
1262 1263 1264 |
# File 'app/models/taxon_name.rb', line 1262 def get_original_combination_html nil end |
#get_valid_taxon_name ⇒ TaxonName
Returns a valid taxon_name for an invalid name or self for valid name. a stub here - See Protonym and Combination.
1048 1049 1050 |
# File 'app/models/taxon_name.rb', line 1048 def get_valid_taxon_name nil end |
#icn_author_and_year(taxon) ⇒ Object
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 |
# File 'app/models/taxon_name.rb', line 1520 def (taxon) ay = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) originally_invalid = TaxonNameRelationship.where_object_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Icn::Unaccepting::OriginallyInvalid').first m_obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name mobj = misspelling.empty? ? taxon : misspelling.first.object_taxon_name ay = mobj.try(:author_string) # author string for basionym if self.type == 'Combination' cc = self else current_combination = TaxonNameRelationship.where_object_is_taxon_name(mobj).with_type_string('TaxonNameRelationship::CurrentCombination') cc = current_combination.empty? ? self : current_combination.first.subject_taxon_name end unless originally_invalid.nil? ay = originally_invalid.subject_taxon_name.try(:author_string).to_s + ' ex ' + ay.to_s end if self..present? && mobj.id != cc.id ay = '(' + ay.to_s + ') ' + cc.try(:author_string).to_s end if !misapplication.empty? && m_obj..present? ay += ' non ' + m_obj. end (ay.presence) end |
#iczn_author_and_year(taxon) ⇒ String?
Returns the authors, and year, with parentheses as inferred by the data.
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 |
# File 'app/models/taxon_name.rb', line 1553 def (taxon) ay = nil p = nil misapplication = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_string('TaxonNameRelationship::Iczn::Invalidating::Misapplication') misspelling = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_STRING) mobj = misspelling.empty? ? nil : misspelling.first.object_taxon_name if mobj.present? a = [mobj.try(:author_string)] y = [mobj.try(:year_integer)] else a = [taxon.try(:author_string)] y = [taxon.try(:year_integer)] end if a[0] =~ /^\(.+\)$/ # (Author) a[0] = a[0][1..-2] ## remove parentheses in the author string # TODO: draw from cached_author p = true else p = false end ay = (a + y).compact.join(', ') obj = misapplication.empty? ? nil : misapplication.first.object_taxon_name if SPECIES_RANK_NAMES_ICZN.include?(taxon.rank_string) if p ay = '(' + ay + ')' unless ay.empty? else og = taxon.original_genus if self.type == 'Combination' cg = genus else par = TaxonNameRelationship.where_subject_is_taxon_name(taxon).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING_AUTHOR_PARENTHESES).any? cg = (par == false && !misspelling.empty?) ? og : ancestor_at_rank('genus') end if !og.nil? && !cg.nil? ay = '(' + ay + ')' if !ay.empty? && og.normalized_genus.id != cg.normalized_genus.id end end elsif FAMILY_RANK_NAMES_ICZN.include?(taxon.rank_string) && !y.empty? && cached_nomenclature_date&.year != y.first && !mobj.present? ay = ay + ' [' + cached_nomenclature_date&.year.to_s + ']' ay = ay.gsub(' []', '') end unless misapplication.empty? || obj..blank? ay += ' non ' + ([obj.] + [obj.year_integer]).compact.join(', ') end (ay.presence) end |
#is_ambiguously_invalid? ⇒ Boolean
Has Classification, but no relationship describing why
995 996 997 |
# File 'app/models/taxon_name.rb', line 995 def is_ambiguously_invalid? !is_valid? && (id == cached_valid_taxon_name_id) end |
#is_candidatus? ⇒ True|False
Returns true if this name has a TaxonNameClassification of candidatus.
1028 1029 1030 1031 |
# File 'app/models/taxon_name.rb', line 1028 def is_candidatus? return false unless rank_string =~ /Icnp/ taxon_name_classifications.with_type_contains('Candidatus').any? end |
#is_combination? ⇒ Boolean
1009 1010 1011 |
# File 'app/models/taxon_name.rb', line 1009 def is_combination? type == 'Combination' end |
#is_fossil? ⇒ True|False
Returns true if this name has a TaxonNameClassification of Fossil.
1015 1016 1017 |
# File 'app/models/taxon_name.rb', line 1015 def is_fossil? taxon_name_classifications.with_type_contains('::Fossil').any? end |
#is_genus_or_species_rank? ⇒ Boolean
Returns see subclasses.
1041 1042 1043 |
# File 'app/models/taxon_name.rb', line 1041 def is_genus_or_species_rank? false end |
#is_hybrid? ⇒ Boolean
TODO: ultimately deprecate for type Hybrid names.
1022 1023 1024 |
# File 'app/models/taxon_name.rb', line 1022 def is_hybrid? taxon_name_classifications.with_type_contains('Hybrid').any? end |
#is_italicized? ⇒ Boolean
Returns whether this name needs italics applied.
1001 1002 1003 |
# File 'app/models/taxon_name.rb', line 1001 def is_italicized? is_genus_or_species_rank? || kind_of?(Combination) || kind_of?(Hybrid) end |
#is_protonym? ⇒ Boolean
1005 1006 1007 |
# File 'app/models/taxon_name.rb', line 1005 def is_protonym? type == 'Protonym' end |
#is_valid? ⇒ Boolean
Returns after all inference on the validity of a name, the result is stored in cached_valid_taxon_name_id, #is_valid checks that result.
990 991 992 |
# File 'app/models/taxon_name.rb', line 990 def is_valid? cached_is_valid end |
#list_of_invalid_taxon_names ⇒ Array of TaxonName
Can’t we just use #valid_id now? DD: no this is used for validation of multiple conflicting relationships
this list does not return Combinations
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 |
# File 'app/models/taxon_name.rb', line 1081 def list_of_invalid_taxon_names first_pass = true list = {} while first_pass || !list.keys.select{|t| list[t] == false}.empty? do first_pass = false list_of_taxa_to_check = list.empty? ? [self] : list.keys.select{|t| list[t] == false} list_of_taxa_to_check.each do |t| potentialy_invalid_relationships = t..with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).order_by_oldest_source_first potentialy_invalid_relationships.each do |r| if !TaxonNameClassification.where_taxon_name(r.subject_taxon_name).with_type_array(TAXON_NAME_CLASS_NAMES_VALID).empty? # do nothing, taxon has a status of valid name elsif r == r.subject_taxon_name.first_possible_valid_taxon_name_relationship list[r.subject_taxon_name] = false if list[r.subject_taxon_name].nil? end end list[t] = true if list[t] == false end end return [] if list.empty? list.sort_by{|t, a| (t.cached_nomenclature_date&.to_time || Time.zone.now)}.collect{|t, a| t} end |
#matrix_row_item ⇒ {"matrix_row_item": matrix_column_item, "object": object}, false
See Shared::MatrixHooks the hash corresponding to the keyword used in this tag if it exists !! Assumes it can only be in one matrix, this is wrong !!
1714 1715 1716 1717 1718 1719 1720 1721 1722 |
# File 'app/models/taxon_name.rb', line 1714 def matrix_row_item mri = ObservationMatrixRowItem::TaxonNameRowItem.where(taxon_name_id: id, project_id:).limit(1) if mri.any? return { matrix_row_item: mri.first, object: taxon_name } else return false end end |
#merge_to(to_taxon_name, kind) ⇒ Object
TODO: Deprecate/remove for .unify()
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 |
# File 'app/models/taxon_name.rb', line 1737 def merge_to(to_taxon_name, kind) @result = { failed: 0, passed: 0, kind: } case kind when :taxon_name_relationships all_taxon_name_relationships.each do |r| begin if r.subject_taxon_name_id == id r.update!(subject_taxon_name: to_taxon_name) elsif r.object_taxon_name_id == id r.update!(object_taxon_name: to_taxon_name) else @result[:failed] += 1 end @result[:passed] += 1 rescue ActiveRecord::RecordInvalid @result[:failed] += 1 end end else end @result end |
#minimum_invalidating_year ⇒ Object
743 744 745 |
# File 'app/models/taxon_name.rb', line 743 def minimum_invalidating_year [ taxon_name_classification_minimum_invalidating_year, taxon_name_relationship_minimum_invalidating_year ].compact.sort.first end |
#minimum_years_valid ⇒ Object
747 748 749 750 751 752 753 754 |
# File 'app/models/taxon_name.rb', line 747 def minimum_years_valid a = [year_integer, minimum_invalidating_year].compact if a.size == 2 a.second - a.first else nil end end |
#name_in_gender(gender = nil) ⇒ Object
Returns String, nil then name according to the gender requested.
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 |
# File 'app/models/taxon_name.rb', line 1122 def name_in_gender(gender = nil) case gender when 'masculine' n = masculine_name when 'feminine' n = feminine_name when 'neuter' n = neuter_name else n = nil end n.presence || name end |
#name_is_misapplied?(relationships = nil) ⇒ Boolean
TODO: needs test return [Boolean]
whether there is an ICZN missapplication relationship present on this name
1488 1489 1490 1491 1492 |
# File 'app/models/taxon_name.rb', line 1488 def name_is_misapplied?(relationships = nil ) relationships ||= taxon_name_relationships return true if relationships.pluck(:type).include?('TaxonNameRelationship::Iczn::Invalidating::Misapplication') false end |
#name_with_misspelling(gender) ⇒ String
Returns TODO: does this form of the name contain parens for subgenus? TODO: provide a default to gender (but do NOT eliminate param) TODO: on third thought- eliminate this mess.
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 |
# File 'app/models/taxon_name.rb', line 1456 def name_with_misspelling(gender) if cached_misspelling if rank_string =~ /Icnp/ name_in_gender(gender).to_s + ' (sic)' else name_in_gender(gender).to_s + ' [sic]' end elsif gender.nil? || rank_string =~ /Genus/ name.to_s else name_in_gender(gender).to_s end end |
#next_sibling ⇒ Object
TODO: this should be paginated, not all IDs!
1623 1624 1625 1626 1627 1628 1629 1630 1631 |
# File 'app/models/taxon_name.rb', line 1623 def next_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[ s + 1] ) if s < sibs.length - 1 else nil end end |
#nomeclatural_history ⇒ array
returns array of hashes for history of taxon. Could be used for catalogue construction. Belongs in catatlog or helper
794 795 796 797 798 799 800 801 802 803 804 805 806 |
# File 'app/models/taxon_name.rb', line 794 def nomeclatural_history history = [] TaxonName.where(cached_valid_taxon_name_id: self.id).order(:cached_nomenclature_date).each do |t| item = {} = t.is_combination? ? [t.origin_citation&.source&., t.origin_citation&.source&.year].join(', ') : nil = ' in ' + unless .nil? item[:name] = t.is_combination? ? t.cached_html : t.cached_original_combination_html item[:author_year] = t.is_combination? ? t. + : t. item[:statuses] = t.combined_statuses history.append(item) end return history end |
#nomenclature_date ⇒ Time
!! Overrides and references Shared::Citations#nomenclature_date
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 |
# File 'app/models/taxon_name.rb', line 769 def nomenclature_date return nil if !persisted? if is_protonym? if is_family_rank? family_before_1961 = TaxonNameRelationship::Iczn::PotentiallyValidating::FamilyBefore1961.where_subject_is_taxon_name(self).first end end if family_before_1961.nil? if a = source_nomenclature_date # Alias for nomenclature_date in shared/citations.rb a else year_of_publication ? Time.utc(year_of_publication, 12, 31) : nil end else obj = family_before_1961.object_taxon_name year = obj.year_of_publication ? Time.utc(obj.year_of_publication, 12, 31) : nil b = obj.source_nomenclature_date b ? b : year end end |
#normalized_genus ⇒ Object
Returns Protonym.
1607 1608 1609 1610 1611 |
# File 'app/models/taxon_name.rb', line 1607 def normalized_genus misspelling = TaxonNameRelationship.where_subject_is_taxon_name(self).with_type_array(TAXON_NAME_RELATIONSHIP_NAMES_MISSPELLING) tn = misspelling.empty? ? self : misspelling.first.object_taxon_name return tn.lowest_rank_coordinated_taxon end |
#not_binominal? ⇒ True|False
Returns true if this name has a TaxonNameClassification of not_binominal.
1035 1036 1037 |
# File 'app/models/taxon_name.rb', line 1035 def not_binominal? taxon_name_classifications.with_type_contains('NonBinominal').any? end |
#original_author_year ⇒ String?
Returns Derived from cached_author_year The intent is to remove outer parens for an original combination.
!! DO NOT USE IN BUILDING CACHED !!
See also app/helpers/taxon_names_helper
!! TODO: needs tests badly
!? TODO: cached_author_year should not include `non` likely
!! i.e. it currently differs from cached_author + cached_nomenclature_date.year.
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 |
# File 'app/models/taxon_name.rb', line 918 def return nil unless case nomenclatural_code when :iczn # Only remove if first and last paren if like this: # (Baker, 1899) # Not like this: # (Baker, 1899) non Gillette, 1898 return if cached_misspelling if =~ /^\((.*)\)$/ return $1 end when :icn # TODO: example text in spec if matchdata1 = .match(/(\(.*\))/) return matchdata1[1].gsub(/^\(|\)/, '') end end # This means that misaplied or misspelled names return cached author year end |
#out_of_scope_combinations ⇒ Object
628 629 630 631 632 |
# File 'app/models/taxon_name.rb', line 628 def out_of_scope_combinations ::TaxonName .where(project_id:) .out_of_scope_combinations(id) end |
#part_of_speech_class ⇒ Class
Returns part of speech of a species as class.
828 829 830 |
# File 'app/models/taxon_name.rb', line 828 def part_of_speech_class part_of_speech_instance.try(:type_class) end |
#part_of_speech_instance ⇒ Object
832 833 834 |
# File 'app/models/taxon_name.rb', line 832 def part_of_speech_instance taxon_name_classifications.with_type_base('TaxonNameClassification::Latinized::PartOfSpeech').first end |
#part_of_speech_name ⇒ String
Returns part of speech of a species as string.
838 839 840 |
# File 'app/models/taxon_name.rb', line 838 def part_of_speech_name part_of_speech_instance.try(:classification_label).try(:downcase) end |
#previous_sibling ⇒ Object
TODO: this should be paginated, not all IDs!
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 |
# File 'app/models/taxon_name.rb', line 1634 def previous_sibling if siblings.where(project_id:).any? sibs = self_and_siblings.order(:cached).pluck(:id) s = sibs.index(id) TaxonName.find(sibs[s - 1]) if s != 0 else nil end end |
#rank ⇒ String
Returns rank as human readable short-form, like ‘genus’ or ‘species’.
606 607 608 |
# File 'app/models/taxon_name.rb', line 606 def rank ::RANKS.include?(rank_string) ? rank_name : nil end |
#rank_string ⇒ String
Returns rank (Kindom, Phylum…) as a string, like NomenclaturalRank::Iczn::SpeciesGroup::Species.
612 613 614 |
# File 'app/models/taxon_name.rb', line 612 def rank_string read_attribute(:rank_class) end |
#reified_id ⇒ Object
a reified ID is used when the original combination, which does not yet have it’s own ID, is not the same as the current classification Some observations:
- reified ids are only for original combinations (for which we have no ID)
- reified ids never reference gender changes because they are always in context of original combination, i.e. there is never a gender change
Mental note- consider combination - is_current_placement? (presently excluded in CoL code, which is the correct place to decide that.) Duplicated in COLDP export code
1730 1731 1732 1733 1734 |
# File 'app/models/taxon_name.rb', line 1730 def reified_id return id.to_s if is_combination? return id.to_s unless has_alternate_original? id.to_s + '-' + Digest::MD5.hexdigest(cached_original_combination) end |
#related_taxon_names ⇒ Array of TaxonName
Returns all taxon_names which have relationships to this taxon as an object or subject.
678 679 680 681 682 683 684 |
# File 'app/models/taxon_name.rb', line 678 def TaxonName.find_by_sql( "SELECT tn.* from taxon_names tn join taxon_name_relationships tnr1 on tn.id = tnr1.subject_taxon_name_id and tnr1.object_taxon_name_id = #{self.id} UNION SELECT tn.* from taxon_names tn join taxon_name_relationships tnr2 on tn.id = tnr2.object_taxon_name_id and tnr2.subject_taxon_name_id = #{self.id}" ) end |
#relationship_invalid? ⇒ Boolean
Returns true if there is a relationship where then name is asserted to be invalid.
957 958 959 |
# File 'app/models/taxon_name.rb', line 957 def relationship_invalid? !first_possible_invalid_taxan_name_relationship.nil? end |
#relationships(rebuild = false) ⇒ Object
573 574 575 576 577 578 579 |
# File 'app/models/taxon_name.rb', line 573 def relationships(rebuild = false) if rebuild @relationships = taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a else @relationships ||= taxon_name_relationships.eager_load(:subject_taxon_name, :object_taxon_name).to_a end end |
#reload ⇒ Object
NOT USED attr_accessor :relationships
212 213 214 215 216 217 218 |
# File 'app/models/taxon_name.rb', line 212 def reload(*) super.tap do @related_relationships = nil @taxonomy = nil # @relationships = nil end end |
#safe_self_and_ancestors ⇒ Array of TaxonName
TODO: Integrate with Taxonomy?
Taxonomy.values
Uses parent recursion when record is new and awesome_nested_set index is not yet usable.
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 |
# File 'app/models/taxon_name.rb', line 1290 def safe_self_and_ancestors if new_record? ancestors_through_parents else self_and_ancestors .unscope(:order) .order(generations: :DESC) .to_a end end |
#set_cached ⇒ Object
TODO: We need to isolate this into 2 subclasses, 1 - cached methods that touch author/year 2 - cached methods that do not
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 |
# File 'app/models/taxon_name.rb', line 1164 def set_cached return true if destroyed? n = get_full_name # memoize/var into taxonomy? update_column(:cached, n) # This isn't true according to tests, will be removed shortly. # Import and in-memory requirements should use other checks/auditing. # # Combination should have its own cached setting methods # We can't use the in-memory cache approach for Combinations, force reload each time # n = nil if is_combination? update_columns( cached_html: get_full_name_html(n) ) # one more query, but can be isolated now set_cached_nomenclature_date # Dependent on TaxonNameClassification and TaxonNameRelationship # !! Technically these should not be here. # TODO: Isolate and optimize. These an be isolated as they are not always pertinent to a generalized cascading cache setting # For example, when a TaxonName relationship forces a cached reload it may/not need to call these two things set_cached_valid_taxon_name_id set_cached_is_valid set_cached_classified_as end |
#set_cached_author ⇒ Object
1232 1233 1234 |
# File 'app/models/taxon_name.rb', line 1232 def update_column(:cached_author, ) end |
#set_cached_author_columns ⇒ Object
See TaxonNameAuthor
1201 1202 1203 1204 1205 1206 |
# File 'app/models/taxon_name.rb', line 1201 def # TODO: build author year from cached author and year, not the other way around # * at this point we have already updated date # should be after the 'set_cached_author_year end |
#set_cached_author_year ⇒ Object
1228 1229 1230 |
# File 'app/models/taxon_name.rb', line 1228 def update_column(:cached_author_year, ) end |
#set_cached_classified_as ⇒ Object
1236 1237 1238 |
# File 'app/models/taxon_name.rb', line 1236 def set_cached_classified_as update_column(:cached_classified_as, get_cached_classified_as) end |
#set_cached_is_valid ⇒ Object
1212 1213 1214 1215 |
# File 'app/models/taxon_name.rb', line 1212 def set_cached_is_valid v = is_combination? ? false : !unavailable_or_invalid? update_column(:cached_is_valid, v) end |
#set_cached_nomenclature_date ⇒ Object
1196 1197 1198 |
# File 'app/models/taxon_name.rb', line 1196 def set_cached_nomenclature_date update_columns(cached_nomenclature_date: nomenclature_date) end |
#set_cached_valid_taxon_name_id ⇒ Object
1208 1209 1210 |
# File 'app/models/taxon_name.rb', line 1208 def set_cached_valid_taxon_name_id update_column(:cached_valid_taxon_name_id, get_valid_taxon_name.id) end |
#set_cached_warnings ⇒ Object
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 |
# File 'app/models/taxon_name.rb', line 1217 def set_cached_warnings update_columns( cached: NO_CACHED_MESSAGE, cached_author_year: NO_CACHED_MESSAGE, cached_author: NO_CACHED_MESSAGE, cached_nomenclature_date: NO_CACHED_MESSAGE, cached_classified_as: NO_CACHED_MESSAGE, cached_html: NO_CACHED_MESSAGE ) end |
#statuses_from_classifications ⇒ Array of String
Returns the unique string labels (human readable) derived from TaxonNameClassifications.
844 845 846 847 |
# File 'app/models/taxon_name.rb', line 844 def statuses_from_classifications list = taxon_name_classifications_for_statuses list.empty? ? [] : list.collect{|c| c.classification_label }.sort end |
#statuses_from_relationships ⇒ Array of String
Returns the unique string labels derived from and TaxonNameRelationships.
860 861 862 863 |
# File 'app/models/taxon_name.rb', line 860 def statuses_from_relationships list = taxon_name_relationships.with_type_array(STATUS_TAXON_NAME_RELATIONSHIP_NAMES) list.empty? ? [] : list.collect{|c| c.subject_status}.sort end |
#sv_cached_names ⇒ Object (protected)
1951 1952 1953 |
# File 'app/models/taxon_name.rb', line 1951 def sv_cached_names true # see validation in subclasses end |
#sv_combination_duplicates ⇒ Object (protected)
2003 2004 2005 |
# File 'app/models/taxon_name.rb', line 2003 def sv_combination_duplicates true # see validation in Combination.rb end |
#sv_conflicting_subordinate_taxa ⇒ Object (protected)
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 |
# File 'app/models/taxon_name.rb', line 1899 def sv_conflicting_subordinate_taxa classifications = self.taxon_name_classifications.reload classification_names = classifications.map { |i| i.type_name } compare = TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & classification_names unless compare.empty? unless Protonym.with_parent_taxon_name(self).without_taxon_name_classification_array(TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).empty? compare.each do |i| # taxon is unavailable or invalid, but has valid children soft_validations.add(:base, "Taxon has a status ('#{i.safe_constantize.label}') conflicting with presence of subordinate taxa") end end end end |
#sv_fix_cached_names ⇒ Object (protected)
TODO: This can be made more specific, we don’t need to call some of the methods in set_cached It also should never be required.
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 |
# File 'app/models/taxon_name.rb', line 1915 def sv_fix_cached_names begin TaxonName.transaction do self.set_cached end true rescue false end end |
#sv_fix_parent_is_valid_name ⇒ Object (protected)
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 |
# File 'app/models/taxon_name.rb', line 1874 def sv_fix_parent_is_valid_name res = false if self.parent.unavailable_or_invalid? new_parent = self.parent.get_valid_taxon_name if self.parent != new_parent self.parent = new_parent if self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::GenusGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::SpeciesGroup::Subspecies' self.rank_class = 'NomenclaturalRank::Iczn::SpeciesGroup::Species' elsif self.parent.rank_class.parent.to_s == 'NomenclaturalRank::Iczn::FamilyGroup' && self.rank_class.to_s == 'NomenclaturalRank::Iczn::GenusGroup::Subgenus' self.rank_class = 'NomenclaturalRank::Iczn::GenusGroup::Genus' end # TODO: This doesn't ever hit rescue (save doesn't raise), and save can be invalid, and therefor false not true? begin TaxonName.transaction do self.save res = true end rescue end end end res end |
#sv_homotypic_synonyms ⇒ Object (protected)
1995 1996 1997 |
# File 'app/models/taxon_name.rb', line 1995 def sv_homotypic_synonyms true # see validation in Protonym.rb end |
#sv_hybrid_name_relationships ⇒ Object (protected)
2007 2008 2009 |
# File 'app/models/taxon_name.rb', line 2007 def sv_hybrid_name_relationships true # see validation in Hybrid.rb end |
#sv_incomplete_combination ⇒ Object (protected)
1942 1943 1944 1945 1946 1947 1948 1949 |
# File 'app/models/taxon_name.rb', line 1942 def sv_incomplete_combination soft_validations.add(:base, 'The genus in the combination is not specified') if !cached.nil? && cached.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the combination is not specified') if !cached.nil? && cached.include?('SPECIES NOT SPECIFIED') soft_validations.add(:base, 'The variety in the combination is not specified') if !cached.nil? && cached.include?('VARIETY NOT SPECIFIED') soft_validations.add(:base, 'The form in the combination is not specified') if !cached.nil? && cached.include?('FORM NOT SPECIFIED') soft_validations.add(:base, 'The genus in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('GENUS NOT SPECIFIED') soft_validations.add(:base, 'The species in the original combination is not specified') if !cached_original_combination.nil? && cached_original_combination.include?('SPECIES NOT SPECIFIED') end |
#sv_missing_classifications ⇒ Object (protected)
1967 1968 1969 |
# File 'app/models/taxon_name.rb', line 1967 def sv_missing_classifications true # see validation in Protonym.rb end |
#sv_missing_confidence_level ⇒ Object (protected)
TODO: this needs to go.
1825 1826 1827 1828 1829 |
# File 'app/models/taxon_name.rb', line 1825 def sv_missing_confidence_level # should be removed once the alternative solution is implemented. It is heavily used now. confidence_level_array = [93] confidence_level_array = confidence_level_array & ConfidenceLevel.where(project_id: self.project_id).pluck(:id) soft_validations.add(:base, 'Confidence level is missing') if !confidence_level_array.empty? && (self.confidences.pluck(:confidence_level_id) & confidence_level_array).empty? end |
#sv_missing_etymology ⇒ Object (protected)
def sv_missing_author
true # see Protonym
end
def sv_missing_year
true # see Protonym
end
1864 1865 1866 |
# File 'app/models/taxon_name.rb', line 1864 def sv_missing_etymology true # see Protonym end |
#sv_missing_original_publication ⇒ Object (protected)
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 |
# File 'app/models/taxon_name.rb', line 1831 def sv_missing_original_publication if rank_class.nil? || is_family_or_genus_or_species_rank? if self.source.nil? soft_validations.add(:base, 'Original publication is not selected') elsif self.origin_citation.try(:pages).blank? soft_validations.add(:base, 'Original citation pages are not recorded') elsif self.source.pages.present? matchdata1 = self.origin_citation.pages.match(/^(\d+) ?[-–] ?(\d+)$|^(\d+)$/) if matchdata1 citMinP = matchdata1[1] ? matchdata1[1].to_i : matchdata1[3].to_i citMaxP = matchdata1[2] ? matchdata1[2].to_i : matchdata1[3].to_i matchdata = self.source.pages.match(/(\d+) ?[-–] ?(\d+)|(\d+)/) if citMinP && citMaxP && matchdata minP = matchdata[1] ? matchdata[1].to_i : matchdata[3].to_i maxP = matchdata[2] ? matchdata[2].to_i : matchdata[3].to_i minP = 1 if minP == maxP && %w{book booklet manual mastersthesis phdthesis techreport}.include?(self.source.bibtex_type) unless (maxP && minP && minP <= citMinP && maxP >= citMaxP) soft_validations.add(:base, 'Original citation could be out of the source page range') end end end end end end |
#sv_missing_relationships ⇒ Object (protected)
1959 1960 1961 |
# File 'app/models/taxon_name.rb', line 1959 def sv_missing_relationships true # see validation in Protonym.rb end |
#sv_not_synonym_of_self ⇒ Object (protected)
Required for synonyms of synomyms
1927 1928 1929 1930 1931 |
# File 'app/models/taxon_name.rb', line 1927 def sv_not_synonym_of_self if list_of_invalid_taxon_names.include?(self) soft_validations.add(:base, "Taxon has two conflicting relationships (invalidating and validating). To resolve a conflict, add a status 'Valid' to a valid taxon.") end end |
#sv_parent_is_valid_name ⇒ Object (protected)
1868 1869 1870 1871 1872 |
# File 'app/models/taxon_name.rb', line 1868 def sv_parent_is_valid_name if !parent.nil? && parent.unavailable_or_invalid? soft_validations.add(:parent_id, 'Parent should be a valid taxon', success_message: 'Parent was updated', failure_message: 'Failed to update parent') end end |
#sv_parent_priority ⇒ Object (protected)
1991 1992 1993 |
# File 'app/models/taxon_name.rb', line 1991 def sv_parent_priority true # see validation in Protonym.rb end |
#sv_potential_homonyms ⇒ Object (protected)
1999 2000 2001 |
# File 'app/models/taxon_name.rb', line 1999 def sv_potential_homonyms true # see validation in Protonym.rb end |
#sv_primary_types ⇒ Object (protected)
1975 1976 1977 |
# File 'app/models/taxon_name.rb', line 1975 def sv_primary_types true # see validation in Protonym.rb end |
#sv_single_sub_taxon ⇒ Object (protected)
1987 1988 1989 |
# File 'app/models/taxon_name.rb', line 1987 def sv_single_sub_taxon true # see validation in Protonym.rb end |
#sv_species_gender_agreement ⇒ Object (protected)
1971 1972 1973 |
# File 'app/models/taxon_name.rb', line 1971 def sv_species_gender_agreement true # see validation in Protonym.rb end |
#sv_two_unresolved_alternative_synonyms ⇒ Object (protected)
1933 1934 1935 1936 1937 1938 1939 1940 |
# File 'app/models/taxon_name.rb', line 1933 def sv_two_unresolved_alternative_synonyms r = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM) if r.to_a.size > 1 if r.first.nomenclature_date.to_date == r.second.nomenclature_date.to_date soft_validations.add(:base, 'Taxon has two alternative invalidating relationships with identical dates. To resolve ambiguity, add original sources to the relationships with different priority dates.') end end end |
#sv_type_placement ⇒ Object (protected)
1983 1984 1985 |
# File 'app/models/taxon_name.rb', line 1983 def sv_type_placement true # see validation in Protonym.rb end |
#sv_validate_coordinated_names ⇒ Object (protected)
1979 1980 1981 |
# File 'app/models/taxon_name.rb', line 1979 def sv_validate_coordinated_names true # see validation in Protonym.rb end |
#sv_validate_name ⇒ Object (protected)
1963 1964 1965 |
# File 'app/models/taxon_name.rb', line 1963 def sv_validate_name true # see validation in Protonym.rb end |
#sv_validate_parent_rank ⇒ Object (protected)
1955 1956 1957 |
# File 'app/models/taxon_name.rb', line 1955 def sv_validate_parent_rank true # see validation in Protonym.rb end |
#synonyms ⇒ Scope
Returns Protonym(s) the **broad sense** synonyms of this name.
600 601 602 |
# File 'app/models/taxon_name.rb', line 600 def synonyms TaxonName.with_cached_valid_taxon_name_id(id) end |
#taxon_name_classification_minimum_invalidating_year ⇒ Object
TODO: @proceps write test please)
728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
# File 'app/models/taxon_name.rb', line 728 def taxon_name_classification_minimum_invalidating_year # TODO: Refactor to youngest() a = taxon_name_classifications.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end |
#taxon_name_classifications_for_statuses ⇒ Scope
850 851 852 853 854 855 856 |
# File 'app/models/taxon_name.rb', line 850 def taxon_name_classifications_for_statuses taxon_name_classifications.with_type_array( ICZN_TAXON_NAME_CLASSIFICATION_NAMES + ICN_TAXON_NAME_CLASSIFICATION_NAMES + ICNP_TAXON_NAME_CLASSIFICATION_NAMES + ICVCN_TAXON_NAME_CLASSIFICATION_NAMES) end |
#taxon_name_relationship_minimum_invalidating_year ⇒ Object
Returns Year,nil based on TaxonNameRelationships only at present.
713 714 715 716 717 718 719 720 721 722 723 724 725 |
# File 'app/models/taxon_name.rb', line 713 def taxon_name_relationship_minimum_invalidating_year a = taxon_name_relationships.includes(:source).order_by_oldest_source_first.with_type_array(::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM).first if a b = a.nomenclature_date&.year if b == Date.current.year return nil else b end else nil end end |
#unavailable_or_invalid? ⇒ Boolean
@return [Boolean]
return true if name is unavailable OR invalid, else false, checks both classifications and relationships
!! Should only be referenced when building cached values, all other uses should rather be ‘!is_valid?`
982 983 984 985 |
# File 'app/models/taxon_name.rb', line 982 def unavailable_or_invalid? return false if classification_valid? classification_invalid_or_unavailable? || relationship_invalid? end |
#validate_parent_from_the_same_project ⇒ Object (protected)
1777 1778 1779 1780 1781 |
# File 'app/models/taxon_name.rb', line 1777 def validate_parent_from_the_same_project if parent && project_id.present? errors.add(:project_id, 'The parent taxon is not from the same project') if project_id != parent.project_id end end |
#validate_rank_class_class ⇒ Object (protected)
See subclasses
1799 1800 1801 |
# File 'app/models/taxon_name.rb', line 1799 def validate_rank_class_class true end |
#validate_root_name_is_root ⇒ Object (protected)
1783 1784 1785 |
# File 'app/models/taxon_name.rb', line 1783 def validate_root_name_is_root errors.add(:parent, "most be empty when name is #{ROOT_NAME}") if !parent.nil? end |
#validate_source_type ⇒ Object (protected)
1816 1817 1818 1819 1820 1821 1822 |
# File 'app/models/taxon_name.rb', line 1816 def validate_source_type a = source && source.type != 'Source::Bibtex' b = origin_citation && origin_citation.try(:source).try(:type) != 'Source::Bibtex' if a || b errors.add(:base, 'Source must be a Bibtex') end end |
#year_integer ⇒ Integer
Returns a 4 digit integer representing year of publication, like 1974.
706 707 708 709 |
# File 'app/models/taxon_name.rb', line 706 def year_integer return year_of_publication if !year_of_publication.nil? try(:source).try(:year) end |