|
9 | 9 | import json |
10 | 10 | import logging |
11 | 11 | import os |
| 12 | +from collections import defaultdict |
12 | 13 | from difflib import SequenceMatcher |
13 | 14 | from enum import Enum |
14 | 15 | from typing import Any, Dict, List, Optional, Set, Tuple |
15 | 16 |
|
16 | 17 | import pandas as pd |
17 | 18 |
|
| 19 | +from .reverse_index import section_side |
| 20 | + |
18 | 21 | # Module-level logger (avoid creating logger inside hot paths) |
19 | 22 | logger = logging.getLogger(__name__) |
20 | 23 |
|
@@ -771,88 +774,137 @@ def _should_preserve_label(original_label: str, standardized_label: str) -> bool |
771 | 774 | return False |
772 | 775 |
|
773 | 776 |
|
774 | | -def _derive_section_from_parent(calculation_parent: str, statement_type: str) -> Optional[str]: |
| 777 | +# Parent totals that state a section. The generic totals (Assets, Liabilities, |
| 778 | +# LiabilitiesAndStockholdersEquity) name a section but no side, so they never |
| 779 | +# decide current vs noncurrent for a child. |
| 780 | +_PARENT_TO_SECTION = { |
| 781 | + "assetscurrent": "Current Assets", |
| 782 | + "currentassets": "Current Assets", |
| 783 | + "assetsnoncurrent": "Non-Current Assets", |
| 784 | + "noncurrentassets": "Non-Current Assets", |
| 785 | + "liabilitiescurrent": "Current Liabilities", |
| 786 | + "currentliabilities": "Current Liabilities", |
| 787 | + "liabilitiesnoncurrent": "Non-Current Liabilities", |
| 788 | + "noncurrentliabilities": "Non-Current Liabilities", |
| 789 | + "stockholdersequity": "Equity", |
| 790 | + "stockholdersequityincludingportionattributabletononcontrollinginterest": "Equity", |
| 791 | + "equity": "Equity", |
| 792 | + "assets": "Assets", |
| 793 | + "liabilities": "Liabilities", |
| 794 | + "liabilitiesandstockholdersequity": "Liabilities and Equity", |
| 795 | +} |
| 796 | + |
| 797 | +# Substring patterns, noncurrent first: 'othernoncurrentassets' contains |
| 798 | +# 'currentassets', so testing the current spelling first read it as current. |
| 799 | +_PARENT_SECTION_PATTERNS = ( |
| 800 | + ("assetsnoncurrent", "Non-Current Assets"), |
| 801 | + ("noncurrentassets", "Non-Current Assets"), |
| 802 | + ("liabilitiesnoncurrent", "Non-Current Liabilities"), |
| 803 | + ("noncurrentliabilities", "Non-Current Liabilities"), |
| 804 | + ("assetscurrent", "Current Assets"), |
| 805 | + ("currentassets", "Current Assets"), |
| 806 | + ("liabilitiescurrent", "Current Liabilities"), |
| 807 | + ("currentliabilities", "Current Liabilities"), |
| 808 | + ("stockholdersequity", "Equity"), |
| 809 | + ("equity", "Equity"), |
| 810 | + ("liabilitiesandstockholdersequity", "Liabilities and Equity"), |
| 811 | + ("assets", "Assets"), |
| 812 | + ("liabilities", "Liabilities"), |
| 813 | +) |
| 814 | + |
| 815 | + |
| 816 | +def _bare_parent_name(concept: str) -> str: |
| 817 | + name = concept.lower() |
| 818 | + if ":" in name: |
| 819 | + name = name.split(":")[-1] |
| 820 | + if "_" in name: |
| 821 | + name = name.split("_")[-1] |
| 822 | + return name |
| 823 | + |
| 824 | + |
| 825 | +def _section_from_parent_name(calculation_parent: str, statement_type: str) -> Optional[str]: |
| 826 | + """The section one parent concept states by itself, without its own parents.""" |
| 827 | + name = _bare_parent_name(calculation_parent) |
| 828 | + if name in _PARENT_TO_SECTION: |
| 829 | + return _PARENT_TO_SECTION[name] |
| 830 | + |
| 831 | + # An ...CurrentAndNoncurrent element is on neither side; 'Current' inside |
| 832 | + # its name is not a section (GH #1438). |
| 833 | + unclassified = "currentandnoncurrent" in name |
| 834 | + for pattern, section in _PARENT_SECTION_PATTERNS: |
| 835 | + if unclassified and section_side(section): |
| 836 | + continue |
| 837 | + if pattern in name: |
| 838 | + return section |
| 839 | + |
| 840 | + # A parent with a single standard concept states that concept's section. |
| 841 | + # A parent with several does not: its context-free answer is only the |
| 842 | + # first candidate, which is not evidence for the child (GH #1438). |
| 843 | + try: |
| 844 | + reverse_index = _get_reverse_index() |
| 845 | + result = reverse_index.lookup(calculation_parent) |
| 846 | + if result is None or result.is_ambiguous or len(result.standard_concepts) != 1: |
| 847 | + return None |
| 848 | + from .sections import get_section_for_concept |
| 849 | + section = get_section_for_concept(result.primary_concept, statement_type) |
| 850 | + if section and section != "Totals": |
| 851 | + return section |
| 852 | + # A debt note is not a balance sheet role, but LongTermDebtNoncurrent |
| 853 | + # is noncurrent there too. Only a section that states a side is taken |
| 854 | + # from the untyped lookup. |
| 855 | + section = get_section_for_concept(result.primary_concept) |
| 856 | + if section_side(section): |
| 857 | + return section |
| 858 | + except Exception as e: |
| 859 | + logger.debug("Could not derive section from parent %s: %s", calculation_parent, e) |
| 860 | + |
| 861 | + return None |
| 862 | + |
| 863 | + |
| 864 | +def _derive_section_from_parent(calculation_parent: str, statement_type: str, |
| 865 | + parents_of: Optional[Dict[str, Set[str]]] = None) -> Optional[str]: |
775 | 866 | """ |
776 | 867 | Derive the balance sheet section from a calculation parent concept. |
777 | 868 |
|
778 | | - Phase 3: Uses the calculation parent to determine which section an item |
779 | | - belongs to, enabling disambiguation of ambiguous tags. |
780 | | -
|
781 | | - The key insight is that if an item's calculation parent is "AssetsCurrent", |
782 | | - then the item belongs to the "Current Assets" section. |
| 869 | + If an item's calculation parent is "AssetsCurrent", the item belongs to the |
| 870 | + "Current Assets" section. A parent that states no side by itself (an |
| 871 | + ambiguous element such as OtherBorrowings, or a generic total) passes on |
| 872 | + the side of its own classified ancestor, found through `parents_of` |
| 873 | + (concept -> its calculation parents in the same statement). Ancestors that |
| 874 | + disagree, or a cycle, give no side. |
783 | 875 |
|
784 | 876 | Args: |
785 | 877 | calculation_parent: The calculation parent concept (e.g., "us-gaap:AssetsCurrent") |
786 | 878 | statement_type: The statement type (e.g., "BalanceSheet") |
| 879 | + parents_of: Calculation parents of each concept in the same statement |
787 | 880 |
|
788 | 881 | Returns: |
789 | 882 | Section name (e.g., "Current Assets") or None if not determinable |
790 | 883 | """ |
791 | 884 | if not calculation_parent: |
792 | 885 | return None |
793 | 886 |
|
794 | | - # Normalize the parent concept name |
795 | | - parent_normalized = calculation_parent.lower() |
796 | | - # Remove namespace prefix |
797 | | - if ":" in parent_normalized: |
798 | | - parent_normalized = parent_normalized.split(":")[-1] |
799 | | - if "_" in parent_normalized: |
800 | | - parent_normalized = parent_normalized.split("_")[-1] |
801 | | - |
802 | | - # Map parent totals to their sections |
803 | | - # Items under AssetsCurrent belong to "Current Assets" section |
804 | | - parent_to_section = { |
805 | | - # Current Assets - items rolling up to AssetsCurrent |
806 | | - "assetscurrent": "Current Assets", |
807 | | - "currentassets": "Current Assets", |
808 | | - |
809 | | - # Non-Current Assets - items rolling up to AssetsNoncurrent |
810 | | - "assetsnoncurrent": "Non-Current Assets", |
811 | | - "noncurrentassets": "Non-Current Assets", |
812 | | - |
813 | | - # Current Liabilities - items rolling up to LiabilitiesCurrent |
814 | | - "liabilitiescurrent": "Current Liabilities", |
815 | | - "currentliabilities": "Current Liabilities", |
816 | | - |
817 | | - # Non-Current Liabilities - items rolling up to LiabilitiesNoncurrent |
818 | | - "liabilitiesnoncurrent": "Non-Current Liabilities", |
819 | | - "noncurrentliabilities": "Non-Current Liabilities", |
820 | | - |
821 | | - # Equity - items rolling up to StockholdersEquity |
822 | | - "stockholdersequity": "Equity", |
823 | | - "stockholdersequityincludingportionattributabletononcontrollinginterest": "Equity", |
824 | | - "equity": "Equity", |
825 | | - |
826 | | - # Top-level totals (less specific) |
827 | | - "assets": "Assets", |
828 | | - "liabilities": "Liabilities", |
829 | | - "liabilitiesandstockholdersequity": "Liabilities and Equity", |
830 | | - } |
831 | | - |
832 | | - # Direct lookup |
833 | | - if parent_normalized in parent_to_section: |
834 | | - return parent_to_section[parent_normalized] |
835 | | - |
836 | | - # Partial match fallback |
837 | | - for pattern, section in parent_to_section.items(): |
838 | | - if pattern in parent_normalized: |
839 | | - return section |
840 | | - |
841 | | - # Try reverse index as last resort |
842 | | - try: |
843 | | - reverse_index = _get_reverse_index() |
844 | | - parent_standard = reverse_index.get_standard_concept(calculation_parent) |
845 | | - |
846 | | - if parent_standard: |
847 | | - from .sections import get_section_for_concept |
848 | | - section = get_section_for_concept(parent_standard, statement_type) |
849 | | - if section and section != "Totals": |
850 | | - return section |
851 | | - |
852 | | - except Exception as e: |
853 | | - logger.debug("Could not derive section from parent %s: %s", calculation_parent, e) |
854 | | - |
855 | | - return None |
| 887 | + own = _section_from_parent_name(calculation_parent, statement_type) |
| 888 | + if section_side(own) or not parents_of: |
| 889 | + return own |
| 890 | + |
| 891 | + # Walk up to the nearest ancestors that state a side. |
| 892 | + sides: Set[str] = set() |
| 893 | + seen = {calculation_parent} |
| 894 | + frontier = list(parents_of.get(calculation_parent, ())) |
| 895 | + while frontier: |
| 896 | + ancestor = frontier.pop() |
| 897 | + if ancestor in seen: |
| 898 | + continue |
| 899 | + seen.add(ancestor) |
| 900 | + section = _section_from_parent_name(ancestor, statement_type) |
| 901 | + if section_side(section): |
| 902 | + sides.add(section) |
| 903 | + else: |
| 904 | + frontier.extend(parents_of.get(ancestor, ())) |
| 905 | + if len(sides) == 1: |
| 906 | + return sides.pop() |
| 907 | + return own |
856 | 908 |
|
857 | 909 |
|
858 | 910 | def _assign_sections_bottom_up( |
@@ -1007,6 +1059,13 @@ def standardize_statement(statement_data: List[Dict[str, Any]], mapper: ConceptM |
1007 | 1059 | items_to_standardize = [] |
1008 | 1060 | statement_type = statement_data[0].get("statement_type", "") if statement_data else "" |
1009 | 1061 |
|
| 1062 | + # Calculation parents of each concept in this statement, so a parent that |
| 1063 | + # states no side can pass on its own classified ancestor's (GH #1438). |
| 1064 | + parents_of: Dict[str, Set[str]] = defaultdict(set) |
| 1065 | + for item in statement_data: |
| 1066 | + if item.get("concept") and item.get("calculation_parent") and not item.get("is_dimension", False): |
| 1067 | + parents_of[item["concept"]].add(item["calculation_parent"]) |
| 1068 | + |
1010 | 1069 | # First pass - identify which items need standardization and prepare context |
1011 | 1070 | for i, item in enumerate(statement_data): |
1012 | 1071 | # Skip abstract elements and dimensions as they don't need standardization |
@@ -1034,7 +1093,7 @@ def standardize_statement(statement_data: List[Dict[str, Any]], mapper: ConceptM |
1034 | 1093 |
|
1035 | 1094 | # Phase 3: Derive section from calculation parent if available |
1036 | 1095 | if calculation_parent: |
1037 | | - context["section"] = _derive_section_from_parent(calculation_parent, statement_type) |
| 1096 | + context["section"] = _derive_section_from_parent(calculation_parent, statement_type, parents_of) |
1038 | 1097 |
|
1039 | 1098 | items_to_standardize.append((i, concept, label, context)) |
1040 | 1099 |
|
|
0 commit comments