Skip to content

Commit

Permalink
Allow named units to have a LaTeX representation (WIP) (#1069)
Browse files Browse the repository at this point in the history
* Allow named units to have a LaTeX representation (WIP)

* Add some LaTeX representations and a test for this
  • Loading branch information
rieder authored Oct 31, 2024
1 parent 06ef418 commit 8f44615
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
4 changes: 4 additions & 0 deletions src/amuse/test/suite/core_tests/test_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,7 @@ def test10(self):
"], ["+tmp+", "+tmp+"]] au")
self.assertEqual(str(pi), "3.14 none")
set_printing_strategy("default")

def test_latex(self):
self.assertEqual(str(units.MSun), "MSun")
self.assertEqual(str(units.MSun.latex()), r"M_{\odot}")
13 changes: 11 additions & 2 deletions src/amuse/units/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ class unit(object):
Units can also be named, by creating a named unit.
"""

_latex_representation = None
__array_priority__ = 100

def __mul__(self, other):
Expand Down Expand Up @@ -142,6 +144,12 @@ def __ne__(self, other):
def __hash__(self):
return self._hash

def latex(self):
if self._latex_representation is not None:
return self._latex_representation
else:
return self.symbol

@late
def _hash(self):
return hash(id(self))
Expand Down Expand Up @@ -853,15 +861,16 @@ class named_unit(unit):
>>> (20.0 | (60.0 * si.s)).as_quantity_in(minute)
quantity<20.0 min>
"""
def __init__(self, name, symbol, unit):

def __init__(self, name, symbol, unit, latex=None):
self.name = name
self.symbol = symbol
self.local_unit = unit
self._latex_representation = latex

def __str__(self):
return self.symbol


def reference_string(self):
return self.to_simple_form().reference_string()

Expand Down
6 changes: 3 additions & 3 deletions src/amuse/units/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@
Mpc = named("mega parsec", "Mpc", 10**6 * parsec)
Gpc = named("giga parsec", "Gpc", 10**9 * parsec)
lightyear = named("light year", "ly", 9460730472580.8 * km)
LSun = named("solar luminosity", "LSun", 3.839e26 * W)
MSun = named("solar mass", "MSun", 1.98892e30 * kg)
RSun = named("solar radius", "RSun", 6.955e8 * m)
LSun = named("solar luminosity", "LSun", 3.839e26 * W, latex=r"L_{\odot}")
MSun = named("solar mass", "MSun", 1.98892e30 * kg, latex=r"M_{\odot}")
RSun = named("solar radius", "RSun", 6.955e8 * m, latex=r"R_{\odot}")
MJupiter = named("jupiter mass", "MJupiter", 1.8987e27 * kg)
RJupiter = named("jupiter radius", "RJupiter", 71492.0 * km)
MEarth = named("earth mass", "MEarth", 5.9722e24 * kg)
Expand Down

0 comments on commit 8f44615

Please sign in to comment.