001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.math4.ml.neuralnet.oned;
019
020import java.io.Serializable;
021import java.io.ObjectInputStream;
022
023import org.apache.commons.math4.exception.NumberIsTooSmallException;
024import org.apache.commons.math4.exception.OutOfRangeException;
025import org.apache.commons.math4.ml.neuralnet.FeatureInitializer;
026import org.apache.commons.math4.ml.neuralnet.Network;
027
028/**
029 * Neural network with the topology of a one-dimensional line.
030 * Each neuron defines one point on the line.
031 *
032 * @since 3.3
033 */
034public class NeuronString implements Serializable {
035    /** Serial version ID */
036    private static final long serialVersionUID = 1L;
037    /** Underlying network. */
038    private final Network network;
039    /** Number of neurons. */
040    private final int size;
041    /** Wrap. */
042    private final boolean wrap;
043
044    /**
045     * Mapping of the 1D coordinate to the neuron identifiers
046     * (attributed by the {@link #network} instance).
047     */
048    private final long[] identifiers;
049
050    /**
051     * Constructor with restricted access, solely used for deserialization.
052     *
053     * @param wrap Whether to wrap the dimension (i.e the first and last
054     * neurons will be linked together).
055     * @param featuresList Arrays that will initialize the features sets of
056     * the network's neurons.
057     * @throws NumberIsTooSmallException if {@code num < 2}.
058     */
059    NeuronString(boolean wrap,
060                 double[][] featuresList) {
061        size = featuresList.length;
062
063        if (size < 2) {
064            throw new NumberIsTooSmallException(size, 2, true);
065        }
066
067        this.wrap = wrap;
068
069        final int fLen = featuresList[0].length;
070        network = new Network(0, fLen);
071        identifiers = new long[size];
072
073        // Add neurons.
074        for (int i = 0; i < size; i++) {
075            identifiers[i] = network.createNeuron(featuresList[i]);
076        }
077
078        // Add links.
079        createLinks();
080    }
081
082    /**
083     * Creates a one-dimensional network:
084     * Each neuron not located on the border of the mesh has two
085     * neurons linked to it.
086     * <br>
087     * The links are bi-directional.
088     * Neurons created successively are neighbours (i.e. there are
089     * links between them).
090     * <br>
091     * The topology of the network can also be a circle (if the
092     * dimension is wrapped).
093     *
094     * @param num Number of neurons.
095     * @param wrap Whether to wrap the dimension (i.e the first and last
096     * neurons will be linked together).
097     * @param featureInit Arrays that will initialize the features sets of
098     * the network's neurons.
099     * @throws NumberIsTooSmallException if {@code num < 2}.
100     */
101    public NeuronString(int num,
102                        boolean wrap,
103                        FeatureInitializer[] featureInit) {
104        if (num < 2) {
105            throw new NumberIsTooSmallException(num, 2, true);
106        }
107
108        size = num;
109        this.wrap = wrap;
110        identifiers = new long[num];
111
112        final int fLen = featureInit.length;
113        network = new Network(0, fLen);
114
115        // Add neurons.
116        for (int i = 0; i < num; i++) {
117            final double[] features = new double[fLen];
118            for (int fIndex = 0; fIndex < fLen; fIndex++) {
119                features[fIndex] = featureInit[fIndex].value();
120            }
121            identifiers[i] = network.createNeuron(features);
122        }
123
124        // Add links.
125        createLinks();
126    }
127
128    /**
129     * Retrieves the underlying network.
130     * A reference is returned (enabling, for example, the network to be
131     * trained).
132     * This also implies that calling methods that modify the {@link Network}
133     * topology may cause this class to become inconsistent.
134     *
135     * @return the network.
136     */
137    public Network getNetwork() {
138        return network;
139    }
140
141    /**
142     * Gets the number of neurons.
143     *
144     * @return the number of neurons.
145     */
146    public int getSize() {
147        return size;
148    }
149
150    /**
151     * Retrieves the features set from the neuron at location
152     * {@code i} in the map.
153     *
154     * @param i Neuron index.
155     * @return the features of the neuron at index {@code i}.
156     * @throws OutOfRangeException if {@code i} is out of range.
157     */
158    public double[] getFeatures(int i) {
159        if (i < 0 ||
160            i >= size) {
161            throw new OutOfRangeException(i, 0, size - 1);
162        }
163
164        return network.getNeuron(identifiers[i]).getFeatures();
165    }
166
167    /**
168     * Creates the neighbour relationships between neurons.
169     */
170    private void createLinks() {
171        for (int i = 0; i < size - 1; i++) {
172            network.addLink(network.getNeuron(i), network.getNeuron(i + 1));
173        }
174        for (int i = size - 1; i > 0; i--) {
175            network.addLink(network.getNeuron(i), network.getNeuron(i - 1));
176        }
177        if (wrap) {
178            network.addLink(network.getNeuron(0), network.getNeuron(size - 1));
179            network.addLink(network.getNeuron(size - 1), network.getNeuron(0));
180        }
181    }
182
183    /**
184     * Prevents proxy bypass.
185     *
186     * @param in Input stream.
187     */
188    private void readObject(ObjectInputStream in) {
189        throw new IllegalStateException();
190    }
191
192    /**
193     * Custom serialization.
194     *
195     * @return the proxy instance that will be actually serialized.
196     */
197    private Object writeReplace() {
198        final double[][] featuresList = new double[size][];
199        for (int i = 0; i < size; i++) {
200            featuresList[i] = getFeatures(i);
201        }
202
203        return new SerializationProxy(wrap,
204                                      featuresList);
205    }
206
207    /**
208     * Serialization.
209     */
210    private static class SerializationProxy implements Serializable {
211        /** Serializable. */
212        private static final long serialVersionUID = 20130226L;
213        /** Wrap. */
214        private final boolean wrap;
215        /** Neurons' features. */
216        private final double[][] featuresList;
217
218        /**
219         * @param wrap Whether the dimension is wrapped.
220         * @param featuresList List of neurons features.
221         * {@code neuronList}.
222         */
223        SerializationProxy(boolean wrap,
224                           double[][] featuresList) {
225            this.wrap = wrap;
226            this.featuresList = featuresList;
227        }
228
229        /**
230         * Custom serialization.
231         *
232         * @return the {@link NeuronString} for which this instance is the proxy.
233         */
234        private Object readResolve() {
235            return new NeuronString(wrap,
236                                    featuresList);
237        }
238    }
239}