// Support functions

        private void LoadNetworkDescription(StreamReader FileStream)
        {
            string line;

            while ((line = FileStream.ReadLine()) != null && line != "Data")
            {
                // convert string to int
                int x;
                Int32.TryParse(line, out x);
                NetworkDescription.Add(x);
            }

            // Check loaded data validity
            if (NetworkDescription.Count < 2)
            {
                throw new Exception("The description of neural net you have entered is not valid!\n\nA valid description must contain at least two values:\n   The number of inputs into the network\n   The number of output neurons\n\n In both cases the minimum value allowed is 1!\n\n");
            }

            for (int Layer = 0; Layer < NetworkDescription.Count; Layer++)
            {
                if (NetworkDescription[Layer] < 1)
                {
                    throw new Exception("The description of neural net you have entered is not valid!\n\nA valid description must contain at least two values:\n   The number of inputs into the network\n   The number of output neurons\n\n In both cases the minimum value allowed is 1!\n\n");
                }
            }
        }
示例#2
0
        /// <summary>
        ///  Get max number of "non-restrictionusage" parameters which restrictions has.
        /// </summary>
        /// <param name="description">Network description.</param>
        /// <param name="restrictions">List of restrictions.</param>
        /// <returns>Max number.</returns>
        private int _GetNonRestrictionParametersMaximumCount(NetworkDescription description,
                                                             ICollection <Restriction> restrictions)
        {
            var count = 0;
            ICollection <NetworkAttribute> networkAttributes =
                description.NetworkAttributes;

            foreach (NetworkAttribute attribute in networkAttributes)
            {
                if (attribute.UsageType == NetworkAttributeUsageType.Restriction &&
                    _IsRestrictionEditable(attribute.Name, restrictions))
                {
                    var attributeParametersCount = attribute.Parameters.Count;

                    // If attribute have restrictionusage parameter - reduce number of parameters.
                    if (attribute.RestrictionUsageParameter != null)
                    {
                        attributeParametersCount--;
                    }

                    count = Math.Max(attributeParametersCount, count);
                }
            }

            return(count);
        }
