package edu.hitsz.c102c.cnn;

import java.io.Serializable;

import edu.hitsz.c102c.util.Log;
import edu.hitsz.c102c.util.Util;

/**
 * CNN network layer.
 * 
 * @author jiqunpeng
 * 
 */
public class Layer implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private LayerType type;
	private int outMapNum; ;// output map number
	private Size mapSize;// map size 
	private Size kernelSize; // convolution kernel size, only the convolution layer
	private Size scaleSize;// sample size, only the sampling layer 
	private double[][][][] kernel; // Convolution kernel, only convolutional layer and output layer
	private double[] bias; // Each map corresponds to a bias, only the convolutional and output layers have
        // Save the output map of each batch, outmaps[0][0] represents the 0th output map of the first record training
	private double[][][][] outmaps;
        // Residual, corresponding to d in matlab toolbox
	private double[][][][] errors;

	private static int recordInBatch = 0;

	private int classNum = -1; // Category number

	private Layer() {

	}

	/**
	 * Prepare for the next batch of training·
	 */
	public static void prepareForNewBatch() {
		recordInBatch = 0;
	}

	/**
	 * Prepare the next recorded workout. 
	 */
	public static void prepareForNewRecord() {
		recordInBatch++;
	}

	/**
	 * Build impot layer.
	 * 
	 * @param mapSize
	 * @return
	 */
	public static Layer buildInputLayer(Size mapSize) {
		Layer layer = new Layer();
		layer.type = LayerType.input;
		layer.outMapNum = 1;// ÊäÈë²ãµÄmap¸öÊýΪ1£¬¼´Ò»ÕÅͼ
		layer.setMapSize(mapSize);//
		return layer;
	}

	/**
	 * Build convolution layer.
	 * 
	 * @return
	 */
	public static Layer buildConvLayer(int outMapNum, Size kernelSize) {
		Layer layer = new Layer();
		layer.type = LayerType.conv;
		layer.outMapNum = outMapNum;
		layer.kernelSize = kernelSize;
		return layer;
	}

	/**
	 * Build sampling layer.
	 * 
	 * @param scaleSize
	 * @return
	 */
	public static Layer buildSampLayer(Size scaleSize) {
		Layer layer = new Layer();
		layer.type = LayerType.samp;
		layer.scaleSize = scaleSize;
		return layer;
	}

	/**
	 * Construct the output layer, the number of categories, determine the number of output units according to the number of categories.
	 * @return
	 */
	public static Layer buildOutputLayer(int classNum) {
		Layer layer = new Layer();
		layer.classNum = classNum;
		layer.type = LayerType.output;
		layer.mapSize = new Size(1, 1);
		layer.outMapNum = classNum;
		// int outMapNum = 1;
		// while ((1 << outMapNum) < classNum)
		// outMapNum += 1;
		// layer.outMapNum = outMapNum;
		Log.i("outMapNum:" + layer.outMapNum);
		return layer;
	}

	/**
	 * Get map size.
	 * 
	 * @return
	 */
	public Size getMapSize() {
		return mapSize;
	}

	/**
	 * Set map size.
	 * 
	 * @param mapSize
	 */
	public void setMapSize(Size mapSize) {
		this.mapSize = mapSize;
	}

	/**
	 * Get type.
	 * 
	 * @return
	 */
	public LayerType getType() {
		return type;
	}

	/**
	 * Get number of maps.
	 * 
	 * @return
	 */

	public int getOutMapNum() {
		return outMapNum;
	}

	/**
	 * ÉèÖÃÊä³ömapµÄ¸öÊý
	 * 
	 * @param outMapNum
	 */
	public void setOutMapNum(int outMapNum) {
		this.outMapNum = outMapNum;
	}

	/**
	 * Get the size of the convolution kernel, only the kernel layer has kernelSize, and all other layers are null.
	 * 
	 * @return
	 */
	public Size getKernelSize() {
		return kernelSize;
	}

	/**
	 * Get sample size, only sampling layer has scaleSize, other layers are not null.
	 * 
	 * @return
	 */
	public Size getScaleSize() {
		return scaleSize;
	}

	enum LayerType {
                // The type of network layer: input layer, output layer, convolution layer, sampling layer
		input, output, conv, samp
	}

	/**
	 * Get sample size, only sampling layer has scaleSize, other layers are not null.
	 * 
	 * @author jiqunpeng
	 * 
	 */
	public static class Size implements Serializable {

		private static final long serialVersionUID = 1L;
		public final int x;
		public final int y;

		public Size(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public String toString() {
			StringBuilder s = new StringBuilder("Size(").append(" x = ")
					.append(x).append(" y= ").append(y).append(")");
			return s.toString();
		}

		/**
        	 *  Dividing scaleSize to get a new Size requires this.x, this.
                 * y can be divided by scaleSize.x, scaleSize.y
		 * @param scaleSize
		 * @return
		 */
		public Size divide(Size scaleSize) {
			int x = this.x / scaleSize.x;
			int y = this.y / scaleSize.y;
			if (x * scaleSize.x != this.x || y * scaleSize.y != this.y)
				throw new RuntimeException(this + "²»ÄÜÕû³ý" + scaleSize);
			return new Size(x, y);
		}

		/**
		 * ¼õÈ¥size´óС£¬²¢xºÍy·Ö±ð¸½¼ÓÒ»¸öÖµappend
		 * 
		 * @param size
		 * @param append
		 * @return
		 */
		public Size subtract(Size size, int append) {
			int x = this.x - size.x + append;
			int y = this.y - size.y + append;
			return new Size(x, y);
		}
	}

	/**
	 * Subtract the size size and append a value append to x and y respectively.
	 * @param frontMapNum
	 */
	public void initKernel(int frontMapNum) {
//		int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y;
//		int fan_in = frontMapNum * kernelSize.x * kernelSize.y;
//		double factor = 2 * Math.sqrt(6 / (fan_in + fan_out));
		this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y];
		for (int i = 0; i < frontMapNum; i++)
			for (int j = 0; j < outMapNum; j++)
				kernel[i][j] = Util.randomMatrix(kernelSize.x, kernelSize.y,true);
	}

	/**
	 * Randomly initialize the convolution kernel.
	 * 
	 * @param frontMapNum
	 * @param size
	 */
	public void initOutputKerkel(int frontMapNum, Size size) {
		kernelSize = size;
//		int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y;
//		int fan_in = frontMapNum * kernelSize.x * kernelSize.y;
//		double factor = 2 * Math.sqrt(6 / (fan_in + fan_out));
		this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y];
		for (int i = 0; i < frontMapNum; i++)
			for (int j = 0; j < outMapNum; j++)
				kernel[i][j] = Util.randomMatrix(kernelSize.x, kernelSize.y,false);
	}

	/**
	 * ³õʼ»¯Æ«ÖÃ
	 * 
	 * @param frontMapNum
	 */
	public void initBias(int frontMapNum) {
		this.bias = Util.randomArray(outMapNum);
	}

	/**
	 * ³õʼ»¯Êä³ömap
	 * 
	 * @param batchSize
	 */
	public void initOutmaps(int batchSize) {
		outmaps = new double[batchSize][outMapNum][mapSize.x][mapSize.y];
	}

	/**
	 * ÉèÖÃmapÖµ
	 * 
	 * @param mapNo
	 *            µÚ¼¸¸ömap
	 * @param mapX
	 *            mapµÄ¸ß
	 * @param mapY
	 *            mapµÄ¿í
	 * @param value
	 */
	public void setMapValue(int mapNo, int mapX, int mapY, double value) {
		outmaps[recordInBatch][mapNo][mapX][mapY] = value;
	}

	static int count = 0;

	/**
	 * ÒÔ¾ØÕóÐÎʽÉèÖõÚmapNo¸ömapµÄÖµ
	 * 
	 * @param mapNo
	 * @param outMatrix
	 */
	public void setMapValue(int mapNo, double[][] outMatrix) {
		// Log.i(type.toString());
		// Util.printMatrix(outMatrix);
		outmaps[recordInBatch][mapNo] = outMatrix;
	}

	/**
	 * Get the index map matrix. In performance considerations, no duplicate objects are returned, but the reference is returned directly, and the caller must be careful.
* Avoid modifying outmaps. If you need to modify, please call setMapValue(...) 
	 * @param index
	 * @return
	 */
	public double[][] getMap(int index) {
		return outmaps[recordInBatch][index];
	}

	/**
	 * Get the convolution kernel of the previous layer i map to the current layer j map.
	 * 
	 * @param i
	 *            ÉÏÒ»²ãµÄmapϱê
	 * @param j
	 *            µ±Ç°²ãµÄmapϱê
	 * @return
	 */
	public double[][] getKernel(int i, int j) {
		return kernel[i][j];
	}

	/**
	 * 
	 * @param mapNo
	 * @param mapX
	 * @param mapY
	 * @param value
	 */
	public void setError(int mapNo, int mapX, int mapY, double value) {
		errors[recordInBatch][mapNo][mapX][mapY] = value;
	}

	/**
	 * 
	 * @param mapNo
	 * @param matrix
	 */
	public void setError(int mapNo, double[][] matrix) {
		// Log.i(type.toString());
		// Util.printMatrix(matrix);
		errors[recordInBatch][mapNo] = matrix;
	}

	/**
	 *  Get the mapNo map of the residual. Does not return a copy of the object, but directly returns a reference, call the cautious,
* Avoid modifying errors. If you need to modify, please call setError(...) 
	 * @param mapNo
	 * @return
	 */
	public double[][] getError(int mapNo) {
		return errors[recordInBatch][mapNo];
	}

	/**
	 * Get all the residuals (each record and each map).
	 * 
	 * @return
	 */
	public double[][][][] getErrors() {
		return errors;
	}

	/**
	 * Initiazlie errors.
	 * 
	 * @param batchSize
	 */
	public void initErros(int batchSize) {
		errors = new double[batchSize][outMapNum][mapSize.x][mapSize.y];
	}

	/**
	 * 
	 * @param lastMapNo
	 * @param mapNo
	 * @param kernel
	 */
	public void setKernel(int lastMapNo, int mapNo, double[][] kernel) {
		this.kernel[lastMapNo][mapNo] = kernel;
	}

	/**
	 * Get Bias.
	 * 
	 * @param mapNo
	 * @return
	 */
	public double getBias(int mapNo) {
		return bias[mapNo];
	}

	/**
	 * Set bias.
	 * 
	 * @param mapNo
	 * @param value
	 */
	public void setBias(int mapNo, double value) {
		bias[mapNo] = value;
	}

	/**
	 * »ñÈ¡batch¸÷¸ömap¾ØÕó
	 * 
	 * @return
	 */

	public double[][][][] getMaps() {
		return outmaps;
	}

	/**
	 * Get the residual of mapNo in the recordId record.
	 * 
	 * @param recordId
	 * @param mapNo
	 * @return
	 */
	public double[][] getError(int recordId, int mapNo) {
		return errors[recordId][mapNo];
	}

	/**
	 * Set map.
	 * 
	 * @param recordId
	 * @param mapNo
	 * @return
	 */
	public double[][] getMap(int recordId, int mapNo) {
		return outmaps[recordId][mapNo];
	}

	/**
	 * Get type.
	 * 
	 * @return
	 */
	public int getClassNum() {
		return classNum;
	}

	/**
	 * Get kernel.
	 * 
	 * @return
	 */
	public double[][][][] getKernel() {
		return kernel;
	}

}

 

Ads help maintain this website.