/// <summary>
        /// Creates the fitness. Must be overriden
        /// </summary>
        /// <returns>
        /// The fitness
        /// </returns>
        public virtual IFitness CreateFitness()
        {
            AFitness f = new AFitness();

            f.FitnessFuncToPass = c =>
            {
                GADataSet.SolutionsDataTable sols            = new GADataSet.SolutionsDataTable();
                GADataSet.SolutionsRow       currentSolution = sols.NewSolutionsRow();
                // GADataSet.SolutionsDataTable sols = new GADataSet.SolutionsDataTable();

                // GADataSet.SolutionsRow currentSolution = sols.NewSolutionsRow();

                currentSolution.Initialize(c.GetGenes());
                currentSolution.ProblemID = PROBLEMID;

                //  initializeRows(ref currentSolution, ref c);

                FillBasic(ref currentSolution);

                double fit = currentSolution.Fitness; //STORE THE VALUE OF FITNESS
                sols.Dispose();

                return(fit);
            };

            return(f);
        }
示例#2
0
        /// <summary>
        /// BASIC CALCULATION NECESSARY FOR FITNESS
        /// </summary>
        /// <param name="r"></param>
        /// <param name="c"></param>
        public override void FillBasic(ref GADataSet.SolutionsRow r)
        {
            GADataSet.DataRow d = r.DataAxuliar.NewDataRow();
            r.DataAxuliar.AddDataRow(d);
            //auxiliar data row
            for (int i = 0; i < VariableNames.Length; i++)
            {
                //Field A, B or C
                double dummy = Aid.SetBasic(r.GenesAsInts, ProblemData, VariableNames[i]);
                d.SetField(VariableNames[i], dummy); //first
                                                     //save total in a dataauxiliar Row
            }

            DataRow row = d;

            object[] results = findFines(ref row);
            r.Okays = results[0] as string;
            double fine = Convert.ToDouble(results[1]);

            r.Okays   += " " + Decimal.Round(Convert.ToDecimal(fine), 3);
            r.Fitness  = d.C;
            r.Fitness /= (1 + fine); //max vol, max value * (1+fine)

            r.Genotype = Aid.SetStrings(r.GenesAsInts);
        }
        private void fillStrings()
        {
            GADataSet ds = GARow.Table.DataSet as GADataSet;

            for (int i = 0; i < listOfSolutions.Count; i++)
            {
                GADataSet.SolutionsRow currentSolution = listOfSolutions.ElementAt(i);

                GADataSet.StringsRow currentString;
                currentString = ds.Strings.NewStringsRow();
                currentString.Initialize();
                ds.Strings.AddStringsRow(currentString);

                currentString.GAID       = currentSolution.GAID;
                currentString.ProblemID  = currentSolution.ProblemID;
                currentString.SolutionID = currentSolution.ID;

                currentSolution.Counter = 1;

                //decode
                FillStrings(ref currentSolution, ref currentString);

                //  GNUPLOT(ref currentSolution);
                //assign string ID... //this should be better
            }
        }
