code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2011 Google Inc. * * Licensed 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 com.googlecode.leptonica.android; import android.graphics.Bitmap; import java.io.File; /** * @author alanv@google.com (Alan Viverette) */ public class WriteFile { static { System.loadLibrary("lept"); } /* Default JPEG quality */ public static final int DEFAULT_QUALITY = 85; /* Default JPEG progressive encoding */ public static final boolean DEFAULT_PROGRESSIVE = true; /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @return a byte array where each byte represents a single 8-bit pixel */ public static byte[] writeBytes8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (pixs.getDepth() != 8) { Pix pix8 = Convert.convertTo8(pixs); pixs.recycle(); pixs = pix8; } byte[] data = new byte[size]; writeBytes8(pixs, data); return data; } /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @param data A byte array large enough to hold the pixels of pixs. * @return the number of bytes written to data */ public static int writeBytes8(Pix pixs, byte[] data) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (data.length < size) throw new IllegalArgumentException("Data array must be large enough to hold image bytes"); int bytesWritten = nativeWriteBytes8(pixs.mNativePix, data); return bytesWritten; } /** * Writes all the images in a Pixa array to individual files using the * specified format. The output file extension will be determined by the * format. * <p> * Output file names will take the format <path>/<prefix><index>.<extension> * * @param pixas The source Pixa image array. * @param path The output directory. * @param prefix The prefix to give output files. * @param format The format to use for output files. * @return <code>true</code> on success */ public static boolean writeFiles(Pixa pixas, File path, String prefix, int format) { if (pixas == null) throw new IllegalArgumentException("Source pixa must be non-null"); if (path == null) throw new IllegalArgumentException("Destination path non-null"); if (prefix == null) throw new IllegalArgumentException("Filename prefix must be non-null"); throw new RuntimeException("writeFiles() is not currently supported"); } /** * Write a Pix to a byte array using the specified encoding from * Constants.IFF_*. * * @param pixs The source image. * @param format A format from Constants.IFF_*. * @return a byte array containing encoded bytes */ public static byte[] writeMem(Pix pixs, int format) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeWriteMem(pixs.mNativePix, format); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Uses default quality and progressive encoding settings. * * @param pixs Source image. * @param file The file to write. * @return <code>true</code> on success */ public static boolean writeImpliedFormat(Pix pixs, File file) { return writeImpliedFormat(pixs, file, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Notes: * <ol> * <li>This determines the output format from the filename extension. * <li>The last two args are ignored except for requests for jpeg files. * <li>The jpeg default quality is 75. * </ol> * * @param pixs Source image. * @param file The file to write. * @param quality (Only for lossy formats) Quality between 1 - 100, 0 for * default. * @param progressive (Only for JPEG) Whether to encode as progressive. * @return <code>true</code> on success */ public static boolean writeImpliedFormat( Pix pixs, File file, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (file == null) throw new IllegalArgumentException("File must be non-null"); return nativeWriteImpliedFormat( pixs.mNativePix, file.getAbsolutePath(), quality, progressive); } /** * Writes a Pix to an Android Bitmap object. The output Bitmap will always * be in ARGB_8888 format, but the input Pixs may be any bit-depth. * * @param pixs The source image. * @return a Bitmap containing a copy of the source image, or <code>null * </code> on failure */ public static Bitmap writeBitmap(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); final int[] dimensions = pixs.getDimensions(); final int width = dimensions[Pix.INDEX_W]; final int height = dimensions[Pix.INDEX_H]; //final int depth = dimensions[Pix.INDEX_D]; final Bitmap.Config config = Bitmap.Config.ARGB_8888; final Bitmap bitmap = Bitmap.createBitmap(width, height, config); if (nativeWriteBitmap(pixs.mNativePix, bitmap)) { return bitmap; } bitmap.recycle(); return null; } // *************** // * NATIVE CODE * // *************** private static native int nativeWriteBytes8(int nativePix, byte[] data); private static native boolean nativeWriteFiles(int nativePix, String rootname, int format); private static native byte[] nativeWriteMem(int nativePix, int format); private static native boolean nativeWriteImpliedFormat( int nativePix, String fileName, int quality, boolean progressive); private static native boolean nativeWriteBitmap(int nativePix, Bitmap bitmap); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed 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 com.googlecode.leptonica.android; /** * Image binarization methods. * * @author alanv@google.com (Alan Viverette) */ public class Binarize { static { System.loadLibrary("lept"); } // Otsu thresholding constants /** Desired tile X dimension; actual size may vary */ public final static int OTSU_SIZE_X = 32; /** Desired tile Y dimension; actual size may vary */ public final static int OTSU_SIZE_Y = 32; /** Desired X smoothing value */ public final static int OTSU_SMOOTH_X = 2; /** Desired Y smoothing value */ public final static int OTSU_SMOOTH_Y = 2; /** Fraction of the max Otsu score, typically 0.1 */ public final static float OTSU_SCORE_FRACTION = 0.1f; /** * Performs locally-adaptive Otsu threshold binarization with default * parameters. * * @param pixs An 8 bpp PIX source image. * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold(Pix pixs) { return otsuAdaptiveThreshold( pixs, OTSU_SIZE_X, OTSU_SIZE_Y, OTSU_SMOOTH_X, OTSU_SMOOTH_Y, OTSU_SCORE_FRACTION); } /** * Performs locally-adaptive Otsu threshold binarization. * <p> * Notes: * <ol> * <li>The Otsu method finds a single global threshold for an image. This * function allows a locally adapted threshold to be found for each tile * into which the image is broken up. * <li>The array of threshold values, one for each tile, constitutes a * highly downscaled image. This array is optionally smoothed using a * convolution. The full width and height of the convolution kernel are (2 * * smoothX + 1) and (2 * smoothY + 1). * <li>The minimum tile dimension allowed is 16. If such small tiles are * used, it is recommended to use smoothing, because without smoothing, each * small tile determines the splitting threshold independently. A tile that * is entirely in the image bg will then hallucinate fg, resulting in a very * noisy binarization. The smoothing should be large enough that no tile is * only influenced by one type (fg or bg) of pixels, because it will force a * split of its pixels. * <li>To get a single global threshold for the entire image, use input * values of sizeX and sizeY that are larger than the image. For this * situation, the smoothing parameters are ignored. * <li>The threshold values partition the image pixels into two classes: one * whose values are less than the threshold and another whose values are * greater than or equal to the threshold. This is the same use of * 'threshold' as in pixThresholdToBinary(). * <li>The scorefract is the fraction of the maximum Otsu score, which is * used to determine the range over which the histogram minimum is searched. * See numaSplitDistribution() for details on the underlying method of * choosing a threshold. * <li>This uses enables a modified version of the Otsu criterion for * splitting the distribution of pixels in each tile into a fg and bg part. * The modification consists of searching for a minimum in the histogram * over a range of pixel values where the Otsu score is within a defined * fraction, scoreFraction, of the max score. To get the original Otsu * algorithm, set scoreFraction == 0. * </ol> * * @param pixs An 8 bpp PIX source image. * @param sizeX Desired tile X dimension; actual size may vary. * @param sizeY Desired tile Y dimension; actual size may vary. * @param smoothX Half-width of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param smoothY Half-height of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param scoreFraction Fraction of the max Otsu score; typ. 0.1 (use 0.0 * for standard Otsu). * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold( Pix pixs, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixs.getDepth() != 8) throw new IllegalArgumentException("Source pix depth must be 8bpp"); int nativePix = nativeOtsuAdaptiveThreshold( pixs.mNativePix, sizeX, sizeY, smoothX, smoothY, scoreFraction); if (nativePix == 0) throw new RuntimeException("Failed to perform Otsu adaptive threshold on image"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeOtsuAdaptiveThreshold( int nativePix, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFract); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed 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 com.googlecode.leptonica.android; /** * @author alanv@google.com (Alan Viverette) */ public class Rotate { static { System.loadLibrary("lept"); } // Rotation default /** Default rotation quality is high. */ public static final boolean ROTATE_QUALITY = true; /** * Performs rotation using the default parameters. * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees) { return rotate(pixs, degrees, false); } /** * Performs rotation with resizing using the default parameters. * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @param quality Whether to use high-quality rotation. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees, boolean quality) { return rotate(pixs, degrees, quality, true); } /** * Performs basic image rotation about the center. * <p> * Notes: * <ol> * <li>Rotation is about the center of the image. * <li>For very small rotations, just return a clone. * <li>Rotation brings either white or black pixels in from outside the * image. * <li>Above 20 degrees, if rotation by shear is requested, we rotate by * sampling. * <li>Colormaps are removed for rotation by area map and shear. * <li>The dest can be expanded so that no image pixels are lost. To invoke * expansion, input the original width and height. For repeated rotation, * use of the original width and height allows the expansion to stop at the * maximum required size, which is a square with side = sqrt(w*w + h*h). * </ol> * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @param quality Whether to use high-quality rotation. * @param resize Whether to expand the output so that no pixels are lost. * <strong>Note:</strong> 1bpp images are always resized when * quality is {@code true}. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees, boolean quality, boolean resize) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeRotate(pixs.mNativePix, degrees, quality, resize); if (nativePix == 0) return null; return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeRotate(int nativePix, float degrees, boolean quality, boolean resize); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed 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 com.googlecode.leptonica.android; /** * Image rotation and skew detection methods. * * @author alanv@google.com (Alan Viverette) */ public class Skew { static { System.loadLibrary("lept"); } // Text alignment defaults /** Default range for sweep, will detect rotation of + or - 30 degrees. */ public final static float SWEEP_RANGE = 30.0f; /** Default sweep delta, reasonably accurate within 0.05 degrees. */ public final static float SWEEP_DELTA = 5.0f; /** Default sweep reduction, one-eighth the size of the original image. */ public final static int SWEEP_REDUCTION = 8; /** Default sweep reduction, one-fourth the size of the original image. */ public final static int SEARCH_REDUCTION = 4; /** Default search minimum delta, reasonably accurate within 0.05 degrees. */ public final static float SEARCH_MIN_DELTA = 0.01f; /** * Finds and returns the skew angle using default parameters. * * @param pixs Input pix (1 bpp). * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs) { return findSkew(pixs, SWEEP_RANGE, SWEEP_DELTA, SWEEP_REDUCTION, SEARCH_REDUCTION, SEARCH_MIN_DELTA); } /** * Finds and returns the skew angle, doing first a sweep through a set of * equal angles, and then doing a binary search until convergence. * <p> * Notes: * <ol> * <li>In computing the differential line sum variance score, we sum the * result over scanlines, but we always skip: * <ul> * <li>at least one scanline * <li>not more than 10% of the image height * <li>not more than 5% of the image width * </ul> * </ol> * * @param pixs Input pix (1 bpp). * @param sweepRange Half the full search range, assumed about 0; in * degrees. * @param sweepDelta Angle increment of sweep; in degrees. * @param sweepReduction Sweep reduction factor = 1, 2, 4 or 8. * @param searchReduction Binary search reduction factor = 1, 2, 4 or 8; and * must not exceed redsweep. * @param searchMinDelta Minimum binary search increment angle; in degrees. * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeFindSkew(pixs.mNativePix, sweepRange, sweepDelta, sweepReduction, searchReduction, searchMinDelta); } // *************** // * NATIVE CODE * // *************** private static native float nativeFindSkew(int nativePix, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed 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 com.googlecode.leptonica.android; /** * Image adaptive mapping methods. * * @author alanv@google.com (Alan Viverette) */ public class AdaptiveMap { static { System.loadLibrary("lept"); } // Background normalization constants /** Image reduction value; possible values are 1, 2, 4, 8 */ private final static int NORM_REDUCTION = 16; /** Desired tile size; actual size may vary */ private final static int NORM_SIZE = 3; /** Background brightness value; values over 200 may result in clipping */ private final static int NORM_BG_VALUE = 200; /** * Normalizes an image's background using default parameters. * * @param pixs A source pix image. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph(Pix pixs) { return backgroundNormMorph(pixs, NORM_REDUCTION, NORM_SIZE, NORM_BG_VALUE); } /** * Normalizes an image's background to a specified value. * <p> * Notes: * <ol> * <li>This is a top-level interface for normalizing the image intensity by * mapping the image so that the background is near the input value 'bgval'. * <li>The input image is either grayscale or rgb. * <li>For each component in the input image, the background value is * estimated using a grayscale closing; hence the 'Morph' in the function * name. * <li>An optional binary mask can be specified, with the foreground pixels * typically over image regions. The resulting background map values will be * determined by surrounding pixels that are not under the mask foreground. * The origin (0,0) of this mask is assumed to be aligned with the origin of * the input image. This binary mask must not fully cover pixs, because then * there will be no pixels in the input image available to compute the * background. * <li>The map is computed at reduced size (given by 'reduction') from the * input pixs and optional pixim. At this scale, pixs is closed to remove * the background, using a square Sel of odd dimension. The product of * reduction * size should be large enough to remove most of the text * foreground. * <li>No convolutional smoothing needs to be done on the map before * inverting it. * <li>A 'bgval' target background value for the normalized image. This * should be at least 128. If set too close to 255, some clipping will occur * in the result. * </ol> * * @param pixs A source pix image. * @param normReduction Reduction at which morphological closings are done. * @param normSize Size of square Sel for the closing. * @param normBgValue Target background value. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph( Pix pixs, int normReduction, int normSize, int normBgValue) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeBackgroundNormMorph( pixs.mNativePix, normReduction, normSize, normBgValue); if (nativePix == 0) throw new RuntimeException("Failed to normalize image background"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeBackgroundNormMorph( int nativePix, int reduction, int size, int bgval); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed 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 com.googlecode.leptonica.android; /** * Image sharpening methods. * * @author alanv@google.com (Alan Viverette) */ public class Enhance { static { System.loadLibrary("lept"); } /** * Performs unsharp masking (edge enhancement). * <p> * Notes: * <ul> * <li>We use symmetric smoothing filters of odd dimension, typically use * sizes of 3, 5, 7, etc. The <code>halfwidth</code> parameter for these is * (size - 1)/2; i.e., 1, 2, 3, etc.</li> * <li>The <code>fract</code> parameter is typically taken in the range: 0.2 * &lt; <code>fract</code> &lt; 0.7</li> * </ul> * * @param halfwidth The half-width of the smoothing filter. * @param fraction The fraction of edge to be added back into the source * image. * @return an edge-enhanced Pix image or copy if no enhancement requested */ public static Pix unsharpMasking(Pix pixs, int halfwidth, float fraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeUnsharpMasking(pixs.mNativePix, halfwidth, fraction); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeUnsharpMasking(int nativePix, int halfwidth, float fract); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed 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 com.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * JPEG input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class JpegIO { static { System.loadLibrary("lept"); } /** Default quality is 85%, which is reasonably good. */ public static final int DEFAULT_QUALITY = 85; /** Progressive encoding is disabled by default to increase compatibility. */ public static final boolean DEFAULT_PROGRESSIVE = false; /** * Returns a compressed JPEG byte representation of this Pix using default * parameters. * * @param pixs * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs) { return compressToJpeg(pixs, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Returns a compressed JPEG byte representation of this Pix. * * @param pixs A source pix image. * @param quality The quality of the compressed image. Valid range is 0-100. * @param progressive Whether to use progressive compression. * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (quality < 0 || quality > 100) throw new IllegalArgumentException("Quality must be between 0 and 100 (inclusive)"); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); final Bitmap bmp = WriteFile.writeBitmap(pixs); bmp.compress(CompressFormat.JPEG, quality, byteStream); bmp.recycle(); final byte[] encodedData = byteStream.toByteArray(); try { byteStream.close(); } catch (IOException e) { e.printStackTrace(); } return encodedData; } // *************** // * NATIVE CODE * // *************** private static native byte[] nativeCompressToJpeg( int nativePix, int quality, boolean progressive); }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed 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 com.googlecode.leptonica.android; /** * Leptonica constants. * * @author alanv@google.com (Alan Viverette) */ public class Constants { /*-------------------------------------------------------------------------* * Access and storage flags * *-------------------------------------------------------------------------*/ /* * For Pix, Box, Pta and Numa, there are 3 standard methods for handling the * retrieval or insertion of a struct: (1) direct insertion (Don't do this * if there is another handle somewhere to this same struct!) (2) copy * (Always safe, sets up a refcount of 1 on the new object. Can be * undesirable if very large, such as an image or an array of images.) (3) * clone (Makes another handle to the same struct, and bumps the refcount up * by 1. Safe to do unless you're changing data through one of the handles * but don't want those changes to be seen by the other handle.) For Pixa * and Boxa, which are structs that hold an array of clonable structs, there * is an additional method: (4) copy-clone (Makes a new higher-level struct * with a refcount of 1, but clones all the structs in the array.) Unlike * the other structs, when retrieving a string from an Sarray, you are * allowed to get a handle without a copy or clone (i.e., that you don't * own!). You must not free or insert such a string! Specifically, for an * Sarray, the copyflag for retrieval is either: TRUE (or 1 or L_COPY) or * FALSE (or 0 or L_NOCOPY) For insertion, the copyflag is either: TRUE (or * 1 or L_COPY) or FALSE (or 0 or L_INSERT) Note that L_COPY is always 1, * and L_INSERT and L_NOCOPY are always 0. */ /* Stuff it in; no copy, clone or copy-clone */ public static final int L_INSERT = 0; /* Make/use a copy of the object */ public static final int L_COPY = 1; /* Make/use clone (ref count) of the object */ public static final int L_CLONE = 2; /* * Make a new object and fill with with clones of each object in the * array(s) */ public static final int L_COPY_CLONE = 3; /*--------------------------------------------------------------------------* * Sort flags * *--------------------------------------------------------------------------*/ /* Sort in increasing order */ public static final int L_SORT_INCREASING = 1; /* Sort in decreasing order */ public static final int L_SORT_DECREASING = 2; /* Sort box or c.c. by horiz location */ public static final int L_SORT_BY_X = 3; /* Sort box or c.c. by vert location */ public static final int L_SORT_BY_Y = 4; /* Sort box or c.c. by width */ public static final int L_SORT_BY_WIDTH = 5; /* Sort box or c.c. by height */ public static final int L_SORT_BY_HEIGHT = 6; /* Sort box or c.c. by min dimension */ public static final int L_SORT_BY_MIN_DIMENSION = 7; /* Sort box or c.c. by max dimension */ public static final int L_SORT_BY_MAX_DIMENSION = 8; /* Sort box or c.c. by perimeter */ public static final int L_SORT_BY_PERIMETER = 9; /* Sort box or c.c. by area */ public static final int L_SORT_BY_AREA = 10; /* Sort box or c.c. by width/height ratio */ public static final int L_SORT_BY_ASPECT_RATIO = 11; /* ------------------ Image file format types -------------- */ /* * The IFF_DEFAULT flag is used to write the file out in the same (input) * file format that the pix was read from. If the pix was not read from * file, the input format field will be IFF_UNKNOWN and the output file * format will be chosen to be compressed and lossless; namely, IFF_TIFF_G4 * for d = 1 and IFF_PNG for everything else. IFF_JP2 is for jpeg2000, which * is not supported in leptonica. */ public static final int IFF_UNKNOWN = 0; public static final int IFF_BMP = 1; public static final int IFF_JFIF_JPEG = 2; public static final int IFF_PNG = 3; public static final int IFF_TIFF = 4; public static final int IFF_TIFF_PACKBITS = 5; public static final int IFF_TIFF_RLE = 6; public static final int IFF_TIFF_G3 = 7; public static final int IFF_TIFF_G4 = 8; public static final int IFF_TIFF_LZW = 9; public static final int IFF_TIFF_ZIP = 10; public static final int IFF_PNM = 11; public static final int IFF_PS = 12; public static final int IFF_GIF = 13; public static final int IFF_JP2 = 14; public static final int IFF_DEFAULT = 15; public static final int IFF_SPIX = 16; }
Java
/* * Copyright (C) 2011 Google Inc. * * Licensed 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 com.googlecode.leptonica.android; /** * Image scaling methods. * * @author alanv@google.com (Alan Viverette) */ public class Scale { static { System.loadLibrary("lept"); } public enum ScaleType { /* Scale in X and Y independently, so that src matches dst exactly. */ FILL, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink or * expand src to fit dst. */ FIT, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink src to * fit dst, but will not expand it. */ FIT_SHRINK, } /** * Scales the Pix to a specified width and height using a specified scaling * type (fill, stretch, etc.). Returns a scaled image or a clone of the Pix * if no scaling is required. * * @param pixs * @param width * @param height * @param type * @return a scaled image or a clone of the Pix if no scaling is required */ public static Pix scaleToSize(Pix pixs, int width, int height, ScaleType type) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int pixWidth = pixs.getWidth(); int pixHeight = pixs.getHeight(); float scaleX = width / (float) pixWidth; float scaleY = height / (float) pixHeight; switch (type) { case FILL: // Retains default scaleX and scaleY values break; case FIT: scaleX = Math.min(scaleX, scaleY); scaleY = scaleX; break; case FIT_SHRINK: scaleX = Math.min(1.0f, Math.min(scaleX, scaleY)); scaleY = scaleX; break; } return scale(pixs, scaleX, scaleY); } /** * Scales the Pix to specified scale. If no scaling is required, returns a * clone of the source Pix. * * @param pixs the source Pix * @param scale dimension scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scale) { return scale(pixs, scale, scale); } /** * Scales the Pix to specified x and y scale. If no scaling is required, * returns a clone of the source Pix. * * @param pixs the source Pix * @param scaleX x-dimension (width) scaling factor * @param scaleY y-dimension (height) scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scaleX, float scaleY) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (scaleX <= 0.0f) throw new IllegalArgumentException("X scaling factor must be positive"); if (scaleY <= 0.0f) throw new IllegalArgumentException("Y scaling factor must be positive"); int nativePix = nativeScale(pixs.mNativePix, scaleX, scaleY); if (nativePix == 0) throw new RuntimeException("Failed to natively scale pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeScale(int nativePix, float scaleX, float scaleY); }
Java
package math; public class Complex { private double real; private double imag; public Complex(double real, double imag) { this.real = real; this.imag = imag; } public String toString() { if(imag<0) { return new String(real+" - i"+Math.abs(imag)); } else { return new String(real+" + i"+imag); } } public static final Complex multiply(Complex c1, Complex c2) { double re = c1.real*c2.real - c1.imag*c2.imag; double im = c1.real*c2.imag + c1.imag*c2.real; return new Complex(re, im); } public static Complex scale(Complex c, double x) { return new Complex(c.real*x, c.imag*x); } public static final Complex add(Complex c1, Complex c2) { double re = c1.real + c2.real; double im = c1.imag + c2.imag; return new Complex(re, im); } public static final Complex substract(Complex c1, Complex c2) { double re = c1.real - c2.real; double im = c1.imag - c2.imag; return new Complex(re, im); } public static Complex conjugate(Complex c) { return new Complex(c.real, -c.imag); } public static double abs(Complex c) { return Math.sqrt(c.real*c.real+c.imag*c.imag); } public static double[] abs(Complex[] c) { int N = c.length; double[] mag = new double[N]; for(int i=0; i<N; i++) { mag[i] = Math.sqrt(c[i].real*c[i].real+c[i].imag*c[i].imag); } return mag; } public static final Complex nthRootOfUnity(int n, int N) { double re = Math.cos(2*Math.PI*n/N); double im = Math.sin(2*Math.PI*n/N); return new Complex(re, im); } }
Java
package math; public class DFT { public static final int RECTANGULAR = 0; public static final int HANN = 1; public static final int HAMMING = 2; public static final int BLACKMANN = 3; public static final double[] forwardMagnitude(double[] input) { int N = input.length; double[] mag = new double[N]; double[] c = new double[N]; double[] s = new double[N]; double twoPi = 2*Math.PI; for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { c[i] += input[j]*Math.cos(i*j*twoPi/N); s[i] -= input[j]*Math.sin(i*j*twoPi/N); } c[i]/=N; s[i]/=N; mag[i]=Math.sqrt(c[i]*c[i]+s[i]*s[i]); } return mag; } public static final double[] window(double[] input, int type) { int N = input.length; double[] windowed = new double[N]; switch(type) { case RECTANGULAR: return input; case HANN: for(int n=0; n<N; n++) { windowed[n] = 0.5*(1-Math.cos(2*Math.PI*n/(N-1))) * input[n]; } break; case HAMMING: for (int n = 0; n < input.length; n++) { windowed[n] = (0.53836-0.46164*Math.cos(Tools.TWO_PI*n/(N-1))) * input[n]; } case BLACKMANN: for(int n=0; n<N; n++) { windowed[n] = (0.42-0.5*Math.cos(2*Math.PI*n/(N-1))+0.08*Math.cos(4*Math.PI*n/(N-1)) ) * input[n]; } break; } return windowed; } }
Java
package math; public class Tools { public static final double TWO_PI = 2*Math.PI; public static final double LOG_OF_2_BASE_10 = 1/Math.log10(2); public static double log2(double x) { return Math.log10(x)/Math.log10(2.0); } public static final double[] lowpass(double[] signal, int nPoints) { int N = signal.length; double[] ret = new double[N]; for(int i=0; i<nPoints/2; i++) { ret[i] = signal[i]; } for(int i=nPoints/2; i<N-nPoints/2; i++) { for(int j=0; j<nPoints; j++) { ret[i]=0; ret[i]+=signal[i-nPoints/2+j]; ret[i]/=nPoints; } } for(int i=N-nPoints/2; i<N; i++) { ret[i]=signal[i]; } return ret; } public static final double[] addArrays(double[] x, double[] y) { double[] sum = new double[x.length]; for(int i=0; i<x.length; i++) { sum[i] = x[i] + y[i]; } return sum; } public static final Complex[] addArrays(Complex[] x, Complex[] y) { Complex[] sum = new Complex[x.length]; for(int i=0; i<x.length; i++) { sum[i] = Complex.add(x[i], y[i]); } return sum; } public static final Complex[] substractArrays(Complex[] x, Complex[] y) { Complex[] sum = new Complex[x.length]; for(int i=0; i<x.length; i++) { sum[i] = Complex.substract(x[i], y[i]); } return sum; } public static final double[] dotProduct(double[] x, double[] y) { double[] sum = new double[x.length]; for(int i=0; i<x.length; i++) { sum[i] = x[i] * y[i]; } return sum; } public static final Complex[] dotProduct(Complex[] x, Complex[] y) { Complex[] sum = new Complex[x.length]; for(int i=0; i<x.length; i++) { sum[i] = Complex.multiply(x[i], y[i]); } return sum; } public static Complex[] makeComplex(double[] x) { int N = x.length; Complex[] c = new Complex[N]; for(int i=0; i<N; i++) { c[i] = new Complex(x[i],0); } return c; } public static void printArray(double[] arr) { for (double d : arr) { System.out.format("%.4f ", d); } System.out.println(); } }
Java
package math; /* * http://www.cs.princeton.edu/introcs/97data/FFT.java.html * Should be optimized. w_n may be looked up from a table etc. * * Java DSP book */ public class FFT { // private static int length; private static double[] r_data = null; private static double[] i_data = null; private static boolean forward = true; /* private void computeRootArray(int N) { Complex[] w = new Complex[N/2]; for(int i=0; i<N/2; i++) { w[i] = Complex.nthRootOfUnity(i, N); } } */ public static Complex[] forward(Complex[] x) { int N = x.length; if( N == 1 ) { return new Complex[] { x[0] }; } else { Complex[] even = new Complex[N/2]; Complex[] odd = new Complex[N/2]; for(int i=0; i<N/2; i++) { even[i]=x[2*i]; odd[i]=x[2*i+1]; } Complex[] left = forward(even); Complex[] right = forward(odd); Complex[] c = new Complex[N]; for(int n=0; n<N/2; n++) { double nth = -2*n*Math.PI/N; Complex wn = new Complex(Math.cos(nth), Math.sin(nth)); c[n] = Complex.add(left[n], Complex.multiply(wn, right[n])); c[n+N/2] = Complex.substract(left[n], Complex.multiply(wn, right[n])); } return c; } } public static int bitReverse(int index) { // if length = 8 index goes from 0 to 7 // to write 8 we need log2(8)+1=3+1=4 bits. // 8 = 1000, 7 = 111 // so to write 7 we need log2(8)=3 bits. int numBits = (int)Tools.log2(8); int ret = 0; for (int i = 0; i < numBits; i++) { ret = (ret<<1) + (index&1); index = index>>1; } return ret; } public static double[] magnitudeSpectrum(double[] realPart) { // length = realPart.length; // int localN; // // int numBits = (int)Tools.log2(length); // // for(int m = 1; m <= numBits; m++) { // // localN = 2^m; // localN = 1<<m; // } double[] imaginaryPart = new double[realPart.length]; for (int i = 0; i < imaginaryPart.length; i++) { imaginaryPart[i] = 0; } forwardFFT(realPart, imaginaryPart); for (int i = 0; i < realPart.length; i++) { realPart[i] = Math.sqrt( r_data[i]*r_data[i] + i_data[i]*i_data[i] ); } return realPart; } // swap Zi with Zj private static void swapInt(int i, int j) { double tempr; int ti; int tj; ti = i - 1; tj = j - 1; tempr = r_data[tj]; r_data[tj] = r_data[ti]; r_data[ti] = tempr; tempr = i_data[tj]; i_data[tj] = i_data[ti]; i_data[ti] = tempr; } private static void bitReverse2() { // System.out.println("fft: bit reversal"); /* bit reversal */ int n = r_data.length; int j = 1; int k; for (int i = 1; i < n; i++) { if (i < j) swapInt(i, j); k = n / 2; while (k >= 1 && k < j) { j = j - k; k = k / 2; } j = j + k; } } public static void forwardFFT(double in_r[], double in_i[]) { int id; int localN; double wtemp, Wjk_r, Wjk_i, Wj_r, Wj_i; double theta, tempr, tempi; // int ti, tj; int numBits = (int)Tools.log2(in_r.length); if (forward) { //centering(in_r); } // Truncate input data to a power of two int length = 1 << numBits; // length = 2**nu int n = length; int nby2; // Copy passed references to variables to be used within // fft routines & utilities r_data = in_r; i_data = in_i; bitReverse2(); for (int m = 1; m <= numBits; m++) { // localN = 2^m; localN = 1 << m; nby2 = localN / 2; Wjk_r = 1; Wjk_i = 0; theta = Math.PI / nby2; // for recursive comptutation of sine and cosine Wj_r = Math.cos(theta); Wj_i = -Math.sin(theta); if (forward == false) { Wj_i = -Wj_i; } for (int j = 0; j < nby2; j++) { // This is the FFT innermost loop // Any optimizations that can be made here will yield // great rewards. for (int k = j; k < n; k += localN) { id = k + nby2; tempr = Wjk_r * r_data[id] - Wjk_i * i_data[id]; tempi = Wjk_r * i_data[id] + Wjk_i * r_data[id]; // Zid = Zi -C r_data[id] = r_data[k] - tempr; i_data[id] = i_data[k] - tempi; r_data[k] += tempr; i_data[k] += tempi; } // (eq 6.23) and (eq 6.24) wtemp = Wjk_r; Wjk_r = Wj_r * Wjk_r - Wj_i * Wjk_i; Wjk_i = Wj_r * Wjk_i + Wj_i * wtemp; } } // normalize output of fft. // if (forward) if(false) for (int i = 0; i < r_data.length; i++) { r_data[i] = r_data[i] / (double) n; i_data[i] = i_data[i] / (double) n; } in_r = r_data; in_r = i_data; } public static Complex[] inverse(Complex[] c) { int N = c.length; Complex[] x = new Complex[N]; for(int i=0; i<N; i++) { x[i] = Complex.conjugate(c[i]); } x = forward(x); for(int i=0; i<N; i++) { x[i] = Complex.conjugate(x[i]); x[i] = Complex.scale(x[i], 1.0/N); } return x; } }
Java
package wpam.recognizer; public class Spectrum { private double[] spectrum; private int length; public Spectrum(double[] spectrum) { this.spectrum = spectrum; this.length = spectrum.length; } public void normalize() { double maxValue = 0.0; for(int i=0;i<length; ++i) if(maxValue < spectrum[i]) maxValue = spectrum[i]; if(maxValue != 0) for(int i=0;i<length; ++i) spectrum[i] /= maxValue; } public double get(int index) { return spectrum[index]; } public int length() { return length; } }
Java
package wpam.recognizer; public class Tone { private int lowFrequency; private int highFrequency; private char key; private static int FREQUENCY_DELTA = 2; public Tone(int lowFrequency, int highFrequency, char key) { this.lowFrequency = lowFrequency; this.highFrequency = highFrequency; this.key = key; } public int getLowFrequency() { return lowFrequency; } public int getHighFrequency() { return highFrequency; } public char getKey() { return key; } public boolean isDistrinct(boolean[] distincts) { if(match(lowFrequency, distincts) && match(highFrequency,distincts)) return true; return false; } private boolean match(int frequency, boolean[] distincts) { for(int i = frequency - FREQUENCY_DELTA; i <= frequency + FREQUENCY_DELTA; ++i) if(distincts[i]) return true; return false; } public boolean match(int lowFrequency, int highFrequency) { if(matchFrequency(lowFrequency, this.lowFrequency) && matchFrequency(highFrequency, this.highFrequency)) return true; return false; } private boolean matchFrequency(int frequency, int frequencyPattern) { if((frequency - frequencyPattern) * (frequency - frequencyPattern) < FREQUENCY_DELTA * FREQUENCY_DELTA) return true; return false; } }
Java
package wpam.recognizer; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import android.content.Context; import android.util.Log; public class History implements Serializable { private ArrayList<HistoryItem> history; private Context context; private static String filename = "history"; public History(Context context) { this.context = context; history = new ArrayList<HistoryItem>(); } public void save() { FileOutputStream fos = null; ObjectOutputStream out = null; try { fos = context.openFileOutput(filename, Context.MODE_PRIVATE); out = new ObjectOutputStream(fos); out.writeObject(history); out.close(); } catch(IOException ex) { Log.e("IOException", "History.save()"); } } @SuppressWarnings("unchecked") public void load() { try { FileInputStream fin = context.openFileInput(filename); ObjectInputStream ois = new ObjectInputStream(fin); history = (ArrayList<HistoryItem>) ois.readObject(); ois.close(); } catch (Exception e) { Log.e("Exception", "History.load()"); } } public HistoryItem get(int index) { return history.get(index); } public void add(String text) { if(!text.equals("")) history.add(0, new HistoryItem(text)); } public int getCount() { return history.size(); } }
Java
package wpam.recognizer; import java.util.ArrayList; import java.util.Collection; public class StatelessRecognizer { private Spectrum spectrum; private Collection<Tone> tones; public StatelessRecognizer(Spectrum spectrum) { this.spectrum = spectrum; tones = new ArrayList<Tone>(); fillTones(); } private void fillTones() { tones.add(new Tone(45, 77, '1')); tones.add(new Tone(45, 86, '2')); tones.add(new Tone(45, 95, '3')); tones.add(new Tone(49, 77, '4')); tones.add(new Tone(49, 86, '5')); tones.add(new Tone(49, 95, '6')); tones.add(new Tone(55, 77, '7')); tones.add(new Tone(55, 86, '8')); tones.add(new Tone(55, 95, '9')); tones.add(new Tone(60, 77, '*')); tones.add(new Tone(60, 86, '0')); tones.add(new Tone(60, 95, '#')); } public char getRecognizedKey() { SpectrumFragment lowFragment= new SpectrumFragment(0, 75, spectrum); SpectrumFragment highFragment= new SpectrumFragment(75, 150, spectrum); int lowMax = lowFragment.getMax(); int highMax = highFragment.getMax(); SpectrumFragment allSpectrum = new SpectrumFragment(0, 150, spectrum); int max = allSpectrum.getMax(); if(max != lowMax && max != highMax) return ' '; for (Tone t : tones) { if(t.match(lowMax, highMax)) return t.getKey(); } return ' '; } }
Java
package wpam.recognizer; import java.util.ArrayList; public class Recognizer { ArrayList<Character> history; char acctualVaue; public Recognizer() { clear(); } private void clear() { history = new ArrayList<Character>(); acctualVaue = ' '; } public char getRecognizedKey(char recognizedKey) { history.add(recognizedKey); if(history.size() <= 4) return ' '; history.remove(0); int count = 0; for (Character c: history) { if(c.equals(recognizedKey)) count++; } if(count >= 3) acctualVaue = recognizedKey; return acctualVaue; } }
Java
package wpam.recognizer; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Calendar; public class HistoryItem implements Serializable { String dataTime; String text; public HistoryItem(final String text) { this.text = text; this.dataTime = now(); } private static String now() { final Calendar cal = Calendar.getInstance(); final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy (HH:mm)"); return sdf.format(cal.getTime()); } public String getText() { return text; } public String getFormatedTimestamp() { return dataTime; } }
Java
package wpam.recognizer; import java.util.concurrent.BlockingQueue; import math.FFT; import android.media.AudioFormat; import android.media.AudioRecord; import android.os.AsyncTask; public class RecordTask extends AsyncTask<Void, Object, Void> { int frequency = 16000; int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; int audioEncoding = AudioFormat.ENCODING_PCM_16BIT; int blockSize = 1024; Controller controller; BlockingQueue<DataBlock> blockingQueue; public RecordTask(Controller controller, BlockingQueue<DataBlock> blockingQueue) { this.controller = controller; this.blockingQueue = blockingQueue; } @Override protected Void doInBackground(Void... params) { int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding); AudioRecord audioRecord = new AudioRecord(controller.getAudioSource(), frequency, channelConfiguration, audioEncoding, bufferSize); try { short[] buffer = new short[blockSize]; audioRecord.startRecording(); while (controller.isStarted()) { int bufferReadSize = audioRecord.read(buffer, 0, blockSize); DataBlock dataBlock = new DataBlock(buffer, blockSize, bufferReadSize); blockingQueue.put(dataBlock); } } catch (Throwable t) { //Log.e("AudioRecord", "Recording Failed"); } audioRecord.stop(); return null; } }
Java
package wpam.recognizer; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.widget.ImageView; public class SpectrumView { ImageView imageView; Bitmap bitmap; Canvas canvas; Paint paint; public void setImageView(ImageView imageView) { this.imageView = imageView; bitmap = Bitmap.createBitmap((int) 512, (int) 100, Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); paint = new Paint(); this.imageView.setImageBitmap(bitmap); } public void draw(Spectrum spectrum) { canvas.drawColor(Color.BLACK); for (int i = 0; i < spectrum.length(); ++i) { int downy = (int) (100 - (spectrum.get(i) * 100)); int upy = 100; if(i >= 40 && i <= 65) paint.setColor(Color.rgb(130, 130, 130)); else if(i >= 75 && i <= 100) paint.setColor(Color.rgb(130, 130, 130)); else paint.setColor(Color.WHITE); canvas.drawLine(i, downy, i, upy, paint); } paint.setColor(Color.RED); SpectrumFragment fragment = new SpectrumFragment(80, 200, spectrum); boolean[] distincts = fragment.getDistincts(); int averageLineLevel = (int)(100 - fragment.getAverage() * 2 * 100); canvas.drawLine(0, averageLineLevel, 500, averageLineLevel, paint); imageView.invalidate(); } }
Java
package wpam.recognizer; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class HistoryRowAdapter extends ArrayAdapter<HistoryItem> { private History history; public HistoryRowAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); this.history = new History(context); this.history.load(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.history_row, null); } HistoryItem h = history.get(position); if (h != null) { TextView tt = (TextView) v.findViewById(R.id.text); TextView bt = (TextView) v.findViewById(R.id.timestamp); if (tt != null) { tt.setText(h.getText()); } if(bt != null) { bt.setText(h.getFormatedTimestamp()); } } return v; } @Override public int getCount() { return this.history.getCount(); } }
Java
package wpam.recognizer; import java.util.HashMap; import java.util.Map; import android.widget.Button; public class NumericKeyboard { private Map<Character, Button> buttons; public NumericKeyboard() { buttons = new HashMap<Character, Button>(); } public void add(char c, Button button) { buttons.put(c, button); } public void setEnabled(boolean enabled) { for (Map.Entry<Character, Button> e : buttons.entrySet()) { e.getValue().setEnabled(enabled); } } public void setActive(Character key) { for (Map.Entry<Character, Button> e : buttons.entrySet()) { if(e.getKey().equals(key)) e.getValue().setPressed(true); else e.getValue().setPressed(false); } } }
Java
package wpam.recognizer; import math.FFT; public class DataBlock { private double[] block; public DataBlock(short[] buffer, int blockSize, int bufferReadSize) { block = new double[blockSize]; for (int i = 0; i < blockSize && i < bufferReadSize; i++) { block[i] = (double) buffer[i]; } } public DataBlock() { } public void setBlock(double[] block) { this.block = block; } public double[] getBlock() { return block; } public Spectrum FFT() { return new Spectrum(FFT.magnitudeSpectrum(block)); } }
Java
package wpam.recognizer; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class Controller { private boolean started; private RecordTask recordTask; private RecognizerTask recognizerTask; private MainActivity mainActivity; BlockingQueue<DataBlock> blockingQueue; private Character lastValue; public Controller(MainActivity mainActivity) { this.mainActivity = mainActivity; } public void changeState() { if (started == false) { lastValue = ' '; blockingQueue = new LinkedBlockingQueue<DataBlock>(); mainActivity.start(); recordTask = new RecordTask(this,blockingQueue); recognizerTask = new RecognizerTask(this,blockingQueue); recordTask.execute(); recognizerTask.execute(); started = true; } else { mainActivity.stop(); recognizerTask.cancel(true); recordTask.cancel(true); started = false; } } public void clear() { mainActivity.clearText(); } public boolean isStarted() { return started; } public int getAudioSource() { return mainActivity.getAudioSource(); } public void spectrumReady(Spectrum spectrum) { mainActivity.drawSpectrum(spectrum); } public void keyReady(char key) { mainActivity.setAciveKey(key); if(key != ' ') if(lastValue != key) mainActivity.addText(key); lastValue = key; } public void debug(String text) { mainActivity.setText(text); } }
Java
package wpam.recognizer; import pl.polidea.apphance.Apphance; import android.R.string; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.media.MediaRecorder; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private Button stateButton; private Button clearButton; private EditText recognizeredEditText; private SpectrumView spectrumView; private NumericKeyboard numKeyboard; Controller controller; private String recognizeredText; History history; public static final String APP_KEY = "806785c1fb7aed8a867039282bc21993eedbc4e4"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Apphance.start(this, APP_KEY); setContentView(R.layout.main); controller = new Controller(this); stateButton = (Button)this.findViewById(R.id.stateButton); stateButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { controller.changeState(); } }); clearButton = (Button)this.findViewById(R.id.clearButton); clearButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { controller.clear(); } }); spectrumView = new SpectrumView(); spectrumView.setImageView((ImageView) this.findViewById(R.id.spectrum)); recognizeredEditText = (EditText)this.findViewById(R.id.recognizeredText); recognizeredEditText.setFocusable(false); numKeyboard = new NumericKeyboard(); numKeyboard.add('0', (Button)findViewById(R.id.button0)); numKeyboard.add('1', (Button)findViewById(R.id.button1)); numKeyboard.add('2', (Button)findViewById(R.id.button2)); numKeyboard.add('3', (Button)findViewById(R.id.button3)); numKeyboard.add('4', (Button)findViewById(R.id.button4)); numKeyboard.add('5', (Button)findViewById(R.id.button5)); numKeyboard.add('6', (Button)findViewById(R.id.button6)); numKeyboard.add('7', (Button)findViewById(R.id.button7)); numKeyboard.add('8', (Button)findViewById(R.id.button8)); numKeyboard.add('9', (Button)findViewById(R.id.button9)); numKeyboard.add('0', (Button)findViewById(R.id.button0)); numKeyboard.add('#', (Button)findViewById(R.id.buttonHash)); numKeyboard.add('*', (Button)findViewById(R.id.buttonAsterisk)); setEnabled(false); recognizeredText = ""; history = new History(this); history.load(); } public void start() { stateButton.setText(R.string.stop); setEnabled(true); } public void stop() { history.add(recognizeredText); stateButton.setText(R.string.start); setEnabled(false); } public int getAudioSource() { TelephonyManager telephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); if (telephonyManager.getCallState() != TelephonyManager.PHONE_TYPE_NONE) return MediaRecorder.AudioSource.VOICE_DOWNLINK; return MediaRecorder.AudioSource.MIC; } public void drawSpectrum(Spectrum spectrum) { spectrumView.draw(spectrum); } public void clearText() { history.add(recognizeredText); recognizeredText = ""; recognizeredEditText.setText(""); } public void addText(Character c) { recognizeredText += c; recognizeredEditText.setText(recognizeredText); } public void setText(String text) { recognizeredEditText.setText(text); } public void setEnabled(boolean enabled) { recognizeredEditText.setEnabled(enabled); numKeyboard.setEnabled(enabled); } public void setAciveKey(char key) { numKeyboard.setActive(key); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.layout.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.history: showHistory(); break; case R.id.send: sendRecognizeredText(); break; case R.id.about: showAbout(); break; } return true; } private void showHistory() { history.add(recognizeredText); history.save(); Intent intent = new Intent(this, HistoryActivity.class); startActivity(intent); } private void sendRecognizeredText() { final Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND); sendIntent.setType("text/plain"); sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, recognizeredText); startActivity(Intent.createChooser(sendIntent, getString(R.string.send)+":")); } private void showAbout() { AlertDialog about = new AlertDialog.Builder(this).create(); about.setTitle(getString(R.string.app_name)+" ("+getVersion()+")"); about.setIcon(R.drawable.icon); about.setMessage(getString(R.string.about_text)); about.show(); } private String getVersion() { PackageManager manager = getPackageManager(); PackageInfo info = null; try { info = manager.getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException e) { Log.wtf("NameNotFoundException", "getVersion() NameNotFoundException"); } return info.versionName; } @Override protected void onDestroy() { history.add(recognizeredText); history.save(); super.onDestroy(); } @Override protected void onPause() { if (controller.isStarted()) controller.changeState(); super.onPause(); } }
Java
package wpam.recognizer; import android.app.ListActivity; import android.os.Bundle; public class HistoryActivity extends ListActivity { private HistoryRowAdapter historyRowAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.history); this.historyRowAdapter = new HistoryRowAdapter(this, R.layout.history_row); setListAdapter(this.historyRowAdapter); } }
Java
package wpam.recognizer; import java.util.concurrent.BlockingQueue; import android.os.AsyncTask; public class RecognizerTask extends AsyncTask<Void, Object, Void> { private Controller controller; private BlockingQueue<DataBlock> blockingQueue; private Recognizer recognizer; public RecognizerTask(Controller controller, BlockingQueue<DataBlock> blockingQueue) { this.controller = controller; this.blockingQueue = blockingQueue; recognizer = new Recognizer(); } @Override protected Void doInBackground(Void... params) { while(controller.isStarted()) { try { DataBlock dataBlock = blockingQueue.take(); Spectrum spectrum = dataBlock.FFT(); spectrum.normalize(); StatelessRecognizer statelessRecognizer = new StatelessRecognizer(spectrum); Character key = recognizer.getRecognizedKey(statelessRecognizer.getRecognizedKey()); publishProgress(spectrum, key); // SpectrumFragment spectrumFragment = new SpectrumFragment(75, 100, spectrum); // publishProgress(spectrum, spectrumFragment.getMax()); } catch (InterruptedException e) { // TODO Auto-generated catch block } } return null; } protected void onProgressUpdate(Object... progress) { Spectrum spectrum = (Spectrum)progress[0]; controller.spectrumReady(spectrum); Character key = (Character)progress[1]; controller.keyReady(key); // Integer key = (Integer)progress[1]; // controller.debug(key.toString()); } }
Java
package annas.misc; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import annas.graph.EdgeInterface; import annas.graph.WeightedEdgeInterface; public class GraphPath<V, E extends EdgeInterface<V>> { private Set<E> edges; public GraphPath() { super(); this.edges = new LinkedHashSet<E>(); } public boolean addEdge(E e) { return this.edges.add(e); } public double getDistance() { double r = 0; Iterator<E> i = this.edges.iterator(); while (i.hasNext()) { r += (this.getWeight(i.next())); } return r; } public double getLength() { int r = 0; Iterator<E> i = this.edges.iterator(); while (i.hasNext()) { r++; i.next(); } return r == 0 ? 0 : r + 1; } public boolean contains(E e) { return this.edges.contains(e); } public Iterator<E> getIterator() { return new Iterator<E>() { Iterator<E> it = GraphPath.this.edges.iterator(); @Override public boolean hasNext() { return this.it.hasNext(); } @Override public E next() { return this.it.next(); } @Override public void remove() { } }; } private double getWeight(EdgeInterface<V> e) { if (e instanceof WeightedEdgeInterface<?>) { return ((WeightedEdgeInterface<V>) e).getWeight(); } return 1.0; } }
Java
package annas.misc; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import annas.graph.GraphInterface; import annas.graph.IntegerEdge; public class Graph6FileReader implements Iterable<GraphInterface<Integer,IntegerEdge>> { private String filename; public Graph6FileReader(String filename) { super(); this.filename = filename; } @Override public Iterator<GraphInterface<Integer, IntegerEdge>> iterator() { return new GraphIterator(this.filename); } class GraphIterator implements Iterator<GraphInterface<Integer, IntegerEdge>> { private BufferedReader in; private String filename; private String newLine; private boolean preread = false; public GraphIterator(String filename) { super(); this.filename = filename; try { this.in = new BufferedReader(new FileReader(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } this.newLine = ""; } @Override public boolean hasNext() { if(this.preread == true){ return true; } String line; try { line = in.readLine(); } catch (IOException e) { return false; } if (line != null) { this.preread = true; this.newLine = line; return true; } else { return false; } } @Override public GraphInterface<Integer, IntegerEdge> next() { String line = null; if (this.preread != true) { try { line = this.in.readLine(); } catch (IOException e) { e.printStackTrace(); } } else { line = this.newLine; this.preread = false; } return Graph6.decodeGraph(line); } @Override public void remove() { throw new NoSuchMethodError(); } @Override public String toString(){ return "GraphIterator: Connected to "+ this.filename; } } @Override public String toString(){ return "Graph6FileReader: Connected to "+ this.filename; } }
Java
package annas.misc; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Iterator; import annas.graph.GraphInterface; import annas.graph.IntegerEdge; import annas.graph.UndirectedGraph; import annas.math.Matrix; public class GraphIterator implements Iterator<GraphInterface<Integer,IntegerEdge>> { private ResultSet rs; public GraphIterator(ResultSet rs) { super(); this.rs = rs; } @Override public boolean hasNext() { try { return rs.next(); } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public GraphInterface<Integer,IntegerEdge> next() { try { return unpackgraph(rs.getString("sgraph")); } catch (SQLException e) { e.printStackTrace(); } return null; } @Override public void remove() { throw new UnsupportedOperationException(); } private GraphInterface<Integer, IntegerEdge> unpackgraph(String sgraph) { return Fromg6.fromg6(sgraph); } private static class Fromg6 { public static GraphInterface<Integer, IntegerEdge> fromg6(String str) { Matrix m = decodeGraph(StringToIntArray(str)); GraphInterface<Integer, IntegerEdge> graph = new UndirectedGraph<Integer, IntegerEdge>( IntegerEdge.class); for (int i = 0; i < m.getMatrix().length; i++) { graph.addVertex(i); } double[][] ma = m.getMatrix(); for (int i = 0; i < ma.length; i++) { for (int j = 0; j < ma.length; j++) { if (ma[i][j] == 1) { graph.addEdge(i, j); } } } return graph; } private static Matrix decodeGraph(int[] i) { long nuNodes = decodeN(i); String a = ""; if (nuNodes <= 62) { a = decodeR(Arrays.copyOfRange(i, 1, i.length)); } else if (nuNodes > 62 && nuNodes <= 258047) { a = decodeR(Arrays.copyOfRange(i, 4, i.length)); } else { a = decodeR(Arrays.copyOfRange(i, 8, i.length)); } int[][] adj = new int[(int) nuNodes][(int) nuNodes]; int q = 0; for (int w = 0; w < nuNodes; w++) { for (int e = 0; e < w; e++) { adj[w][e] = Integer.parseInt((a.charAt(q)) + ""); q++; } } return new Matrix(adj); } private static long decodeN(int i[]) { if (i.length > 2 && i[0] == 126 && i[1] == 126) { return Long.parseLong(decodeR(new int[] { i[2], i[3], i[4], i[5], i[6], i[7] }), 2); } else if (i.length > 1 && i[0] == 126) { return Long.parseLong(decodeR(new int[] { i[1], i[2], i[3] }), 2); } else { return i[0] - 63; } } private static String decodeR(int[] bytes) { String retval = ""; for (int i = 0; i < bytes.length; i++) { retval += padL(Integer.toBinaryString(bytes[i] - 63), 6); } return retval; } private static String padL(String str, int h) { String retval = ""; for (int i = 0; i < h - str.length(); i++) { retval += "0"; } return retval + str; } private static int[] StringToIntArray(String str) { int[] v = new int[str.length()]; for (int l = 0; l < str.length(); l++) { v[l] = str.charAt(l); } return v; } } }
Java
package annas.misc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; /** * This class provides a means of persistence, providing the ability to * push/pull a graph to a SQL (Sqlite) database. * * * @see java.sql.Connection * * @author Sam Wilson * @version v1.0 */ public class GraphDatabase { /** * Connection to the database server */ private Connection conn; /** * Statement to execute at the server. */ private Statement stmt; /** * Table name */ private static final String table_name = "annas_graph"; private String filename; /** * Statement to create a table suitable of storing graphs. */ private static final String create_tbl = "CREATE TABLE IF NOT EXISTS " + GraphDatabase.table_name + " (id INT PRIMARY KEY, name TEXT, sgraph LONGBLOB, num_vertices INT, num_edges INT, encoding TINYTEXT); "; public GraphDatabase(String filename) { super(); this.filename = filename; try { Class.forName("org.sqlite.JDBC"); this.conn = DriverManager.getConnection("jdbc:sqlite:" + filename); this.stmt = this.conn.createStatement(); this.stmt.setQueryTimeout(30); this.setupTable(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } this.conn.toString(); } public boolean insert(String name, String sgraph, int order, int size) throws SQLException { PreparedStatement pstmt = this.conn .prepareStatement("INSERT INTO " + GraphDatabase.table_name + " (name,sgraph,num_vertices,num_edges,encoding) VALUES (?,?,?,?,?); "); pstmt.setString(1, name); pstmt.setString(2, sgraph); pstmt.setInt(3, order); pstmt.setInt(4, size); pstmt.setString(5, "g6"); return pstmt.execute(); } public GraphIterator getAllGraphs() throws SQLException { return new GraphIterator(this.stmt.executeQuery("SELECT * FROM " + GraphDatabase.table_name + ";")); } public GraphIterator getGraphOfOrder(int n) throws SQLException { return new GraphIterator(this.stmt.executeQuery("SELECT * FROM " + GraphDatabase.table_name + " WHERE num_vertices = " + n + " ;")); } public GraphIterator getGraphOfOrderGreaterThan(int n) throws SQLException { return new GraphIterator(this.stmt.executeQuery("SELECT * FROM " + GraphDatabase.table_name + " WHERE num_vertices > " + n + " ;")); } public GraphIterator getGraphOfOrderLessThan(int n) throws SQLException { return new GraphIterator(this.stmt.executeQuery("SELECT * FROM " + GraphDatabase.table_name + " WHERE num_vertices < " + n + " ;")); } public GraphIterator getGraphOfSize(int n) throws SQLException { return new GraphIterator(this.stmt.executeQuery("SELECT * FROM " + GraphDatabase.table_name + " WHERE num_edges = " + n + " ;")); } public GraphIterator getGraphOfSizeGreaterThan(int n) throws SQLException { return new GraphIterator(this.stmt.executeQuery("SELECT * FROM " + GraphDatabase.table_name + " WHERE num_edges > " + n + " ;")); } public GraphIterator getGraphOfSizeLessThan(int n) throws SQLException { return new GraphIterator(this.stmt.executeQuery("SELECT * FROM " + GraphDatabase.table_name + " WHERE num_edges < " + n + " ;")); } private boolean setupTable() throws SQLException { return this.stmt.execute(GraphDatabase.create_tbl); } @Override public String toString(){ return "SQLite: Connected to " + this.filename; } }
Java
package annas.misc; import java.util.Arrays; import annas.graph.GraphInterface; import annas.graph.IntegerEdge; import annas.graph.SimpleUndirectedGraph; import annas.graph.util.Utilities; import annas.math.Matrix; /** * Encodes and decodes graphs in graph6 format. * * @author Sam Wilson * @version v1.0 */ public class Graph6 { /** * Given a string representing a graph in graph6 format this method returns * a Simple Undircted graph. * * @param entry * String representing a graph in graph6 format. * @return the graph represented by the given string */ public static GraphInterface<Integer, IntegerEdge> decodeGraph(String entry) { SimpleUndirectedGraph<Integer, IntegerEdge> graph = new SimpleUndirectedGraph<>( IntegerEdge.class); Matrix m = Graph6.decodeGraph(StringToIntArray(entry)); for (int h = 0; h < m.getMatrix().length; h++) { graph.addVertex(h); } for (int i = 0; i < m.getMatrix().length; i++) { for (int j = 0; j < i; j++) { if (m.getMatrix()[i][j] != 0) { graph.addEdge(i, j); } } } return graph; } /** * This method given a graph produces a string representing the graph in * graph6 file format. * * @param graph * @return String representing the graph in graph6 file format. */ public static String encodeGraph(GraphInterface<?, ?> graph) { double[][] m = Utilities.getAdjacencyMatrix(graph).getMatrix(); String adjmatrix = ""; for (int i = 0; i < m.length; i++) { for (int j = 1 + i; j < m.length; j++) { if (m[i][j] != 0) { adjmatrix += "1"; } else { adjmatrix += "0"; } } } return Graph6.encodeGraph(graph.getOrder(), adjmatrix); } private static Matrix decodeGraph(int[] i) { long nuNodes = decodeN(i); String a = ""; if (nuNodes <= 62) { a = decodeR(Arrays.copyOfRange(i, 1, i.length)); } else if (nuNodes > 62 && nuNodes <= 258047) { a = decodeR(Arrays.copyOfRange(i, 4, i.length)); } else { a = decodeR(Arrays.copyOfRange(i, 8, i.length)); } int[][] adj = new int[(int) nuNodes][(int) nuNodes]; int q = 0; for (int w = 0; w < nuNodes; w++) { for (int e = 0; e < w; e++) { adj[w][e] = Integer.parseInt((a.charAt(q)) + ""); q++; } } return new Matrix(adj); } private static String encodeGraph(int NoNodes, String adjmatrix) { String rv = ""; int[] nn = encodeN(NoNodes); int[] adj = encodeR(adjmatrix); int[] res = new int[nn.length + adj.length]; System.arraycopy(nn, 0, res, 0, nn.length); System.arraycopy(adj, 0, res, nn.length, adj.length); for (int i = 0; i < res.length; i++) { rv = rv + (char) res[i]; } return rv; } private static int[] encodeN(long i) { if (0 <= i && i <= 62) { return new int[] { (int) (i + 63) }; } else if (63 <= i && i <= 258047) { int[] ret = new int[4]; ret[0] = 126; int[] g = R(padL(Long.toBinaryString(i), 18)); for (int j = 0; j < 3; j++) ret[j + 1] = g[j]; return ret; } else { int[] ret = new int[8]; ret[0] = 126; ret[1] = 126; int[] g = R(padL(Long.toBinaryString(i), 36)); for (int j = 0; j < 6; j++) ret[j + 2] = g[j]; return ret; } } private static long decodeN(int i[]) { if (i.length > 2 && i[0] == 126 && i[1] == 126) { return Long.parseLong(decodeR(new int[] { i[2], i[3], i[4], i[5], i[6], i[7] }), 2); } else if (i.length > 1 && i[0] == 126) { return Long.parseLong(decodeR(new int[] { i[1], i[2], i[3] }), 2); } else { return i[0] - 63; } } private static int[] R(String a) { int[] bytes = new int[a.length() / 6]; for (int i = 0; i < a.length() / 6; i++) { bytes[i] = Integer.valueOf(a.substring(i * 6, ((i * 6) + 6)), 2); bytes[i] = (byte) (bytes[i] + 63); } return bytes; } private static int[] encodeR(String a) { a = padR(a); return R(a); } private static String decodeR(int[] bytes) { String retval = ""; for (int i = 0; i < bytes.length; i++) { retval += padL(Integer.toBinaryString(bytes[i] - 63), 6); } return retval; } private static int[] StringToIntArray(String str) { int[] v = new int[str.length()]; for (int l = 0; l < str.length(); l++) { v[l] = str.charAt(l); } return v; } private static String padR(String str) { int padwith = 6 - (str.length() % 6); for (int i = 0; i < padwith; i++) { str += "0"; } return str; } private static String padL(String str, int h) { String retval = ""; for (int i = 0; i < h - str.length(); i++) { retval += "0"; } return retval + str; } }
Java
package annas.misc; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import annas.graph.GraphInterface; /** * This class provides a means of persistence, providing the ability to * push/pull a graph to a SQL (MySQL) database. * * This class requires a SQL compatible server and suitable java database * connectors to be available on the classpath. A suitable connector should * implement the java.sql.Connection interface. * * @see java.sql.Connection * * @author Sam Wilson * @version v1.0 */ public class GraphStorage { /** * Connection to the database server */ private Connection conn; /** * Statement to execute at the server. */ private Statement stmt; /** * Schema name */ private static final String schema = "annas"; /** * Table name */ private static final String table_name = "annas_graph"; /** * Statement to create a database. */ private static final String create_db = "CREATE DATABASE IF NOT EXISTS " + GraphStorage.schema + "; "; /** * Statement to drop the database and subsequently the tables in it. */ private static final String drop_db = "DROP DATABASE IF EXISTS " + GraphStorage.schema + "; "; /** * Statement to select the database */ private static final String use = "USE " + GraphStorage.schema + "; "; /** * Statement to create a table suitable of storing graphs. */ private static final String create_tbl = "CREATE TABLE IF NOT EXISTS " + GraphStorage.table_name + " (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name TINYTEXT,class TEXT, Des TEXT,sgraph LONGBLOB); "; /** * Statement to check if the database exists */ private static final String check_db = "SELECT COUNT(*) as COUNT FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" + GraphStorage.schema + "'; "; private static final String check_table = "SELECT COUNT(*) as COUNT FROM information_schema.tables \n WHERE table_schema = '" + GraphStorage.schema + "' AND table_name = '" + GraphStorage.table_name + "';"; /** * Statement to insert a graph into the database. */ private static final String insert_tbl = "INSERT INTO " + GraphStorage.table_name + " (name,class,Des,sgraph) VALUES (?,?,?,?); "; /** * Statement to list the names of the graph in the database. */ private static final String select_graph = "SELECT name FROM " + GraphStorage.table_name + "; "; /** * Statement to select a graph by name. */ private static final String select_graph_by_name = "SELECT * FROM " + GraphStorage.table_name + " WHERE name = "; /** * Statement to select a graph by id. */ private static final String select_graph_by_ID = "SELECT * FROM " + GraphStorage.table_name + " WHERE id = "; private static final String get_size = "SELECT count(*) TABLES, concat(round(sum(data_length+index_length)/(1024*1024),2),'') total_size FROM information_schema.TABLES WHERE table_name LIKE \"" + GraphStorage.table_name + "\";"; /** * Constructor * * @param connection * Connection to the database server * @throws SQLException */ public GraphStorage(Connection connection) throws SQLException { super(); this.conn = connection; this.stmt = this.conn.createStatement(); if (!this.isSetup()) { this.SetupDatabase(conn); } stmt.execute(GraphStorage.use); } /** * Gets the size in Megabytes of the data in the table * * @return gets the size of the table */ public double getTableSize() { ResultSet rs; try { rs = this.stmt.executeQuery(GraphStorage.get_size); rs.next(); return rs.getDouble("total_size"); } catch (Exception e) { } return -1; } /** * Stores a graph in the database. * * @param name * Name of the graph * @param Des * Description of the graph * @param graph * Graph object * @return true if the graph was successfully stored. * @throws SQLException * @throws IOException * @throws ClassNotFoundException */ public int store(String name, String Des, GraphInterface<?, ?> graph) throws SQLException, IOException, ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos); out.writeObject(graph); out.close(); byte[] buf = bos.toByteArray(); if (this.get(name) == null) { PreparedStatement pstmt = this.conn .prepareStatement(GraphStorage.insert_tbl); pstmt.setString(1, name); pstmt.setString(2, graph.getClass().getCanonicalName()); pstmt.setString(3, Des); Blob blob = this.conn.createBlob(); blob.setBytes(1, buf); pstmt.setBlob(4, blob); pstmt.execute(); ResultSet rs = this.stmt .executeQuery(GraphStorage.select_graph_by_name + " '" + name + "' ;"); if (rs.next()) { int id = rs.getInt("id"); return id; } else { return -1; } } else { return -1; } } /** * Gets a graph from the database. * * @param name * Name of the graph to retrieve. * @return GraphInterface of the graph (casting may be required). * @throws SQLException * @throws ClassNotFoundException * @throws IOException */ public GraphInterface<?, ?> get(String name) throws SQLException, ClassNotFoundException, IOException { ResultSet rs = this.stmt.executeQuery(GraphStorage.select_graph_by_name + " '" + name + "' ;"); if (rs.next()) { ByteArrayInputStream bos = new ByteArrayInputStream(rs .getBytes("sgraph")); ObjectInput in = new ObjectInputStream(bos); Object f = in.readObject(); // Object f = new Object(); GraphInterface<?, ?> gi = (GraphInterface<?, ?>) Class.forName( rs.getString("class")).cast(f); return gi; } else { return null; } } /** * Gets a graph from the database. * * @param id * id of the graph to retrieve. * @return GraphInterface of the graph (casting may be required). * @throws SQLException * @throws ClassNotFoundException * @throws IOException */ public GraphInterface<?, ?> get(int id) throws SQLException, ClassNotFoundException, IOException { ResultSet rs = this.stmt.executeQuery(GraphStorage.select_graph_by_ID + " '" + id + "' ;"); if (rs.next()) { ByteArrayInputStream bos = new ByteArrayInputStream(rs .getBytes("sgraph")); ObjectInput in = new ObjectInputStream(bos); Object f = in.readObject(); // Object f = new Object(); GraphInterface<?, ?> gi = (GraphInterface<?, ?>) Class.forName( rs.getString("class")).cast(f); return gi; } else { return null; } } /** * Lists all of the graph stored in the database * * @return Array of string containing the names of the graph. * @throws SQLException */ public String[] getName() throws SQLException { ArrayList<String> names = new ArrayList<String>(); ResultSet rs = this.stmt.executeQuery(GraphStorage.select_graph); while (rs.next()) { names.add(rs.getString("name")); } return names.toArray(new String[names.size()]); } /** * Removes the database from the database server. #### This will loose all * graph stored in the database #### * * @return True if the operation is successful. * @throws SQLException */ public boolean drop() throws SQLException { return this.Drop(this.conn); } /** * Creates the database and tables ready for graphs to be stored. * * @param conn * @return true if the database was set up successfully * @throws SQLException */ private boolean SetupDatabase(Connection conn) throws SQLException { this.stmt.execute(GraphStorage.create_db); this.stmt.execute(GraphStorage.use); this.stmt.execute(GraphStorage.create_tbl); ResultSet rs = this.stmt.executeQuery(GraphStorage.check_db); rs.next(); return rs.getInt("COUNT") == 1; } /** * Drops the database from the server. * * @param conn * @return true if the connection was successfully dropped * @throws SQLException */ private boolean Drop(Connection conn) throws SQLException { this.stmt.execute(GraphStorage.drop_db); ResultSet rs = this.stmt.executeQuery(GraphStorage.check_db); rs.next(); return rs.getInt("COUNT") == 0; } /** * Check if the database is setup to store graph objects. * * @return True if the database is setup to store graph objects. * @throws SQLException */ private boolean isSetup() throws SQLException { ResultSet rs = this.stmt.executeQuery(GraphStorage.check_db); rs.next(); if (rs.getInt("COUNT") == 0) return false; else rs = this.stmt.executeQuery(GraphStorage.check_table); rs.next(); if (rs.getInt("COUNT") == 0) return false; return true; } }
Java
package annas.graph; @SuppressWarnings("serial") public class SimpleDirectedGraph<V, E extends EdgeInterface<V>> extends DirectedGraph<V, E> { public SimpleDirectedGraph(Class<? extends E> edgeClass) { super(edgeClass); this.allowloops = false; this.allowparallelEdges = false; } public SimpleDirectedGraph(EdgeFactory<V, E> edgeFactory) { super(edgeFactory); this.allowloops = false; this.allowparallelEdges = false; } }
Java
package annas.graph; import annas.util.EqualityChecker; public class UndirectedEdgeEqualityChecker<V, E extends EdgeInterface<V>> implements EqualityChecker<E> { @SuppressWarnings("unchecked") @Override public boolean check(Object a, Object b) { E e1 = (E) a; E e2 = (E) b; boolean oneway = e1.getHead().equals(e2.getHead()) && e1.getTail().equals(e2.getTail()); boolean otherway = e1.getHead().equals(e2.getTail()) && e1.getTail().equals(e2.getHead()); boolean sameObject = e1 == e2; return (oneway || otherway) && sameObject; } }
Java
/** * */ package annas.graph; /** * Base class for all weighted graphs using the default implementation. * * @author Sam * */ @SuppressWarnings("serial") public abstract class AbstractWeightedGraph<V, E extends EdgeInterface<V>> implements GraphInterface<V, E> { }
Java
package annas.graph.isomorphism.precondition; import annas.graph.GraphInterface; public interface Precondition { public boolean evaluate(GraphInterface<?, ?> g1, GraphInterface<?, ?> g2); }
Java
package annas.graph.isomorphism.precondition; import annas.graph.GraphInterface; /** * Checks if the size of two graphs is equal. * * @author Sam Wilson */ public class SizePrecondition implements Precondition { @Override public boolean evaluate(GraphInterface<?, ?> g1, GraphInterface<?, ?> g2) { return g1.getSize() == g2.getSize(); } }
Java
package annas.graph.isomorphism.precondition; import annas.graph.GraphInterface; /** * Checks if the order of two graphs is equal. * * @author Sam Wilson */ public class OrderPrecondition implements Precondition { @Override public boolean evaluate(GraphInterface<?, ?> g1, GraphInterface<?, ?> g2) { return g1.getOrder() == g2.getOrder(); } }
Java
package annas.graph.isomorphism; import java.util.Iterator; import java.util.List; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; public class IsomorphicInducedSubgraphGenerator<V, E extends EdgeInterface<V>> implements Iterable<List<V>> { private GraphInterface<V, E> target; private GraphInterface<V, E> src; public IsomorphicInducedSubgraphGenerator(GraphInterface<V, E> target, GraphInterface<V, E> src) { super(); this.target = target; this.src = src; } @Override public Iterator<List<V>> iterator() { return new IsomorphicInducedSubgraphIterator<V, E>(target, src); } }
Java
package annas.graph.isomorphism; import java.util.ArrayList; import java.util.Collection; import java.util.List; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.util.InducedSubgraph; import annas.math.combinatorics.PermutationGenerator; /** * * @author Sam Wilson * */ public class SubgraphIsomorphism<V, E extends EdgeInterface<V>> { private GraphInterface<V, E> target; private GraphInterface<V, E> src; public SubgraphIsomorphism(GraphInterface<V, E> target, GraphInterface<V, E> src) { super(); this.target = target; this.src = src; } public boolean isInducedSubgraph(Collection<V> vertices) { return this.isInducedSubgraph(this.target, this.src, vertices); } private boolean isInducedSubgraph( GraphInterface<V, ? extends EdgeInterface<V>> target, GraphInterface<V, ? extends EdgeInterface<V>> src, Collection<V> vertices) { if (src.getOrder() != vertices.size()) { throw new IllegalArgumentException( "Order of src should be equal to size of vertex set"); } GraphInterface<V, ? extends EdgeInterface<V>> id = InducedSubgraph .inducedSubgraphOf(target, vertices); PermutationGenerator<V> perm = new PermutationGenerator<V>(vertices); for (List<V> ll : perm) if (subgraphEquality(id, src, ll)) { return true; } return false; } private boolean subgraphEquality( GraphInterface<V, ? extends EdgeInterface<V>> target, GraphInterface<V, ? extends EdgeInterface<V>> src, List<V> vertices) { if (src.getOrder() != target.getOrder() && src.getSize() != target.getSize()) { return false; } List<V> lst = new ArrayList<V>(src.getVertices()); for (V v : lst) { for (V u : lst) { if (src.getEdges(v, u).size() != target.getEdges( vertices.get(lst.indexOf(v)), vertices.get(lst.indexOf(u))).size()) { return false; } } } return true; } }
Java
package annas.graph.isomorphism; import java.util.Iterator; import java.util.List; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.math.combinatorics.SimpleCombinationGenerator; public class IsomorphicInducedSubgraphIterator<V, E extends EdgeInterface<V>> implements Iterator<List<V>> { private Iterator<List<V>> comb; private SubgraphIsomorphism<V, E> si; public IsomorphicInducedSubgraphIterator(GraphInterface<V, E> target, GraphInterface<V, E> src) { super(); SimpleCombinationGenerator<V> g = new SimpleCombinationGenerator<V>( target.getVertices(), src.getOrder()); this.comb = g.iterator(); this.si = new SubgraphIsomorphism<V, E>(target, src); } /** * Returns true if there is a possibility that there is another isomorphic * induced subgraph. There is a possibility that this method returns true when * the iterator has no next item, this behavior is guaranteed to only occur on the last * element of the iterator. */ @Override public boolean hasNext() { return this.comb.hasNext(); } @Override /** * Returns a set of vertices which are an induced subgraph. Returns null if * there are no more isomorphic induced subgraphs. */ public List<V> next() { List<V> vertices; while (this.comb.hasNext()) { vertices = this.comb.next(); if (si.isInducedSubgraph(vertices)) { return vertices; } } return null; } @Override public void remove() { throw new UnsupportedOperationException(); } }
Java
/** * */ package annas.graph.isomorphism; import java.util.LinkedList; import java.util.List; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.isomorphism.precondition.Precondition; /** * @author Sam Wilson * */ public abstract class GraphIsomorphism<V, E extends EdgeInterface<V>> { private List<Precondition> precons; /** * */ public GraphIsomorphism() { super(); this.precons = new LinkedList<Precondition>(); } /** * Tests if two graphs are isomorphic * @param g1 * @param g2 * @return True if the two graphs are isomorphic, false otherwise. */ public boolean isIsomorphic(GraphInterface<V, E> g1, GraphInterface<V, E> g2){ return this.getBijection(g1, g2) != null; } /** * Gets a Bijection between the two graphs if one exists. * @param g1 * @param g2 * @return A mapping between vertices of g1 and g2. returns null if know such map can be found. */ public Map<V,V> getBijection(GraphInterface<V, E> g1, GraphInterface<V, E> g2){ if(this.evaluatePreconitions(g1, g2)){ return this.find_Isomorphism(g1, g2); } return null; } /** * Adds a precondition two be tested before the graph isomorphism algorithm runs. * @param p * @return true if the precondition was successfully added */ public boolean addPrecondition(Precondition p){ return this.precons.add(p); } /** * Evaluates the preconditions in the order they appear in the list. * @param g1 * @param g2 * @return True if all preconditions pass, false otherwise. */ protected boolean evaluatePreconitions(GraphInterface<V, E> g1, GraphInterface<V, E> g2){ for(Precondition p : precons){ if(!p.evaluate(g1, g2)){ return false; } } return true; } /** * This method does the "hard" work. Should be implemented by extending classes. * @param g1 * @param g2 * @return A mapping between vertices of g1 and g2. returns null if know such map can be found. */ protected abstract Map<V,V> find_Isomorphism(GraphInterface<V, E> g1, GraphInterface<V, E> g2); }
Java
package annas.graph; import java.io.Serializable; /** * Factory used to construct edge. * * @author Sam * * @param <V> * Vertex type * @param <E> * Edge type */ public interface EdgeFactory<V, E extends EdgeInterface<V>> extends Serializable { /** * Construct a new edge. * * @param tail * endpoint * * @param head * endpoint * * @return newly constructed edge. */ public E create(V tail, V head); /** * Gets the edge class * @return edhe class */ public Class<?> getEdgeClass(); }
Java
package annas.graph; import java.io.Serializable; import java.util.Collection; import java.util.Set; /** * Base interface for all Graphs * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public interface GraphInterface<V, E extends EdgeInterface<V>> extends Serializable { /** * Adds a vertex to the graph * * @param vertex * to add to the graph * * @return true is vertex was successfully added. */ public boolean addVertex(V vertex); /** * Adds all vertices in the array * * @param vertices * * @return true is all vertices were successfully added. */ public boolean addVertices(Collection<? extends V> vertices); /** * Removes a vertex from the graph * * @param vertex * to remove from the graph * @return true if the vertex was successfully removed from the graph */ public boolean removeVertex(V vertex); /** * Remove a set of vertices * * @param vertices * Set of vertices to remove * * @return true if all vertices were successfully removed */ public boolean removeVertices(Collection<? extends V> vertices); /** * Gets the set of vertices of the graph * * @return set of vertices in the graph */ public Set<V> getVertices(); /** * Adds an edge to the graph * * @param tail * Tail of the edge * @param head * Head of the edge * @return the new edge */ public E addEdge(V tail, V head); /** * Gets all edge incident to a given vertex * * @param tail * tail of the edge * @return Set of all edge incident to a given vertex */ public Set<E> getEdges(V tail); /** * Gets all edges from the tail to the head * * @param tail * tail of the edge * @param head * head of the edge * @return Set of all edge between tail and head. */ public Set<E> getEdges(V tail, V head); /** * Get the Edges of the graph * * @return Set of edges */ public Set<E> getEdges(); /** * Removes a set of edges * * @param edges * Set of edges to remove * @return true if all edges were removed successfully */ public boolean removeEdges(Collection<? extends E> edges); /** * Removes an edge from the graph * * @param edge * to remove * @return true if the edge was successfully removed. */ public boolean removeEdge(E edge); /** * Removes all edge from the graph between tail and head * * @param tail * tail of the edge to remove * @param head * head of the edge to remove * * @return true if the edge was successfully removed. */ public boolean removeEdge(V tail, V head); /** * Removes all edge incident with a vertex * * @param tail * tail of the edge * * @return true if all edges were deleted incident to a vertex */ public boolean removeEdge(V tail); /** * Removes all edges from the graph * * @return true if all edges were removed */ public boolean resetEdges(); /** * Gets the EdgeFactory used by the graph * * @return EdgeFactory used by the graph */ public EdgeFactory<V, E> getEdgeFactory(); /** * Checks if a vertex is in the graph * * @return true if the edge is in the graph */ public boolean containsEdge(V head, V tail); /** * Checks if a vertex is in the graph * * @param edge * @return true if the edge is in the graph */ public boolean containsEdge(E edge); /** * Checks if a vertex is in the graph * * @param vertex * @return true if the vertex is in the graph */ public boolean containsVertex(V vertex); /** * Number of edges contained within the graph * * @return number of edges in the graph */ public int getSize(); /** * Number of vertices contained within the graph * * @return number of vertices in the graph */ public int getOrder(); /** * Degree of vertex (Out degree for directed graphs) * * @param vertex * @return degree of the given vertex */ public int getDegree(V vertex); /** * Current GraphObserver * * @return GraphObserver */ public GraphObserver<V,E> getObserver(); /** * Set the GraphObserver. * * @param GO */ public void setObserver(GraphObserver<V,E> GO); /** * Gets edge class * @return edge class */ public Class<?> getEdgeClass(); /** * Returns if the graph is directed * @return true if the graph is directed */ public boolean isDirected(); }
Java
package annas.graph; /** * Factory for creating vertices * * @author Sam Wilson * * @param <V> * Vertex type */ public interface VertexFactory<V> { public V createVertex(); }
Java
package annas.graph; @SuppressWarnings("serial") public class ClassEdgeFactory<V, E extends EdgeInterface<V>> implements EdgeFactory<V, E> { private Class<? extends E> edgeClass; public ClassEdgeFactory(Class<? extends E> edgeClass) { this.edgeClass = edgeClass; } @Override public E create(V source, V target) { try { return edgeClass.newInstance(); } catch (Exception ex) { throw new RuntimeException("Cant get new instance of edge type", ex); } } @Override public Class<?> getEdgeClass(){ return this.edgeClass; } }
Java
package annas.graph; import java.io.IOException; import java.io.ObjectInputStream; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * * A MultiMap is a Map with slightly different semantics. Putting a value into * the map will add the value to a Collection at that key. Getting a value will * return a Collection, holding all the values put to that key. * * This implementation uses an ArrayList as the collection. The internal storage * list is made available without cloning via the get(Object) and entrySet() * methods. The implementation returns null when there are no values mapped to a * key. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class MultiHashMap<K, V> extends HashMap { /** * Inner iterator to view the elements. */ private class ValueIterator implements Iterator<V> { private Iterator<V> backedIterator; private Iterator<V> tempIterator; private ValueIterator() { backedIterator = MultiHashMap.super.values().iterator(); } @Override public boolean hasNext() { return searchNextIterator(); } @Override public V next() { if (searchNextIterator() == false) { throw new NoSuchElementException(); } return tempIterator.next(); } @Override public void remove() { if (tempIterator == null) { throw new IllegalStateException(); } tempIterator.remove(); } private boolean searchNextIterator() { while (tempIterator == null || tempIterator.hasNext() == false) { if (backedIterator.hasNext() == false) { return false; } tempIterator = ((Collection) backedIterator.next()).iterator(); } return true; } } /** * Inner class to view the elements. */ private class Values extends AbstractCollection { @Override public void clear() { MultiHashMap.this.clear(); } @Override public Iterator iterator() { return new ValueIterator(); } @Override public int size() { int compt = 0; Iterator it = iterator(); while (it.hasNext()) { it.next(); compt++; } return compt; } } // backed values collection private transient Collection values = null; private static final long serialVersionUID = 1943563828307035349L; /** * Constructor. */ public MultiHashMap() { super(); } /** * Constructor. * * @param initialCapacity * the initial map capacity */ public MultiHashMap(int initialCapacity) { super(initialCapacity); } /** * Constructor. * * @param initialCapacity * the initial map capacity * @param loadFactor * the amount 0.0-1.0 at which to resize the map */ public MultiHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Clear the map. * * This clears each collection in the map, and so may be slow. */ @Override public void clear() { // For gc, clear each list in the map Set pairs = super.entrySet(); Iterator pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { Map.Entry keyValuePair = (Map.Entry) pairsIterator.next(); Collection coll = (Collection) keyValuePair.getValue(); coll.clear(); } super.clear(); } // ----------------------------------------------------------------------- /** * Clones the map creating an independent copy. * * The clone will shallow clone the collections as well as the map. * * @return the cloned map */ @Override public Object clone() { MultiHashMap cloned = (MultiHashMap) super.clone(); // clone each Collection container for (Iterator it = cloned.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Collection coll = (Collection) entry.getValue(); Collection newColl = createCollection(coll); entry.setValue(newColl); } return cloned; } /** * Checks whether the map contains the value specified. * * This checks all collections against all keys for the value, and thus * could be slow. * * @param value * the value to search for * @return true if the map contains the value */ @Override public boolean containsValue(Object value) { Set pairs = super.entrySet(); if (pairs == null) { return false; } Iterator pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { Map.Entry keyValuePair = (Map.Entry) pairsIterator.next(); Collection coll = (Collection) keyValuePair.getValue(); if (coll.contains(value)) { return true; } } return false; } /** * Checks whether the collection at the specified key contains the value. * * @param value * the value to search for * @return true if the map contains the value * @since Commons Collections 3.1 */ public boolean containsValue(Object key, Object value) { Collection coll = getCollection(key); if (coll == null) { return false; } return coll.contains(value); } /** * Creates a new instance of the map value Collection container. * * This method can be overridden to use your own collection type. * * @param coll * the collection to copy, may be null * @return the new collection */ protected Collection createCollection(Collection coll) { if (coll == null) { return new ArrayList(); } else { return new ArrayList(coll); } } /** * Gets the collection mapped to the specified key. This method is a * convenience method to typecast the result of get(key). * * @param key * the key to retrieve * @return the collection mapped to the key, null if no mapping * @since Commons Collections 3.1 */ public Collection getCollection(Object key) { return (Collection) get(key); } /** * Gets an iterator for the collection mapped to the specified key. * * @param key * the key to get an iterator for * @return the iterator of the collection at the key, empty iterator if key * not in map * @since Commons Collections 3.1 */ public Iterator iterator(Object key) { Collection coll = getCollection(key); if (coll == null) { return new ArrayList().iterator(); } return coll.iterator(); } /** * Adds the value to the collection associated with the specified key. * * Unlike a normal Map the previous value is not replaced. Instead the new * value is added to the collection stored against the key. * * @param key * the key to store against * @param value * the value to add to the collection at the key * @return the value added if the map changed and null if the map did not * change */ @Override public Object put(Object key, Object value) { // NOTE:: put is called during deserialization in JDK < 1.4 !!!!!! // so we must have a readObject() Collection coll = getCollection(key); if (coll == null) { coll = createCollection(null); super.put(key, coll); } boolean results = coll.add(value); return (results ? value : null); } /** * Adds a collection of values to the collection associated with the * specified key. * * @param key * the key to store against * @param values * the values to add to the collection at the key, null ignored * @return true if this map changed * @since Commons Collections 3.1 */ public boolean putAll(Object key, Collection values) { if (values == null || values.size() == 0) { return false; } Collection coll = getCollection(key); if (coll == null) { coll = createCollection(values); if (coll.size() == 0) { return false; } super.put(key, coll); return true; } else { return coll.addAll(values); } } /** * Read the object during deserialization. */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { // This method is needed because the 1.2/1.3 Java deserialisation called // put and thus messed up that method // default read object s.defaultReadObject(); // problem only with jvm <1.4 String version = "1.2"; try { version = System.getProperty("java.version"); } catch (SecurityException ex) { // ignore and treat as 1.2/1.3 } if (version.startsWith("1.2") || version.startsWith("1.3")) { for (Iterator iterator = entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); // put has created a extra collection level, remove it super.put(entry.getKey(), ((Collection) entry.getValue()) .iterator().next()); } } } /** * Removes a specific value from map. * * The item is removed from the collection mapped to the specified key. * Other values attached to that key are unaffected. * * If the last value for a key is removed, null will be returned from a * subsequant get(key). * * @param key * the key to remove from * @param item * the value to remove * @return the value removed (which was passed in), null if nothing removed */ public Object remove(Object key, Object item) { Collection valuesForKey = getCollection(key); if (valuesForKey == null) { return null; } valuesForKey.remove(item); if (valuesForKey.isEmpty()) { remove(key); } return item; } /** * Gets the size of the collection mapped to the specified key. * * @param key * the key to get size for * @return the size of the collection at the key, zero if key not in map * @since Commons Collections 3.1 */ public int size(Object key) { Collection<K> coll = getCollection(key); if (coll == null) { return 0; } return coll.size(); } /** * Gets the total size of the map by counting all the values. * * @return the total size of the map counting all values * @since Commons Collections 3.1 */ public int totalSize() { int total = 0; Collection<V> values = super.values(); for (Iterator<V> it = values.iterator(); it.hasNext();) { Collection<V> coll = (Collection<V>) it.next(); total += coll.size(); } return total; } /** * Gets a collection containing all the values in the map. * * This returns a collection containing the combination of values from all * keys. * * @return a collection view of the values contained in this map */ @Override public Collection<V> values() { Collection<V> vs = values; return (vs != null ? vs : (values = new Values())); } }
Java
package annas.graph; @SuppressWarnings("serial") public class DefaultWeightedEdge<V> implements WeightedEdgeInterface<V> { private V head; private V tail; private double weight; public DefaultWeightedEdge() { super(); } @Override public String toString() { return this.tail + "-[" +this.weight + "]->"+ this.head; } @Override public V getHead() { return head; } @Override public void setHead(V head) { this.head = head; } @Override public V getTail() { return tail; } @Override public void setTail(V tail) { this.tail = tail; } @Override public double getWeight() { return this.weight; } @Override public void setWeight(double weight) { this.weight = weight; } @Override public boolean isIncident(V vertex) { return this.head.equals(vertex) || this.tail.equals(vertex); } @Override public V getOtherEndpoint(V vertex) { if (this.head.equals(vertex)) { return this.tail; } else if(this.tail.equals(vertex)) { return this.head; }else { return null; } } }
Java
package annas.graph.generate; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.VertexFactory; /** * See Graph classes for description of class <a * href="http://www.graphclasses.org/smallgraphs.html#families_XF">Graph * classes</a> * * @author Sam * * @param <N> * @param <A> */ public class XF_2<N, A extends EdgeInterface<N>> implements GraphGenerator<N, EdgeInterface<N>> { private int n; public XF_2(int n) { super(); } @Override public void generateGraph(GraphInterface<N, EdgeInterface<N>> target, VertexFactory<N> factory, Map<String, ?> Additionalinfo) { N fan = factory.createVertex(); target.addVertex(fan); N pend1 = factory.createVertex(); N pend2 = factory.createVertex(); N pend3 = factory.createVertex(); target.addVertex(pend1); target.addVertex(pend2); target.addVertex(pend3); target.addEdge(pend3, fan); N newnode = factory.createVertex(); N tmp; target.addVertex(newnode); target.addEdge(pend1, newnode); tmp = newnode; for (int i = 0; i < this.n - 1; i++) { newnode = factory.createVertex(); target.addVertex(newnode); target.addEdge(tmp, newnode); target.addEdge(fan, newnode); tmp = newnode; } target.addEdge(tmp, pend2); } }
Java
package annas.graph.generate; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; /** * See Graph classes for description of class <a * href="http://www.graphclasses.org/smallgraphs.html#families_XF">Graph * classes</a> * * @author Sam * * @param <N> * @param <A> */ public class XF_1<N, A extends EdgeInterface<N>> implements GraphGenerator<N, EdgeInterface<N>> { private int n; public XF_1(int n) { super(); } @Override public void generateGraph(GraphInterface<N, EdgeInterface<N>> target, annas.graph.VertexFactory<N> factory, Map<String, ?> Additionalinfo) { N fan = factory.createVertex(); target.addVertex(fan); N pend1 = factory.createVertex(); N pend2 = factory.createVertex(); target.addVertex(pend1); target.addVertex(pend2); N newnode = factory.createVertex(); N tmp; target.addVertex(newnode); target.addEdge(pend1, newnode); tmp = newnode; for (int i = 0; i < this.n - 1; i++) { newnode = factory.createVertex(); target.addVertex(newnode); target.addEdge(tmp, newnode); target.addEdge(fan, newnode); tmp = newnode; } target.addEdge(tmp, pend2); } }
Java
package annas.graph.generate; import annas.graph.VertexFactory; public class DefaultVertexFactory implements VertexFactory<Integer> { private int count; public DefaultVertexFactory() { super(); this.count = -1; } @Override public Integer createVertex() { this.count++; return Integer.valueOf(count); } }
Java
package annas.graph.generate; import java.util.ArrayList; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.VertexFactory; /** * Generates a Hyper Graph @see <a * href="http://mathworld.wolfram.com/Hypergraph.html"> shown here</a> * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public class HyperGraphGenerator<V, E extends EdgeInterface<V>> implements GraphGenerator<V, E> { /** * Number of dimensions */ private int dim; public HyperGraphGenerator(int dim) { super(); if (dim < 0) { throw new IllegalArgumentException( "dimensions must be >= 0"); } this.dim = dim; } @Override public void generateGraph(GraphInterface<V, E> target, VertexFactory<V> vertexFactory, Map<String, ?> Additionalinfo) { if (target == null) return; int order = (int) Math.pow(2, dim); ArrayList<V> vertices = new ArrayList<V>(); for (int i = 0; i < order; i++) { V newnode = vertexFactory.createVertex(); target.addVertex(newnode); vertices.add(newnode); } for (int i = 0; i < order; i++) { for (int j = i + 1; j < order; j++) { for (int z = 0; z < dim; z++) { if ((j ^ i) == (1 << z)) { target.addEdge(vertices.get(i), vertices.get(j)); break; } } } } } }
Java
package annas.graph.generate; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.VertexFactory; public interface GraphGenerator<V, E extends EdgeInterface<V>> { public void generateGraph(GraphInterface<V, E> graph, VertexFactory<V> vertexFactory, Map<String, ?> Additionalinfo); }
Java
package annas.graph.generate; import java.util.ArrayList; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.VertexFactory; /** * Generates a graph with n vertices which are cyclically order where each * vertex is adjacent to a set of vertices specified as parameters. * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public class CirculantGraphGenerator<V, E extends EdgeInterface<V>> implements GraphGenerator<V, E> { /** * Number of vertices in the target graph */ private int order; private int[] adjacency; public CirculantGraphGenerator(int order, int... adjacency) { super(); if (order < 0) { throw new IllegalArgumentException("order must be >= 0"); } for (int i = 0; i < adjacency.length; i++) { if (adjacency[i] >= order) { throw new IllegalArgumentException("vertex out of bounds"); } } this.order = order; this.adjacency = adjacency; } @Override public void generateGraph(GraphInterface<V, E> target, VertexFactory<V> vertexFactory, Map<String, ?> Additionalinfo) { if (target == null) return; ArrayList<V> vertices = new ArrayList<V>(this.order); for (int i = 0; i < this.order; i++) { vertices.add(vertexFactory.createVertex()); target.addVertex(vertices.get(i)); } for (int i = 0; i < this.order; i++) { for (int j = 0; j < this.adjacency.length; j++) { int adj = ((this.adjacency[j] + i) % (this.order)); target.addEdge(vertices.get(i), vertices.get(adj)); } } } }
Java
package annas.graph.generate; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.VertexFactory; /** * Generates an empty Graph @see <a * href="http://mathworld.wolfram.com/EmptyGraph.html"> shown here</a> * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public class EmptyGraphGenerator<V, E extends EdgeInterface<V>> implements GraphGenerator<V, E> { /** * Number of nodes in the target graph */ private int order; public EmptyGraphGenerator(int order) { super(); if (order < 0) { throw new IllegalArgumentException("order must be >= 0"); } this.order = order; } @Override public void generateGraph(GraphInterface<V, E> target, VertexFactory<V> vertexFactory, Map<String, ?> Additionalinfo) { if (target == null) return; for (int i = 0; i < this.order; i++) target.addVertex(vertexFactory.createVertex()); } }
Java
package annas.graph.generate; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.VertexFactory; /** * Generates a linear Graph, a straight line graph * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public class LinearGraphGenerator<V, E extends EdgeInterface<V>> implements GraphGenerator<V, E> { /** * Start vertex */ private V start_vertex; /** * End vertex */ private V end_vertex; /** * Number of vertexs in the target graph */ private int length; public LinearGraphGenerator(int length) { super(); if (length < 0) { throw new IllegalArgumentException("order must be >= 0"); } this.length = length; } /** * @return the start_vertex */ public V getStart_vertex() { return start_vertex; } /** * @return the end_vertex */ public V getEnd_vertex() { return end_vertex; } /** * @return the length */ public int getLength() { return length; } @Override public void generateGraph(GraphInterface<V, E> target, VertexFactory<V> vertexFactory, Map<String, ?> Additionalinfo) { if (target == null) return; V newvertex = vertexFactory.createVertex(); V tmp; this.start_vertex = newvertex; target.addVertex(newvertex); tmp = newvertex; for (int i = 0; i < this.length - 1; i++) { newvertex = vertexFactory.createVertex(); target.addVertex(newvertex); target.addEdge(tmp, newvertex); tmp = newvertex; } this.end_vertex = tmp; } }
Java
package annas.graph.generate; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.VertexFactory; /** * Generates a Star Graph @see <a * href="http://mathworld.wolfram.com/StarGraph.html"> shown here</a> * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public class StarGraphGenerator<V, E extends EdgeInterface<V>> implements GraphGenerator<V, E> { /** * Number of vertices in the target graph */ private int order; public StarGraphGenerator(int order) { super(); if (order < 0) { throw new IllegalArgumentException("order must be >= 0"); } this.order = order; } @Override public void generateGraph(GraphInterface<V, E> target, VertexFactory<V> vertexFactory, Map<String, ?> Additionalinfo) { if (target == null) return; V Hub = vertexFactory.createVertex(); V tmp = null; target.addVertex(Hub); for (int i = 0; i < this.order - 1; i++) { tmp = vertexFactory.createVertex(); target.addVertex(tmp); target.addEdge(Hub, tmp); } } }
Java
package annas.graph.generate; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.VertexFactory; /** * Generates a Wheel Graph @see <a * href="http://mathworld.wolfram.com/WheelGraph.html"> shown here</a> * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public class WheelGraphGenerator<V, E extends EdgeInterface<V>> implements GraphGenerator<V, E> { /** * Number of nodes in the target graph */ private int order; public WheelGraphGenerator(int order) { super(); if (order < 4) { throw new IllegalArgumentException("order must be >= 3"); } this.order = order; } @Override public void generateGraph(GraphInterface<V, E> target, VertexFactory<V> vertexFactory, Map<String, ?> Additionalinfo) { if (target == null) return; V Hub = vertexFactory.createVertex(); V newnode = vertexFactory.createVertex(); V tmp; V start_node = newnode; target.addVertex(newnode); tmp = newnode; for (int i = 0; i < this.order - 2; i++) { newnode = vertexFactory.createVertex(); target.addVertex(newnode); target.addEdge(tmp, newnode); tmp = newnode; } V end_node = tmp; target.addEdge(end_node, start_node); target.addVertex(Hub); for (V tmp1 : target.getVertices()) { if (tmp1 != Hub) { target.addEdge(Hub, tmp1); } } } }
Java
package annas.graph.generate; import java.util.Map; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.VertexFactory; /** * Generates a Complete Graph @see <a * href="http://mathworld.wolfram.com/CompleteGraph.html"> shown here</a> * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public class CompleteGraphGenerator<V, E extends EdgeInterface<V>> implements GraphGenerator<V, E> { /** * Number of vertices in the target graph */ private int order; public CompleteGraphGenerator(int order) { super(); if (order < 0) { throw new IllegalArgumentException("order must be >= 0"); } this.order = order; } @Override public void generateGraph(GraphInterface<V, E> target, VertexFactory<V> vertexFactory, Map<String, ?> Additionalinfo) { if (target == null) return; for (int i = 0; i < order; i++) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); } for (V v : target.getVertices()) { for (V u : target.getVertices()) { if (v != u) target.addEdge(v, u); } } } }
Java
package annas.graph.generate; import java.util.Collection; import java.util.Map; import java.util.Random; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.SimpleDirectedGraph; import annas.graph.SimpleUndirectedGraph; import annas.graph.VertexFactory; public class RandomGraph<V, E extends EdgeInterface<V>> implements GraphGenerator<V, E> { private int order; private int size; public RandomGraph(int order, int size) { super(); if (order < 0) { throw new IllegalArgumentException("order must be >= 0"); } if (size < 0) { throw new IllegalArgumentException("size must be >= 0"); } this.order = order; this.size = size; } @Override public void generateGraph(GraphInterface<V, E> graph, VertexFactory<V> vertexFactory, Map<String, ?> Additionalinfo) { int maxSize = Integer.MAX_VALUE; if (graph instanceof SimpleDirectedGraph) { maxSize = this.order * this.order - 1; } else if (graph instanceof SimpleUndirectedGraph) { maxSize = (this.order * (this.order - 1)) / 2; } if (this.size <= maxSize) { for (int i = 0; i < this.order; i++) { graph.addVertex(vertexFactory.createVertex()); } while (graph.getSize() != this.size) { V head = randomSelect(graph.getVertices()); V tail = randomSelect(graph.getVertices()); graph.addEdge(tail, head); } } else { throw new IllegalArgumentException("size must be <= " + maxSize); } } @SuppressWarnings("unchecked") private V randomSelect(Collection<V> col) { Random r = new Random(); return ((V[]) col.toArray())[r.nextInt(col.size())]; } }
Java
package annas.graph; @SuppressWarnings("serial") public class DefaultEdge implements EdgeInterface<String> { private String head; private String tail; public DefaultEdge() { super(); } @Override public String toString() { return this.tail + "->" + this.head; } @Override public String getHead() { return head; } @Override public void setHead(String head) { this.head = head; } @Override public String getTail() { return tail; } @Override public void setTail(String tail) { this.tail = tail; } @Override public boolean isIncident(String vertex) { return this.head.equals(vertex) || this.tail.equals(vertex); } @Override public String getOtherEndpoint(String vertex) { if (this.head.equals(vertex)) { return this.tail; } else if (this.tail.equals(vertex)) { return this.head; } else if (this.head.equals(this.tail)) { return this.head; } else { return null; } } }
Java
package annas.graph; public class GraphFactory { public static <V, E extends EdgeInterface<V>,C extends GraphInterface<V,E>> C getGraphByClass(Class<C> c) { try { return c.newInstance(); } catch (Exception ex) { throw new RuntimeException("Cant get new instance of graph type", ex); } } }
Java
package annas.graph; import java.util.Set; /** * @author Sam * */ @SuppressWarnings("serial") public class UndirectedGraph<V, E extends EdgeInterface<V>> extends AbstractGraph<V, E> { public UndirectedGraph(EdgeFactory<V, E> edgeFactory) { super(edgeFactory, false); this.checker = new UndirectedEdgeEqualityChecker<V, E>(); } public UndirectedGraph(Class<E> edgeClass) { super(edgeClass, false); this.checker = new UndirectedEdgeEqualityChecker<V, E>(); } @Override public E addEdge(V tail, V head) { if (!this.allowparallelEdges && this.containsEdge(tail, head)) return null; if (!this.allowloops && tail == head) return null; E edge = this.edgeFactory.create(tail, head); edge.setHead(head); edge.setTail(tail); boolean added = this.vertexMap.get(tail).put(head, edge) != null; added &= this.vertexMap.get(head).put(tail, edge) != null; if (added) { return edge; } else { return null; } } @Override public boolean addVertex(V vertex) { if (!this.containsVertex(vertex)) { return this.vertexMap.put(vertex, new MultiHashMap<V, E>()) == null; } return false; } @Override public boolean removeEdge(E edge) { return this.vertexMap.get(edge.getTail()).remove(edge.getHead(), edge) != null && this.vertexMap.get(edge.getHead()).remove(edge.getTail(), edge) != null; } @Override public boolean removeEdge(V tail, V head) { Set<E> edges = this.getEdges(tail, head); boolean successful = true; for (E e : edges) { successful &= this.removeEdge(e); } return successful; } @Override public boolean removeEdge(V tail) { Set<E> edges = this.getEdges(tail); boolean successful = true; for (E e : edges) { successful &= this.removeEdge(e); } return successful; } @Override public boolean removeVertex(V vertex) { this.removeEdge(vertex); return this.vertexMap.remove(vertex) != null; } }
Java
package annas.graph; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Hashtable; import java.util.Map; import java.util.Set; import annas.util.ArraySet; import annas.util.EqualityChecker; /** * Base class for all graphs using the default implementation. * * @author Sam * */ @SuppressWarnings("serial") public abstract class AbstractGraph<V, E extends EdgeInterface<V>> implements GraphInterface<V, E> { protected GraphObserver<V, E> go; protected int version; protected EdgeFactory<V, E> edgeFactory; protected Map<V, MultiHashMap<V, E>> vertexMap; protected EqualityChecker<E> checker; protected boolean allowloops; protected boolean allowparallelEdges; protected boolean directed; public AbstractGraph(EdgeFactory<V, E> edgeFactory, boolean directed) { super(); this.edgeFactory = edgeFactory; this.version = 0; this.vertexMap = new Hashtable<V, MultiHashMap<V, E>>(); this.allowloops = true; this.allowparallelEdges = true; this.directed = directed; } public AbstractGraph(Class<? extends E> edgeClass, boolean directed) { this(new ClassEdgeFactory<V, E>(edgeClass), directed); } @Override public boolean addVertices(Collection<? extends V> vertices) { boolean successful = true; for (V vertex : vertices) { successful &= this.addVertex(vertex); } return successful; } @SuppressWarnings("unchecked") public boolean addVertices(V... vs) { boolean successful = true; for (V vertex : vs) { successful &= this.addVertex(vertex); } return successful; } @Override public boolean removeVertices(Collection<? extends V> vertices) { boolean successful = true; for (V vertex : vertices) { successful &= this.removeEdge(vertex); } return successful; } @Override public boolean removeEdges(Collection<? extends E> edges) { boolean successful = true; for (E edge : edges) { successful &= this.removeEdge(edge); } return successful; } @Override public Set<V> getVertices() { return Collections.unmodifiableSet(this.vertexMap.keySet()); } @Override public boolean resetEdges() { return this.removeEdges(this.getEdges()); } @Override public boolean containsEdge(E edge) { return this.getEdges().contains(edge); } @Override public boolean containsEdge(V tail, V head) { return !this.getEdges(tail, head).isEmpty(); } @Override public boolean containsVertex(V vertex) { return this.getVertices().contains(vertex); } @Override public EdgeFactory<V, E> getEdgeFactory() { return this.edgeFactory; } @Override public int getSize() { return this.getEdges().size(); } @Override public int getOrder() { return this.getVertices().size(); } public int getVersion() { return this.version; } @Override public GraphObserver<V, E> getObserver() { return this.go; } @Override public void setObserver(GraphObserver<V, E> graphObserver) { this.go = graphObserver; } protected boolean assertVertexExist(V vertex) { if (containsVertex(vertex)) { return true; } else if (vertex == null) { throw new NullPointerException(); } else { throw new IllegalArgumentException("Vertex is not in the graph"); } } @Override public Set<E> getEdges(V tail) { Set<E> edges = new ArraySet<E>( new UndirectedEdgeEqualityChecker<V, E>()); Collection<E> es = new ArrayList<E>(); Collection<E> h = this.vertexMap.get(tail).values(); if (h == null) { return Collections.unmodifiableSet(edges); } es.addAll(h); for (E edge : es) { edges.add(edge); } return Collections.unmodifiableSet(edges); } @SuppressWarnings("unchecked") @Override public Set<E> getEdges(V tail, V head) { Set<E> edges = new ArraySet<E>( new UndirectedEdgeEqualityChecker<V, E>()); Collection<E> es = new ArrayList<E>(); Collection<E> h = null; try { h = this.vertexMap.get(tail).getCollection(head); } catch (NullPointerException e) { } if (h == null) { return Collections.unmodifiableSet(edges); } es.addAll(h); for (E edge : es) { edges.add(edge); } return Collections.unmodifiableSet(edges); } @Override public Set<E> getEdges() { Set<E> edges = new ArraySet<E>( new UndirectedEdgeEqualityChecker<V, E>()); Collection<E> es = new ArrayList<E>(); for (V vertex : this.vertexMap.keySet()) { try { es.addAll(this.vertexMap.get(vertex).values()); } catch (NullPointerException e) { } } for (E edge : es) { edges.add(edge); } return Collections.unmodifiableSet(edges); } @Override public int getDegree(V vertex) { return this.getEdges(vertex).size(); } public boolean allowLoops() { return allowloops; } public boolean allowMultipleEdges() { return allowparallelEdges; } public boolean isDirected() { return this.directed; } @Override public Class<?> getEdgeClass() { return this.edgeFactory.getEdgeClass(); } @Override public String toString() { String ret = "Graph on "; switch (this.getOrder()) { case 0: return "Null graph"; case 1: ret += "1 vertex "; break; default: ret += this.getOrder() + " vertices "; break; } ret += "with "; switch (this.getSize()) { case 0: ret += "no edges"; break; case 1: ret += "1 edge"; break; default: ret += this.getSize() + " edges"; break; } ret += "."; return ret; } }
Java
/** * */ package annas.graph.observable; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.GraphObserver; /** * Provides a way for observing a graph. * * @author scsswi */ public class ObservableGraph<V, E extends EdgeInterface<V>> extends DynamicProxy { private ObservableGraph(GraphInterface<V, E> obj) { super(obj); } /** * Returns a graph that is the observable form of the graph provided as an argument. * For a method to be seen by the observe the method must be called on the returned graph not * the graph provided as the argument. * @param graph * @return an observable graph of the provided graph */ @SuppressWarnings("unchecked") public static <V, E extends EdgeInterface<V>> GraphInterface<V, E> getObservableGraph( GraphInterface<V, E> graph) { return (GraphInterface<V, E>) Proxy.newProxyInstance(graph.getClass() .getClassLoader(), new Class[] { GraphInterface.class }, new ObservableGraph<V, E>(graph)); } @Override protected void beforeMethod(Object graph, Method m, Object[] args) { return; } @SuppressWarnings("unchecked") @Override protected void afterMethod(Object graph, Method m, Object[] args, Object retval) { GraphObserver<V, E> go = ((GraphInterface<V, E>) graph).getObserver(); if (go != null) { switch (m.getName()) { case "addEdge": go.edgeAdded((GraphInterface<V, E>) graph, args); break; case "addVertex": go.vertexAdded((GraphInterface<V, E>) graph, args); break; case "removeEdge": go.edgeRemoved((GraphInterface<V, E>) graph, args); break; case "removeVertex": go.vertexRemoved((GraphInterface<V, E>) graph, args); break; } } } }
Java
package annas.graph.observable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * This class provides a mechanism for intercepting called on a graph. * * * @author scsswi */ public abstract class DynamicProxy implements InvocationHandler { private Object obj; public DynamicProxy(Object obj) { super(); this.obj = obj; } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { try { this.beforeMethod(this.obj, m, args); Object retval = m.invoke(obj, args); this.afterMethod(this.obj, m, args, retval); return retval; } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw e; } } /** * Method called before the action is called on the object. * * @param obj * @param m * Method called * @param args * arguments passed to the method */ protected abstract void beforeMethod(Object obj, Method m, Object[] args); /** * Method called after the action is called on the object. * * @param obj * Objected the method was called on * @param m * Method called * @param args * arguments passed to the method * @param retval * return value from the method */ protected abstract void afterMethod(Object obj, Method m, Object[] args, Object retval); }
Java
/** * */ package annas.graph; import java.util.ArrayList; import java.util.Collections; import java.util.Set; import annas.util.ArraySet; /** * @author Sam * */ @SuppressWarnings("serial") public class DirectedGraph<V, E extends EdgeInterface<V>> extends AbstractGraph<V, E> { public DirectedGraph(EdgeFactory<V, E> edgeFactory) { super(edgeFactory, true); this.checker = new DirectedEdgeEqualityChecker<V, E>(); } public DirectedGraph(Class<? extends E> edgeClass) { super(edgeClass, true); this.checker = new DirectedEdgeEqualityChecker<V, E>(); } @Override public E addEdge(V tail, V head) { if (!this.allowparallelEdges && this.containsEdge(tail, head)) return null; if (!this.allowloops && tail == head) return null; E edge = this.edgeFactory.create(tail, head); edge.setHead(head); edge.setTail(tail); boolean added = this.vertexMap.get(tail).put(head, edge) != null; if (added) { return edge; } else { return null; } } @Override public boolean addVertex(V vertex) { if (!this.containsVertex(vertex)) { return this.vertexMap.put(vertex, new MultiHashMap<V, E>()) == null; } return false; } @Override public boolean removeEdge(E edge) { return this.vertexMap.get(edge.getTail()).remove(edge.getHead(), edge) != null && this.vertexMap.get(edge.getHead()).remove(edge.getTail(), edge) != null; } @Override public boolean removeEdge(V tail, V head) { Set<E> edges = this.getEdges(tail, head); boolean successful = true; for (E e : edges) { successful &= this.removeEdge(e); } return successful; } @Override public boolean removeEdge(V tail) { Set<E> edges = this.getEdges(tail); boolean successful = true; for (E e : edges) { successful &= this.removeEdge(e); } return successful; } @Override public boolean removeVertex(V vertex) { ArrayList<V> m = new ArrayList<V>(this.vertexMap.keySet()); // boolean successful = true; for (V mhm : m) { this.vertexMap.get(mhm).remove(vertex); // successful &= !this.vertexMap.get(mhm).containsKey(vertex); } return this.vertexMap.remove(vertex) != null; } public Set<E> getInEdges(V vertex) { Set<E> n = this.getEdges(); Set<E> m = new ArraySet<E>(new UndirectedEdgeEqualityChecker<V, E>()); for (E e : n) { if (e.getHead().equals(vertex)) { m.add(e); } } return Collections.unmodifiableSet(m); } public Set<E> getOutEdges(V vertex) { return this.getEdges(vertex); } }
Java
package annas.graph; import annas.util.EqualityChecker; public class DirectedEdgeEqualityChecker<V, E extends EdgeInterface<V>> implements EqualityChecker<E> { @SuppressWarnings("unchecked") @Override public boolean check(Object a, Object b) { E e1 = (E) a; E e2 = (E) b; boolean oneway = e1.getHead().equals(e2.getHead()) && e1.getTail().equals(e2.getTail()); boolean sameObject = e1 == e2; return (oneway) && sameObject; } }
Java
package annas.graph; public interface WeightedEdgeInterface<V> extends EdgeInterface<V> { public double getWeight(); public void setWeight(double weight); }
Java
package annas.graph; import java.util.Collection; import java.util.Set; @SuppressWarnings("serial") public class UnmodifiableGraph<V, E extends EdgeInterface<V>> implements GraphInterface<V, E> { private GraphInterface<V, E> graph; private final String err_msg = "Method not supported on Unmodifiable graph"; public UnmodifiableGraph(GraphInterface<V, E> graph) { super(); this.graph = graph; } @Override public E addEdge(V tail, V head) { throw new UnsupportedOperationException(err_msg); } @Override public boolean addVertex(V vertex) { throw new UnsupportedOperationException(err_msg); } @Override public boolean addVertices(Collection<? extends V> vertices) { throw new UnsupportedOperationException(err_msg); } @Override public boolean containsEdge(V head, V tail) { return this.graph.containsEdge(head, tail); } @Override public boolean containsEdge(E edge) { return this.graph.containsEdge(edge); } @Override public boolean containsVertex(V vertex) { return this.graph.containsVertex(vertex); } @Override public int getDegree(V vertex) { return this.graph.getDegree(vertex); } @Override public EdgeFactory<V, E> getEdgeFactory() { return this.graph.getEdgeFactory(); } @Override public Set<E> getEdges(V tail) { return this.graph.getEdges(tail); } @Override public Set<E> getEdges(V tail, V head) { return this.graph.getEdges(tail, head); } @Override public Set<E> getEdges() { return this.graph.getEdges(); } @Override public GraphObserver<V,E> getObserver() { return this.graph.getObserver(); } @Override public int getOrder() { return this.graph.getOrder(); } @Override public int getSize() { return this.graph.getSize(); } @Override public Set<V> getVertices() { return this.graph.getVertices(); } @Override public boolean removeEdge(E edge) { throw new UnsupportedOperationException(err_msg); } @Override public boolean removeEdge(V tail, V head) { throw new UnsupportedOperationException(err_msg); } @Override public boolean removeEdge(V tail) { throw new UnsupportedOperationException(err_msg); } @Override public boolean removeEdges(Collection<? extends E> edges) { throw new UnsupportedOperationException(err_msg); } @Override public boolean removeVertex(V vertex) { throw new UnsupportedOperationException(err_msg); } @Override public boolean removeVertices(Collection<? extends V> vertices) { throw new UnsupportedOperationException(err_msg); } @Override public boolean resetEdges() { throw new UnsupportedOperationException(err_msg); } @Override public void setObserver(GraphObserver<V,E> GO) { throw new UnsupportedOperationException(err_msg); } @Override public Class<?> getEdgeClass() { return this.graph.getEdgeClass(); } @Override public boolean isDirected() { return this.graph.isDirected(); } }
Java
package annas.graph; import java.io.Serializable; /** * Any class wishing to observer a graph must implement this interface * * @author Sam Wilson */ public interface GraphObserver<V,E extends EdgeInterface<V>> extends Serializable { /** * Method called when an edge is added to the graph being observed. * @param graph Graph being observed * @param args arguments passed to the method */ public void edgeAdded(GraphInterface<V,E> graph, Object[] args); /** * Method called when an edge is removed from the graph being observed. * @param graph Graph being observed * @param args arguments passed to the method */ public void edgeRemoved(GraphInterface<V,E> graph, Object[] args); /** * Method called when a vertex is added to the graph being observed. * @param graph Graph being observed * @param args arguments passed to the method */ public void vertexAdded(GraphInterface<V,E> graph, Object[] args); /** * Method called when a vertex is removed from the graph being observed. * @param graph Graph being observed * @param args arguments passed to the method */ public void vertexRemoved(GraphInterface<V,E> graph, Object[] args); }
Java
package annas.graph.util; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Stack; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; /** * * Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a graph * theory algorithm for finding the strongly connected components of a graph. As * described in Tarjan, R.: Depth-first search and linear graph algorithms, SIAM * J. Com- put. 1, no. 2, pp. 146-160 * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public class Tarjan<V, E extends EdgeInterface<V>> { private GraphInterface<V, E> graph; private Map<V, vertex<V>> verticies; private ArrayList<ArrayList<V>> comp; private int index; private Stack<vertex<V>> S; public Tarjan(GraphInterface<V, E> graph) { super(); this.graph = graph; this.verticies = new HashMap<V, vertex<V>>(); this.comp = new ArrayList<ArrayList<V>>(); this.index = 0; this.S = new Stack<vertex<V>>(); for (V node : this.graph.getVertices()) { this.verticies.put(node, new vertex<V>(node)); } } /** * executes Tarjan's algorithm of the suppled graph * * @return A list of lists of node which belong to the same component */ public ArrayList<ArrayList<V>> execute() { ArrayList<vertex<V>> tmp = new ArrayList<vertex<V>>(this.verticies .values()); for (int i = 0; i < tmp.size(); i++) { if (tmp.get(i).notNumbered()) { this.execute(tmp.get(i).node); } } return this.comp; } private ArrayList<ArrayList<V>> execute(V n) { this.run(this.verticies.get(n)); return this.comp; } private void run(vertex<V> v) { v.index = this.index; v.lowlink = this.index; this.index++; this.S.push(v); Set<E> edges = this.graph.getEdges(v.node); for (E arc : edges) { vertex<V> vp = this.verticies.get(arc.getHead()); if (vp.index == -1) { this.run(vp); v.lowlink = Math.min(v.lowlink, vp.lowlink); } else if (this.S.contains(vp)) { v.lowlink = Math.min(v.lowlink, vp.index); } } if (v.lowlink == v.index) { vertex<V> j; ArrayList<V> component = new ArrayList<V>(); do { j = this.S.pop(); component.add(j.node); } while (j != v); comp.add(component); } } @SuppressWarnings("hiding") private class vertex<V> { public V node; public int index; public int lowlink; /** * @param n */ public vertex(V n) { super(); this.index = -1; this.lowlink = -1; this.node = n; } public boolean notNumbered() { if (index == -1) { return true; } else { return false; } } @Override public String toString() { return "vertex [index=" + index + ", lowlink=" + lowlink + ", node=" + node + "]"; } } }
Java
package annas.graph.util; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.UndirectedGraph; import annas.math.combinatorics.PowersetIterator; public class InducedSubgraph { /** * Returns the induced subgraph by given vertices. Reuses the vertex * objects, but makes new edges. * * @param graph * @param vertices * @return induced graph graph[vertices] */ public static <V, E extends EdgeInterface<V>> GraphInterface<V, E> inducedSubgraphOf( GraphInterface<V, E> graph, Collection<V> vertices) { if(!graph.getVertices().containsAll(vertices)){ return null; } GraphInterface<V, E> h = new UndirectedGraph<V, E>(graph .getEdgeFactory()); for (V n : vertices) { h.addVertex(n); } for (E e : graph.getEdges()) { V s = e.getTail(); V t = e.getHead(); if (h.containsVertex(s) && h.containsVertex(t)) { h.addEdge(s, t); } } return h; } /** * Provides an iterator for induced subgraphs. * * @param <V> * @param <E> * @param graph * @param poss * Set of vertices to include/exclude from the graph * @return an iterator of graphs which contains the vertices (V \ poss) * union u where u \in powerset(poss). */ public static <V, E extends EdgeInterface<V>> Iterator<GraphInterface<V, E>> inducedSubgraphIterator( final GraphInterface<V, E> graph, final List<V> poss) { return new Iterator<GraphInterface<V, E>>() { PowersetIterator<V> subsets = new PowersetIterator<V>(poss); @Override public boolean hasNext() { return subsets.hasNext(); } @Override public GraphInterface<V, E> next() { Collection<V> vertices = subsets.next(); Set<V> n = graph.getVertices(); n.removeAll(poss); n.addAll(vertices); return inducedSubgraphOf(graph, n); } @Override public void remove() { } }; } /** * Induced subgraph iterator * * @param <V> * @param <E> * @param graph * @return an iterator over all induced subgraphs of a given graph */ public static <V, E extends EdgeInterface<V>> Iterator<GraphInterface<V, E>> inducedSubgraphIterator( final GraphInterface<V, E> graph) { return new Iterator<GraphInterface<V, E>>() { PowersetIterator<V> subsets = new PowersetIterator<V>( graph.getVertices()); @Override public boolean hasNext() { return subsets.hasNext(); } @Override public GraphInterface<V, E> next() { Collection<V> vertices = subsets.next(); return inducedSubgraphOf(graph, vertices); } @Override public void remove() { } }; } }
Java
package annas.graph.util; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.Iterator; import annas.graph.DirectedGraph; import annas.graph.WeightedEdgeInterface; public class FordFulkerson<V, E extends WeightedEdgeInterface<V>> { /** * Holds the flow */ private Hashtable<E, Double> flow; /** * Network */ private DirectedGraph<V, E> graph; /** * Source */ private V source; /** * Sink */ private V sink; public FordFulkerson(DirectedGraph<V, E> graph, V source, V sink) { super(); this.graph = graph; this.sink = sink; this.source = source; this.flow = new Hashtable<E, Double>(graph.getSize()); for (E e : graph.getEdges()) { this.flow.put(e, 0d); } } /** * Computes the Maximum flow for the given graph between Sink and Source * * @return Maximum flow */ public double getMaximumFlow() { ArrayList<E> gp = this.findAugmentingPath(this.source, this.sink, new ArrayList<E>()); while (gp != null) { double leeway = this.getLeeway(gp); updateFlow(gp, leeway); gp = this.findAugmentingPath(this.source, this.sink, new ArrayList<E>()); } return this.calculateMaxFlow(); } /** * Gets the flow along an edge (once the algorithm has been executed, * otherwise returns 0). * * @param e * @return the flow on an edge */ public double getFlow(E e) { return this.flow.get(e); } private double calculateMaxFlow() { double retval = 0; for (E e : this.graph.getEdges(this.source)) { retval += this.flow.get(e); } return retval; } private void updateFlow(ArrayList<E> gp, double leeway) { Iterator<E> it = gp.iterator(); E e = it.next(); E tmp = null; if (e.getTail() == this.source) { this.flow.put(e, this.flow.get(e) + leeway); } else { this.flow.put(e, this.flow.get(e) - leeway); } while (it.hasNext()) { tmp = it.next(); if (e.getHead() == tmp.getTail()) { this.flow.put(tmp, this.flow.get(tmp) + leeway); } else { this.flow.put(tmp, this.flow.get(tmp) - leeway); } e = tmp; } } private ArrayList<E> findAugmentingPath(V source, V sink, ArrayList<E> path) { if (source == sink) { return path; } else { for (E e : this.getEdge(source)) { if (e.getTail() == source) { double res = e.getWeight() - this.flow.get(e); if (res > 0 && !path.contains(e)) { ArrayList<E> copy = new ArrayList<E>(path); copy.add(e); ArrayList<E> result = this.findAugmentingPath(e .getHead(), sink, copy); if (result != null) { return result; } } } else { double res = this.flow.get(e); if (res > 0 && !path.contains(e)) { ArrayList<E> copy = new ArrayList<E>(path); copy.add(e); ArrayList<E> result = this.findAugmentingPath(e .getHead(), sink, copy); if (result != null) { return result; } } } } } return null; } private ArrayList<E> getEdge(V v) { ArrayList<E> edges = new ArrayList<E>(); for (E e : graph.getEdges()) { if (e.getHead() == v || e.getTail() == v) { edges.add(e); } } return edges; } private double getLeeway(ArrayList<E> gp) { ArrayList<Double> leeway = new ArrayList<Double>(); Iterator<E> it = gp.iterator(); E e = it.next(); E tmp = null; if (e.getTail() == this.source) { leeway.add(this.getExcess(e)); } else { leeway.add(this.flow.get(e)); } while (it.hasNext()) { tmp = it.next(); if (e.getHead() == tmp.getTail()) { leeway.add(this.getExcess(tmp)); } else { leeway.add(this.flow.get(tmp)); } e = tmp; } Collections.sort(leeway); return leeway.get(0); } private double getExcess(E e) { return e.getWeight() - this.flow.get(e); } }
Java
package annas.graph.util; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; public interface MinimumSpanningTree<V, E extends EdgeInterface<V>> { public GraphInterface<V,E> execute(); public double getCost(); }
Java
package annas.graph.util; import java.util.ArrayList; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.WeightedEdgeInterface; import annas.misc.GraphPath; /** * Determines all pair shortest paths, as described <a * href="http://mathworld.wolfram.com/Floyd-WarshallAlgorithm.html"> here</a> * * @author Sam Wilson * * @param <V> * Vertex type * @param <E> * Edge type */ public class Floyd<V, E extends EdgeInterface<V>> { private final double DEFAULT_EDGE_WEIGHT = 1.0d; /** * Graph to perform the algorithm on. */ private GraphInterface<V, E> g; /** * Integer array containing the route from source to destination. */ private int[][] R; /** * Double array containing the distance from source to destination. */ private double[][] D; /** * Default constructor * * @param g * Graph o perform algorithm on. */ public Floyd(GraphInterface<V, E> g) { super(); this.g = g; makeMatrix(); run(); } /** * The route matrix for the current graph. * * @return The route matrix. */ public int[][] getR() { return R; } /** * The distance matrix for the current graph. * * @return distance matrix */ public double[][] getD() { return D; } /** * Finds the distance between the two nodes, by looking in the distance * matrix. * * @param a * Source * @param b * Destination * @return Distance between the nodes. */ public double getDistance(V a, V b) { return D[indexOf(a)][indexOf(b)]; } /** * Find the route through the Graph from the source node to the destination * node, by using the route matrix. * * @param a * Source * @param b * Destination * @return Graph of the route between the two nodes. */ public GraphPath<V, E> getRoute(V a, V b) { GraphPath<V, E> m = new GraphPath<V, E>(); V t = a; int col = indexOf(b); int row = indexOf(a); int temp = row; ArrayList<V> fg = new ArrayList<V>(this.g.getVertices()); while (temp != col) { row = R[col][row] - 1; m.addEdge(this.g.getEdges(t, fg.get(row)).iterator().next()); t = fg.get(row); temp = row; } return m; } /** * Runs the algorithm that finds the shortest path between all pairs. */ private void run() { int loc; for (int it = 1; it <= this.D.length; it++) { loc = it - 1; for (int x = 0; x < this.D.length; x++) { for (int y = 0; y < this.D[0].length; y++) { if ((D[loc][y] + D[x][loc] < D[x][y]) && (x != loc || y != loc)) { D[x][y] = D[it - 1][y] + D[x][loc]; this.R[x][y] = this.R[loc][y]; } } } } } private int indexOf(V vertex) { int index = 0; for (V v : this.g.getVertices()) { if (v == vertex) { return index; } index++; } return -1; } /** * Sets up the matrices, and converts from the adjacent list format into * distance matrix. */ private void makeMatrix() { int SIZE = this.g.getOrder(); D = new double[SIZE][SIZE]; R = new int[SIZE][SIZE]; for (int i = 0; i < R.length; i++) { for (int j = 0; j < R[0].length; j++) { R[i][j] = i + 1; } } for (int i = 0; i < D.length; i++) { for (int j = 0; j < D[0].length; j++) { D[i][j] = Double.MAX_VALUE; } } for (V current : this.g.getVertices()) { int x = indexOf(current); for (E edge : this.g.getEdges(current)) { D[x][indexOf(edge.getOtherEndpoint(current))] = getWeight(edge); } } } private double getWeight(E edge) { if (edge instanceof WeightedEdgeInterface<?>) { return ((WeightedEdgeInterface<?>) edge).getWeight(); } return DEFAULT_EDGE_WEIGHT; } }
Java
/******************************************************************************* * Copyright (c) 2013 scsswi. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * scsswi - initial API and implementation ******************************************************************************/ package annas.graph.util; import annas.graph.EdgeInterface; /** * Class for all algorithms to extend. This provides the base functionality to * determine if an algorithm is suitable for use with directed or undirected * graphs. * * @author scsswi * * @param <V> * Vertex type * @param <E> * Edge type */ public class Algorithm<V, E extends EdgeInterface<V>> { public Algorithm() { } }
Java
package annas.graph.util.traverse; import java.util.Iterator; import annas.graph.EdgeInterface; /** * Interface for traversal algorithms. * * @author Sam Wilson * * @param <V> * @param <E> */ public interface Traversal<V, E extends EdgeInterface<V>> extends Iterable<V> { /** * Get an iterator containing the vertices of the traversal in the order * dictated by the traversal algorithm. * * @return an iterator of vertices order according to the travseral algorithm. */ public Iterator<V> getTraversal(); }
Java
package annas.graph.util.traverse; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; import annas.graph.GraphInterface; import annas.graph.util.Utilities; public class NewDepthFirst<V> implements Iterable<V> { private GraphInterface<V, ?> graph; private V startVertex; public NewDepthFirst(GraphInterface<V, ?> graph) { super(); this.graph = graph; } public NewDepthFirst(GraphInterface<V, ?> graph, V startV) { super(); this.graph = graph; this.startVertex = startV; } public V getStartVertex() { return startVertex; } public void setStartVertex(V startVertex) { this.startVertex = startVertex; } @Override public Iterator<V> iterator() { if (this.startVertex != null) { return new DepthFirstIterator(this.graph, this.startVertex); } else { return new DepthFirstIterator(this.graph, this.graph.getVertices() .iterator().next()); } } private class DepthFirstIterator implements Iterator<V> { private Deque<V> stack; private GraphInterface<V, ?> graph; private Collection<V> visited; public DepthFirstIterator(GraphInterface<V, ?> graph, V startVertex) { super(); this.graph = graph; this.stack = new ArrayDeque<V>(); this.visited = new ArrayList<V>(); if (this.graph.containsVertex(startVertex)) { this.stack.add(startVertex); } else { throw new IllegalArgumentException(startVertex + " not in graph"); } } @Override public boolean hasNext() { return !this.stack.isEmpty(); } @Override public V next() { if (!this.stack.isEmpty()) { V retval = this.stack.pop(); for (V u : Utilities.getOpenNeighbourhood(this.graph, retval)) { if (!this.visited.contains(u) && !this.stack.contains(u)) { this.stack.push(u); } } this.visited.add(retval); return retval; } else { throw new NoSuchElementException("No more elements"); } } @Override public void remove() { throw new UnsupportedOperationException(); } } }
Java
package annas.graph.util.traverse; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; import annas.graph.GraphInterface; import annas.graph.util.Utilities; public class NewBreadthFirst<V> implements Iterable<V> { private GraphInterface<V, ?> graph; private V startVertex; public NewBreadthFirst(GraphInterface<V, ?> graph) { super(); this.graph = graph; } public NewBreadthFirst(GraphInterface<V, ?> graph, V startV) { super(); this.graph = graph; this.startVertex = startV; } public V getStartVertex() { return startVertex; } public void setStartVertex(V startVertex) { this.startVertex = startVertex; } @Override public Iterator<V> iterator() { if (this.startVertex != null) { return new DepthFirstIterator(this.graph, this.startVertex); } else { return new DepthFirstIterator(this.graph, this.graph.getVertices() .iterator().next()); } } private class DepthFirstIterator implements Iterator<V> { private Deque<V> stack; private GraphInterface<V, ?> graph; private Collection<V> visited; public DepthFirstIterator(GraphInterface<V, ?> graph, V startVertex) { super(); this.graph = graph; this.stack = new ArrayDeque<V>(); this.visited = new ArrayList<V>(); if (this.graph.containsVertex(startVertex)) { this.stack.add(startVertex); } else { throw new IllegalArgumentException(startVertex + " not in graph"); } } @Override public boolean hasNext() { return !this.stack.isEmpty(); } @Override public V next() { if (!this.stack.isEmpty()) { V retval = this.stack.pop(); for (V u : Utilities.getOpenNeighbourhood(this.graph, retval)) { if (!this.visited.contains(u) && !this.stack.contains(u)) { this.stack.add(u); } } this.visited.add(retval); return retval; } else { throw new NoSuchElementException("No more elements"); } } @Override public void remove() { throw new UnsupportedOperationException(); } } }
Java
package annas.graph.util.traverse; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; public class LexBFS<V, E extends EdgeInterface<V>> implements Traversal<V, E> { private GraphInterface<V, E> graph; private List<V> output; public LexBFS(GraphInterface<V, E> graph) { super(); this.graph = graph; this.output = new ArrayList<V>(this.graph.getOrder()); } public void run() { ArrayList<List<V>> input = new ArrayList<List<V>>(); input.add(new ArrayList<V>(graph.getVertices())); lexbfs(input); } public List<V> getOutput() { return output; } private void lexbfs(List<List<V>> input) { while (!input.isEmpty()) { V vertex = input.get(0).remove(0); if (input.get(0).isEmpty()) { input.remove(0); } this.output.add(vertex); ArrayList<List<V>> input_new = new ArrayList<List<V>>(); for (int i = 0; i < input.size(); i++) { ArrayList<V> tmp_in = new ArrayList<V>(); ArrayList<V> tmp_out = new ArrayList<V>(); for (int j = 0; j < input.get(i).size(); j++) { if (this.graph.getEdges(vertex, input.get(i).get(j)).size() != 0) { tmp_in.add(input.get(i).get(j)); } else { tmp_out.add(input.get(i).get(j)); } } if (!tmp_in.isEmpty()) input_new.add(tmp_in); if (!tmp_out.isEmpty()) input_new.add(tmp_out); } input = input_new; } } @SuppressWarnings("unused") private void lexbfs_complement(List<List<V>> input) { while (!input.isEmpty()) { V vertex = input.get(0).remove(0); if (input.get(0).isEmpty()) { input.remove(0); } this.output.add(vertex); ArrayList<List<V>> input_new = new ArrayList<List<V>>(); for (int i = 0; i < input.size(); i++) { ArrayList<V> tmp_in = new ArrayList<V>(); ArrayList<V> tmp_out = new ArrayList<V>(); for (int j = 0; j < input.get(i).size(); j++) { if (this.graph.getEdges(vertex, input.get(i).get(j)).size() != 0) { tmp_in.add(input.get(i).get(j)); } else { tmp_out.add(input.get(i).get(j)); } } if (!tmp_out.isEmpty()) input_new.add(tmp_out); if (!tmp_in.isEmpty()) input_new.add(tmp_in); } input = input_new; } } @Override public Iterator<V> getTraversal() { return this.output.iterator(); } @Override public Iterator<V> iterator() { return this.output.iterator(); } }
Java
package annas.graph.util.traverse; import java.util.Iterator; import java.util.LinkedList; import java.util.Set; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; /** * Performs a depth first traversal * * @author Sam Wilson * @see annas.graph.util.traverse.Traversal * @param <V> * Vertex type * @param <E> * Edge type */ public class DepthFirst<V, E extends EdgeInterface<V>> implements Traversal<V, E> { private GraphInterface<V, E> graph; private LinkedList<V> Order; private int depth; private int tmp; private V s; public DepthFirst(GraphInterface<V, E> g, V s) { super(); this.depth = 0; this.tmp = 0; this.graph = g; this.s = s; this.Order = new LinkedList<V>(); } /** * Performs a Depth first traversal on the graph from the source vertex * * @return Iterator of the traversal */ @Override public Iterator<V> getTraversal() { this.DF(this.s); return this.Order.iterator(); } @Override public Iterator<V> iterator() { this.DF(this.s); return this.Order.iterator(); } private void DF(V n) { if (!this.Order.contains(n)) { this.Order.add(n); Set<E> edges = this.graph.getEdges(n); if (edges.size() == 0 && this.tmp > this.depth) { // leave node this.depth = this.tmp; } for (E e : edges) { this.tmp++; this.DF(e.getOtherEndpoint(n)); } this.tmp--; } } /** * Gets the graph of the graph being traversed. * * @return the graph being traversed */ public GraphInterface<V, E> getGraph() { return graph; } /** * * @return the depth of the traversal */ public int getDepth() { return depth; } }
Java
package annas.graph.util.traverse; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Set; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; /** * Performs a Breadth first traversal * * @author Sam Wilson * @see annas.graph.util.traverse.Traversal * @param <V> * Vertex type * @param <E> * Edge type */ public class BreadthFirst<V, E extends EdgeInterface<V>> implements Traversal<V, E> { private GraphInterface<V, E> graph; private LinkedList<V> Order; private HashMap<V, Integer> map; private boolean Bipartite = true; private V s; public BreadthFirst(GraphInterface<V, E> g, V s) { super(); this.graph = g; this.s = s; this.map = new HashMap<V, Integer>(); this.Order = new LinkedList<V>(); } @Override public Iterator<V> getTraversal() { this.BF(this.s); return this.Order.iterator(); } @Override public Iterator<V> iterator() { this.BF(this.s); return this.Order.iterator(); } private void BF(V n) { Queue<V> l = new LinkedList<V>(); map.put(n, 0); l.offer(n); while (l.size() > 0) { V m = l.poll(); this.Order.add(m); Set<E> edges = this.graph.getEdges(m); for (E e : edges) { V head = this.getOtherEndPoint(m, e); if (this.Order.contains(head)) { } else { l.offer(head); } if (!map.containsKey(head)) { map.put(head, this.label(map.get(m))); } else { if (map.get(this.getOtherEndPoint(m, e)) % 2 == map.get(m) % 2) { this.Bipartite = false; } } } } } private int label(int i) { return i + 1; } public int getLevel(V node) { return this.map.get(node); } private V getOtherEndPoint(V tail, E edge) { if (edge.getHead() == edge.getTail()) { return edge.getHead(); } else { if (edge.getHead() == tail) { return edge.getTail(); } else { return edge.getHead(); } } } public boolean isBipartite() { return Bipartite; } }
Java
package annas.graph.util.filter; public interface FilterPredicate<T> { public boolean evaluate(T object); }
Java
package annas.graph.util.filter; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; public interface Filter<V, E extends EdgeInterface<V>> { public GraphInterface<V, E> filter(GraphInterface<V, E> graph); }
Java
package annas.graph.util; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import annas.graph.DefaultWeightedEdge; import annas.graph.DirectedGraph; import annas.graph.EdgeInterface; import annas.graph.UndirectedGraph; import annas.graph.WeightedEdgeInterface; import annas.graph.classifier.BipartiteRecogniser; import annas.graph.classifier.Classifier; public class BipartiteMatching<V, E extends EdgeInterface<V>> { private UndirectedGraph<V, E> graph; private List<V> x; private List<V> y; public BipartiteMatching(UndirectedGraph<V, E> graph) throws Exception { super(); Classifier<V, E> c = new BipartiteRecogniser<V, E>(); if (!c.classify(graph)) { throw new Exception("Graph is not bipartite"); } this.graph = graph; this.x = new ArrayList<V>(); this.y = new ArrayList<V>(); partition(); } @SuppressWarnings({ "unchecked", "rawtypes" }) public List<E> getMatching() { DirectedGraph g = new DirectedGraph(DefaultWeightedEdge.class); Object src = new Object(); Object sink = new Object(); g.addVertex(src); g.addVertex(sink); for (V v : graph.getVertices()) { g.addVertex(v); } WeightedEdgeInterface<V> e; for (V v : x) { e = (DefaultWeightedEdge<V>) g.addEdge(src, v); e.setWeight(1d); } System.out.println(g.getSize()); for (V v : y) { e = (DefaultWeightedEdge<V>) g.addEdge(v, sink); e.setWeight(1d); } System.out.println(g.getSize()); for (E f : graph.getEdges()) { if (x.contains(f.getTail()) && y.contains(f.getHead())) { e = (DefaultWeightedEdge<V>) g.addEdge(f.getTail(), f.getHead()); e.setWeight(1); } else if (x.contains(f.getHead()) && y.contains(f.getTail())) { e = (DefaultWeightedEdge<V>) g.addEdge(f.getHead(), f.getTail()); e.setWeight(1); } } System.out.println(g.getSize()); FordFulkerson ff = new FordFulkerson(g, src, sink); System.out.println(ff.getMaximumFlow()); ArrayList<E> edges = new ArrayList<E>(); for (Object o : g.getEdges()) { WeightedEdgeInterface<V> ee = (WeightedEdgeInterface<V>) o; if (ff.getFlow(ee) == 1 && (ee.getHead() != src && ee.getTail() != sink && ee.getHead() != sink && ee.getTail() != src)) { edges.add(graph.getEdges(ee.getTail(), ee.getHead()).iterator() .next()); } } return edges; } private void partition() { Set<V> n = new TreeSet<V>(graph.getVertices()); while (!n.isEmpty()) { V v = n.iterator().next(); if (!x.contains(v) && !y.contains(v)) { y.add(v); n.remove(v); } dfsX(v, n); } System.out.println(x); System.out.println(y); } private void dfsX(V v, Set<V> n) { for (E e : graph.getEdges(v)) { V u = e.getOtherEndpoint(v); if (!x.contains(u) && !y.contains(u)) { n.remove(u); x.add(u); dfsY(u, n); } } } private void dfsY(V v, Set<V> n) { for (E e : graph.getEdges(v)) { V u = e.getOtherEndpoint(v); if (!y.contains(u) && !x.contains(u)) { n.remove(u); y.add(u); dfsX(u, n); } } } }
Java
package annas.graph.util; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; /** * All algorithms that operate on directed graphs should extend this class. * * @author scsswi * * @param <V> * Vertex type * @param <E> * Edge type */ public class DirectedGraphAlgorithm<V, E extends EdgeInterface<V>> extends Algorithm<V, E> { public DirectedGraphAlgorithm(GraphInterface<V, E> graph) { super(); if (!graph.isDirected()) { throw new IllegalArgumentException( "Algorithm incompatible with type " + graph.getClass() + " derived from UndirectedGraph"); } } }
Java
package annas.graph.util; import java.util.Comparator; import java.util.PriorityQueue; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.UndirectedGraph; import annas.graph.WeightedEdgeInterface; import annas.util.DisjointSet; public class Kruskal<V, E extends EdgeInterface<V>> implements MinimumSpanningTree<V, E> { private final double DEFAULT_EDGE_WEIGHT = 1d; private GraphInterface<V, E> graph; private PriorityQueue<E> EdgeList; public Kruskal(GraphInterface<V, E> g) { this.graph = g; this.EdgeList = new PriorityQueue<E>(graph.getSize(), new DoubleFieldComparator()); } @Override public GraphInterface<V, E> execute() { @SuppressWarnings({ "unchecked", "rawtypes" }) GraphInterface<V, E> tree = new UndirectedGraph(this.graph.getEdgeClass()); DisjointSet<V> ds = new DisjointSet<>(this.graph.getVertices()); this.EdgeList.addAll(this.graph.getEdges()); for(E edge : this.EdgeList){ if(!ds.findSet(edge.getHead()).equals(ds.findSet(edge.getTail()))){ tree.addVertex(edge.getHead()); tree.addVertex(edge.getTail()); EdgeInterface<V> e = tree.addEdge(edge.getTail(), edge.getHead()); if(edge instanceof WeightedEdgeInterface){ ((WeightedEdgeInterface<V>) e).setWeight(((WeightedEdgeInterface<V>) edge).getWeight()); } ds.union(edge.getHead(), edge.getTail()); } } return tree; } @Override public double getCost() { GraphInterface<?, E> graph = this.execute(); double d = 0; for(E edge : graph.getEdges()){ if (edge instanceof WeightedEdgeInterface<?>) { d += ((WeightedEdgeInterface<?>) edge).getWeight(); }else{ d += 1; } } return d; } class DoubleFieldComparator implements Comparator<E> { @Override public int compare(E arg0, E arg1) { Double d = DEFAULT_EDGE_WEIGHT; Double e = DEFAULT_EDGE_WEIGHT; if (arg0 instanceof WeightedEdgeInterface<?>) { d = ((WeightedEdgeInterface<?>) arg0).getWeight(); } if (arg1 instanceof WeightedEdgeInterface<?>) { e = ((WeightedEdgeInterface<?>) arg1).getWeight(); } return d.compareTo(e); } } }
Java
package annas.graph.util.certifying; public abstract class CertifyingAlgorithm { public abstract void compute(); public abstract boolean verify(); }
Java
package annas.graph.util.certifying; public interface Verifier<I, O, C extends Certificate> { public boolean check(I input, O output, C certificate); }
Java
package annas.graph.util.certifying; public interface Certificate { }
Java
package annas.graph.util; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.misc.GraphPath; public interface SingleSourceShortestPath<V, E extends EdgeInterface<V>> { public GraphInterface<V, E> execute(V v); public GraphPath<V, E> execute(V v, V u); }
Java
/******************************************************************************* * Copyright (c) 2013 scsswi. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * scsswi - initial API and implementation ******************************************************************************/ package annas.graph.util; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; /** * All algorithms that operate on undirected graphs should extend this class. * * @author scsswi * * @param <V> * Vertex type * @param <E> * Edge type */ public class UndirectedGraphAlgorithm<V, E extends EdgeInterface<V>> extends Algorithm<V, E> { public UndirectedGraphAlgorithm(GraphInterface<V, E> graph) { super(); if (graph.isDirected()) { throw new IllegalArgumentException( "Algorithm incompatible with type " + graph.getClass() + " derived from DirectedGraph"); } } }
Java
package annas.graph.util; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.Map; import java.util.PriorityQueue; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.WeightedEdgeInterface; import annas.misc.GraphPath; public class Dijkstra<V, E extends EdgeInterface<V>> { private final double DEFAULT_EDGEWEIGHT = 1.0; private GraphInterface<V, E> graph; private Map<V, Marker<V>> lookup; private PriorityQueue<Marker<V>> queue; public Dijkstra(GraphInterface<V, E> graph) { super(); this.graph = graph; this.queue = new PriorityQueue<Marker<V>>(this.graph.getVertices() .size()); this.lookup = new Hashtable<V, Marker<V>>(this.graph.getVertices() .size()); for (V n : this.graph.getVertices()) { this.lookup.put(n, new Marker<V>(n)); } } public GraphPath<V, E> execute(V source, V destination) { int order = 0; Marker<V> m = this.lookup.get(source); m.setDistance(0); this.queue.add(m); Marker<V> tmp = m; while (tmp.getRepresenting() != destination && this.queue.peek() != null) { tmp = this.queue.poll(); tmp.setOrder(order); order++; tmp.setPermenant(); for (E edge : this.graph.getEdges(tmp.getRepresenting())) { double weight = this.getWeight(edge); double distanceThrutmo = tmp.getDistance() + weight; Marker<V> mm = this.lookup.get(edge.getOtherEndpoint(tmp.representing)); if (distanceThrutmo < mm.getDistance()) { this.queue.remove(mm); mm.setDistance(distanceThrutmo); mm.setPrevious(tmp.getRepresenting()); this.queue.add(mm); } } } GraphPath<V, E> gp = new GraphPath<V, E>(); V tmppp = destination; V tmpp = null; ArrayList<V> path = new ArrayList<V>(); path.add(tmppp); while (tmppp != source) { tmpp = this.lookup.get(tmppp).getPrevious(); if (tmpp == null) { return gp; } path.add(tmpp); tmppp = tmpp; } Marker<V> d, s = null; for (int i = path.size() - 1; i != 0; i--) { d = this.lookup.get(path.get(i - 1)); s = this.lookup.get(path.get(i)); gp.addEdge(getEdge(d.representing, s.representing, d.getDistance() - s.getDistance())); } return gp; } private E getEdge(V tail, V head, double weight) { Collection<E> edges = this.graph.getEdges(tail, head); for (E e : edges) { if (this.getWeight(e) == weight) { return e; } } return null; } private double getWeight(EdgeInterface<V> e) { if (e instanceof WeightedEdgeInterface) { return ((WeightedEdgeInterface<V>) e).getWeight(); } return DEFAULT_EDGEWEIGHT; } private class Marker<N> implements Comparable<Marker<N>> { private N representing; private int order; private double distance; private N previous; private boolean permenant; public Marker(N representing) { super(); this.representing = representing; this.order = Integer.MAX_VALUE; this.distance = Double.POSITIVE_INFINITY; this.permenant = false; } public N getRepresenting() { return representing; } public void setOrder(int order) { this.order = order; } public void setPermenant() { this.permenant = true; } public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } @Override public int compareTo(Marker<N> o) { return Double.compare(this.distance, o.getDistance()); } public N getPrevious() { return previous; } public void setPrevious(N previous) { this.previous = previous; } @Override public String toString() { return "Marker [distance=" + distance + ", order=" + order + ", permenant=" + permenant + ", previous=" + previous + ", representing=" + representing + "]"; } } }
Java
package annas.graph.util; public interface Matching { }
Java
package annas.graph.util; import java.util.Comparator; import java.util.PriorityQueue; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.UndirectedGraph; import annas.graph.WeightedEdgeInterface; public class Prim<V, E extends EdgeInterface<V>> implements MinimumSpanningTree<V, E> { private final double DEFAULT_EDGE_WEIGHT = 1d; private GraphInterface<V, E> graph; private PriorityQueue<E> EdgeList; public Prim(GraphInterface<V, E> graph) { super(); this.graph = graph; this.EdgeList = new PriorityQueue<E>(graph.getSize(), new DoubleFieldComparator()); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public GraphInterface<V, E> execute() { GraphInterface<V, E> tree = new UndirectedGraph( this.graph.getEdgeClass()); V vertex = this.graph.getVertices().iterator().next(); tree.addVertex(vertex); this.EdgeList.addAll(this.graph.getEdges(vertex)); while (tree.getOrder() != this.graph.getOrder() && !this.EdgeList.isEmpty()) { E edge = this.EdgeList.poll(); V v = this.getOtherEnd(tree, edge); System.out.println(v); if (!tree.containsVertex(v)) { tree.addVertex(v); EdgeInterface<V> e = tree.addEdge(edge.getTail(), edge.getHead()); if (edge instanceof WeightedEdgeInterface) { ((WeightedEdgeInterface<V>) e) .setWeight(((WeightedEdgeInterface<V>) edge) .getWeight()); } this.EdgeList.remove(edge); this.EdgeList.addAll(this.graph.getEdges(v)); } } return tree; } private V getOtherEnd(GraphInterface<V, ?> g, E edge) { if (g.containsVertex(edge.getHead())) { return edge.getTail(); } else { return edge.getHead(); } } @Override public double getCost() { GraphInterface<?, E> graph = this.execute(); double d = 0; for (E edge : graph.getEdges()) { if (edge instanceof WeightedEdgeInterface<?>) { d += ((WeightedEdgeInterface<?>) edge).getWeight(); } else { d += 1; } } return d; } class DoubleFieldComparator implements Comparator<E> { @Override public int compare(E arg0, E arg1) { Double d = DEFAULT_EDGE_WEIGHT; Double e = DEFAULT_EDGE_WEIGHT; if (arg0 instanceof WeightedEdgeInterface<?>) { d = ((WeightedEdgeInterface<?>) arg0).getWeight(); } if (arg1 instanceof WeightedEdgeInterface<?>) { e = ((WeightedEdgeInterface<?>) arg1).getWeight(); } return d.compareTo(e); } } }
Java
package annas.graph.util; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.Stack; import annas.graph.AbstractGraph; import annas.graph.DirectedGraph; import annas.graph.EdgeInterface; import annas.graph.GraphInterface; import annas.graph.UndirectedGraph; import annas.math.Matrix; import annas.math.combinatorics.CombinatoricUtil; public final class Utilities { /** * Computes the complement of the graph, the vertices are reused. * * @param <V> * @param <E> * @param graph * @return the complement of the given graph */ public <V, E extends EdgeInterface<V>> GraphInterface<V, E> getComplement( GraphInterface<V, E> graph) { // TODO return null; } /** * Gets the adjacency matrix of the given graph. * * @param <V> * @param <E> * @param graph * @return the adjacency matrix of the given graph */ public static <V, E extends EdgeInterface<V>> Matrix getAdjacencyMatrix( GraphInterface<V, ?> graph) { int order = graph.getOrder(); double[][] adj = new double[order][order]; Iterator<V> outer = graph.getVertices().iterator(); Iterator<V> inner = null; for (int i = 0; outer.hasNext(); i++) { V vertex = outer.next(); inner = graph.getVertices().iterator(); for (int j = 0; inner.hasNext(); j++) { if (graph.getEdges(vertex, inner.next()).size() != 0) { adj[i][j] = 1; } else { adj[i][j] = 0; } } } return new Matrix(adj); } /** * Gets the connected components of the graph. * * @param <V> * @param <E> * @param graph * @return A collection of collections containing the vertices of the * connected components */ public static <V, E extends EdgeInterface<V>> Collection<Collection<V>> getConnectedComponents( GraphInterface<V, E> graph) { ArrayList<V> toVisit = new ArrayList<V>(graph.getVertices()); ArrayList<Collection<V>> components = new ArrayList<Collection<V>>(); Stack<V> stack = new Stack<V>(); List<V> Visited = new ArrayList<V>(); while (!toVisit.isEmpty()) { stack.push(toVisit.get(0)); while (!stack.isEmpty()) { V current = stack.pop(); Visited.add(current); toVisit.remove(current); Set<E> edges = graph.getEdges(current); for (E edge : edges) { V otherEnd = null; if (edge.getHead() == current) { otherEnd = edge.getTail(); } else { otherEnd = edge.getHead(); } if (!stack.contains(otherEnd) && toVisit.contains(otherEnd)) { stack.add(otherEnd); } } } components.add(Visited); Visited = new ArrayList<V>(); } return components; } /** * Gets the closed neighbourhood of a vertex. * * @param <V> * @param <E> * @param graph * @param vertex * @return The set of vertices adjacent to the given vertex (including the * given vertex). */ public static <V, E extends EdgeInterface<V>> Collection<V> getClosedNeighbourhood( GraphInterface<V, E> graph, V vertex) { Collection<V> vertices = Utilities.getOpenNeighbourhood(graph, vertex); vertices.add(vertex); return vertices; } /** * Gets the closed neighbourhood of a vertex up to n distance from the * central vertex * * @param <V> * @param <E> * @param graph * Graph * @param vertex * central vertex * @param n * distance from central vertex * @return Gets a collection of the vertices that are within a specified * distance from a central vertex including the central vertex. */ public static <V, E extends EdgeInterface<V>> Set<V> getClosedNNeighborhood( GraphInterface<V, E> graph, V vertex, int n) { Set<V> neighbors = new HashSet<V>(graph.getDegree(vertex)); neighbors.add(vertex); for (int i = 0; i < n; i++) { Set<V> newneighbors = new HashSet<V>(graph.getVertices().size()); for (V v : neighbors) { newneighbors.addAll(Utilities.getOpenNeighbourhood(graph, v)); } neighbors.addAll(newneighbors); } return neighbors; } /** * Gets the open neighbourhood of a given vertex. * * @param <V> * @param <E> * @param graph * @param vertex * @return A collection of vertices adjacent to a given vertex. */ public static <V, E extends EdgeInterface<V>> Collection<V> getOpenNeighbourhood( GraphInterface<V, E> graph, V vertex) { Collection<V> vertices = new LinkedHashSet<V>(); Set<E> edges = graph.getEdges(vertex); for (E edge : edges) { if (edge.getHead() == vertex) { vertices.add(edge.getTail()); } else { vertices.add(edge.getHead()); } } return vertices; } /** * Gets the closed neighbourhood of a vertex up to n distance from the * central vertex * * @param <V> * @param <E> * @param graph * Graph * @param vertex * central vertex * @param n * distance from central vertex * @return Gets a collection of the vertices that are within a specified * distance from a central vertex. */ public static <V, E extends EdgeInterface<V>> Set<V> getOpenNNeighborhood( GraphInterface<V, E> graph, V vertex, int n) { Set<V> neighbors = new HashSet<V>(graph.getDegree(vertex)); neighbors.add(vertex); for (int i = 0; i < n; i++) { Set<V> newneighbors = new HashSet<V>(graph.getVertices().size()); for (V v : neighbors) { newneighbors.addAll(Utilities.getOpenNeighbourhood(graph, v)); } neighbors.addAll(newneighbors); } neighbors.remove(vertex); return neighbors; } /** * Gets the vertices of even degree. * * @param <V> * @param <E> * @param graph * @return A collection of vertices of even degree. */ public static <V, E extends EdgeInterface<V>> Collection<V> getEvenDegreeVertices( GraphInterface<V, E> graph) { ArrayList<V> vertices = new ArrayList<V>(); for (V vertex : graph.getVertices()) { if ((graph.getEdges(vertex).size() % 2) == 0) { vertices.add(vertex); } } return vertices; } /** * Gets the vertices of odd degree. * * @param <V> * @param <E> * @param graph * @return A collection of vertices of odd degree. */ public static <V, E extends EdgeInterface<V>> Collection<V> getOddDegreeVertices( GraphInterface<V, E> graph) { ArrayList<V> vertices = new ArrayList<V>(); for (V vertex : graph.getVertices()) { if ((graph.getEdges(vertex).size() % 2) == 1) { vertices.add(vertex); } } return vertices; } /** * Gets the vertices of a specified degree. * * @param <V> * @param <E> * @param graph * @param degree * specified degree. * @return A collection of vertices with a specified degree */ public static <V, E extends EdgeInterface<V>> Collection<V> getVerticesOfDegree( GraphInterface<V, E> graph, int degree) { ArrayList<V> vertices = new ArrayList<V>(); for (V vertex : graph.getVertices()) { if ((graph.getEdges(vertex).size()) == degree) { vertices.add(vertex); } } return vertices; } /** * Gets the minimum degree * * @param <V> * @param <E> * @param graph * @return minimum degree */ public static <V, E extends EdgeInterface<V>> int getMinimumDegree( GraphInterface<V, E> graph) { int degree = Integer.MAX_VALUE; for (V vertex : graph.getVertices()) { degree = Math.min(degree, graph.getEdges(vertex).size()); } return degree; } /** * Gets the maximum degree * * @param <V> * @param <E> * @param graph * @return maximum degree */ public static <V, E extends EdgeInterface<V>> int getMaximumDegree( GraphInterface<V, E> graph) { int degree = 0; for (V vertex : graph.getVertices()) { degree = Math.max(degree, graph.getEdges(vertex).size()); } return degree; } /** * Gets the diameter of the graph * * @param <V> * @param <E> * @param graph * @return diameter of the given graph */ public static <V, E extends EdgeInterface<V>> int getDiameter( GraphInterface<V, E> graph) { // TODO CHECK THIS, should use adjacency instead of weighted edges. Floyd<V, E> f = new Floyd<V, E>(graph); double[][] d = f.getD(); int max = 0; for (int i = 0; i < d.length; i++) { for (int j = 0; j < i; j++) { if (d[i][j] > max) { max = (int) d[i][j]; } } } return max; } /** * Gets the the graph has no edges. * * @param <V> * @param <E> * @param graph * @return true if the graph is empty, false otherwise. */ public static <V, E extends EdgeInterface<V>> boolean isEmpty( GraphInterface<V, E> graph) { return graph.getEdges().size() == 0; } public static <V, E extends EdgeInterface<V>> GraphInterface<V, E> constructPowerGraph( GraphInterface<V, E> graph, int n) { UndirectedGraph<V, E> retval = new UndirectedGraph<V, E>(graph .getEdgeFactory()); for (V v : graph.getVertices()) { retval.addVertex(v); } for (V v : graph.getVertices()) { Set<V> neigs = Utilities.getOpenNNeighborhood(graph, v, n); for (V u : neigs) { if (!retval.containsEdge(v, u)) { retval.addEdge(v, u); } } } return retval; } /** * Gets the density of the graph. The density of a graph is the number of * edge over the maximum number of edges in a graph of the same number of * vertices. * * @param <V> * @param <E> * @param graph * @return density of a given graph */ public static <V, E extends EdgeInterface<V>> double getDensity( GraphInterface<V, E> graph) { if (((AbstractGraph<V, E>) graph).allowMultipleEdges()) { throw new IllegalArgumentException("Graph allows multiple edge"); } if (graph instanceof DirectedGraph) { return graph.getSize() / Math.pow(2, CombinatoricUtil .nChooseK(graph.getOrder(), 2)); } if (graph instanceof UndirectedGraph) { return graph.getSize() / graph.getOrder() * (graph.getOrder() - 1) / 2; } return -1; } /** * Gets the average degree of the graph. * @param <V> * @param <E> * @param graph * @return the mean degree of the graph */ public static <V, E extends EdgeInterface<V>> double getAverageDegree( GraphInterface<V, E> graph) { long sumDegree = 0; for (V v : graph.getVertices()) { sumDegree += graph.getDegree(v); } return sumDegree / graph.getOrder(); } /** * Gets a histogram of the degrees of the graph. * @param <V> * @param <E> * @param graph * @return array of longs where the degree is the index. */ public static <V, E extends EdgeInterface<V>> long[] getDegreeHistograph( GraphInterface<V, E> graph) { long[] degrees = new long[Utilities.getMaximumDegree(graph) + 1]; for (V v : graph.getVertices()) { degrees[graph.getDegree(v)] += 1; } return degrees; } /** * Gets the degree sequence of the graph * @param <V> * @param <E> * @param graph * @return an unsorted degree sequence. */ public static <V, E extends EdgeInterface<V>> long[] getDegreeSequence( GraphInterface<V, E> graph) { long[] degrees = new long[graph.getOrder()]; int i = 0; for (V v : graph.getVertices()) { degrees[i] = graph.getDegree(v); i++; } return degrees; } /** * Checks if a set of vertices is an independent set. * @param <V> * @param <E> * @param graph * @param vertices * @return true if the set is independent, false otherwise. */ public static <V, E extends EdgeInterface<V>> boolean isIndependentSet( GraphInterface<V, E> graph, Set<V> vertices) { for (V v1 : vertices) { for (V v2 : vertices) { if (v1 != v2) { if (graph.containsEdge(v1, v2)) { return false; } } } } return true; } /** * Checks if a set of vertices is an independent set. * @param <V> * @param <E> * @param graph * @param vertices * @return true if the set is independent, false otherwise. */ @SuppressWarnings("unchecked") public static <V, E extends EdgeInterface<V>> boolean isIndependentSet( GraphInterface<V, E> graph,V...vertices) { for (V v1 : vertices) { for (V v2 : vertices) { if (v1 != v2) { if (graph.containsEdge(v1, v2)) { return false; } } } } return true; } /** * Checks if a set of vertices is a clique. * @param <V> * @param <E> * @param graph * @param vertices * @return true if the set is a clique, false otherwise. */ public static <V, E extends EdgeInterface<V>> boolean isClique( GraphInterface<V, E> graph, Set<V> vertices) { for (V v1 : vertices) { for (V v2 : vertices) { if (v1 != v2) { if (!graph.containsEdge(v1, v2)) { return false; } } } } return true; } /** * Checks if a set of vertices is a clique. * @param <V> * @param <E> * @param graph * @param vertices * @return true if the set is a clique, false otherwise. */ @SuppressWarnings("unchecked") public static <V, E extends EdgeInterface<V>> boolean isClique( GraphInterface<V, E> graph,V...vertices) { for (V v1 : vertices) { for (V v2 : vertices) { if (v1 != v2) { if (!graph.containsEdge(v1, v2)) { return false; } } } } return true; } }
Java
package annas.graph; @SuppressWarnings("serial") public class IntegerEdge implements EdgeInterface<Integer> { private Integer head; private Integer tail; public IntegerEdge() { super(); } @Override public String toString() { return this.tail + "->" + this.head; } @Override public Integer getHead() { return head; } @Override public void setHead(Integer head) { this.head = head; } @Override public Integer getTail() { return tail; } @Override public void setTail(Integer tail) { this.tail = tail; } @Override public boolean isIncident(Integer vertex) { return this.head.equals(vertex) || this.tail.equals(vertex); } @Override public Integer getOtherEndpoint(Integer vertex) { if (this.head.equals(vertex)) { return this.tail; } else if(this.tail.equals(vertex)) { return this.head; }else { return null; } } }
Java