/**
 * Copyright (c) 2011 Michael Kutschke.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Michael Kutschke - initial API and implementation.
 */
package bayesnet.internal.jayes.util;

import java.util.HashMap;
import java.util.Map;

import bayesnet.jayes.factor.AbstractFactor;
import bayesnet.jayes.util.MathUtils;

public final class AddressCalc {

    private AddressCalc() {
    }

    public static void incrementMultiDimensionalCounter(final int[] counter, final int[] dimensions) {
        int dimension = counter.length - 1;

        counter[dimension]++;
        while (counter[dimension] == dimensions[dimension]) {
            // overflow, assume the counter was valid before and less than the
            // maximal counter
            counter[dimension] = 0;
            dimension--;
            counter[dimension]++;
        }
    }

    /**
     * computes a linear map that can be used to transform the factors' addresses to the corresponding index of the flat
     * value array of another factor consisting of the dimensions with the given dimensionIDs. dimensionIDs is expected
     * to be a superset of the dimension ids of the first factor
     */
    public static int[] computeLinearMap(AbstractFactor factor, int... dimensionIDs) {
        return computeLinearMap(computeIdToDimensionIndexMap(factor), factor.getDimensions(), dimensionIDs);
    }

    private static int[] computeLinearMap(Map foreignIdToIndex, int[] foreignDimensions,
            int[] dimensionIds) {
        int[] kernel = new int[dimensionIds.length];

        for (int i = 0; i < kernel.length; i++) {
            int dimensionId = dimensionIds[i];
            if (foreignIdToIndex.containsKey(dimensionId)) {
                kernel[i] = MathUtils.productOfRange(foreignDimensions, foreignIdToIndex.get(dimensionId) + 1,
                        foreignDimensions.length);
            }
        }

        return kernel;
    }

    private static Map computeIdToDimensionIndexMap(AbstractFactor factor) {
        Map foreignIds = new HashMap();
        for (int i = 0; i < factor.getDimensionIDs().length; i++) {
            foreignIds.put(factor.getDimensionIDs()[i], i);
        }
        return foreignIds;
    }
}

 

Ads help maintain this website.