示例#4
0
        public override void FillStrings <T>(ref GADataSet.SolutionsRow r, ref T stringRow)
        {
            GADataSet.StringsRow s = stringRow as GADataSet.StringsRow;
            s.AString = String.Join(" ", r.DataAxuliar.Select(d => Aid.DecimalTxt(d.A)));
            s.BString = String.Join(" ", r.DataAxuliar.Select(d => Aid.DecimalTxt(d.B)));

            s.CString = String.Join(" ", r.DataAxuliar.Select(d => Aid.DecimalTxt(d.C)));
        }
        /// <summary>
        /// Generic RunWorker Completed for the background worker
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private static void GNUPLOT(ref GADataSet.SolutionsRow s)
        {
            string script = "set grid\n";

            script += "set title 'Trajectories'\n";
            script += "set xlabel 'X'\n";
            script += "set ylabel 'Y'\n";

            GADataSet.DataRow[] data = s.ProblemsRow.GetKnapDataRows();
            double min = data.Min(o => o.A);
            double max = data.Max(o => o.A);

            script += "set xrange[" + (min - 1) + ":" + (max + 1) + "]\n";
            min     = data.Min(o => o.B);
            max     = data.Max(o => o.B);
            script += "set yrange[" + (min - 1) + ":" + (max + 1) + "]\n";

            script += "set terminal gif animate delay 100\n";
            script += "set output FILENAME\n";

            //get genotype string
            string[] a = s.Genotype.Split(' ');

            //clean nulls
            a = a.Where(o => !string.IsNullOrEmpty(o)).ToArray();

            //make a data .txt file with A,B,C points
            for (int i = 0; i < a.Length; i++)
            {
                // if (string.IsNullOrEmpty(a[i])) continue;
                string aa = data.ElementAt(Convert.ToInt32(a[i]) - 1).A + "\t";
                aa += data.ElementAt(Convert.ToInt32(a[i]) - 1).B + "\t";
                aa += data.ElementAt(Convert.ToInt32(a[i]) - 1).C;
                // string fileindex = i;
                script += "plot '" + i + ".txt' using 1:2:3 with points palette pointsize 2 pointtype 5\n";
                System.IO.File.WriteAllText(i + ".txt", aa);
            }

            //make gnuplot script file
            string scriptFile = Guid.NewGuid().ToString().Substring(0, 6);

            System.IO.File.WriteAllText(scriptFile + ".gp", script);

            //execute gnuplot
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName    = "gnuplot";
            p.StartInfo.Arguments   = "-e \"FILENAME='" + scriptFile + ".gif'\" " + scriptFile + ".gp";
            p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            p.Start();
            p.WaitForExit();

            //add image to Chromosome
            s.Chromosome = System.IO.File.ReadAllBytes(scriptFile + ".gif");
        }
示例#6
0
 public override void FillStrings <T>(ref GADataSet.SolutionsRow r, ref T s)
 {
     for (int i = 0; i < VariableNames.Length; i++)
     {
         string  dummy = Aid.DecodeStrings(r.GenesAsInts, ProblemData, VariableNames[i]);
         string  field = VariableNames[i] + "String";
         DataRow row   = s as DataRow;
         if (row.Table.Columns.Contains(field))
         {
             row.SetField(field, dummy); //first
         }
     }
 }
