com.ricston.akka.matrix.Main.java Source code

Java tutorial

Introduction

Here is the source code for com.ricston.akka.matrix.Main.java

Source

/*
 * Copyright (c) Ricston Ltd  All rights reserved.  http://www.ricston.com
 *
 * The software in this package is published under the terms of the CPAL v1.0
 * license, a copy of which has been included with this distribution in the
 * LICENSE.txt file.
 */

package com.ricston.akka.matrix;

import static akka.actor.Actors.actorOf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import akka.actor.ActorRef;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;

import com.ricston.akka.matrix.msgs.AllJobsMsg;

public class Main {

    public static String GENERATE = "generate";
    public static String GENERATE_ARGS = "<filename> <comma-delimited-dimensions-of-matrices>";
    public static String GENERATE_DESCRIPTION = "generate 2 random matrices from the given "
            + "dimensions (row1, column1, row2, column2) and writes them to the given filename."
            + "Example -generate /home/xyz/somefile.txt 5,5,5,5";
    public static String COMPUTE = "compute";
    public static String COMPUTE_ARG = "<colon-delimited-filenames-containing-matrices-to-compute>";
    public static String COMPUTE_DESCRIPTION = "computes the multiplication of the matrices in the colon"
            + " delimited list of files supplied as argument. The format of the files needs to be equivalent "
            + "to that generated by the -generate option. " + "Example -compute /matrices/10mtrx:/matrices/20mtrx";
    public static String ACTORS = "actors";
    public static String ACTORS_ARG = "<number-of-actors>";
    public static String ACTORS_DESCRIPTION = "the number of actors to use." + " Example -actors 5";

    private static HelpFormatter formatter = new HelpFormatter();

    public static void main(String[] args) throws InterruptedException, NumberFormatException, IOException {

        CommandLineParser parser = new GnuParser();
        int numberOfActors = -1;

        Options options = new Options();
        // Set the command line options recognized by this program.
        setUpCLOptions(options);
        // Parse the command line arguments.
        CommandLine cmd = null;
        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e) {
            quitApp(options);
        }

        if (cmd.hasOption(ACTORS)) {
            // Set the number of actors to create if the user supplied this argument.
            numberOfActors = Integer.parseInt(cmd.getOptionValue(ACTORS));
        }
        if (cmd.hasOption(GENERATE)) {
            // Generate a file containing two randomly generated matrices.
            String[] genArgs = cmd.getOptionValues(GENERATE);
            if (genArgs.length != 5) {
                quitApp(options);
            }
            MatrixFile.writeMatrixFile(genArgs[0],
                    generateMatrix(Integer.parseInt(genArgs[1]), Integer.parseInt(genArgs[2])),
                    generateMatrix(Integer.parseInt(genArgs[3]), Integer.parseInt(genArgs[4])),
                    new ArrayList<List<Double>>());

        }
        if (cmd.hasOption(COMPUTE)) {
            // Compute the matrix multiplication of the matrices in the files
            // given as argument.
            String[] compArgs = cmd.getOptionValues(COMPUTE);
            ActorRef managerRef = null;

            if (numberOfActors > 0) {
                final int actors = numberOfActors;
                managerRef = actorOf(new UntypedActorFactory() {
                    public UntypedActor create() {
                        return new ManagerActor(actors);
                    }
                });
            } else {
                managerRef = actorOf(ManagerActor.class);
            }
            // Start the manager actor.
            managerRef.start();
            // Create and send an AllJobsMsg.
            managerRef.tell(new AllJobsMsg(compArgs));
        }
        if (cmd.getArgs().length > 0 || args.length == 0) {
            // Handle unrecognized arguments.
            quitApp(options);
        }

    }

    @SuppressWarnings("static-access")
    private static void setUpCLOptions(Options options) {
        Option generateOpt = OptionBuilder.withArgName(GENERATE_ARGS).hasArgs(5)
                .withDescription(GENERATE_DESCRIPTION).withValueSeparator(',').create(GENERATE);
        Option computeOpt = OptionBuilder.withArgName(COMPUTE_ARG).hasArgs().withDescription(COMPUTE_DESCRIPTION)
                .withValueSeparator(':').create(COMPUTE);
        Option actorOpt = OptionBuilder.withArgName(ACTORS_ARG).hasArg().withDescription(ACTORS_DESCRIPTION)
                .create(ACTORS);

        options.addOption(generateOpt);
        options.addOption(computeOpt);
        options.addOption(actorOpt);
    }

    private static List<List<Double>> generateMatrix(int rows, int columns) {

        Random rand = new Random(System.currentTimeMillis());

        List<List<Double>> data = new ArrayList<List<Double>>(rows);

        for (int i = 0; i < rows; i++) {
            List<Double> row = new ArrayList<Double>(columns);
            for (int j = 0; j < columns; j++) {
                row.add(j, rand.nextDouble() * 20);
            }
            data.add(i, row);
        }

        return data;
    }

    private static void quitApp(Options options) {
        formatter.printHelp(new Main().getClass().getName(), options);
        System.exit(-1);
    }

}