示例#3
0
        /// <summary>
        /// React on DataGridCollectionViewSource CommittingEdit.
        /// </summary>
        /// <param name="sender">Ignored.</param>
        /// <param name="e">Data grid item cancel event arguments </param>
        private void DataGridCollectionViewSource_CommittingEdit(object sender,
                                                                 DataGridItemCancelEventArgs e)
        {
            try
            {
                var selectedItem = xceedGrid.CurrentItem as RestrictionDataWrapper;

                IVrpSolver         solver             = App.Current.Solver;
                SolverSettings     solverSettings     = solver.SolverSettings;
                NetworkDescription networkDescription = solver.NetworkDescription;

                ICollection <NetworkAttribute> networkAttributes =
                    networkDescription.NetworkAttributes;
                foreach (NetworkAttribute attribute in networkAttributes)
                {
                    if (selectedItem.Restriction.Name.Equals(attribute.Name,
                                                             StringComparison.OrdinalIgnoreCase))
                    {
                        ICollection <NetworkAttributeParameter> paramColl = attribute.Parameters;
                        Debug.Assert(null != paramColl);
                        _UpdateValue(selectedItem, solverSettings, attribute);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            e.Handled = true;
        }
示例#4
0
        /// <summary>
        /// Does validate.
        /// </summary>
        /// <param name="value">Value to validation.</param>
        /// <param name="culture">Culture info.</param>
        /// <param name="context">Cell validation context.</param>
        /// <returns>Validation result.</returns>
        public override ValidationResult Validate(object value,
                                                  CultureInfo culture,
                                                  CellValidationContext context)
        {
            bool isValid = true;

            string             newValue           = value as string;
            IVrpSolver         solver             = App.Current.Solver;
            NetworkDescription networkDescription = solver.NetworkDescription;

            if (newValue != null && networkDescription != null)
            {
                var wrapper = context.DataItem as RestrictionDataWrapper;

                ICollection <NetworkAttribute> networkAttributes = networkDescription.NetworkAttributes;
                foreach (NetworkAttribute attribute in networkAttributes)
                {
                    // If it is current attribute - find parameter to validate.
                    if (wrapper.Restriction.Name.Equals(attribute.Name,
                                                        StringComparison.OrdinalIgnoreCase))
                    {
                        Debug.Assert(null != attribute.Parameters);
                        NetworkAttributeParameter[] parameters = attribute.Parameters.ToArray();

                        int paramIndex = Parameters.GetIndex(context.Cell.FieldName);

                        // If parameter index was found.
                        if (paramIndex != -1)
                        {
                            var parameter = wrapper.Parameters[paramIndex];

                            // Get corresponding network attribute parameter
                            // and check that value can be converted to parameter type.
                            NetworkAttributeParameter param = parameters.FirstOrDefault(
                                x => x.Name == parameter.Name);

                            // If string is not empty or if parameter doesn't accept empty string -
                            // try to convert value.
                            if ((string)value != string.Empty || !param.IsEmptyStringValid)
                            {
                                try
                                {
                                    Convert.ChangeType(value, param.Type); // NOTE: ignore result
                                }
                                catch
                                {
                                    isValid = false;
                                }
                            }
                        }

                        break;
                    }
                }
            }

            return((isValid) ? ValidationResult.ValidResult :
                   new ValidationResult(false, App.Current.FindString("NotValidValueText")));
        }
示例#5
0
 private Task CreateNetworkAsyncHelper(string networkName, NetworkDescription networkDescription, TimeSpan timeout, CancellationToken cancellationToken)
 {
     return(Utility.WrapNativeAsyncInvokeInMTA(
                (callback) => this.CreateNetworkBeginWrapper(networkName, networkDescription, timeout, callback),
                this.CreateNetworkEndWrapper,
                cancellationToken,
                "NetworkManager.CreateNetworkAsync"));
 }
示例#6
0
            /// <summary>
            ///   <para>Creates the specific Service Fabric container network.</para>
            /// </summary>
            /// <param name="networkName">
            ///   <para>The name of the container network.</para>
            /// </param>
            /// <param name="networkDescription">
            ///   <para>The description of the container network.</para>
            /// <param name="timeout">
            /// <para>Defines the maximum amount of time the system will allow this operation to continue before returning <see cref="System.TimeoutException" />.</para>
            /// </param>
            /// </param>
            /// <param name="cancellationToken">
            /// <para>The CancellationToken that the operation is observing. It can be used to propagate notification that the operation should be canceled.</para>
            /// </param>
            /// <returns>
            ///   <para>A <see cref="System.Threading.Tasks.Task" /> representing the operation.</para>
            /// </returns>
            public Task CreateNetworkAsync(string networkName, NetworkDescription networkDescription, TimeSpan timeout, CancellationToken cancellationToken)
            {
                this.fabricClient.ThrowIfDisposed();
                Requires.Argument <string>("networkName", networkName).NotNullOrWhiteSpace();
                Requires.Argument <NetworkDescription>("networkDescription", networkDescription).NotNull();
                NetworkDescription.Validate(networkDescription);

                return(this.CreateNetworkAsyncHelper(networkName, networkDescription, timeout, cancellationToken));
            }
示例#7
0
        /// <summary>
        /// Inits data grid.
        /// </summary>
        private void _InitDataGrid()
        {
            try
            {
                // If active schedule hasn't been set - do it.
                if (App.Current.Project != null &&
                    App.Current.Project.Schedules.ActiveSchedule == null)
                {
                    // Load schedule for current date.
                    var currentSchedule = OptimizeAndEditHelpers.LoadSchedule(
                        App.Current.Project,
                        App.Current.CurrentDate,
                        OptimizeAndEditHelpers.FindScheduleToSelect);

                    // If current date schedule have routes -
                    // select current schedule as active.
                    if (currentSchedule.Routes.Count > 0)
                    {
                        App.Current.Project.Schedules.ActiveSchedule = currentSchedule;
                    }
                }

                _ClearGridSource();

                IVrpSolver                solver         = App.Current.Solver;
                SolverSettings            solverSettings = solver.SolverSettings;
                ICollection <Restriction> restrictions   = solverSettings.Restrictions;
                if (0 < restrictions.Count)
                {
                    NetworkDescription networkDescription = solver.NetworkDescription;

                    // Obtain max "non-restriction" parameters count.
                    int maxParametersCount = _GetNonRestrictionParametersMaximumCount(
                        networkDescription, restrictions);

                    _InitDataGridLayout(maxParametersCount);
                }
            }
            catch (Exception ex)
            {
                Logger.Critical(ex);
            }
        }
 public void Dispose_Of_Network()
 {
     NetworkDescription.Clear();
     NeuralNetwork.Clear();
 }
示例#9
0
        /// <summary>
        /// Inits grid source.
        /// </summary>
        /// <param name="maxParametersCount">Maximum number of attribute parameters.</param>
        /// <param name="collectionSource">Data grid collection source.</param>
        private void _InitGridSource(int maxParametersCount,
                                     DataGridCollectionViewSource collectionSource)
        {
            IVrpSolver                solver             = App.Current.Solver;
            SolverSettings            solverSettings     = solver.SolverSettings;
            NetworkDescription        networkDescription = solver.NetworkDescription;
            ICollection <Restriction> restrictions       = solverSettings.Restrictions;

            var restrictionWrappers = new List <RestrictionDataWrapper>();

            var networkAttributes = networkDescription.NetworkAttributes;

            foreach (NetworkAttribute attribute in networkAttributes)
            {
                if (attribute.UsageType == NetworkAttributeUsageType.Restriction)
                {
                    Restriction restriction = _FindRestriction(attribute.Name, restrictions);
                    if (restriction.IsEditable)
                    {
                        Debug.Assert(null != attribute.Parameters);

                        // Create collection of all non "restriction usage" attribute parameters.
                        IList <NetworkAttributeParameter> attrParams;
                        if (attribute.RestrictionUsageParameter != null)
                        {
                            attrParams = attribute.Parameters.Where(
                                param => param.Name != attribute.RestrictionUsageParameter.Name).ToList();
                        }
                        else
                        {
                            attrParams = attribute.Parameters.ToList();
                        }

                        var parameters = new Parameters(maxParametersCount);
                        for (int index = 0; index < maxParametersCount; ++index)
                        {
                            string value = null;
                            if (index < attrParams.Count())
                            {
                                NetworkAttributeParameter param = attrParams.ElementAt(index);
                                value             = _GetParameterValue(attribute.Name, param.Name, solverSettings);
                                parameters[index] = new Parameter(param.Name, value);
                            }
                            else
                            {
                                parameters[index] = new Parameter();
                            }
                        }

                        // Create wrapper for restriction.
                        var wrapper = new RestrictionDataWrapper(restriction.IsEnabled,
                                                                 restriction.NetworkAttributeName,
                                                                 restriction.Description, parameters);

                        // If attribute has restriction usage parameter - add this parameter
                        // to wrapper.
                        if (attribute.RestrictionUsageParameter != null)
                        {
                            var restrictionUsageParameterValue = _GetParameterValue(attribute.Name,
                                                                                    attribute.RestrictionUsageParameter.Name, solverSettings);
                            var restrictionParameter = new Parameter(attribute.RestrictionUsageParameter.Name,
                                                                     restrictionUsageParameterValue);
                            wrapper.RestrictionUsageParameter = restrictionParameter;
                        }

                        restrictionWrappers.Add(wrapper);
                    }
                }
            }

            collectionSource.Source = restrictionWrappers;
        }
示例#10
0
        private IEnumerator TrainingProcess()
        {
            var neuralNetworkConfig = new NetworkDescription()
            {
                Layers = new List <LayerParamaters>()
                {
                    new LayerParamaters()
                    {
                        LayerType   = ELayerType.Input,
                        NeuronCount = InputAttributeCount,
                        NeuronType  = ENeruonType.Input
                    },
                    new LayerParamaters()
                    {
                        LayerType   = ELayerType.Hidden,
                        NeuronCount = 64,
                        NeuronType  = ENeruonType.Sigmoid
                    },
                    new LayerParamaters()
                    {
                        LayerType   = ELayerType.Hidden,
                        NeuronCount = 16,
                        NeuronType  = ENeruonType.Sigmoid
                    },
                    new LayerParamaters()
                    {
                        LayerType   = ELayerType.Output,
                        NeuronCount = 1,
                        NeuronType  = ENeruonType.Sigmoid
                    },
                }
            };

            var neuralNetwork = new NeuralNetwork(neuralNetworkConfig);

            neuralNetwork.InitNetworkWithRandomValues(-0.05f, 0.05f);

            var networkEvaluator = new NetworkEvaluator(neuralNetwork);


            var tempResult = new NativeArray2D <float>(1, 1);

            //Test inital accuracy
            TestInitialAccuracy(networkEvaluator, tempResult.Slice());

            //Learn over a number of iterations
            for (int epoch = 0; epoch < Epochs; epoch++)
            {
                //For each epoch, perform training
                for (int tc = 0; tc < _dataset.TrainingSetSize; tc++)
                {
                    _dataset.GetTrainingCase(tc, out var trainingInput, out var trainingResult);

                    //Evolve network
                    var jobHandle = networkEvaluator.GradientDescentBackpropigate(trainingInput, trainingResult, 1, out _);
                    jobHandle.Complete();
                }

                float totalError   = 0.0f;
                int   totalCorrect = 0;

                for (int i = 0; i < _dataset.TestingSetSize; i++)
                {
                    _dataset.GetTestCase(i, out var trainingInput, out var trainingResult);
                    networkEvaluator.Evaluate(trainingInput, tempResult.Slice(), 1).Complete();

                    var  error      = Math.Abs(tempResult[0, 0] - trainingResult[0, 0]);
                    bool wasCorrect = error < 0.5f;
                    totalCorrect += wasCorrect ? 1 : 0;
                    totalError   += error;
                }

                float averageError = totalError / (float)_dataset.TestingSetSize;
                float accuracy     = (float)totalCorrect / (float)_dataset.TestingSetSize;

                //Forward test
                Debug.Log($"Epoch {epoch}: Accuracy:{accuracy:P2}  Average Error:{averageError:F4}");

                yield return(null);
            }

            tempResult.BackingStore.Dispose();
        }
示例#11
0
 /// <summary>
 ///   <para>Creates the specific Service Fabric container network.</para>
 /// </summary>
 /// <param name="networkName">
 ///   <para>The name of the container network.</para>
 /// </param>
 /// <param name="networkDescription">
 ///   <para>The description of the container network.</para>
 /// </param>
 /// <returns>
 ///   <para>A <see cref="System.Threading.Tasks.Task" /> representing the operation.</para>
 /// </returns>
 public Task CreateNetworkAsync(string networkName, NetworkDescription networkDescription)
 {
     return(this.CreateNetworkAsync(networkName, networkDescription, FabricClient.DefaultTimeout, CancellationToken.None));
 }
示例#12
0
 private NativeCommon.IFabricAsyncOperationContext CreateNetworkBeginWrapper(string networkName, NetworkDescription networkDescription, TimeSpan timeout, NativeCommon.IFabricAsyncOperationCallback callback)
 {
     using (var pin = new PinCollection())
     {
         return(this.nativeNetworkManagementClient.BeginCreateNetwork(
                    pin.AddObject(networkName),
                    networkDescription.ToNative(pin),
                    Utility.ToMilliseconds(timeout, "timeout"),
                    callback));
     }
 }