示例#7
0
文件: Aid.cs 项目: fulviofarina/GAlgo
        /// <summary>
        /// FUNCTION TO PERFORM AVERAGE AND HISTOGRAM
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="problema"></param>
        public static void DoStatistics <T>(T problema)
        {
            GADataSet.ProblemsRow currentProblem = problema as GADataSet.ProblemsRow;

            IEnumerable <GADataSet.GARow> gasrows = currentProblem.GetGARows();

            int min = gasrows.Min(o => o.ChromosomeLength);
            int max = gasrows.Max(o => o.ChromosomeLength);

            HashSet <string> hash;
            List <GADataSet.SolutionsRow> list;

            //    List<GADataSet.StringsRow> strs;
            hash = new HashSet <string>();
            list = new List <GADataSet.SolutionsRow>();
            //    strs = new List<GADataSet.StringsRow>();

            //create lamda expression to filter
            Func <GADataSet.SolutionsRow, bool> funcion;

            funcion = FilterByGenotype(ref hash, ref list);

            //iterate min max chromosome lenght for all genetic algorithms
            for (int j = min; j <= max; j++)
            {
                gasrows = currentProblem.GetGARows();

                IEnumerable <GADataSet.GARow> subs = gasrows
                                                     .Where(o => o.ChromosomeLength == j)
                                                     .ToList();

                GADataSet.GARow subFirst = subs.FirstOrDefault();
                subFirst.AverageGA(ref subs);

                //select GARow childrens
                IEnumerable <GADataSet.SolutionsRow> knaprows = subs
                                                                .SelectMany(o => o.GetSolutionsRows()).ToList();

                hash.Clear(); //clear
                list.Clear(); //clear

                foreach (GADataSet.SolutionsRow item in knaprows)
                {
                    funcion(item);
                }

                double bestFitness = list.Max(o => o.Fitness);
                subFirst.Fitness = bestFitness;

                int count = knaprows.Count();

                for (int d = knaprows.Count() - 1; d >= 0; d--)
                {
                    GADataSet.SolutionsRow s = knaprows.ElementAt(d);
                    if (s.ShouldDelete)
                    {
                        if (s.StringsRowParent != null)
                        {
                            s.StringsRowParent.Delete();
                        }
                        s.Delete();
                    }
                    else
                    {
                        s.GAID         = subFirst.ID;
                        s.Generations /= s.Counter;
                        s.TimeSpan    /= s.Counter;
                    }
                }

                count = subs.Count();
                for (int d = subs.Count() - 1; d >= 1; d--)
                {
                    subs.ElementAt(d).Delete();
                }
            }
        }
 /// <summary>
 /// DECODES THE CHROMOSOME DATA CALCULATIONS INTO STRINGS OF TEXT
 /// Fills the Strings Table based on the variableNames
 /// Needs to be overriden
 /// </summary>
 /// <typeparam name="T">DataRow of StringsTable</typeparam>
 /// <param name="r">Solutions row</param>
 /// <param name="s">DataRow of stringsTable to fill, e.g. Strings</param>
 public abstract void FillStrings <T>(ref GADataSet.SolutionsRow r, ref T s);
 /// <summary>
 /// Finds the fitness and Fine for the chromosome
 /// Function necessary during Fitness.Evaluation()
 /// Function necessary during PostScript printing
 /// Needs to be overriden
 /// </summary>
 /// <param name="r"></param>
 /// <param name="s"></param>
 /// <param name="c"></param>
 public abstract void FillBasic(ref GADataSet.SolutionsRow r);
示例#10
0
        /// <summary>
        /// BASIC CALCULATION NECESSARY FOR FITNESS
        /// </summary>
        /// <param name="r"></param>
        /// <param name="c"></param>
        public override void FillBasic(ref GADataSet.SolutionsRow r)
        {
            int badRoute = 1;

            HashSet <int> nonRepeated = new HashSet <int>();

            r.GenesAsInts.Where(o => nonRepeated.Add(o)).ToList();

            double  Fine = 0;
            DataRow cond = Conditions.FirstOrDefault();

            //if non-repeated list counts to number of variables.. OK!
            if (nonRepeated.Count == ProblemData.Count())
            {
                try
                {
                    List <int> fullList = nonRepeated.ToList();
                    fullList.Add(0); //adds origin to the end

                    //create rows for subtable Data auxiliar
                    for (int j = 0; j < fullList.Count; j++)
                    {
                        GADataSet.DataRow d = r.DataAxuliar.NewDataRow();
                        r.DataAxuliar.AddDataRow(d);
                        //auxiliar data row
                        for (int i = 0; i < VariableNames.Length; i++)
                        {
                            //Field A, B or C
                            string varField = VariableNames[i];
                            double var      = Aid.SetDifferences(cond, fullList, j, ProblemData, varField);
                            d.SetField <double>(varField, var); //set Distance Differences for A or B
                        }
                    }

                    foreach (GADataSet.DataRow item in r.DataAxuliar)
                    {
                        double a2 = Math.Pow(item.A, 2); //x^2
                        double b2 = Math.Pow(item.B, 2); //y^2
                        item.C = Math.Sqrt(a2 + b2);     //distance = sqrt (x^2,y^2)
                    }
                    //put total distance parcourred
                    double totalDistance = r.DataAxuliar.Sum(i => i.C);

                    Fine = totalDistance / (r.DataAxuliar.Count * 10);

                    fullList.Insert(0, 0);

                    foreach (GADataSet.ConditionsRow c in Conditions)
                    {
                        string prohibited = c.MinC.ToString() + c.MaxC.ToString();
                        string genotype   = String.Join("", fullList.Select(o => o));
                        if (genotype.Contains(prohibited))
                        {
                            badRoute++;
                        }
                    }

                    //   if (s.Fine > 1 && badRoute>1) s.Fine = 0.80;
                    if (Fine > 1)
                    {
                        Fine = 0.90;
                    }

                    fullList.Clear();
                    fullList = null;
                }
                catch (SystemException ex)
                {
                    // e = ex.StackTrace;
                }
            }
            else
            {
                Fine = cond.Field <double>("CFine"); //a million
            }
            nonRepeated.Clear();
            nonRepeated = null;

            r.Okays = badRoute.ToString() + " " + Decimal.Round(Convert.ToDecimal(Fine), 3);

            r.Fitness = 1 - Fine; //max vol, max value * (1+fine)

            r.Fitness /= badRoute;

            r.Genotype = Aid.SetStrings(r.GenesAsInts);
        }
