From a908679ddd60e0faed28ba9b56a1971d037673c4 Mon Sep 17 00:00:00 2001 From: fbeutel Date: Thu, 10 Dec 2020 11:57:26 +0100 Subject: [PATCH] Add parse_alphanumeric as inverse of id_to_alphanumeric --- gdshelpers/helpers/small.py | 15 +++++++++++++++ gdshelpers/tests/test_helpers.py | 8 ++++++++ 2 files changed, 23 insertions(+) diff --git a/gdshelpers/helpers/small.py b/gdshelpers/helpers/small.py index e7f82a7..073b5fb 100644 --- a/gdshelpers/helpers/small.py +++ b/gdshelpers/helpers/small.py @@ -1,6 +1,7 @@ import string import numpy as np import numpy.linalg as linalg +import re def raith_eline_dosefactor_to_datatype(dose_factor): @@ -47,6 +48,20 @@ def id_to_alphanumeric(column, row): return int_to_alphabet(row) + str(int(column)) +def parse_alphanumeric(text): + """ + Do the reverse of `id_to_alphanumeric`. + Returns the (column, row) tuple. + """ + regex = "([A-Z]*)[^0-9]*([0-9]*)" + m = re.match(regex, text.strip(), re.I) + letters, number = m.group(1), int(m.group(2)) + letter_num = 0 + for i in range(len(letters)): + letter_num += (ord(letters[i]) - 64) * (26 ** (len(letters) - i - 1)) + return number, letter_num - 1 + + def normalize_phase(phase, zero_to_two_pi=False): """ Normalize a phase to be within +/- pi. diff --git a/gdshelpers/tests/test_helpers.py b/gdshelpers/tests/test_helpers.py index 83fe0a3..ac4e11a 100644 --- a/gdshelpers/tests/test_helpers.py +++ b/gdshelpers/tests/test_helpers.py @@ -3,6 +3,7 @@ import numpy.testing as npt from gdshelpers.helpers import int_to_alphabet, id_to_alphanumeric, find_line_intersection +from gdshelpers.helpers.small import parse_alphanumeric class HelpersTestCase(unittest.TestCase): @@ -15,6 +16,13 @@ def test_int_to_alphabet(self): def test_id_to_alphanumeric(self): self.assertEqual(id_to_alphanumeric(4, 26 + 25), 'AZ4') + def test_parse_alphanumeric(self): + self.assertEqual((4, 26 + 25), parse_alphanumeric('AZ4')) + self.assertEqual((4, 26 + 25), parse_alphanumeric(' AZ4 ')) + + for pair in [(0, 0), (0, 10), (0, 100), (100, 0), (100, 100)]: + self.assertEqual(pair, parse_alphanumeric(id_to_alphanumeric(*pair))) + def test_find_line_intersection(self): test_intersection = find_line_intersection(np.array((2, 0)), np.pi / 2, np.array((0, 1)), 0) npt.assert_almost_equal(test_intersection[0], (2, 1))