Mark Bishop

Analytical Chemistry and

Signal Acquisition/Analysis



/**
 * Copyright 2009 Mark Bishop
 *  This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version. 
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details: http://www.gnu.org/licenses
 
    The author makes no warranty for the accuracy, completeness, safety, or usefulness
    of any information provided and does not represent that its use would not infringe
    privately owned right.
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
import javax.swing.JFileChooser;
 
public class Utilities {
 
	/**
	 * 
	 * @param str
	 *            a string
	 * @return True if pattern is regex match "-?\d+(\.\d+)?" i.e. a number
	 *         with optional '-' and decimal point.
	 */
	public static boolean isNumeric(String str) {
		return str.matches("-?\d+(\.\d+)?");
	}
 
	/**
	 * 
	 * @param a
	 *            A(m,n)
	 * @return vector representation of A(m,n):
	 *         (A(0,0)...A(0,n))...(A(m,0)...A(m,n))
	 */
	public static float[] To1D(float[][] A) {
		int m = A.length;
		int n = A[0].length;
		float[] v = new float[m * n];
		int count = 0;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				v[count] = A[i][j];
				count += 1;
			}
		}
		return v;
	}
 
	/**
	 * 
	 * @param v
	 *            vector representation of A(m,n)
	 *            (A(0,0)...A(0,n))...(A(m,0)...A(m,n))
	 * @param m
	 * @param n
	 * @return A(m,n)
	 */
	public static float[][] To2D(float[] v, int m, int n) {
		float[][] A = new float[m][n];
		int count = 0;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				A[i][j] = v[count];
				count += 1;
			}
		}
		return A;
	}
 
	/**
	 * 
	 * @param v
	 *            vector representation of A(m,n) as int[][]
	 *            (A(0,0)...A(0,n))...(A(m,0)...A(m,n))
	 * @param m
	 * @param n
	 * @return A(m,n)
	 */
	public static float[][] To2D(int[] v, int m, int n) {
		float[][] A = new float[m][n];
		int count = 0;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				A[i][j] = v[count];
				count += 1;
			}
		}
		return A;
	}
 
	/**
	 * @return v(n) with random elements (reproducible) between +/- multiplier/2
	 */
	public static float[] createRandomFloatData(int n, float multiplier) {
		Random random = new Random(0);
		float v[] = new float[n];
		for (int i = 0; i < n; i++) {
			v[i] = multiplier * random.nextFloat() - multiplier / 2;
		}
		return v;
	}
 
	/**
	 * 
	 * @return A(m,n) with random elements (reproducible) between +/-
	 *         multiplier/2
	 */
	public static float[][] createRandomFloatData(int m, int n, float multiplier) {
		Random random = new Random(0);
		float A[][] = new float[m][n];
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				A[i][j] = multiplier * random.nextFloat() - multiplier / 2;
			}
		}
		return A;
	}
 
	/**
	 * 
	 * @param A
	 *            A(m,n)
	 * @return Tab ('	') delimited string with '
' row terminators
	 */
	public static String ToTsv(float[][] A) {
		int m = A.length;
		int n = A[0].length;
		NumberFormat formatter = new DecimalFormat("0.00000E0");
 
		StringBuilder sb = new StringBuilder();
 
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				sb.append(formatter.format(A[i][j]));
				sb.append("	");
			}
			sb.append("
");
		}
		return sb.toString();
	}
 
	/**
	 * 
	 * @param A
	 *            v(n)
	 * @return Tab ('	') delimited string with a '
' terminator
	 */
	public static String ToTsv(float[] v) {
		int m = v.length;
 
		NumberFormat formatter = new DecimalFormat("0.00000E0");
 
		StringBuilder sb = new StringBuilder();
 
		for (int i = 0; i < m; i++) {
			sb.append(formatter.format(v[i]));
			sb.append("	");
		}
		sb.append("
");
		return sb.toString();
	}
 
	/**
	 * 
	 * @param A
	 *            v(n) as int[]
	 * @return Tab ('	') delimited string with a '
' terminator
	 */
	public static String ToTsv(int[] v) {
		int n = v.length;
		NumberFormat formatter = new DecimalFormat("0.00000E0");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < n; i++) {
			sb.append(formatter.format(v[i]));
			sb.append("	");
		}
		sb.append("
");
		return sb.toString();
	}
 
	/**
	 * 
	 * @param A
	 *            A(m,n)
	 * @return comma-delimited, "
" line-terminated string representing A(m,n)
	 */
	public static String ToCsvString(float[][] A) {
		int m = A.length;
		int n = A[0].length;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				sb.append(A[i][j]);
				if (j < n - 1) {
					sb.append(",");
				}
			}
			if (i < m - 1) {
				sb.append("
");
			}
		}
		String result = sb.toString();
		return result;
	}
 
	/**
	 * 
	 * @param A
	 *            A[m][n]
	 * @return Copy of A[m][n] where the copy has a separate pointer in memory
	 *         (deep copy)
	 */
	public static float[][] CloneMatrix(float[][] A) {
		int m = A.length;
		int n = A[0].length;
		float[][] copy = new float[m][n];
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				copy[i][j] = A[i][j];
			}
		}
		return copy;
	}
 
	/**
	 * 
	 * @param v
	 *            v[n]
	 * @return Copy of A[m][n] where the copy has a separate pointer in memory
	 *         (deep copy)
	 */
	public static float[] CloneVector(float[] v) {
		int n = v.length;
		float[] copy = new float[n];
		for (int j = 0; j < n; j++) {
			copy[j] = v[j];
		}
		return copy;
	}
 
	/**
	 * 
	 * @param file
	 *            a Java.IO.File object
	 * @return A[m][n]
	 */
	public static float[][] OpenCsvMatrix(File file) {
		String[] rows = OpenCsvAsStringArray(file);
		int m = rows.length;
		List<float[]> lColSets = new ArrayList<float[]>(m);
		for (int i = 0; i < m; i++) {
			String[] sColSet = rows[i].split("	");
			int n = sColSet.length;
			float[] elements = new float[n];
			for (int j = 0; j < n; j++) {
				if (isNumeric(sColSet[j])) {
					elements[j] = Float.parseFloat(sColSet[j]);
				}
			}
			lColSets.add(elements);
		}
		float[][] A = new float[m][lColSets.get(0).length];
		for (int i = 0; i < m; i++) {
			A[i] = lColSets.get(i);
		}
		return A;
	}
 
	/**
	 * 
	 * @param a
	 *            Java.IO.File object
	 * @return Vector (float[]) from a 
 delimited text file containing a
	 *         list of numbers (column vector format).
	 */
	public static float[] OpenCsvVector(File file) {
		float[][] b2D = OpenCsvMatrix(file);
		int n = b2D.length;
		float[] vector = new float[n];
		for (int j = 0; j < n; j++) {
			vector[j] = b2D[j][0];
		}
		return vector;
	}
 
	/**
	 * 
	 * @param file
	 *            a Java.IO.File object
	 * @return v[n] as a string with tab delimited values and 
 line
	 *         terminators
	 */
	private static String[] OpenCsvAsStringArray(File file) {
		StringBuilder sb = new StringBuilder();
		BufferedReader br = null;
		try {
 
			String sCurrentLine;
			br = new BufferedReader(new FileReader(file.getCanonicalPath()));
			while ((sCurrentLine = br.readLine()) != null) {
				sb.append(sCurrentLine);
				sb.append("
");
			}
		} catch (IOException e) {
			e.getMessage();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		sb.replace(0, sb.length() - 1, sb.toString().replaceAll(",", "	"));
		String[] rows = sb.toString().split("
");
		return rows;
	}
 
	/**
	 * 
	 * @param fileSpec
	 *            path/fileName
	 * @param A
	 *            A(m,n)
	 * @throws IOException
	 */
	public static void SaveCsv(File fileSpec, float[][] A) throws IOException {
		String csv = ToCsvString(A);
		BufferedWriter writer = new BufferedWriter(new FileWriter(fileSpec));
		writer.write(csv);
		writer.close();
	}
 
	public static File OpenDialog(File defaultDirectory) {
		JFileChooser fileDialog = new JFileChooser(defaultDirectory);
		int openChoice = fileDialog.showOpenDialog(null);
		File openFile = null;
		if (openChoice == JFileChooser.APPROVE_OPTION) {
			openFile = fileDialog.getSelectedFile();
		}
		return openFile;
	}
 
	public static File SaveDialog(File defaultDirectory) {
		JFileChooser fileDialog = new JFileChooser(defaultDirectory);
		int saveChoice = fileDialog.showSaveDialog(null);
		File saveFile = null;
		if (saveChoice == JFileChooser.APPROVE_OPTION) {
			saveFile = fileDialog.getSelectedFile();
		}
		return saveFile;
	}
 
	public static void Print(String label, float[][] Matrix) {
		int m = Matrix.length;
		int n = Matrix[0].length;
		if (m * n < 100) {
			System.out.println(label);
			System.out.println(Utilities.ToTsv(Matrix) + "
");
		}
	}
 
	public static void Print(String label, float[] vector) {
		int m = vector.length;
		if (m < 100) {
			System.out.println(label);
			System.out.println(Utilities.ToTsv(vector) + "
");
		}
	}
 
	public static void Print(String label, int[] vector) {
		int m = vector.length;
		if (m < 100) {
			System.out.println(label);
			System.out.println(Utilities.ToTsv(vector) + "
");
		}
	}
}
 
ID may be exposed