pax_global_header00006660000000000000000000000064143573123440014520gustar00rootroot0000000000000052 comment=7032e42336613ba4ac4739f75c4ec79ec5d0d6b0 python-measurement-3.2.2/000077500000000000000000000000001435731234400153705ustar00rootroot00000000000000python-measurement-3.2.2/.editorconfig000066400000000000000000000004251435731234400200460ustar00rootroot00000000000000# http://editorconfig.org root = true [*] indent_style = space indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true charset = utf-8 end_of_line = lf max_line_length = 88 [*.{json,yml,yaml,toml}] indent_size = 2 [LICENSE] insert_final_newline = false python-measurement-3.2.2/.github/000077500000000000000000000000001435731234400167305ustar00rootroot00000000000000python-measurement-3.2.2/.github/dependabot.yml000066400000000000000000000002651435731234400215630ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: pip directory: "/" schedule: interval: weekly - package-ecosystem: github-actions directory: "/" schedule: interval: weekly python-measurement-3.2.2/.github/workflows/000077500000000000000000000000001435731234400207655ustar00rootroot00000000000000python-measurement-3.2.2/.github/workflows/ci.yml000066400000000000000000000035211435731234400221040ustar00rootroot00000000000000name: CI on: push: branches: - master - 3.x pull_request: jobs: lint: runs-on: ubuntu-latest strategy: matrix: lint-command: - bandit -r . -x ./tests - black --check --diff . - flake8 . - isort --check-only --diff . - pydocstyle . steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: "3.x" cache: 'pip' cache-dependency-path: 'linter-requirements.txt' - run: python -m pip install -r linter-requirements.txt - run: ${{ matrix.lint-command }} docs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v3 with: python-version: 3.11 - run: sudo apt-get install -y graphviz - run: python -m pip install -e '.[docs]' - run: python -m sphinx -W -b html docs docs/_build dist: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: "3.x" - run: python -m pip install --upgrade pip build wheel twine - run: python -m build --sdist --wheel - run: python -m twine check dist/* - uses: actions/upload-artifact@v3 with: path: dist/* pytest: needs: - lint strategy: matrix: os: - ubuntu-latest - windows-latest - macos-latest python-version: - 3.7 - 3.8 - 3.9 runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - run: python -m pip install .[test] - run: python -m pytest - uses: codecov/codecov-action@v3 python-measurement-3.2.2/.github/workflows/release.yml000066400000000000000000000007431435731234400231340ustar00rootroot00000000000000name: Release on: release: types: [published] jobs: PyPi: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: 3.x - run: python -m pip install --upgrade pip build wheel twine - run: python -m build --sdist --wheel - run: python -m twine upload dist/* env: TWINE_USERNAME: ${{ secrets.TWINE_USERNAME }} TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD }} python-measurement-3.2.2/.gitignore000066400000000000000000000001751435731234400173630ustar00rootroot00000000000000*.pyc *egg-info* .Python bin/* build/ .eggs/ dist/ include/ lib/ docs/_build/ .coverage # packaging measurement/_version.py python-measurement-3.2.2/.readthedocs.yaml000066400000000000000000000005511435731234400206200ustar00rootroot00000000000000# .readthedocs.yaml # Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details version: 2 build: os: ubuntu-20.04 tools: python: "3.11" apt_packages: - graphviz sphinx: configuration: docs/conf.py python: install: - method: pip path: . extra_requirements: - docs python-measurement-3.2.2/.travis.yml000066400000000000000000000007511435731234400175040ustar00rootroot00000000000000language: python dist: xenial python: - '3.5' - '3.6' - '3.7' - nightly matrix: allow_failures: - python: nightly script: python setup.py test deploy: provider: pypi user: codingjoe password: secure: nYe/kosb8Yz/YuOfJHvw8ff0GsKTT2P5gRvvqBB/+8entr+UjtW3AuORbUvk3YmMLdzAzhl7xSeP3VfNnl9wZw9Mw0BGwjMo715YRAgLEGk2IGu7IamH0NY/JPi7H1XeASFmQJe0nbugbJjtmgIICCOhw/RoBrth5sV5tzwSl5I= on: tags: true distributions: sdist bdist_wheel repo: coddingtonbear/python-measurement python-measurement-3.2.2/CONTRIBUTING.md000066400000000000000000000007031435731234400176210ustar00rootroot00000000000000# Contributing ### Run tests ```bash python setup.py test ``` ### Build Sphinx documentation ```bash python setup.py build_sphinx ``` ### Releases Please create new releases via GitHub's release functionality or using the GitHub CLI. ```bash hub release create origin ``` We follow [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html). Make sure to add the changelog of each release into the release description. python-measurement-3.2.2/LICENSE000066400000000000000000000020721435731234400163760ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2014 Adam Coddington Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-measurement-3.2.2/MANIFEST.in000066400000000000000000000000721435731234400171250ustar00rootroot00000000000000exclude .* exclude CONTRIBUTING.md prune tests prune docs python-measurement-3.2.2/README.rst000066400000000000000000000036411435731234400170630ustar00rootroot00000000000000.. image:: https://travis-ci.org/coddingtonbear/python-measurement.svg?branch=master :target: https://travis-ci.org/coddingtonbear/python-measurement Easily use and manipulate unit-aware measurement objects in Python. `django.contrib.gis.measure `_ has these wonderful 'Distance' objects that can be used not only for storing a unit-aware distance measurement, but also for converting between different units and adding/subtracting these objects from one another. This module not only provides those Distance and Area measurement objects, but also other measurements including: - Energy - Speed - Temperature - Time - Volume - Weight Example: .. code-block:: python >>> from measurement.measures import Weight >>> weight_1 = Weight(lb=125) >>> weight_2 = Weight(kg=40) >>> added_together = weight_1 + weight_2 >>> added_together Weight(lb=213.184976807) >>> added_together.kg # Maybe I actually need this value in kg? 96.699 .. warning:: Measurements are stored internally by converting them to a floating-point number of a (generally) reasonable SI unit. Given that floating-point numbers are very slightly lossy, you should be aware of any inaccuracies that this might cause. TLDR: Do not use this in `navigation algorithms guiding probes into the atmosphere of extraterrestrial worlds `_. - Documentation for python-measurement is available an `ReadTheDocs `_. - Please post issues on `Github `_. - Test status available on `Travis-CI `_. .. image:: https://d2weczhvl823v0.cloudfront.net/coddingtonbear/python-measurement/trend.png :alt: Bitdeli badge :target: https://bitdeli.com/free python-measurement-3.2.2/docs/000077500000000000000000000000001435731234400163205ustar00rootroot00000000000000python-measurement-3.2.2/docs/conf.py000066400000000000000000000007531435731234400176240ustar00rootroot00000000000000"""Sphinx configuration file.""" from pkg_resources import get_distribution project = 'python-measurement' copyright = '2013, Adam Coddington' release = get_distribution('measurement').version version = '.'.join(release.split('.')[:2]) master_doc = 'index' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', 'sphinx.ext.intersphinx', 'sphinx.ext.doctest', ] intersphinx_mapping = { 'python': ('https://docs.python.org/3', None), } python-measurement-3.2.2/docs/index.rst000066400000000000000000000030531435731234400201620ustar00rootroot00000000000000.. python-measurement documentation master file, created by sphinx-quickstart on Tue Jan 22 20:02:38 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. python-measurement ================== .. image:: https://travis-ci.org/coddingtonbear/python-measurement.svg?branch=master :target: https://travis-ci.org/coddingtonbear/python-measurement Easily use and manipulate unit-aware measurement objects in Python. `django.contrib.gis.measure `_ has these wonderful 'Distance' objects that can be used not only for storing a unit-aware distance measurement, but also for converting between different units and adding/subtracting these objects from one another. This module not only provides those Distance and Area measurement objects (courtesy of Django), but also other measurements including Weight, Volume, and Temperature. .. warning:: Measurements are stored internally by converting them to a floating-point number of a (generally) reasonable SI unit. Given that floating-point numbers are very slightly lossy, you should be aware of any inaccuracies that this might cause. TLDR: Do not use this in `navigation algorithms guiding probes into the atmosphere of extraterrestrial worlds `_. Contents: .. toctree:: :maxdepth: 2 :glob: topics/* Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python-measurement-3.2.2/docs/topics/000077500000000000000000000000001435731234400176215ustar00rootroot00000000000000python-measurement-3.2.2/docs/topics/creating_your_own_class.rst000066400000000000000000000121731435731234400253010ustar00rootroot00000000000000 Creating your own Measure Class =============================== You can create your own measures easily by subclassing either ``measurement.base.MeasureBase`` or ``measurement.base.BidimensionalMeasure``. Simple Measures --------------- If your measure is not a measure dependent upon another measure (e.g speed, distance/time) you can create new measurement by creating a subclass of ``measurement.base.MeasureBase``. A simple example is Weight: .. code-block:: python from measurement.base import MeasureBase class Weight(MeasureBase): STANDARD_UNIT = 'g' UNITS = { 'g': 1.0, 'tonne': 1000000.0, 'oz': 28.3495, 'lb': 453.592, 'stone': 6350.29, 'short_ton': 907185.0, 'long_ton': 1016000.0, } ALIAS = { 'gram': 'g', 'ton': 'short_ton', 'metric tonne': 'tonne', 'metric ton': 'tonne', 'ounce': 'oz', 'pound': 'lb', 'short ton': 'short_ton', 'long ton': 'long_ton', } SI_UNITS = ['g'] Important details: * ``STANDARD_UNIT`` defines what unit will be used internally by the library for storing the value of this measurement. * ``UNITS`` provides a mapping relating a unit of your ``STANDARD_UNIT`` to any number of defined units. In the example above, you will see that we've established ``28.3495 g`` to be equal to ``1 oz``. * ``ALIAS`` provides a list of aliases mapping keyword arguments to ``UNITS``. these values are allowed to be used as keyword arguments when either creating a new unit or guessing a measurement using ``measurement.utils.guess``. * ``SI_UNITS`` provides a list of units that are SI Units. Units in this list will automatically have new units and aliases created for each of the main SI magnitudes. In the above example, this causes the list of ``UNITS`` and ``ALIAS`` es to be extended to include the following units (aliases): ``yg`` (yottagrams), ``zg`` (zeptograms), ``ag`` (attograms), ``fg`` (femtograms), ``pg`` (picograms), ``ng`` (nanograms), ``ug`` (micrograms), ``mg`` (milligrams), ``kg`` (kilograms), ``Mg`` (megagrams), ``Gg`` (gigagrams), ``Tg`` (teragrams), ``Pg`` (petagrams), ``Eg`` (exagrams), ``Zg`` (zetagrams), ``Yg`` (yottagrams). Using formula-based conversions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In some situations, your conversions between units may not be simple enough to be accomplished by using simple conversions (e.g. temperature); for situations like that, you should use ``sympy`` to create expressions relating your measure's standard unit and the unit you're defining: .. code-block:: python from sympy import S, Symbol from measurement.base import MeasureBase class Temperature(MeasureBase): SU = Symbol('kelvin') STANDARD_UNIT = 'k' UNITS = { 'c': SU - S(273.15), 'f': (SU - S(273.15)) * S('9/5') + 32, 'k': 1.0 } ALIAS = { 'celsius': 'c', 'fahrenheit': 'f', 'kelvin': 'k', } Important details: * See above 'Important Details' under `Normal Measures`. * ``SU`` must define the symbol used in expressions relating your measure's ``STANDARD_UNIT`` to the unit you're defining. Bi-dimensional Measures ----------------------- Some measures are really just compositions of two separate measures -- Speed, being a measure of the amount of distance covered over a unit of time, is one common example of such a measure. You can create such measures by subclassing ``measurement.base.BidimensionalMeasure``. .. code-block:: python from measurement.base import BidimensionalMeasure from measurement.measures.distance import Distance from measurement.measures.time import Time class Speed(BidimensionalMeasure): PRIMARY_DIMENSION = Distance REFERENCE_DIMENSION = Time ALIAS = { 'mph': 'mi__hr', 'kph': 'km__hr', } Important details: * ``PRIMARY_DIMENSION`` is a class that measures the variable dimension of this measure. In the case of 'miles-per-hour', this would be the 'miles' or 'distance' dimension of the measurement. * ``REFERENCE_DIMENSION`` is a class that measures the unit (reference) dimension of the measure. In the case of 'miles-per-hour', this would be the 'hour' or 'time' dimension of the measurement. * ``ALIAS`` defines a list of convenient abbreviations for use either when creating or defining a new instance of this measurement. In the above case, you can create an instance of speed like ``Speed(mph=10)`` (equivalent to ``Speed(mile__hour=10)``) or convert to an existing measurement ( ``speed_measurement``) into one of the aliased measures by accessing the attribute named -- ``speed_measurement.kph`` (equivalent to ``speed_measurement.kilometer__hour``). .. note:: Although unit aliases defined in a bi-dimensional measurement's ``ALIAS`` dictionary can be used either as keyword arguments or as attributes used for conversion, unit aliases defined in simple measurements (those subclassing ``measurement.base.MeasureBase``) can be used only as keyword arguments. python-measurement-3.2.2/docs/topics/installation.rst000066400000000000000000000005301435731234400230520ustar00rootroot00000000000000 Installation ============ You can either install from pip:: pip install measurement *or* checkout and install the source from the `github repository `_:: git clone https://github.com/coddingtonbear/python-measurement.git cd python-measurement python setup.py install python-measurement-3.2.2/docs/topics/measures.rst000066400000000000000000000256721435731234400222130ustar00rootroot00000000000000Measures ======== This application provides the following measures: .. note:: Python has restrictions on what can be used as a method attribute; if you are not very familiar with python, the below chart outlines which units can be used only when creating a new measurement object ('Acceptable as Arguments') and which are acceptable for use either when creating a new measurement object, or for converting a measurement object to a different unit ('Acceptable as Arguments or Attributes') Units that are acceptable as arguments (like the distance measurement term ``km``) can be used like:: >>> from measurement.measures import Distance >>> distance = Distance(km=10) or can be used for converting other measures into kilometers: >>> from measurement.measures import Distance >>> distance = Distance(mi=10).km but units that are only acceptable as arguments (like the distance measurement term ``kilometer``) can *only* be used to create a measurement: >>> from measurement.measures import Distance >>> distance = Distance(kilometer=10) You also might notice that some measures have arguments having spaces in their name marked as 'Acceptable as Arguments'; their primary use is for when using ``measurement.guess``:: >>> from measurement.utils import guess >>> unit = 'U.S. Foot' >>> value = 10 >>> measurement = guess(value, unit) >>> print measurement 10.0 U.S. Foot Area ---- * *Acceptable as Arguments or Attributes*: ``acre``, ``hectare``, ``sq_Em``, ``sq_Gm``, ``sq_Mm``, ``sq_Pm``, ``sq_Tm``, ``sq_Ym``, ``sq_Zm``, ``sq_am``, ``sq_british_chain_benoit``, ``sq_british_chain_sears_truncated``, ``sq_british_chain_sears``, ``sq_british_ft``, ``sq_british_yd``, ``sq_chain_benoit``, ``sq_chain_sears``, ``sq_chain``, ``sq_clarke_ft``, ``sq_clarke_link``, ``sq_cm``, ``sq_dam``, ``sq_dm``, ``sq_fathom``, ``sq_fm``, ``sq_ft``, ``sq_german_m``, ``sq_gold_coast_ft``, ``sq_hm``, ``sq_inch``, ``sq_indian_yd``, ``sq_km``, ``sq_link_benoit``, ``sq_link_sears``, ``sq_link``, ``sq_m``, ``sq_mi``, ``sq_mm``, ``sq_nm_uk``, ``sq_nm``, ``sq_pm``, ``sq_rod``, ``sq_sears_yd``, ``sq_survey_ft``, ``sq_um``, ``sq_yd``, ``sq_ym``, ``sq_zm`` * *Acceptable as Arguments*: ``Acre``, ``British chain (Benoit 1895 B)``, ``British chain (Sears 1922 truncated)``, ``British chain (Sears 1922)``, ``British foot (Sears 1922)``, ``British foot``, ``British yard (Sears 1922)``, ``British yard``, ``Chain (Benoit)``, ``Chain (Sears)``, ``Clarke's Foot``, ``Clarke's link``, ``Foot (International)``, ``German legal metre``, ``Gold Coast foot``, ``ha``, ``Hectare``, ``Indian yard``, ``Link (Benoit)``, ``Link (Sears)``, ``Nautical Mile (UK)``, ``Nautical Mile``, ``U.S. Foot``, ``US survey foot``, ``Yard (Indian)``, ``Yard (Sears)``, ``attometer``, ``attometre``, ``centimeter``, ``centimetre``, ``decameter``, ``decametre``, ``decimeter``, ``decimetre``, ``exameter``, ``exametre``, ``femtometer``, ``femtometre``, ``foot``, ``gigameter``, ``gigametre``, ``hectometer``, ``hectometre``, ``in``, ``inches``, ``kilometer``, ``kilometre``, ``megameter``, ``megametre``, ``meter``, ``metre``, ``micrometer``, ``micrometre``, ``mile``, ``millimeter``, ``millimetre``, ``nanometer``, ``nanometre``, ``petameter``, ``petametre``, ``picometer``, ``picometre``, ``terameter``, ``terametre``, ``yard``, ``yoctometer``, ``yoctometre``, ``yottameter``, ``yottametre``, ``zeptometer``, ``zeptometre``, ``zetameter``, ``zetametre`` Distance -------- * *Acceptable as Arguments or Attributes*: ``Em``, ``Gm``, ``Mm``, ``Pm``, ``Tm``, ``Ym``, ``Zm``, ``am``, ``british_chain_benoit``, ``british_chain_sears_truncated``, ``british_chain_sears``, ``british_ft``, ``british_yd``, ``chain_benoit``, ``chain_sears``, ``chain``, ``clarke_ft``, ``clarke_link``, ``cm``, ``dam``, ``dm``, ``fathom``, ``fm``, ``ft``, ``german_m``, ``gold_coast_ft``, ``hm``, ``inch``, ``indian_yd``, ``km``, ``link_benoit``, ``link_sears``, ``link``, ``m``, ``mi``, ``mm``, ``nm_uk``, ``nm``, ``pm``, ``rod``, ``sears_yd``, ``survey_ft``, ``um``, ``yd``, ``ym``, ``zm`` * *Acceptable as Arguments*: ``British chain (Benoit 1895 B)``, ``British chain (Sears 1922 truncated)``, ``British chain (Sears 1922)``, ``British foot (Sears 1922)``, ``British foot``, ``British yard (Sears 1922)``, ``British yard``, ``Chain (Benoit)``, ``Chain (Sears)``, ``Clarke's Foot``, ``Clarke's link``, ``Foot (International)``, ``German legal metre``, ``Gold Coast foot``, ``Indian yard``, ``Link (Benoit)``, ``Link (Sears)``, ``Nautical Mile (UK)``, ``Nautical Mile``, ``U.S. Foot``, ``US survey foot``, ``Yard (Indian)``, ``Yard (Sears)``, ``attometer``, ``attometre``, ``centimeter``, ``centimetre``, ``decameter``, ``decametre``, ``decimeter``, ``decimetre``, ``exameter``, ``exametre``, ``femtometer``, ``femtometre``, ``foot``, ``gigameter``, ``gigametre``, ``hectometer``, ``hectometre``, ``inches``, ``kilometer``, ``kilometre``, ``megameter``, ``megametre``, ``meter``, ``metre``, ``micrometer``, ``micrometre``, ``mile``, ``millimeter``, ``millimetre``, ``nanometer``, ``nanometre``, ``petameter``, ``petametre``, ``picometer``, ``picometre``, ``terameter``, ``terametre``, ``yard``, ``yoctometer``, ``yoctometre``, ``yottameter``, ``yottametre``, ``zeptometer``, ``zeptometre``, ``zetameter``, ``zetametre`` Energy ------ * *Acceptable as Arguments or Attributes*: ``C``, ``EJ``, ``Ec``, ``GJ``, ``Gc``, ``J``, ``MJ``, ``Mc``, ``PJ``, ``Pc``, ``TJ``, ``Tc``, ``YJ``, ``Yc``, ``ZJ``, ``Zc``, ``aJ``, ``ac``, ``cJ``, ``c``, ``cc``, ``dJ``, ``daJ``, ``dac``, ``dc``, ``fJ``, ``fc``, ``hJ``, ``hc``, ``kJ``, ``kc``, ``mJ``, ``mc``, ``nJ``, ``nc``, ``pJ``, ``pc``, ``uJ``, ``uc``, ``yJ``, ``yc``, ``zJ``, ``zc`` * *Acceptable as Arguments*: ``Calorie``, ``attocalorie``, ``attojoule``, ``calorie``, ``centicalorie``, ``centijoule``, ``decacalorie``, ``decajoule``, ``decicalorie``, ``decijoule``, ``exacalorie``, ``exajoule``, ``femtocalorie``, ``femtojoule``, ``gigacalorie``, ``gigajoule``, ``hectocalorie``, ``hectojoule``, ``joule``, ``kilocalorie``, ``kilojoule``, ``megacalorie``, ``megajoule``, ``microcalorie``, ``microjoule``, ``millicalorie``, ``millijoule``, ``nanocalorie``, ``nanojoule``, ``petacalorie``, ``petajoule``, ``picocalorie``, ``picojoule``, ``teracalorie``, ``terajoule``, ``yoctocalorie``, ``yoctojoule``, ``yottacalorie``, ``yottajoule``, ``zeptocalorie``, ``zeptojoule``, ``zetacalorie``, ``zetajoule`` Speed ----- .. note:: This is a bi-dimensional measurement; bi-dimensional measures are created by finding an appropriate unit in the measure's primary measurement class, and an appropriate in the measure's reference class, and using them as a double-underscore-separated keyword argument (or, if converting to another unit, as an attribute). For example, to create an object representing 24 miles-per hour:: >>> from measurement.measure import Speed >>> my_speed = Speed(mile__hour=24) >>> print my_speed 24.0 mi/hr >>> print my_speed.km__hr 38.624256 * *Primary Measurement*: Distance * *Reference Measurement*: Time Temperature ----------- * *Acceptable as Arguments or Attributes*: ``c``, ``f``, ``k`` * *Acceptable as Arguments*: ``celsius``, ``fahrenheit``, ``kelvin`` .. warning:: Be aware that, unlike other measures, the zero points of the Celsius and Farenheit scales are arbitrary and non-zero. If you attempt, for example, to calculate the average of a series of temperatures using ``sum``, be sure to supply your 'start' (zero) value as zero Kelvin (read: absolute zero) rather than zero degrees Celsius (which is rather warm comparatively):: >>> temperatures = [Temperature(c=10), Temperature(c=20)] >>> average = sum(temperatures, Temperature(k=0)) / len(temperatures) >>> print average # The value will be shown in Kelvin by default since that is the starting unit 288.15 k >>> print average.c # But, you can easily get the Celsius value 15.0 >>> average.unit = 'c' # Or, make the measurement report its value in Celsius by default >>> print average 15.0 c Time ---- * *Acceptable as Arguments or Attributes*: ``Esec``, ``Gsec``, ``Msec``, ``Psec``, ``Tsec``, ``Ysec``, ``Zsec``, ``asec``, ``csec``, ``dasec``, ``day``, ``dsec``, ``fsec``, ``hr``, ``hsec``, ``ksec``, ``min``, ``msec``, ``nsec``, ``psec``, ``sec``, ``usec``, ``ysec``, ``zsec`` * *Acceptable as Arguments*: ``attosecond``, ``centisecond``, ``day``, ``decasecond``, ``decisecond``, ``exasecond``, ``femtosecond``, ``gigasecond``, ``hectosecond``, ``hour``, ``kilosecond``, ``megasecond``, ``microsecond``, ``millisecond``, ``minute``, ``nanosecond``, ``petasecond``, ``picosecond``, ``second``, ``terasecond``, ``yoctosecond``, ``yottasecond``, ``zeptosecond``, ``zetasecond`` Volume ------ * *Acceptable as Arguments or Attributes*: ``El``, ``Gl``, ``Ml``, ``Pl``, ``Tl``, ``Yl``, ``Zl``, ``al``, ``cl``, ``acre_ft``, ``acre_in``, ``cubic_centimeter``, ``cubic_foot``, ``cubic_inch``, ``cubic_meter``, ``dal``, ``dl``, ``fl``, ``hl``, ``imperial_g``, ``imperial_oz``, ``imperial_pint``, ``imperial_qt``, ``imperial_tbsp``, ``imperial_tsp``, ``kl``, ``l``, ``mil_us_gal``, ``ml``, ``nl``, ``pl``, ``ul``, ``us_cup``, ``us_g``, ``us_oz``, ``us_pint``, ``us_qt``, ``us_tbsp``, ``us_tsp``, ``yl``, ``zl`` * *Acceptable as Arguments*: ``af``, ``acre-ft``, ``acre-in``, ``Imperial Gram``, ``Imperial Ounce``, ``Imperial Pint``, ``Imperial Quart``, ``Imperial Tablespoon``, ``Imperial Teaspoon``, ``Million US Gallons``, ``US Cup``, ``US Fluid Ounce``, ``US Gallon``, ``US Ounce``, ``US Pint``, ``US Quart``, ``US Tablespoon``, ``US Teaspoon``, ``attoliter``, ``attolitre``, ``centiliter``, ``centilitre``, ``cubic centimeter``, ``cubic foot``, ``cubic inch``, ``cubic meter``, ``decaliter``, ``decalitre``, ``deciliter``, ``decilitre``, ``exaliter``, ``exalitre``, ``femtoliter``, ``femtolitre``, ``gigaliter``, ``gigalitre``, ``hectoliter``, ``hectolitre``, ``kiloliter``, ``kilolitre``, ``liter``, ``litre``, ``megaliter``, ``megalitre``, ``microliter``, ``microlitre``, ``milliliter``, ``millilitre``, ``nanoliter``, ``nanolitre``, ``petaliter``, ``petalitre``, ``picoliter``, ``picolitre``, ``teraliter``, ``teralitre``, ``yoctoliter``, ``yoctolitre``, ``yottaliter``, ``yottalitre``, ``zeptoliter``, ``zeptolitre``, ``zetaliter``, ``zetalitre`` Weight ------ * *Acceptable as Arguments or Attributes*: ``Eg``, ``Gg``, ``Mg``, ``Pg``, ``Tg``, ``Yg``, ``Zg``, ``ag``, ``cg``, ``dag``, ``dg``, ``fg``, ``g``, ``hg``, ``kg``, ``lb``, ``long_ton``, ``mg``, ``ng``, ``oz``, ``pg``, ``short_ton``, ``stone``, ``tonne``, ``ug``, ``yg``, ``zg`` * *Acceptable as Arguments*: ``attogram``, ``centigram``, ``decagram``, ``decigram``, ``exagram``, ``femtogram``, ``gigagram``, ``gram``, ``hectogram``, ``kilogram``, ``long ton``, ``mcg``, ``megagram``, ``metric ton``, ``metric tonne``, ``microgram``, ``milligram``, ``nanogram``, ``ounce``, ``petagram``, ``picogram``, ``pound``, ``short ton``, ``teragram``, ``ton``, ``yoctogram``, ``yottagram``, ``zeptogram``, ``zetagram`` python-measurement-3.2.2/docs/topics/use.rst000066400000000000000000000044631435731234400211560ustar00rootroot00000000000000 Using Measurement Objects ========================= You can import any of the above measures from `measurement.measures` and use it for easily handling measurements like so:: >>> from measurement.measures import Weight >>> w = Weight(lb=135) # Represents 135lbs >>> print w 135.0 lb >>> print w.kg 61.234919999999995 You can create a measurement unit using any compatible unit and can transform it into any compatible unit. See :doc:`measures` for information about which units are supported by which measures. To access the raw integer value of a measurement in the unit it was defined in, you can use the 'value' property:: >>> print w.value 135.0 Guessing Measurements ===================== If you happen to be in a situation where you are processing a list of value/unit pairs (like you might find at the beginning of a recipe), you can use the `guess` function to give you a measurement object.:: >>> from measurement.utils import guess >>> m = guess(10, 'mg') >>> print repr(m) Weight(mg=10.0) By default, this will check all built-in measures, and will return the first measure having an appropriate unit. You may want to constrain the list of measures checked (or your own measurement classes, too) to make sure that your measurement is not mis-guessed, and you can do that by specifying the ``measures`` keyword argument:: >>> from measurement.measures import Distance, Temperature, Volume >>> m = guess(24, 'f', measures=[Distance, Volume, Temperature]) >>> print repr(m) Temperature(f=24) .. warning:: It is absolutely possible for this to misguess due to common measurement abbreviations overlapping -- for example, both Temperature and Energy accept the argument ``c`` for representing degrees celsius and calories respectively. It is advisible that you constrain the list of measurements to check to ones that you would consider appropriate for your input data. If no match is found, a ``ValueError`` exception will be raised:: >>> m = guess(24, 'f', measures=[Distance, Volume]) Traceback (most recent call last): File "", line 1, in File "measurement/utils.py", line 61, in guess ', '.join([m.__name__ for m in measures]) ValueError: No valid measure found for 24 f; checked Distance, Volume python-measurement-3.2.2/docs/util.py000066400000000000000000000036761435731234400176630ustar00rootroot00000000000000from __future__ import print_function from measurement.base import MeasureBase, BidimensionalMeasure from measurement.utils import get_all_measures for measure in get_all_measures(): classname = measure.__name__ print(classname) print('-' * len(classname)) print() if issubclass(measure, MeasureBase): units = measure.get_units() aliases = measure.get_aliases() print( '* *Acceptable as Arguments or Attributes*: %s' % ( ', '.join(sorted(['``%s``' % unit for unit in units])) ) ) print( '* *Acceptable as Arguments*: %s' % ( ', '.join(sorted(['``%s``' % alias for alias in aliases])) ) ) elif issubclass(measure, BidimensionalMeasure): print(".. note::") print(" This is a bi-dimensional measurement; bi-dimensional") print(" measures are created by finding an appropriate unit in the") print(" measure's primary measurement class, and an appropriate") print(" in the measure's reference class, and using them as a") print(" double-underscore-separated keyword argument (or, if") print(" converting to another unit, as an attribute).") print() print(" For example, to create an object representing 24 miles-per") print(" hour::") print() print(" >>> from measurement.measure import Speed") print(" >>> my_speed = Speed(mile__hour=24)") print(" >>> print my_speed") print(" 24.0 mi/hr") print(" >>> print my_speed.km__hr") print(" 38.624256") print() print( "* *Primary Measurement*: %s" % ( measure.PRIMARY_DIMENSION.__name__ ) ) print( "* *Reference Measurement*: %s" % ( measure.REFERENCE_DIMENSION.__name__ ) ) print() python-measurement-3.2.2/linter-requirements.txt000066400000000000000000000001211435731234400221410ustar00rootroot00000000000000bandit==1.7.4 black==22.10.0 flake8==5.0.4 isort==5.10.1 pydocstyle[toml]==6.1.1 python-measurement-3.2.2/measurement/000077500000000000000000000000001435731234400177155ustar00rootroot00000000000000python-measurement-3.2.2/measurement/__init__.py000066400000000000000000000002341435731234400220250ustar00rootroot00000000000000"""Easily use and manipulate unit-aware measurements in Python.""" from . import _version __version__ = _version.version VERSION = _version.version_tuple python-measurement-3.2.2/measurement/base.py000066400000000000000000000520511435731234400212040ustar00rootroot00000000000000# Copyright (c) 2007, Robert Coup # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of Distance nor the names of its contributors may be used # to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from decimal import Decimal import sympy from sympy.solvers import solve_linear from measurement.utils import total_ordering NUMERIC_TYPES = int, float, Decimal def pretty_name(obj): return obj.__name__ if obj.__class__ == type else obj.__class__.__name__ class classproperty(property): def __get__(self, cls, owner): return self.fget.__get__(None, owner)() @total_ordering class MeasureBase(object): STANDARD_UNIT = None ALIAS = {} UNITS = {} SI_UNITS = [] SI_PREFIXES = { 'yocto': 'y', 'zepto': 'z', 'atto': 'a', 'femto': 'f', 'pico': 'p', 'nano': 'n', 'micro': 'u', 'milli': 'm', 'centi': 'c', 'deci': 'd', 'deca': 'da', 'hecto': 'h', 'kilo': 'k', 'mega': 'M', 'giga': 'G', 'tera': 'T', 'peta': 'P', 'exa': 'E', 'zeta': 'Z', 'yotta': 'Y', } SI_MAGNITUDES = { 'yocto': 1e-24, 'zepto': 1e-21, 'atto': 1e-18, 'femto': 1e-15, 'pico': 1e-12, 'nano': 1e-9, 'micro': 1e-6, 'milli': 1e-3, 'centi': 1e-2, 'deci': 1e-1, 'deca': 1e1, 'hecto': 1e2, 'kilo': 1e3, 'mega': 1e6, 'giga': 1e9, 'tera': 1e12, 'peta': 1e15, 'exa': 1e18, 'zeta': 1e21, 'yotta': 1e24, } def __init__(self, default_unit=None, **kwargs): value, default = self.default_units(kwargs) self._default_unit = default setattr(self, self.STANDARD_UNIT, value) if default_unit and isinstance(default_unit, str): self._default_unit = default_unit @classmethod def get_units(cls): units = cls.UNITS.copy() for unit in cls.SI_UNITS: unit_value = units[unit] for magnitude, value in cls.SI_MAGNITUDES.items(): unit_abbreviation = cls.SI_PREFIXES[magnitude] + unit units[unit_abbreviation] = unit_value * value return units @classmethod def get_si_aliases(cls): si_aliases = {} for alias, abbrev in cls.ALIAS.items(): if abbrev in cls.SI_UNITS: si_aliases[alias] = abbrev return si_aliases @classmethod def get_aliases(cls): aliases = cls.ALIAS.copy() si_aliases = cls.get_si_aliases() for si_alias, unit_abbrev in si_aliases.items(): for magnitude, _ in cls.SI_MAGNITUDES.items(): magnitude_alias = magnitude + si_alias prefix = cls.SI_PREFIXES[magnitude] aliases[magnitude_alias] = prefix + unit_abbrev return aliases @classmethod def get_lowercase_aliases(self): lowercased = {} for alias, value in self.get_aliases().items(): lowercased[alias.lower()] = value return lowercased @property def standard(self): return getattr(self, self.STANDARD_UNIT) @standard.setter def standard(self, value): setattr(self, self.STANDARD_UNIT, value) @property def value(self): return getattr(self, self._default_unit) @value.setter def value(self, value): units = self.get_units() u1 = units[self.STANDARD_UNIT] u2 = units[self.unit] self.standard = value * (u2 / u1) @property def unit(self): return self._default_unit @unit.setter def unit(self, value): aliases = self.get_aliases() laliases = self.get_lowercase_aliases() units = self.get_units() unit = None if value in self.UNITS: unit = value elif value in aliases: unit = aliases[value] elif value.lower() in units: unit = value.lower() elif value.lower() in laliases: unit = laliases[value.lower] if not unit: raise ValueError('Invalid unit %s' % value) self._default_unit = unit def __getattr__(self, name): units = self.get_units() if name in units: return self._convert_value_to( units[name], self.standard, ) else: raise AttributeError('Unknown unit type: %s' % name) def __repr__(self): return '%s(%s=%s)' % ( pretty_name(self), self.unit, getattr(self, self._default_unit) ) def __str__(self): return '%s %s' % ( getattr(self, self._default_unit), self.unit ) # **** Comparison methods **** def __eq__(self, other): if isinstance(other, self.__class__): return self.standard == other.standard else: return NotImplemented def __lt__(self, other): if isinstance(other, self.__class__): return self.standard < other.standard else: return NotImplemented # **** Operators methods **** def __add__(self, other): if isinstance(other, self.__class__): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard + other.standard)} ) else: raise TypeError( '%(class)s must be added with %(class)s' % { "class": pretty_name(self) } ) def __iadd__(self, other): if isinstance(other, self.__class__): self.standard += other.standard return self else: raise TypeError( '%(class)s must be added with %(class)s' % { "class": pretty_name(self) } ) def __sub__(self, other): if isinstance(other, self.__class__): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard - other.standard)} ) else: raise TypeError( '%(class)s must be subtracted from %(class)s' % { "class": pretty_name(self) } ) def __isub__(self, other): if isinstance(other, self.__class__): self.standard -= other.standard return self else: raise TypeError( '%(class)s must be subtracted from %(class)s' % { "class": pretty_name(self) } ) def __mul__(self, other): if isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard * other)} ) else: raise TypeError( '%(class)s must be multiplied with number' % { "class": pretty_name(self) } ) def __imul__(self, other): if isinstance(other, NUMERIC_TYPES): self.standard *= float(other) return self else: raise TypeError( '%(class)s must be multiplied with number' % { "class": pretty_name(self) } ) def __rmul__(self, other): return self * other def __truediv__(self, other): if isinstance(other, self.__class__): return self.standard / other.standard if isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard / other)} ) else: raise TypeError( '%(class)s must be divided with number or %(class)s' % { "class": pretty_name(self) } ) def __div__(self, other): # Python 2 compatibility return type(self).__truediv__(self, other) def __itruediv__(self, other): if isinstance(other, NUMERIC_TYPES): self.standard /= float(other) return self else: raise TypeError( '%(class)s must be divided with number' % { "class": pretty_name(self) } ) def __idiv__(self, other): # Python 2 compatibility return type(self).__itruediv__(self, other) def __bool__(self): return bool(self.standard) def __nonzero__(self): # Python 2 compatibility return type(self).__bool__(self) def _convert_value_to(self, unit, value): if not isinstance(value, float): value = float(value) if isinstance(unit, sympy.Expr): result = unit.evalf( subs={ self.SU: value } ) return float(result) return value / unit def _convert_value_from(self, unit, value): if not isinstance(value, float): value = float(value) if isinstance(unit, sympy.Expr): _, result = solve_linear(unit, value) return result return unit * value def default_units(self, kwargs): """ Return the unit value and the default units specified from the given keyword arguments dictionary. """ aliases = self.get_aliases() laliases = self.get_lowercase_aliases() units = self.get_units() val = 0.0 default_unit = self.STANDARD_UNIT for unit, value in kwargs.items(): if unit in units: val = self._convert_value_from(units[unit], value) default_unit = unit elif unit in aliases: u = aliases[unit] val = self._convert_value_from(units[u], value) default_unit = u else: lower = unit.lower() if lower in units: val = self._convert_value_from(units[lower], value) default_unit = lower elif lower in laliases: u = laliases[lower] val = self._convert_value_from(units[u], value) default_unit = u else: raise AttributeError('Unknown unit type: %s' % unit) return val, default_unit @classmethod def unit_attname(cls, unit_str): """ Retrieves the unit attribute name for the given unit string. For example, if the given unit string is 'metre', 'm' would be returned. An exception is raised if an attribute cannot be found. """ laliases = cls.get_lowercase_aliases() units = cls.get_units() lower = unit_str.lower() if unit_str in units: return unit_str elif lower in units: return lower elif lower in laliases: return laliases[lower] else: raise Exception( 'Could not find a unit keyword associated with "%s"' % ( unit_str, ) ) @total_ordering class BidimensionalMeasure(object): PRIMARY_DIMENSION = None REFERENCE_DIMENSION = None ALIAS = { } def __init__(self, **kwargs): if 'primary' in kwargs and 'reference' in kwargs: self.primary = kwargs['primary'] self.reference = kwargs['reference'] else: if len(kwargs) > 1: raise ValueError('Only one keyword argument is expected') measure_string, value = kwargs.popitem() self.primary, self.reference = self._get_measures( measure_string, value ) def _get_unit_parts(self, measure_string): if measure_string in self.ALIAS: measure_string = self.ALIAS[measure_string] try: primary_unit, reference_unit = measure_string.split('__') except ValueError: raise AttributeError( ( 'Unit not found: \'%s\';' 'Units should be expressed using double-underscore ' 'separated units; for example: meters-per-second would be ' 'expressed with either \'meter__second\' or \'m__sec\'.' ) % ( measure_string ) ) return primary_unit, reference_unit def _get_measures(self, measure_string, value): primary_unit, reference_unit = self._get_unit_parts(measure_string) primary = self.PRIMARY_DIMENSION(**{primary_unit: value}) reference = self.REFERENCE_DIMENSION(**{reference_unit: 1}) return primary, reference @property def standard(self): return self.primary.standard / self.reference.standard @classproperty @classmethod def STANDARD_UNIT(self): return '%s__%s' % ( self.PRIMARY_DIMENSION.STANDARD_UNIT, self.REFERENCE_DIMENSION.STANDARD_UNIT, ) @property def value(self): return self.primary.value @property def unit(self): return '%s__%s' % ( self.primary.unit, self.reference.unit, ) @unit.setter def unit(self, value): primary, reference = value.split('__') reference_units = self.REFERENCE_DIMENSION.get_units() if reference != self.reference.unit: reference_chg = ( reference_units[self.reference.unit]/reference_units[reference] ) self.primary.standard = self.primary.standard / reference_chg self.primary.unit = primary self.reference.unit = reference def _normalize(self, other): std_value = getattr(other, self.unit) primary = self.PRIMARY_DIMENSION(**{self.primary.unit: std_value}) reference = self.REFERENCE_DIMENSION(**{self.reference.unit: 1}) return self.__class__(primary=primary, reference=reference) def __getattr__(self, measure_string): primary_units = self.PRIMARY_DIMENSION.get_units() reference_units = self.REFERENCE_DIMENSION.get_units() p1, r1 = self.primary.unit, self.reference.unit p2, r2 = self._get_unit_parts(measure_string) primary_chg = primary_units[p2]/primary_units[p1] reference_chg = reference_units[r2]/reference_units[r1] return self.primary.value / primary_chg * reference_chg def __repr__(self): return '%s(%s__%s=%s)' % ( pretty_name(self), self.primary.unit, self.reference.unit, self.primary.value, ) def __str__(self): return '%s %s/%s' % ( self.primary.value, self.primary.unit, self.reference.unit, ) def __eq__(self, other): if isinstance(other, self.__class__): return self.standard == other.standard else: return NotImplemented def __lt__(self, other): if isinstance(other, self.__class__): return self.standard < other.standard else: return NotImplemented def __add__(self, other): if isinstance(other, self.__class__): normalized = self._normalize(other) total_value = normalized.primary.value + self.primary.value return self.__class__( primary=self.PRIMARY_DIMENSION( **{self.primary.unit: total_value} ), reference=self.REFERENCE_DIMENSION( **{self.reference.unit: 1} ) ) else: raise TypeError( '%(class)s must be added with %(class)s' % { "class": pretty_name(self) } ) def __iadd__(self, other): if isinstance(other, self.__class__): normalized = self._normalize(other) self.primary.standard += normalized.primary.standard return self else: raise TypeError( '%(class)s must be added with %(class)s' % { "class": pretty_name(self) } ) def __sub__(self, other): if isinstance(other, self.__class__): normalized = self._normalize(other) total_value = self.primary.value - normalized.primary.value return self.__class__( primary=self.PRIMARY_DIMENSION( **{self.primary.unit: total_value} ), reference=self.REFERENCE_DIMENSION( **{self.reference.unit: 1} ) ) else: raise TypeError( '%(class)s must be added with %(class)s' % { "class": pretty_name(self) } ) def __isub__(self, other): if isinstance(other, self.__class__): normalized = self._normalize(other) self.primary.standard -= normalized.primary.standard return self else: raise TypeError( '%(class)s must be added with %(class)s' % { "class": pretty_name(self) } ) def __mul__(self, other): if isinstance(other, NUMERIC_TYPES): total_value = self.primary.value * other return self.__class__( primary=self.PRIMARY_DIMENSION( **{self.primary.unit: total_value} ), reference=self.REFERENCE_DIMENSION( **{self.reference.unit: 1} ) ) else: raise TypeError( '%(class)s must be multiplied with number' % { "class": pretty_name(self) } ) def __rmul__(self, other): return self * other def __imul__(self, other): if isinstance(other, NUMERIC_TYPES): self.primary.standard *= float(other) return self else: raise TypeError( '%(class)s must be multiplied with number' % { "class": pretty_name(self) } ) def __truediv__(self, other): if isinstance(other, self.__class__): normalized = self._normalize(other) return self.primary.standard / normalized.primary.standard if isinstance(other, NUMERIC_TYPES): total_value = self.primary.value / other return self.__class__( primary=self.PRIMARY_DIMENSION( **{self.primary.unit: total_value} ), reference=self.REFERENCE_DIMENSION( **{self.reference.unit: 1} ) ) else: raise TypeError( '%(class)s must be divided with number or %(class)s' % { "class": pretty_name(self) } ) def __itruediv__(self, other): if isinstance(other, NUMERIC_TYPES): self.primary.standard /= float(other) return self else: raise TypeError( '%(class)s must be divided with number' % { "class": pretty_name(self) } ) def __div__(self, other): # Python 2 compatibility return type(self).__truediv__(self, other) def __idiv__(self, other): # Python 2 compatibility return type(self).__itruediv__(self, other) def __bool__(self): return bool(self.primary.standard) def __nonzero__(self): # Python 2 compatibility return type(self).__bool__(self) python-measurement-3.2.2/measurement/measures/000077500000000000000000000000001435731234400215415ustar00rootroot00000000000000python-measurement-3.2.2/measurement/measures/__init__.py000066400000000000000000000012301435731234400236460ustar00rootroot00000000000000from measurement.measures.distance import * from measurement.measures.energy import * from measurement.measures.temperature import * from measurement.measures.volume import * from measurement.measures.volumetric_flow import * from measurement.measures.mass import * from measurement.measures.speed import * from measurement.measures.time import * from measurement.measures.voltage import * from measurement.measures.resistance import * from measurement.measures.capacitance import * from measurement.measures.frequency import * from measurement.measures.current import * from measurement.measures.pressure import * from measurement.measures.radioactivity import * python-measurement-3.2.2/measurement/measures/capacitance.py000066400000000000000000000003521435731234400243460ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Capacitance' ] class Capacitance(MeasureBase): STANDARD_UNIT = 'F' UNITS = { 'F': 1.0, } ALIAS = { 'farad': 'F', } SI_UNITS = ['F'] python-measurement-3.2.2/measurement/measures/current.py000066400000000000000000000003671435731234400236030ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Current' ] class Current(MeasureBase): STANDARD_UNIT = 'A' UNITS = { 'A': 1.0, } ALIAS = { 'amp': 'A', 'ampere': 'A', } SI_UNITS = ['A'] python-measurement-3.2.2/measurement/measures/distance.py000066400000000000000000000137671435731234400237230ustar00rootroot00000000000000# Copyright (c) 2007, Robert Coup # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of Distance nor the names of its contributors may be used # to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # """ Distance and Area objects to allow for sensible and convenient calculation and conversions. Authors: Robert Coup, Justin Bronn, Riccardo Di Virgilio Inspired by GeoPy (http://exogen.case.edu/projects/geopy/) and Geoff Biggs' PhD work on dimensioned units for robotics. """ from measurement.base import MeasureBase, NUMERIC_TYPES, pretty_name __all__ = [ 'Distance', 'Area', ] AREA_PREFIX = "sq_" class Distance(MeasureBase): STANDARD_UNIT = "m" UNITS = { 'chain': 20.1168, 'chain_benoit': 20.116782, 'chain_sears': 20.1167645, 'british_chain_benoit': 20.1167824944, 'british_chain_sears': 20.1167651216, 'british_chain_sears_truncated': 20.116756, 'british_ft': 0.304799471539, 'british_yd': 0.914398414616, 'clarke_ft': 0.3047972654, 'clarke_link': 0.201166195164, 'fathom': 1.8288, 'ft': 0.3048, 'german_m': 1.0000135965, 'gold_coast_ft': 0.304799710181508, 'indian_yd': 0.914398530744, 'inch': 0.0254, 'link': 0.201168, 'link_benoit': 0.20116782, 'link_sears': 0.20116765, 'm': 1.0, 'mi': 1609.344, 'nm_uk': 1853.184, 'rod': 5.0292, 'sears_yd': 0.91439841, 'survey_ft': 0.304800609601, 'yd': 0.9144, } SI_UNITS = [ 'm' ] # Unit aliases for `UNIT` terms encountered in Spatial Reference WKT. ALIAS = { 'foot': 'ft', 'inches': 'inch', 'in': 'inch', 'meter': 'm', 'metre': 'm', 'mile': 'mi', 'yard': 'yd', 'British chain (Benoit 1895 B)': 'british_chain_benoit', 'British chain (Sears 1922)': 'british_chain_sears', 'British chain (Sears 1922 truncated)': ( 'british_chain_sears_truncated' ), 'British foot (Sears 1922)': 'british_ft', 'British foot': 'british_ft', 'British yard (Sears 1922)': 'british_yd', 'British yard': 'british_yd', "Clarke's Foot": 'clarke_ft', "Clarke's link": 'clarke_link', 'Chain (Benoit)': 'chain_benoit', 'Chain (Sears)': 'chain_sears', 'Foot (International)': 'ft', 'German legal metre': 'german_m', 'Gold Coast foot': 'gold_coast_ft', 'Indian yard': 'indian_yd', 'Link (Benoit)': 'link_benoit', 'Link (Sears)': 'link_sears', 'Nautical Mile': 'nm', 'Nautical Mile (UK)': 'nm_uk', 'US survey foot': 'survey_ft', 'U.S. Foot': 'survey_ft', 'Yard (Indian)': 'indian_yd', 'Yard (Sears)': 'sears_yd' } def __mul__(self, other): if isinstance(other, self.__class__): return Area( default_unit=AREA_PREFIX + self._default_unit, **{ AREA_PREFIX + self.STANDARD_UNIT: ( self.standard * other.standard ) } ) elif isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard * other)} ) else: raise TypeError( '%(dst)s must be multiplied with number or %(dst)s' % { "dst": pretty_name(self.__class__), } ) class Area(MeasureBase): STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT # Getting the square units values and the alias dictionary. UNITS = { **{ '%s%s' % (AREA_PREFIX, k): v ** 2 for k, v in Distance.get_units().items() }, 'acre': 43560 * (Distance(ft=1).m ** 2), 'hectare': (10000), # 10,000 sq_m } ALIAS = { **{ k: '%s%s' % (AREA_PREFIX, v) for k, v in Distance.get_aliases().items() }, 'Acre': 'acre', 'Hectare': 'hectare', 'ha': 'hectare', } def __truediv__(self, other): if isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard / other)} ) else: raise TypeError( '%(class)s must be divided by a number' % { "class": pretty_name(self) } ) def __div__(self, other): # Python 2 compatibility return type(self).__truediv__(self, other) python-measurement-3.2.2/measurement/measures/energy.py000066400000000000000000000006201435731234400234020ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Energy' ] class Energy(MeasureBase): STANDARD_UNIT = 'J' UNITS = { 'c': 4.18400, 'C': 4184.0, 'J': 1.0, 'eV': 1.602177e-19, 'tonne_tnt': 4184000000, } ALIAS = { 'joule': 'J', 'calorie': 'c', 'Calorie': 'C', } SI_UNITS = ['J', 'c', 'eV', 'tonne_tnt'] python-measurement-3.2.2/measurement/measures/frequency.py000066400000000000000000000004031435731234400241110ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Frequency' ] class Frequency(MeasureBase): STANDARD_UNIT = 'Hz' UNITS = { 'Hz': 1.0, 'rpm': 1.0 / 60, } ALIAS = { 'hertz': 'Hz', } SI_UNITS = ['Hz'] python-measurement-3.2.2/measurement/measures/mass.py000066400000000000000000000012321435731234400230540ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Mass', 'Weight', ] class Mass(MeasureBase): STANDARD_UNIT = 'g' UNITS = { 'g': 1.0, 'tonne': 1000000.0, 'oz': 28.3495, 'lb': 453.592, 'stone': 6350.29, 'short_ton': 907185.0, 'long_ton': 1016000.0, } ALIAS = { 'mcg': 'ug', 'gram': 'g', 'ton': 'short_ton', 'metric tonne': 'tonne', 'metric ton': 'tonne', 'ounce': 'oz', 'pound': 'lb', 'short ton': 'short_ton', 'long ton': 'long_ton', } SI_UNITS = ['g'] # For backward compatibility Weight = Mass python-measurement-3.2.2/measurement/measures/pressure.py000066400000000000000000000010421435731234400237600ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Pressure' ] class Pressure(MeasureBase): """Pressure measurements.""" STANDARD_UNIT = 'pa' UNITS = { 'pa': 1.0, 'bar': 100000, 'at': 98066.5, 'atm': 101325, 'torr': 133.322, 'psi': 6894.757293168, } ALIAS = { 'pascal': 'pa', 'bar': 'bar', 'technical atmosphere': 'at', 'atmosphere': 'atm', 'torr': 'torr', 'pounds per square inch': 'psi' } SI_UNITS = ['pa'] python-measurement-3.2.2/measurement/measures/radioactivity.py000066400000000000000000000007531435731234400247730ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Radioactivity' ] class Radioactivity(MeasureBase): """Radioactivity measurements.""" STANDARD_UNIT = 'bq' UNITS = { 'bq': 1, 'ci': 37000000000, 'rd': 1000000, 'dpm': 1/60, } ALIAS = { 'becquerel': 'bq', 'Bq': 'bq', 'curie': 'ci', 'Ci': 'ci', 'rutherford': 'rd', 'disintegrations per minute': 'dpm', } SI_UNITS = ['bq'] python-measurement-3.2.2/measurement/measures/resistance.py000066400000000000000000000003301435731234400242470ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Resistance' ] class Resistance(MeasureBase): STANDARD_UNIT = 'ohm' UNITS = { 'ohm': 1.0, } ALIAS = { } SI_UNITS = ['ohm'] python-measurement-3.2.2/measurement/measures/speed.py000066400000000000000000000005301435731234400232110ustar00rootroot00000000000000from measurement.base import BidimensionalMeasure from measurement.measures.distance import Distance from measurement.measures.time import Time __all__ = [ 'Speed' ] class Speed(BidimensionalMeasure): PRIMARY_DIMENSION = Distance REFERENCE_DIMENSION = Time ALIAS = { 'mph': 'mi__hr', 'kph': 'km__hr', } python-measurement-3.2.2/measurement/measures/temperature.py000066400000000000000000000006131435731234400244500ustar00rootroot00000000000000from sympy import S, Symbol from measurement.base import MeasureBase __all__ = [ 'Temperature' ] class Temperature(MeasureBase): SU = Symbol('kelvin') STANDARD_UNIT = 'k' UNITS = { 'c': SU - S(273.15), 'f': (SU - S(273.15)) * S('9/5') + 32, 'k': 1.0 } ALIAS = { 'celsius': 'c', 'fahrenheit': 'f', 'kelvin': 'k', } python-measurement-3.2.2/measurement/measures/time.py000066400000000000000000000013001435731234400230430ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Time', ] class Time(MeasureBase): """Time measurements (generally for multidimensional measures). Please do not use this for handling durations of time unrelated to measure classes -- python's built-in datetime module has much better functionality for handling intervals of time than this class provides. """ STANDARD_UNIT = 's' UNITS = { 's': 1.0, 'min': 60.0, 'hr': 3600.0, 'day': 86400.0 } ALIAS = { 'second': 's', 'sec': 's', # For backward compatibility 'minute': 'min', 'hour': 'hr', 'day': 'day' } SI_UNITS = ['s'] python-measurement-3.2.2/measurement/measures/voltage.py000066400000000000000000000003371435731234400235570ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Voltage' ] class Voltage(MeasureBase): STANDARD_UNIT = 'V' UNITS = { 'V': 1.0 } ALIAS = { 'volt': 'V' } SI_UNITS = ['V'] python-measurement-3.2.2/measurement/measures/volume.py000066400000000000000000000037701435731234400234310ustar00rootroot00000000000000from measurement.base import MeasureBase __all__ = [ 'Volume', ] class Volume(MeasureBase): STANDARD_UNIT = 'cubic_meter' UNITS = { 'us_g': 0.00378541, 'mil_us_g': 3785.41, 'us_qt': 0.000946353, 'us_pint': 0.000473176, 'us_cup': 0.000236588, 'us_oz': 2.9574e-5, 'us_tbsp': 1.4787e-5, 'us_tsp': 4.9289e-6, 'cubic_millimeter': 0.000000001, 'cubic_centimeter': 0.000001, 'cubic_decimeter': 0.001, 'cubic_meter': 1.0, 'l': 0.001, 'cubic_foot': 0.0283168, 'cubic_inch': 1.6387e-5, 'cubic_yard': 0.76455486121558, 'imperial_g': 0.00454609, 'imperial_qt': 0.00113652, 'imperial_pint': 0.000568261, 'imperial_oz': 2.8413e-5, 'imperial_tbsp': 1.7758e-5, 'imperial_tsp': 5.9194e-6, 'acre_in': 102.79015461, 'acre_ft': 1233.48185532, } ALIAS = { 'US Gallon': 'us_g', 'Million US Gallons': 'mil_us_g', 'US Quart': 'us_qt', 'US Pint': 'us_pint', 'US Cup': 'us_cup', 'US Ounce': 'us_oz', 'US Fluid Ounce': 'us_oz', 'US Tablespoon': 'us_tbsp', 'US Teaspoon': 'us_tsp', 'cubic millimeter': 'cubic_millimeter', 'cubic centimeter': 'cubic_centimeter', 'cubic decimeter': 'cubic_decimeter', 'cubic meter': 'cubic_meter', 'liter': 'l', 'litre': 'l', 'cubic foot': 'cubic_foot', 'cubic inch': 'cubic_inch', 'cubic yard': 'cubic_yard', 'Imperial Gram': 'imperial_g', 'Imperial Quart': 'imperial_qt', 'Imperial Pint': 'imperial_pint', 'Imperial Ounce': 'imperial_oz', 'Imperial Tablespoon': 'imperial_tbsp', 'Imperial Teaspoon': 'imperial_tsp', 'acre-in': 'acre_in', 'acre-ft': 'acre_ft', 'af': 'acre_ft', } SI_UNITS = ['l'] def __init__(self, *args, **kwargs): super(Volume, self).__init__(*args, **kwargs) python-measurement-3.2.2/measurement/measures/volumetric_flow.py000066400000000000000000000023741435731234400253410ustar00rootroot00000000000000from measurement.base import BidimensionalMeasure from measurement.measures.time import Time from measurement.measures.volume import Volume __all__ = [ 'VolumetricFlow' ] class VolumetricFlow(BidimensionalMeasure): """Volumetric Flow measurements (generally for water flow).""" PRIMARY_DIMENSION = Volume REFERENCE_DIMENSION = Time ALIAS = { 'cfs': 'cubic_foot__s', 'cubic feet per second': 'cubic_foot__s', 'cubic feet per minute': 'cubic_foot__min', 'cubic feet per hour': 'cubic_foot__hr', 'cubic feet per day': 'cubic_foot__day', 'cubic yards per second': 'cubic_yard__s', 'cubic yards per minute': 'cubic_yard__min', 'cubic yards per hour': 'cubic_yard__hr', 'cubic yards per day': 'cubic_yard__day', 'gps': 'us_g__s', 'gpm': 'us_g__min', 'gph': 'us_g__hr', 'gpd': 'us_g__day', 'cms': 'cubic_meter__s', 'cumecs': 'cubic_meter__s', 'million gallons per hour': 'mil_us_g__hr', 'million gallons per day': 'mil_us_g__day', 'acre-inches per hour': 'acre_in__hr', 'acre-inches per day': 'acre_in__day', 'acre-feet per hour': 'acre_ft__hr', 'acre-feet per day': 'acre_ft__day', } python-measurement-3.2.2/measurement/utils.py000066400000000000000000000050641435731234400214340ustar00rootroot00000000000000import inspect import sys if sys.version_info >= (2,7,2): from functools import total_ordering else: # For Python < 2.7.2. Python 2.6 does not have total_ordering, and # total_ordering in 2.7 versions prior to 2.7.2 is buggy. See # http://bugs.python.org/issue10042 for details. For these versions use # code borrowed from Python 2.7.3. def total_ordering(cls): """Class decorator that fills in missing ordering methods""" convert = { '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), ('__le__', lambda self, other: self < other or self == other), ('__ge__', lambda self, other: not self < other)], '__le__': [('__ge__', lambda self, other: not self <= other or self == other), ('__lt__', lambda self, other: self <= other and not self == other), ('__gt__', lambda self, other: not self <= other)], '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)), ('__ge__', lambda self, other: self > other or self == other), ('__le__', lambda self, other: not self > other)], '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other), ('__gt__', lambda self, other: self >= other and not self == other), ('__lt__', lambda self, other: not self >= other)] } roots = set(dir(cls)) & set(convert) if not roots: raise ValueError('must define at least one ordering operation: < > <= >=') root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ for opname, opfunc in convert[root]: if opname not in roots: opfunc.__name__ = opname opfunc.__doc__ = getattr(int, opname).__doc__ setattr(cls, opname, opfunc) return cls def get_all_measures(): from measurement import measures m = [] for name, obj in inspect.getmembers(measures): if inspect.isclass(obj): m.append(obj) return m def guess(value, unit, measures=None): if measures is None: measures = get_all_measures() for measure in measures: try: return measure(**{unit: value}) except AttributeError: pass raise ValueError( 'No valid measure found for %s %s; checked %s' % ( value, unit, ', '.join([m.__name__ for m in measures]) ) ) python-measurement-3.2.2/pyproject.toml000066400000000000000000000041461435731234400203110ustar00rootroot00000000000000[build-system] requires = ["flit_core>=3.2", "flit_scm", "wheel"] build-backend = "flit_scm:buildapi" [project] name = "measurement" authors = [ { name = "Adam Coddington", email = "me@adamcoddington.net" }, { name = "Johannes Maron", email = "johannes@maron.family" } ] readme = "README.rst" license = { file = "LICENSE" } dynamic = ["version", "description"] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: JavaScript", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3 :: Only", "Topic :: Software Development", "Topic :: Utilities", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Astronomy", "Topic :: Scientific/Engineering :: Atmospheric Science", "Topic :: Scientific/Engineering :: Chemistry", "Topic :: Scientific/Engineering :: GIS", "Topic :: Scientific/Engineering :: Mathematics", "Topic :: Scientific/Engineering :: Physics", "Topic :: Software Development :: Localization", ] keywords = [ "measurement", ] requires-python = ">=3.7" dependencies = [ "sympy" ] [project.optional-dependencies] test = [ "pytest", "pytest-cov", ] docs = [ "sphinx", "python-docs-theme", ] [project.urls] Project-URL = "http://github.com/coddingtonbear/python-measurement" [tool.flit.module] name = "measurement" [tool.setuptools_scm] write_to = "measurement/_version.py" [tool.pytest.ini_options] minversion = "6.0" addopts = "--doctest-glob=*.rst --doctest-modules --cov=measurement" testpaths = [ "tests", ] [tool.coverage.report] show_missing = true [tool.isort] atomic = true line_length = 88 known_first_party = "measurement, tests" include_trailing_comma = true default_section = "THIRDPARTY" combine_as_imports = true [tool.pydocstyle] add_ignore = "D1" match_dir = "(?!tests|env|docs|\\.).*" match = "(?!setup).*.py" python-measurement-3.2.2/setup.cfg000066400000000000000000000001241435731234400172060ustar00rootroot00000000000000[flake8] max-line-length=88 select = C,E,F,W,B,B950 ignore = E203, E501, W503, E731 python-measurement-3.2.2/tests/000077500000000000000000000000001435731234400165325ustar00rootroot00000000000000python-measurement-3.2.2/tests/__init__.py000066400000000000000000000000001435731234400206310ustar00rootroot00000000000000python-measurement-3.2.2/tests/base.py000066400000000000000000000001111435731234400200070ustar00rootroot00000000000000import unittest class MeasurementTestBase(unittest.TestCase): pass python-measurement-3.2.2/tests/test_distance.py000066400000000000000000000033571435731234400217450ustar00rootroot00000000000000# -*- coding: utf-8 -*- from .base import MeasurementTestBase from measurement.measures import Distance, Area class DistanceTest(MeasurementTestBase): def test_conversion_equivalence(self): miles = Distance(mi=1) kilometers = Distance(km=1.609344) self.assertAlmostEqual( miles.km, kilometers.km ) def test_attrib_conversion(self): kilometers = Distance(km=1) expected_meters = 1000 self.assertAlmostEqual( kilometers.m, expected_meters ) def test_identity_conversion(self): expected_miles = 10 miles = Distance(mi=expected_miles) self.assertAlmostEqual( miles.mi, expected_miles ) def test_auto_si_kwargs(self): meters = Distance(meter=1e6) megameters = Distance(megameter=1) self.assertEqual( meters, megameters, ) def test_auto_si_attrs(self): one_meter = Distance(m=1) micrometers = one_meter.um self.assertEqual( one_meter.value * 10**6, micrometers ) def test_area_sq_km(self): one_sq_km = Area(sq_km=10) miles_sqd = Area(sq_mi=3.8610216) self.assertAlmostEqual( one_sq_km.standard, miles_sqd.standard, places=1 ) def test_set_value(self): distance = Distance(mi=10) expected_standard = 16093.44 self.assertEqual( distance.standard, expected_standard, ) distance.value = 11 expected_standard = 17702.784 self.assertEqual( distance.standard, expected_standard ) python-measurement-3.2.2/tests/test_energy.py000066400000000000000000000005261435731234400214370ustar00rootroot00000000000000from .base import MeasurementTestBase from measurement.measures import Energy class EnergyTest(MeasurementTestBase): def test_dietary_calories_kwarg(self): calories = Energy(Calorie=2000) kilojoules = Energy(kJ=8368) self.assertEqual( calories.standard, kilojoules.standard, ) python-measurement-3.2.2/tests/test_speed.py000066400000000000000000000107241435731234400212470ustar00rootroot00000000000000from .base import MeasurementTestBase from measurement.measures import Speed class SpeedTest(MeasurementTestBase): def test_attrconversion(self): meters_per_second = Speed(meter__second=10) miles_per_hour = 22.3694 self.assertAlmostEqual( miles_per_hour, meters_per_second.mi__hr, places=3 ) def test_attrconversion_nonstandard(self): miles_per_hour = Speed(mi__hr=22.3694) kilometers_per_minute = 0.599748864 self.assertAlmostEqual( kilometers_per_minute, miles_per_hour.km__min, places=3 ) def test_addition(self): train_1 = Speed(mile__hour=10) train_2 = Speed(mile__hour=5) actual_value = train_1 + train_2 expected_value = Speed(mile__hour=15) self.assertEqual( actual_value, expected_value ) def test_iadd(self): train_1 = Speed(mile__hour=10) train_2 = Speed(mile__hour=5) actual_value = train_1 actual_value += train_2 expected_value = Speed(mile__hour=15) self.assertEqual( actual_value, expected_value, ) def test_sub(self): train_1 = Speed(mile__hour=10) train_2 = Speed(mile__hour=5) expected_value = Speed(mile__hour=5) actual_value = train_1 - train_2 self.assertEqual( expected_value, actual_value ) def test_isub(self): train_1 = Speed(mile__hour=10) train_2 = Speed(mile__hour=5) expected_value = Speed(mile__hour=5) actual_value = train_1 actual_value -= train_2 self.assertEqual( expected_value, actual_value, ) def test_mul(self): train_1 = Speed(mile__hour=10) multiplier = 2 actual_value = multiplier * train_1 expected_value = Speed(mile__hour=20) self.assertEqual( actual_value, expected_value, ) def test_imul(self): train_1 = Speed(mile__hour=10) multiplier = 2 actual_value = train_1 actual_value *= multiplier expected_value = Speed(mile__hour=20) self.assertEqual( actual_value, expected_value, ) def test_div(self): train_1 = Speed(mile__hour=10) divider = 2 actual_value = train_1 / divider expected_value = Speed(mile__hour=5) self.assertEqual( actual_value, expected_value, ) def test_idiv(self): train_1 = Speed(mile__hour=10) divider = 2 actual_value = train_1 actual_value /= divider expected_value = Speed(mile__hour=5) self.assertEqual( actual_value, expected_value, ) def test_equals(self): train_1 = Speed(mile__hour=10) train_2 = Speed(mile__hour=10) self.assertEqual( train_1, train_2, ) def test_lt(self): train_1 = Speed(mile__hour=5) train_2 = Speed(mile__hour=10) self.assertTrue( train_1 < train_2 ) def test_bool_true(self): train_1 = Speed(mile__hour=5) self.assertTrue( train_1 ) def test_bool_false(self): train_1 = Speed(mile__hour=0) self.assertFalse( train_1 ) def test_abbreviations(self): train_1 = Speed(mph=4) train_2 = Speed(mile__hour=4) self.assertEqual( train_1, train_2 ) def test_different_units_addition(self): train = Speed(mile__hour=10) increase = Speed(km__day=2) two_km_day_in_mph = 0.0517809327 expected_speed = Speed(mile__hour=10 + two_km_day_in_mph) actual_speed = train + increase self.assertAlmostEqual( expected_speed.standard, actual_speed.standard, ) def test_aliases(self): speed = Speed(mph=10) expected_kph = 16.09344 actual_kph = speed.kph self.assertAlmostEqual( expected_kph, actual_kph, ) def test_set_unit(self): speed = Speed(mi__hr=10) speed.unit = 'm__s' expected_value = 4.4704 actual_value = speed.value self.assertAlmostEqual( expected_value, actual_value, ) python-measurement-3.2.2/tests/test_temperature.py000066400000000000000000000013771435731234400225100ustar00rootroot00000000000000from .base import MeasurementTestBase from measurement.measures import Temperature class TemperatureTest(MeasurementTestBase): def test_sanity(self): fahrenheit = Temperature(fahrenheit=70) celsius = Temperature(celsius=21.1111111) self.assertAlmostEqual( fahrenheit.k, celsius.k ) def test_conversion_to_non_si(self): celsius = Temperature(celsius=21.1111111) expected_farenheit = 70 self.assertAlmostEqual( celsius.f, expected_farenheit ) def test_ensure_that_we_always_output_float(self): kelvin = Temperature(kelvin=10) celsius = kelvin.c self.assertTrue( isinstance(celsius, float) ) python-measurement-3.2.2/tests/test_utils.py000066400000000000000000000011731435731234400213050ustar00rootroot00000000000000from .base import MeasurementTestBase from measurement.measures import Mass, Distance, Temperature from measurement.utils import guess class UtilsTest(MeasurementTestBase): def test_guess_weight(self): result = guess(23, 'g') self.assertEqual( result, Mass(g=23) ) def test_guess_distance(self): result = guess(30, 'mi') self.assertEqual( result, Distance(mi=30) ) def test_guess_temperature(self): result = guess(98, 'f') self.assertEqual( result, Temperature(f=98) ) python-measurement-3.2.2/tests/test_volume.py000066400000000000000000000005331435731234400214530ustar00rootroot00000000000000from .base import MeasurementTestBase from measurement.measures import Volume class VolumeTest(MeasurementTestBase): def test_sub_one_base_si_measure(self): milliliters = Volume(ml=200) fl_oz = Volume(us_oz=6.76280454) self.assertAlmostEqual( milliliters.standard, fl_oz.standard )