From a1e18a186d21f90a4e9c67ea2cf7e37d2d49edb3 Mon Sep 17 00:00:00 2001 From: Mike Lin Date: Fri, 28 Jun 2019 15:10:05 -0700 Subject: [PATCH] transpose() --- WDL/StdLib.py | 18 ++++++++++++++++-- tests/test_5stdlib.py | 22 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/WDL/StdLib.py b/WDL/StdLib.py index f187b09d..678bc864 100644 --- a/WDL/StdLib.py +++ b/WDL/StdLib.py @@ -616,8 +616,22 @@ def infer_type(self, expr: E.Apply) -> T.Base: return expr.arguments[0].type def _call_eager(self, expr: E.Apply, arguments: List[V.Base]) -> V.Base: - raise NotImplementedError() - + ty = self.infer_type(expr) + assert isinstance(ty, T.Array) and isinstance(ty.item_type, T.Array) + mat = arguments[0].coerce(ty) + assert isinstance(mat, V.Array) + n = None + ans = [] + for row in mat.value: + assert isinstance(row, V.Array) + if n is None: + n = len(row.value) + ans = [V.Array(ty.item_type, []) for _ in row.value] + if len(row.value) != n: + raise Error.EvalError(expr, "transpose(): ragged input matrix") + for i in range(len(row.value)): + ans[i].value.append(row.value[i]) + return V.Array(ty, ans) class _Range(EagerFunction): # int -> int array diff --git a/tests/test_5stdlib.py b/tests/test_5stdlib.py index 75ccc19b..31ce8e70 100644 --- a/tests/test_5stdlib.py +++ b/tests/test_5stdlib.py @@ -464,3 +464,25 @@ def test_write(self): with open(outputs["o_json"]) as infile: self.assertEqual(json.load(infile), {"key1": "value1", "key2": "value2"}) self.assertEqual(outputs["o_tsv"], [["one", "two", "three"], ["un", "deux", "trois"]]) + + def test_transpose(self): + outputs = self._test_task(R""" + version 1.0 + task hello { + command {} + output { + Array[Array[Int]] mat = transpose([[0, 1, 2], [3, 4, 5]]) + } + } + """) + self.assertEqual(outputs["mat"], [[0, 3], [1, 4], [2, 5]]) + + outputs = self._test_task(R""" + version 1.0 + task hello { + command {} + output { + Array[Array[Int]] mat = transpose([[0, 1, 2], [3, 4, 5], []]) + } + } + """, expected_exception=WDL.Error.EvalError)