measurement-2.0.1/0000755000372000037200000000000013225177277014714 5ustar travistravis00000000000000measurement-2.0.1/docs/0000755000372000037200000000000013225177277015644 5ustar travistravis00000000000000measurement-2.0.1/docs/topics/0000755000372000037200000000000013225177277017145 5ustar travistravis00000000000000measurement-2.0.1/docs/topics/creating_your_own_class.rst0000644000372000037200000001217213225177223024613 0ustar travistravis00000000000000 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 ``STANDRD_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. measurement-2.0.1/docs/topics/installation.rst0000644000372000037200000000053013225177223022365 0ustar travistravis00000000000000 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 measurement-2.0.1/docs/topics/measures.rst0000644000372000037200000002544013225177223021517 0ustar travistravis00000000000000Measures ======== 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*: ``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*: ``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``, ``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``, ``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``, ``ml``, ``nl``, ``pl``, ``ul``, ``us_cup``, ``us_g``, ``us_oz``, ``us_pint``, ``us_qt``, ``us_tbsp``, ``us_tsp``, ``yl``, ``zl`` * *Acceptable as Arguments*: ``Imperial Gram``, ``Imperial Ounce``, ``Imperial Pint``, ``Imperial Quart``, ``Imperial Tablespoon``, ``Imperial Teaspoon``, ``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`` measurement-2.0.1/docs/topics/use.rst0000644000372000037200000000446313225177223020471 0ustar travistravis00000000000000 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 measurement-2.0.1/docs/Makefile0000644000372000037200000001275413225177223017304 0ustar travistravis00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-measurement.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-measurement.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/python-measurement" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-measurement" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." measurement-2.0.1/docs/conf.py0000644000372000037200000001731713225177223017143 0ustar travistravis00000000000000# -*- coding: utf-8 -*- # # python-measurement documentation build configuration file, created by # sphinx-quickstart on Tue Jan 22 20:02:38 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'python-measurement' copyright = u'2013, Adam Coddington' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'python-measurementdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'python-measurement.tex', u'python-measurement Documentation', u'Adam Coddington', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'python-measurement', u'python-measurement Documentation', [u'Adam Coddington'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'python-measurement', u'python-measurement Documentation', u'Adam Coddington', 'python-measurement', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' measurement-2.0.1/docs/index.rst0000644000372000037200000000305313225177223017475 0ustar travistravis00000000000000.. 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.png?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` measurement-2.0.1/docs/util.py0000644000372000037200000000367613225177223017176 0ustar travistravis00000000000000from __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() measurement-2.0.1/measurement/0000755000372000037200000000000013225177277017241 5ustar travistravis00000000000000measurement-2.0.1/measurement/measures/0000755000372000037200000000000013225177277021065 5ustar travistravis00000000000000measurement-2.0.1/measurement/measures/__init__.py0000644000372000037200000000101013225177223023155 0ustar travistravis00000000000000from measurement.measures.distance import * from measurement.measures.energy import * from measurement.measures.temperature import * from measurement.measures.volume 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 * measurement-2.0.1/measurement/measures/capacitance.py0000644000372000037200000000040213225177223023655 0ustar travistravis00000000000000# -*- coding: utf-8 -*- from measurement.base import MeasureBase __all__ = [ 'Capacitance' ] class Capacitance(MeasureBase): STANDARD_UNIT = 'F' UNITS = { 'F': 1.0, } ALIAS = { 'farad': 'F', } SI_UNITS = ['F'] measurement-2.0.1/measurement/measures/current.py0000644000372000037200000000036713225177223023116 0ustar travistravis00000000000000from measurement.base import MeasureBase __all__ = [ 'Current' ] class Current(MeasureBase): STANDARD_UNIT = 'A' UNITS = { 'A': 1.0, } ALIAS = { 'amp': 'A', 'ampere': 'A', } SI_UNITS = ['A'] measurement-2.0.1/measurement/measures/distance.py0000644000372000037200000001352213225177223023223 0ustar travistravis00000000000000# 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 = dict( [ ('%s%s' % (AREA_PREFIX, k), v ** 2) for k, v in Distance.get_units().items() ] ) ALIAS = dict( [ (k, '%s%s' % (AREA_PREFIX, v)) for k, v in Distance.get_aliases().items() ] ) 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) measurement-2.0.1/measurement/measures/energy.py0000644000372000037200000000062013225177223022715 0ustar travistravis00000000000000from 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'] measurement-2.0.1/measurement/measures/frequency.py0000644000372000037200000000040313225177223023424 0ustar travistravis00000000000000from 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'] measurement-2.0.1/measurement/measures/mass.py0000644000372000037200000000123213225177223022367 0ustar travistravis00000000000000from 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 measurement-2.0.1/measurement/measures/resistance.py0000644000372000037200000000036013225177223023565 0ustar travistravis00000000000000# -*- coding: utf-8 -*- from measurement.base import MeasureBase __all__ = [ 'Resistance' ] class Resistance(MeasureBase): STANDARD_UNIT = 'ohm' UNITS = { 'ohm': 1.0, } ALIAS = { } SI_UNITS = ['ohm'] measurement-2.0.1/measurement/measures/speed.py0000644000372000037200000000053213225177223022526 0ustar travistravis00000000000000from 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', } measurement-2.0.1/measurement/measures/temperature.py0000644000372000037200000000061313225177223023763 0ustar travistravis00000000000000from 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', } measurement-2.0.1/measurement/measures/time.py0000644000372000037200000000130113225177223022357 0ustar travistravis00000000000000from 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'] measurement-2.0.1/measurement/measures/voltage.py0000644000372000037200000000033713225177223023072 0ustar travistravis00000000000000from measurement.base import MeasureBase __all__ = [ 'Voltage' ] class Voltage(MeasureBase): STANDARD_UNIT = 'V' UNITS = { 'V': 1.0 } ALIAS = { 'volt': 'V' } SI_UNITS = ['V'] measurement-2.0.1/measurement/measures/volume.py0000644000372000037200000000331413225177223022736 0ustar travistravis00000000000000from measurement.base import MeasureBase __all__ = [ 'Volume', ] class Volume(MeasureBase): STANDARD_UNIT = 'cubic_meter' UNITS = { 'us_g': 0.00378541, '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, '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, } ALIAS = { 'US Gallon': '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', 'Imperial Gram': 'imperial_g', 'Imperial Quart': 'imperial_qt', 'Imperial Pint': 'imperial_pint', 'Imperial Ounce': 'imperial_oz', 'Imperial Tablespoon': 'imperial_tbsp', 'Imperial Teaspoon': 'imperial_tsp', } SI_UNITS = ['l'] def __init__(self, *args, **kwargs): super(Volume, self).__init__(*args, **kwargs) measurement-2.0.1/measurement/__init__.py0000644000372000037200000000000013225177223021327 0ustar travistravis00000000000000measurement-2.0.1/measurement/base.py0000644000372000037200000005220013225177223020513 0ustar travistravis00000000000000# 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 six import sympy from sympy.solvers import solve_linear from measurement.utils import total_ordering NUMERIC_TYPES = six.integer_types + (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, six.string_types): 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 six.iteritems(kwargs): 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: items = list(six.iteritems(kwargs)) if len(items) > 1: raise ValueError('Only one keyword argument is expected') measure_string, value = items[0] 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) measurement-2.0.1/measurement/utils.py0000644000372000037200000000506413225177223020747 0ustar travistravis00000000000000import 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]) ) ) measurement-2.0.1/measurement.egg-info/0000755000372000037200000000000013225177277020733 5ustar travistravis00000000000000measurement-2.0.1/measurement.egg-info/PKG-INFO0000644000372000037200000000605413225177277022035 0ustar travistravis00000000000000Metadata-Version: 1.1 Name: measurement Version: 2.0.1 Summary: Easily use and manipulate unit-aware measurements in Python Home-page: http://github.com/coddingtonbear/python-measurement Author: Adam Coddington Author-email: me@adamcoddington.net License: MIT License Description-Content-Type: UNKNOWN Description: .. 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 Keywords: measurement Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Utilities measurement-2.0.1/measurement.egg-info/SOURCES.txt0000644000372000037200000000220413225177277022615 0ustar travistravis00000000000000.travis.yml AUTHORS CONTRIBUTING.md ChangeLog LICENSE README.rst requirements.txt setup.cfg setup.py docs/Makefile docs/conf.py docs/index.rst docs/util.py docs/topics/creating_your_own_class.rst docs/topics/installation.rst docs/topics/measures.rst docs/topics/use.rst measurement/__init__.py measurement/base.py measurement/utils.py measurement.egg-info/PKG-INFO measurement.egg-info/SOURCES.txt measurement.egg-info/dependency_links.txt measurement.egg-info/not-zip-safe measurement.egg-info/pbr.json measurement.egg-info/requires.txt measurement.egg-info/top_level.txt measurement/measures/__init__.py measurement/measures/capacitance.py measurement/measures/current.py measurement/measures/distance.py measurement/measures/energy.py measurement/measures/frequency.py measurement/measures/mass.py measurement/measures/resistance.py measurement/measures/speed.py measurement/measures/temperature.py measurement/measures/time.py measurement/measures/voltage.py measurement/measures/volume.py tests/__init__.py tests/base.py tests/test_distance.py tests/test_energy.py tests/test_speed.py tests/test_temperature.py tests/test_utils.py tests/test_volume.pymeasurement-2.0.1/measurement.egg-info/dependency_links.txt0000644000372000037200000000000113225177277025001 0ustar travistravis00000000000000 measurement-2.0.1/measurement.egg-info/not-zip-safe0000644000372000037200000000000113225177277023161 0ustar travistravis00000000000000 measurement-2.0.1/measurement.egg-info/pbr.json0000644000372000037200000000005713225177277022413 0ustar travistravis00000000000000{"git_version": "3efdc3e", "is_release": false}measurement-2.0.1/measurement.egg-info/requires.txt0000644000372000037200000000002613225177277023331 0ustar travistravis00000000000000six>=1.0 sympy>=0.7.3 measurement-2.0.1/measurement.egg-info/top_level.txt0000644000372000037200000000001413225177277023460 0ustar travistravis00000000000000measurement measurement-2.0.1/tests/0000755000372000037200000000000013225177277016056 5ustar travistravis00000000000000measurement-2.0.1/tests/__init__.py0000644000372000037200000000000013225177223020144 0ustar travistravis00000000000000measurement-2.0.1/tests/base.py0000644000372000037200000000011113225177223017322 0ustar travistravis00000000000000import unittest class MeasurementTestBase(unittest.TestCase): pass measurement-2.0.1/tests/test_distance.py0000644000372000037200000000335713225177223021260 0ustar travistravis00000000000000# -*- 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 ) measurement-2.0.1/tests/test_energy.py0000644000372000037200000000052613225177223020752 0ustar travistravis00000000000000from .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, ) measurement-2.0.1/tests/test_speed.py0000644000372000037200000001072413225177223020562 0ustar travistravis00000000000000from .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, ) measurement-2.0.1/tests/test_temperature.py0000644000372000037200000000137713225177223022023 0ustar travistravis00000000000000from .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) ) measurement-2.0.1/tests/test_utils.py0000644000372000037200000000117313225177223020620 0ustar travistravis00000000000000from .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) ) measurement-2.0.1/tests/test_volume.py0000644000372000037200000000053313225177223020766 0ustar travistravis00000000000000from .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 ) measurement-2.0.1/.travis.yml0000644000372000037200000000076413225177223017023 0ustar travistravis00000000000000language: python sudo: false python: - '2.7' - '3.5' - '3.6' - nightly matrix: allow_failures: - python: nightly install: pip install -e . script: pytest 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 measurement-2.0.1/AUTHORS0000644000372000037200000000106413225177277015765 0ustar travistravis00000000000000Adam Coddington Adam Coddington Benjamin Lee Bitdeli Chef Daniël van de Burgt Denis Cornehl Edward Betts Johannes Hoppe Joseph Botros Jörg Benesch Konstantin Schukraft Luc MILLAND Marcos Gabriel Alcázar lucmilland measurement-2.0.1/CONTRIBUTING.md0000644000372000037200000000051113225177223017131 0ustar travistravis00000000000000# Contributing ### Releases Please create new releases via GitHub's release functionality or using the GitHub CLI. ```shell 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. measurement-2.0.1/ChangeLog0000644000372000037200000000453413225177277016474 0ustar travistravis00000000000000CHANGES ======= 2.0.1 ----- * Fix PyPi classifier 2.0.0 ----- * Switch travis-ci badge to svg * Change changelog to GitHub release page * Support latest sympy version * Alias "in" to inch (#20) * Add pbr for automated releases * correct spelling mistake * Change supported Python version (#22) * Removing a now-obsolete command-line argument * Fixed typo in temperature example * Fixing unit setter for aliases 1.8.0 ----- * Release 1.8.0; better SI-based naming * [#8] Changes preserving earlier names for backward-compatibility * Adopt tests to new units * Correct factor for electron volt * Added measures, renamed weight to mass 1.7.3 ----- * Release 1.7.3; fixes out-of-date sympy requirement * Set an upper bound on the sympy requirement * fix sympy requirement * Minor grammatical error; pluralizing 'points' * #5: Updating documentation to add a reminder that 0 C and 0 F are non-zero * s/latestrevision/coddingtonbear/g * Minor alterations to capacitance/resistance classes to work around Python 2's limitations * Fixing capacitance measurement class * Bumping version number * Adding common electrical measurements * Updating readme * Adding license file * Bumping version number * Update measures.rst to reflect @022d494 * Removing remant bitbucket links * Removing hg remnants * Updating readme to reflect the fact that Github is now the authoritative copy * Fixing units for Volumes * missing SI prefixes : forgot commas, oops * Adding missing "centi", "deci", "deca" and "hecto" SI prefixes * Add a Bitdeli badge to README * Updating travis.yml to check Python3.x as well * Added tag 1.5 for changeset 7d7f75eca12e 1.5 --- * Adding Python3 support * Added tag 1.4 for changeset 44a04b8b93ef 1.4 --- * Bumping version number * Updating readme to include short example of use * Removing 'instantiation\_unit' functionality * Updating documentation * Added tag 1.3.8 for changeset 2d506cc391af 1.3.8 ----- * Use bidimensional measurement's standard value directly for equality comparisons * Fix MANIFEST.in to include rst readme rather than markdown * Added tag 1.3.7 for changeset 76b2b9da0fe9 1.3.7 ----- * Fixing issue in which setting a value did not properly alter standard units * Added tag 1.3.5 for changeset 3b6bb9be1d2b 1.3.5 ----- * Allow setting units on bidimensional units; handle changes in reference units * Added tag 1.3.4 for changeset d2663fae9a1b measurement-2.0.1/LICENSE0000644000372000037200000000207213225177223015711 0ustar travistravis00000000000000The 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. measurement-2.0.1/README.rst0000644000372000037200000000364013225177223016375 0ustar travistravis00000000000000.. 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 measurement-2.0.1/requirements.txt0000644000372000037200000000002613225177223020165 0ustar travistravis00000000000000six>=1.0 sympy>=0.7.3 measurement-2.0.1/setup.cfg0000644000372000037200000000123613225177277016537 0ustar travistravis00000000000000[metadata] name = measurement author = Adam Coddington author-email = me@adamcoddington.net summary = Easily use and manipulate unit-aware measurements in Python description-file = README.rst home-page = http://github.com/coddingtonbear/python-measurement license = MIT License classifier = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python Programming Language :: Python :: 2 Programming Language :: Python :: 3 Topic :: Utilities keywords = measurement [files] packages = measurement [egg_info] tag_build = tag_date = 0 measurement-2.0.1/setup.py0000644000372000037200000000015113225177223016412 0ustar travistravis00000000000000#!/usr/bin/env python from setuptools import setup setup( setup_requires=['pbr'], pbr=True, ) measurement-2.0.1/PKG-INFO0000644000372000037200000000605413225177277016016 0ustar travistravis00000000000000Metadata-Version: 1.1 Name: measurement Version: 2.0.1 Summary: Easily use and manipulate unit-aware measurements in Python Home-page: http://github.com/coddingtonbear/python-measurement Author: Adam Coddington Author-email: me@adamcoddington.net License: MIT License Description-Content-Type: UNKNOWN Description: .. 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 Keywords: measurement Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Utilities