[SYSTEMDS-2666] Fix relinking in mmchain optimization rewrite

This patch fixes the relinking logic in the matrix multiplication chain
optimization rewrite in order to support ragged input chains such as
((((a, b), c), (D, E), f), e).

Closes #1058.
diff --git a/src/main/java/org/apache/sysds/hops/rewrite/RewriteMatrixMultChainOptimization.java b/src/main/java/org/apache/sysds/hops/rewrite/RewriteMatrixMultChainOptimization.java
index 145b76c..4be5c8b 100644
--- a/src/main/java/org/apache/sysds/hops/rewrite/RewriteMatrixMultChainOptimization.java
+++ b/src/main/java/org/apache/sysds/hops/rewrite/RewriteMatrixMultChainOptimization.java
@@ -22,6 +22,7 @@
 import java.util.ArrayList;
 import java.util.Arrays;
 
+import org.apache.commons.lang3.mutable.MutableInt;
 import org.apache.sysds.hops.AggBinaryOp;
 import org.apache.sysds.hops.Hop;
 import org.apache.sysds.hops.HopsException;
@@ -197,7 +198,7 @@
 			
 			 // Step 5: Relink the hops using the optimal ordering (split[][]) found from DP.
 			LOG.trace("Optimal MM Chain: ");
-			mmChainRelinkHops(mmOperators.get(0), 0, size - 1, mmChain, mmOperators, 1, split, 1);
+			mmChainRelinkHops(mmOperators.get(0), 0, size - 1, mmChain, mmOperators, new MutableInt(1), split, 1);
 		}
 	}
 	
@@ -263,9 +264,13 @@
 	 * @param split optimal order
 	 * @param level log level
 	 */
-	protected final void mmChainRelinkHops(Hop h, int i, int j, ArrayList<Hop> mmChain, ArrayList<Hop> mmOperators,
-			int opIndex, int[][] split, int level) 
+	protected final void mmChainRelinkHops(Hop h, int i, int j, ArrayList<Hop> mmChain,
+		ArrayList<Hop> mmOperators, MutableInt opIndex, int[][] split, int level)
 	{
+		//NOTE: the opIndex is a MutableInt in order to get the correct positions
+		//in ragged chains like ((((a, b), c), (D, E), f), e) that might be given
+		//like that by the original scripts variable assignments
+		
 		//single matrix - end of recursion
 		if( i == j ) {
 			logTraceHop(h, level);
@@ -283,9 +288,9 @@
 			mmChain.get(i).getParent().add(h);
 		}
 		else {
-			h.getInput().add(mmOperators.get(opIndex));
-			mmOperators.get(opIndex).getParent().add(h);
-			opIndex = opIndex + 1;
+			int ix = opIndex.getAndIncrement();
+			h.getInput().add(mmOperators.get(ix));
+			mmOperators.get(ix).getParent().add(h);
 		}
 
 		// Set Input2 for current Hop h
@@ -294,9 +299,9 @@
 			mmChain.get(j).getParent().add(h);
 		} 
 		else {
-			h.getInput().add(mmOperators.get(opIndex));
-			mmOperators.get(opIndex).getParent().add(h);
-			opIndex = opIndex + 1;
+			int ix = opIndex.getAndIncrement();
+			h.getInput().add(mmOperators.get(ix));
+			mmOperators.get(ix).getParent().add(h);
 		}
 
 		// Find children for both the inputs
diff --git a/src/main/java/org/apache/sysds/hops/rewrite/RewriteMatrixMultChainOptimizationSparse.java b/src/main/java/org/apache/sysds/hops/rewrite/RewriteMatrixMultChainOptimizationSparse.java
index 46db6f7..69301fb 100644
--- a/src/main/java/org/apache/sysds/hops/rewrite/RewriteMatrixMultChainOptimizationSparse.java
+++ b/src/main/java/org/apache/sysds/hops/rewrite/RewriteMatrixMultChainOptimizationSparse.java
@@ -22,6 +22,7 @@
 import java.util.ArrayList;
 import java.util.Arrays;
 
+import org.apache.commons.lang3.mutable.MutableInt;
 import org.apache.sysds.common.Types.OpOpData;
 import org.apache.sysds.hops.Hop;
 import org.apache.sysds.hops.HopsException;
@@ -66,7 +67,7 @@
 			
 			 // Step 5: Relink the hops using the optimal ordering (split[][]) found from DP.
 			LOG.trace("Optimal MM Chain: ");
-			mmChainRelinkHops(mmOperators.get(0), 0, size - 1, mmChain, mmOperators, 1, split, 1);
+			mmChainRelinkHops(mmOperators.get(0), 0, size - 1, mmChain, mmOperators, new MutableInt(1), split, 1);
 		}
 	}
 	
