- 
                Notifications
    You must be signed in to change notification settings 
- Fork 113
Add optional units and uncertainties support with comprehensive geometry integration #1483
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Draft
      
      
            Copilot
  wants to merge
  9
  commits into
  main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
copilot/fix-1482
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
      
        
          +893
        
        
          −0
        
        
          
        
      
    
  
  
     Draft
                    Changes from 6 commits
      Commits
    
    
            Show all changes
          
          
            9 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      daedda1
              
                Initial plan
              
              
                Copilot 4a2eb1b
              
                Add prototype units and uncertainties support with comprehensive anal…
              
              
                Copilot b2897fd
              
                Add pint/uncertainties to requirements and implement proper encoding/…
              
              
                Copilot e531988
              
                Refactor units/uncertainties encoding to follow clean COMPAS dtype/da…
              
              
                Copilot 64ec754
              
                Fix typing import for Python 2.7 compatibility and restructure tests
              
              
                Copilot 640b4ad
              
                Add CHANGELOG entry and comprehensive geometry units integration tests
              
              
                Copilot e3b913b
              
                Address all review feedback: simplify CHANGELOG, remove skipif decora…
              
              
                Copilot ab3989e
              
                Fix IronPython compatibility using compas.IPY conditional checks inst…
              
              
                Copilot ac9fbf5
              
                Add UTF-8 encoding declaration for Python 2.7 compatibility with ± sy…
              
              
                Copilot File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,307 @@ | ||