示例#11
0
        /// <summary>
        /// BASIC CALCULATION NECESSARY FOR FITNESS
        /// </summary>
        /// <param name="r"></param>
        /// <param name="c"></param>
        public override void FillBasic(ref GADataSet.SolutionsRow r)
        {
            y[] func = new y[5];

            func[0] = y1;
            func[1] = y2;
            func[2] = y3;
            func[3] = y4;
            func[4] = y5;

            // int badRoute = 1;

            // HashSet<int> nonRepeated = new HashSet<int>();

            //  r.GenesAsInts.Where(o => nonRepeated.Add(o)).ToList();

            //  string e = string.Empty;
            double Fine = 0;

            double[] ai = r.GenesAsDoubles.ToArray();

            double[] yi = new double[ai.Length];
            double[] di = new double[ai.Length];

            for (int i = 0; i < di.Length; i++)
            {
                di[i] = yi[i] = 0;
            }
            for (int i = 1; i < ai.Length; i++)
            {
                ai[i] *= 5;
            }

            foreach (DataRow d in this.ProblemData)
            {
                double x    = d.Field <double>("A");
                double yexp = d.Field <double>("B");

                //  for (int i = 1; i < ai.Length; i++)
                {
                    //  yi[0] = y1(ai, x);
                    //  yi[1] = y2(ai, x);
                    //  yi[2] = y3(ai, x);
                    //  yi[3] = y4(ai, x);
                    //  yi[4] = y5(ai, x);
                    int index = Convert.ToInt32(ai[0]);
                    yi[0]  = func[index](ai, x);
                    di[0] += Math.Pow(yexp - yi[0], 2);
                    // di[1] += Math.Pow(yexp - yi[1], 2);
                    //  di[2] += Math.Pow(yexp - yi[2], 2);
                    // di[3] += Math.Pow(yexp - yi[3], 2);
                    // di[4] += Math.Pow(yexp - yi[4], 2);
                }
            }

            /*
             * int goodEq = 0;
             * double last = 10000;
             * for (int i = 0; i < di.Length; i++)
             * {
             *  if (di[i] < last)
             *  {
             *      last = di[i];
             *      goodEq = i;
             *      s.Fine = Math.Sqrt(di[i]);
             *
             *      r.Okays = i + " " + Decimal.Round(Convert.ToDecimal(s.Fine), 2);
             *  }
             * }
             */
            Fine      = Math.Sqrt(di[0]);
            r.Okays   = ai[0] + " " + Decimal.Round(Convert.ToDecimal(Fine), 3);
            r.Fitness = 1 / (1 + Fine); //max vol, max value * (1+fine)

            r.Genotype = Aid.SetStrings(r.GenesAsDoubles, 4);

            //  r.Fitness /= badRoute;
        }
示例#12
0
 public override void FillStrings <T>(ref GADataSet.SolutionsRow r, ref T stringRow)
 {
 }