diff --git a/src/test/java/org/apache/sysds/test/functions/rewrite/RewriteMatrixMultChainOptTest2.java b/src/test/java/org/apache/sysds/test/functions/rewrite/RewriteMatrixMultChainOptTest2.java
new file mode 100644
index 0000000..2476585
--- /dev/null
+++ b/src/test/java/org/apache/sysds/test/functions/rewrite/RewriteMatrixMultChainOptTest2.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sysds.test.functions.rewrite;
+
+import java.util.HashMap;
+
+import org.junit.Test;
+import org.apache.sysds.common.Types.ExecMode;
+import org.apache.sysds.runtime.matrix.data.MatrixValue.CellIndex;
+import org.apache.sysds.test.AutomatedTestBase;
+import org.apache.sysds.test.TestConfiguration;
+import org.apache.sysds.test.TestUtils;
+
+public class RewriteMatrixMultChainOptTest2 extends AutomatedTestBase 
+{
+	private static final String TEST_NAME1 = "RewriteMMChainTest1";
+	private static final String TEST_DIR = "functions/rewrite/";
+	private static final String TEST_CLASS_DIR = TEST_DIR + RewriteMatrixMultChainOptTest2.class.getSimpleName() + "/";
+	
+	@Override
+	public void setUp() {
+		TestUtils.clearAssertionInformation();
+		addTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] {"R"}));
+	}
+
+	@Test
+	public void testMMChain1Singlenode() {
+		testMMChain(TEST_NAME1, ExecMode.SINGLE_NODE);
+	}
+	
+	@Test
+	public void testMMChain1Hybrid() {
+		testMMChain(TEST_NAME1, ExecMode.HYBRID);
+	}
+	
+	@Test
+	public void testMMChain1Spark() {
+		testMMChain(TEST_NAME1, ExecMode.HYBRID);
+	}
+
+	private void testMMChain(String testname, ExecMode et)
+	{
+		ExecMode etOld = setExecMode(et);
+		
+		try
+		{
+			TestConfiguration config = getTestConfiguration(testname);
+			loadTestConfiguration(config);
+			
+			String HOME = SCRIPT_DIR + TEST_DIR;
+			fullDMLScriptName = HOME + testname + ".dml";
+			programArgs = new String[]{ "-args", output("R") };
+			fullRScriptName = HOME + testname + ".R";
+			rCmd = getRCmd(expectedDir());
+			
+			//execute tests
+			runTest(true, false, null, -1); 
+			runRScript(true); 
+			
+			//compare matrices 
+			HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("R");
+			HashMap<CellIndex, Double> rfile  = readRMatrixFromFS("R");
+			TestUtils.compareMatrices(dmlfile, rfile, 1e-8, "Stat-DML", "Stat-R");
+		}
+		finally {
+			resetExecMode(etOld);
+		}
+	}
+}
diff --git a/src/test/scripts/functions/rewrite/RewriteMMChainTest1.R b/src/test/scripts/functions/rewrite/RewriteMMChainTest1.R
new file mode 100644
index 0000000..13b8622
--- /dev/null
+++ b/src/test/scripts/functions/rewrite/RewriteMMChainTest1.R
@@ -0,0 +1,33 @@
+#-------------------------------------------------------------
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+# 
+#   http://www.apache.org/licenses/LICENSE-2.0
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+#-------------------------------------------------------------
+
+
+args <- commandArgs(TRUE)
+options(digits=22)
+library("Matrix")
+
+h = matrix(1.0, 3, 3)
+a = matrix(2.0, 3, 3)
+s = matrix(3.0, 3, 1)
+s2 = s %*% t(s)
+h2 = h %*% h %*% s2 %*% a %*% a
+
+writeMM(as(h2, "CsparseMatrix"), paste(args[1], "R", sep=""));
diff --git a/src/test/scripts/functions/rewrite/RewriteMMChainTest1.dml b/src/test/scripts/functions/rewrite/RewriteMMChainTest1.dml
new file mode 100644
index 0000000..c539a13
--- /dev/null
+++ b/src/test/scripts/functions/rewrite/RewriteMMChainTest1.dml
@@ -0,0 +1,28 @@
+#-------------------------------------------------------------
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+# 
+#   http://www.apache.org/licenses/LICENSE-2.0
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+#-------------------------------------------------------------
+
+h = matrix(1.0, 3, 3)
+a = matrix(2.0, 3, 3)
+s = matrix(3.0, 3, 1)
+s2 = s %*% t(s)
+h2 = h %*% h %*% s2 %*% a %*% a
+
+write(h2, $1);