| """ | ||
| Unit and uncertainty support for COMPAS. | ||
|  | ||
| This module provides optional support for physical units and measurement uncertainties | ||
| throughout the COMPAS framework. The implementation follows a gradual typing approach | ||
| where unit-aware inputs produce unit-aware outputs, but plain numeric inputs continue | ||
| to work as before. | ||
| """ | ||
|  | ||
| from __future__ import absolute_import | ||
| from __future__ import division | ||
| from __future__ import print_function | ||
|  | ||
| try: | ||
| from typing import Union | ||
| except ImportError: | ||
| pass | ||
|  | ||
| __all__ = ['UnitRegistry', 'units', 'NumericType', 'UNITS_AVAILABLE', 'UNCERTAINTIES_AVAILABLE', 'PintQuantityEncoder', 'UncertaintiesUFloatEncoder'] | ||
|  | ||
| # Check for optional dependencies | ||
| try: | ||
| import pint | ||
| UNITS_AVAILABLE = True | ||
| except ImportError: | ||
| UNITS_AVAILABLE = False | ||
| pint = None | ||
|  | ||
| try: | ||
| import uncertainties | ||
| UNCERTAINTIES_AVAILABLE = True | ||
| except ImportError: | ||
| UNCERTAINTIES_AVAILABLE = False | ||
| uncertainties = None | ||
|  | ||
| # Define numeric type union | ||
| try: | ||
| NumericType = Union[float, int] | ||
| if UNITS_AVAILABLE: | ||
| NumericType = Union[NumericType, pint.Quantity] | ||
| if UNCERTAINTIES_AVAILABLE: | ||
| NumericType = Union[NumericType, uncertainties.UFloat] | ||
| except NameError: | ||
| # typing.Union not available, just use documentation comment | ||
| NumericType = float # Union[float, int, pint.Quantity, uncertainties.UFloat] when available | ||
|  | ||
|  | ||
| class PintQuantityEncoder: | ||
| """Encoder/decoder for pint.Quantity objects following COMPAS data serialization patterns.""" | ||
|  | ||
| @staticmethod | ||
| def __jsondump__(obj): | ||
| """Serialize a pint.Quantity to COMPAS JSON format. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| obj : pint.Quantity | ||
| The quantity to serialize. | ||
|  | ||
| Returns | ||
| ------- | ||
| dict | ||
| Dictionary with dtype and data keys. | ||
| """ | ||
| return { | ||
| 'dtype': 'compas.units/PintQuantityEncoder', | ||
| 'data': { | ||
| 'magnitude': obj.magnitude, | ||
| 'units': str(obj.units) | ||
| } | ||
| } | ||
|  | ||
| @staticmethod | ||
| def __from_data__(data): | ||
| """Reconstruct a pint.Quantity from serialized data. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| data : dict | ||
| The serialized data containing magnitude and units. | ||
|  | ||
| Returns | ||
| ------- | ||
| pint.Quantity or float | ||
| The reconstructed quantity, or magnitude if pint not available. | ||
| """ | ||
| if UNITS_AVAILABLE: | ||
| # Import units registry from this module | ||
| return units.ureg.Quantity(data['magnitude'], data['units']) | ||
| else: | ||
| # Graceful degradation - return just the magnitude | ||
| return data['magnitude'] | ||
|  | ||
| @staticmethod | ||
| def __jsonload__(data, guid=None, name=None): | ||
| """Load method for COMPAS JSON deserialization.""" | ||
| return PintQuantityEncoder.__from_data__(data) | ||
|  | ||
|  | ||
| class UncertaintiesUFloatEncoder: | ||
| """Encoder/decoder for uncertainties.UFloat objects following COMPAS data serialization patterns.""" | ||
|  | ||
| @staticmethod | ||
| def __jsondump__(obj): | ||
| """Serialize an uncertainties.UFloat to COMPAS JSON format. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| obj : uncertainties.UFloat | ||
| The uncertain value to serialize. | ||
|  | ||
| Returns | ||
| ------- | ||
| dict | ||
| Dictionary with dtype and data keys. | ||
| """ | ||
| return { | ||
| 'dtype': 'compas.units/UncertaintiesUFloatEncoder', | ||
| 'data': { | ||
| 'nominal_value': obj.nominal_value, | ||
| 'std_dev': obj.std_dev | ||
| } | ||
| } | ||
|  | ||
| @staticmethod | ||
| def __from_data__(data): | ||
| """Reconstruct an uncertainties.UFloat from serialized data. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| data : dict | ||
| The serialized data containing nominal_value and std_dev. | ||
|  | ||
| Returns | ||
| ------- | ||
| uncertainties.UFloat or float | ||
| The reconstructed uncertain value, or nominal value if uncertainties not available. | ||
| """ | ||
| if UNCERTAINTIES_AVAILABLE: | ||
| return uncertainties.ufloat(data['nominal_value'], data['std_dev']) | ||
| else: | ||
| # Graceful degradation - return just the nominal value | ||
| return data['nominal_value'] | ||
|  | ||
| @staticmethod | ||
| def __jsonload__(data, guid=None, name=None): | ||
| """Load method for COMPAS JSON deserialization.""" | ||
| return UncertaintiesUFloatEncoder.__from_data__(data) | ||
|  | ||
|  | ||
| class UnitRegistry: | ||
| """Global unit registry for COMPAS. | ||
|  | ||
| This class provides a centralized way to create and manage units throughout | ||
| the COMPAS framework. It gracefully handles the case where pint is not available. | ||
|  | ||
| Examples | ||
| -------- | ||
| >>> from compas.units import units | ||
| >>> length = units.Quantity(1.0, 'meter') # Returns 1.0 if pint not available | ||
| >>> area = units.Quantity(2.5, 'square_meter') | ||
| """ | ||
|  | ||
| def __init__(self): | ||
| if UNITS_AVAILABLE: | ||
| self.ureg = pint.UnitRegistry() | ||
| # Use built-in units - no need to redefine basic units | ||
| # The registry already has meter, millimeter, etc. | ||
| else: | ||
| self.ureg = None | ||
|  | ||
| def Quantity(self, value, unit=None): | ||
| """Create a quantity with units if available, otherwise return plain value. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| value : float | ||
| The numeric value. | ||
| unit : str, optional | ||
| The unit string. If None or if pint is not available, returns plain value. | ||
|  | ||
| Returns | ||
| ------- | ||
| pint.Quantity or float | ||
| A quantity with units if pint is available, otherwise the plain value. | ||
| """ | ||
| if UNITS_AVAILABLE and unit and self.ureg: | ||
| return self.ureg.Quantity(value, unit) | ||
| return value | ||
|  | ||
| def Unit(self, unit_string): | ||
| """Get a unit object if available. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| unit_string : str | ||
| The unit string (e.g., 'meter', 'mm', 'inch'). | ||
|  | ||
| Returns | ||
| ------- | ||
| pint.Unit or None | ||
| A unit object if pint is available, otherwise None. | ||
| """ | ||
| if UNITS_AVAILABLE and self.ureg: | ||
| return self.ureg.Unit(unit_string) | ||
| return None | ||
|  | ||
| @property | ||
| def meter(self): | ||
| """Meter unit for convenience.""" | ||
| return self.Unit('m') | ||
|  | ||
| @property | ||
| def millimeter(self): | ||
| """Millimeter unit for convenience.""" | ||
| return self.Unit('mm') | ||
|  | ||
| @property | ||
| def centimeter(self): | ||
| """Centimeter unit for convenience.""" | ||
| return self.Unit('cm') | ||
|  | ||
|  | ||
| def ensure_numeric(value): | ||
| """Ensure a value is numeric, preserving units and uncertainties if present. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| value : any | ||
| Input value that should be numeric. | ||
|  | ||
| Returns | ||
| ------- | ||
| NumericType | ||
| A numeric value, preserving units/uncertainties if present. | ||
| """ | ||
| # Check for pint Quantity | ||
| if hasattr(value, 'magnitude') and hasattr(value, 'units'): | ||
| return value | ||
|  | ||
| # Check for uncertainties UFloat | ||
| if hasattr(value, 'nominal_value') and hasattr(value, 'std_dev'): | ||
| return value | ||
|  | ||
| # Convert to float for plain values | ||
| return float(value) | ||
|  | ||
|  | ||
| def get_magnitude(value): | ||
| """Get the magnitude of a value, handling units and uncertainties. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| value : NumericType | ||
| A numeric value that may have units or uncertainties. | ||
|  | ||
| Returns | ||
| ------- | ||
| float | ||
| The magnitude/nominal value without units. | ||
| """ | ||
| # Handle pint Quantity | ||
| if hasattr(value, 'magnitude'): | ||
| return float(value.magnitude) | ||
|  | ||
| # Handle uncertainties UFloat | ||
| if hasattr(value, 'nominal_value'): | ||
| return float(value.nominal_value) | ||
|  | ||
| # Plain numeric value | ||
| return float(value) | ||
|  | ||
|  | ||
| def has_units(value): | ||
| """Check if a value has units. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| value : any | ||
| Value to check for units. | ||
|  | ||
| Returns | ||
| ------- | ||
| bool | ||
| True if the value has units, False otherwise. | ||
| """ | ||
| return hasattr(value, 'magnitude') and hasattr(value, 'units') | ||
|  | ||
|  | ||
| def has_uncertainty(value): | ||
| """Check if a value has uncertainty. | ||
|  | ||
| Parameters | ||
| ---------- | ||
| value : any | ||
| Value to check for uncertainty. | ||
|  | ||
| Returns | ||
| ------- | ||
| bool | ||
| True if the value has uncertainty, False otherwise. | ||
| """ | ||
| return hasattr(value, 'nominal_value') and hasattr(value, 'std_dev') | ||
|  | ||
|  | ||
| # Global registry instance | ||
| units = UnitRegistry() | 
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Simplified CHANGELOG entry as suggested - condensed to concise two-line description focusing on key features: gradual typing and unit registry support.
Commit: e3b913b