Пример #1
0
 public totalObjFunction(GearEvaluator gt, candidate c, double[,] stateVars)
 {
     this.gt = gt;
     this.c = c;
     this.stateVars = stateVars;
     findDerivBy = differentiate.Central2;
 }
Пример #2
0
 public void displayBiggest(candidate[] candidates)
 {
     double best = double.NegativeInfinity;
     foreach (candidate c in candidates)
         if (c.f0 > best)
             best = c.f0;
     SearchIO.miscObject = best;
 }
Пример #3
0
 private static void addChildToSortedCandList(List<candidate> candidates, candidate child, int fIndex)
 {
     if (candidates.Count == 0) candidates.Add(child);
     else
     {
         int i = 0;
         double fChild = child.performanceParams[fIndex];
         while ((i < candidates.Count) && (fChild >= candidates[i].performanceParams[fIndex])) i++;
         candidates.Insert(i, child);
     }
 }
 public outputLocationConstraint(double[,] stateVars, candidate c, GearEvaluator gt)
 {
     this.gt = gt;
     this.c = c;
     this.stateVars = stateVars;
     this.findDerivBy = differentiate.Central2;
     this.xtarget = gt.udg.outputLocation[0,3];
     this.ytarget = gt.udg.outputLocation[1,3];
     this.ztarget = gt.udg.outputLocation[2,3];
     this.theta1t = gt.udg.outputLocation[0, 2];
     this.theta2t = gt.udg.outputLocation[1, 2];
     this.theta3t = gt.udg.outputLocation[2, 2];
 }
Пример #5
0
 private double calcSwirlSize(candidate c)
 {
     double minX = double.PositiveInfinity;
     double minY = double.PositiveInfinity;
     double maxX = double.NegativeInfinity;
     double maxY = double.NegativeInfinity;
     foreach (vertex v in c.graph.nodes)
     {
         if (v.x < minX) minX = v.x;
         if (v.x > maxX) maxX = v.x;
         if (v.y < minY) minY = v.y;
         if (v.y > maxY) maxY = v.y;
     }
     return ((maxX - minX) * (maxY - minY));
 }
        /* One can use the functions provided in RecognizeChooseApply.cs under "Invoking the 
         * RecognizeChooseApplyCycle" since these will be inherited into every generation method, 
         * but there is no reason one could not write other functions directly into their specific
         * choose class. */
        public void makeOneRandomAddition(candidate cand)
        {
            /* the RecognizeChooseApplyCycle requires an array of ruleSet limits,
             * since we only intend to make one call on the activeRuleSet we make
             * an array (it should initialize to all zeros) of the proper length
             * and set its one value at the activeRuleSetIndex to 1. */
            int[] numOfCalls = new int[numOfRuleSets];
            numOfCalls[cand.activeRuleSetIndex] = 1;

            /* here the main cycle is invoked. First, we must pass a copy of the candidate
             * to the RCA cycle since the apply set will modify it, and then move the prevoius
             * state onto the prevStates under the candidate. It is not incorrect to state
             * merely the candidate here, but the prevStates will not be stored correctly.*/
            RecognizeChooseApplyCycle(cand, cand.activeRuleSetIndex, numOfCalls);
        }
Пример #7
0
 public override int choose(List<option> options, candidate cand)
 {
     SearchIO.output("There are " + options.Count.ToString() + " recognized locations.", 2);
     if (options.Count == 0)
     {
         SearchIO.output("Sorry there are no rules recognized.", 0);
         return int.MinValue;
     }
     else if (options.Count > Program.settings.maxRulesToDisplay)
     {
         SearchIO.output("Sorry there are too many rules to show.", 0);
         return int.MinValue;
     }
     else
     {
         SearchIO.output("Double-click on one to show the location.", 2);
         chooseDisplay choiceDisplay = new chooseDisplay();
         choiceDisplay.promptUser(options, (Boolean)(cand.recipe.Count == 0));
         return choiceDisplay.choice;
     }
 }
Пример #8
0
        public void evalGT(candidate c)
        {
            current = c;
            reorderNodes(c);
            Boolean found = false;

            /* recall that gearcount is found in reorderNodes, Albert! */
            stateVars = new double[gearcount + 1, 10];

            #region Set up optMethod
            //NelderMead optMethod =
            //    new NelderMead(.001, 10, true);
            //GradientBasedUnconstrained optMethod =
            //    new GradientBasedUnconstrained(10);
            GradientBasedOptimization optMethod = new GradientBasedOptimization(10);
            //SequentialQuadraticProgramming optMethod = new SequentialQuadraticProgramming(true);
            //GeneralizedReducedGradientActiveSet optMethod =
            //    new GeneralizedReducedGradientActiveSet(true);
            optMethod.Add(new ArithmeticMean(optMethod, 0.001, 2, 200));
            //optMethod.Add(new GoldenSection(optMethod, 0.001,200, int.MaxValue));
            //optMethod.Add(new BFGSDirection());
            optMethod.Add(new FletcherReevesDirection());
            optMethod.Add(new convergenceBasic(BasicConvergenceTypes.OrBetweenSetConditions, 200, 0.0001, double.NaN, double.NaN, int.MaxValue));
            //optMethod.Add(new convergenceBasic(BasicConvergenceTypes.AndBetweenSetConditions, 20, 0.01, double.NaN, double.NaN, int.MaxValue));
            optMethod.Add(new squaredExteriorPenalty(optMethod, 10.0));
            //optMethod.Add(new linearExteriorPenaltySum(optMethod, 10.0));
            DiscreteSpaceDescriptor dsd = new DiscreteSpaceDescriptor(optMethod, 4 * gearcount);
            optMethod.Add(dsd);
            #endregion

            for (int i = 0; i < gearcount; i++)
            {
                foreach (GearFamily gf in gearFamilies)
                    if (c.graph.nodes[i].localLabels.Contains(gf.label))
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            if (c.graph.nodes[i].localVariables.Count < j + 1)
                                c.graph.nodes[i].localVariables.Add(double.NaN);
                        }
                        c.graph.nodes[i].localVariables[0] = gf.Sfb;
                        c.graph.nodes[i].localVariables[1] = gf.Sfc;
                        c.graph.nodes[i].localVariables[2] = gf.density;
                        dsd.addLinkedVariableValues(new int[] { 4 * i, 4 * i + 1, 4 * i + 2 }, gf.gears);
                    }
            }
            SearchIO.output("The parametric space is " + dsd.SizeOfSpace.ToString(), 3);
            //setup constraints for optimization
            //slot 1 - number of teeth
            //slot 2 - pitch
            //slot 3 - face Width
            //slot 4 - location variable

            #region Constraint Building Region
            double[] x = new double[4 * gearcount];
            double[] xStar = new double[4 * gearcount];
            //double fStar = double.PositiveInfinity;
            double fStar = 0.0;
            double ftemp = 1000;
            double weightstar = 100;
            double lowestmass = 100;
            double massstar = 100;
            double mass = 100;
            double[,] stateVarsStar = new double[gearcount + 1, 10];

            outputSpeedConstraint oSC =
            new outputSpeedConstraint(stateVars, this);
            optMethod.Add(oSC);

            stressConstraint sc =
            new stressConstraint(stateVars, c, this);
            optMethod.Add(sc);

            boundingboxConstraint bbc =
            new boundingboxConstraint(stateVars, c, this);
            optMethod.Add(bbc);

            outputLocationConstraint olc =
            new outputLocationConstraint(stateVars, c, this);
            optMethod.Add(olc);

            List<samePitch> samePitches = new List<samePitch>();
            for (int i = 0; i < gearcount; i++)
            {
                if ((c.graph.nodes[i].localLabels.Contains("contact")) || (c.graph.nodes[i].localLabels.Contains("bevelcontact")) || (c.graph.nodes[i].localLabels.Contains("wormcontact")))
                {
                    samePitches.Add(new samePitch(((i - 1) * 4) + 1, ((i * 4) + 1)));
                }
            }
            f = new totalObjFunction(this, current, stateVars);
            optMethod.Add(f);
            #endregion
            int numVars = dsd.linkedSpace.Count;
            int[] VarIndices = new int[numVars];
            for (int i = 0; i < numVars; i++)
                VarIndices[i] = 0;
            int[] VarMaxes = new int[numVars];
            for (int i = 0; i < numVars; i++)
                VarMaxes[i] = dsd.linkedSpace[i].GetLength(0);
            int currentI = 0;
            VarIndices[currentI]--;  //this is an unavoidable hack to start at all zeroes.
            do
            {
                VarIndices[currentI]++;
                if (VarIndices[currentI] == VarMaxes[currentI])
                {
                    VarIndices[currentI] = 0;
                    currentI++;
                    if ((currentI > numVars - 3) && (currentI < numVars))
                        SearchIO.output("Index " + currentI.ToString() + " changed to " + VarIndices[currentI].ToString(), 4);
                }
                else
                {
                    currentI = 0;
                    x = dsd.GetDesignVector(null, VarIndices);
                    //fStar = f.calculate(x);
                    Boolean Feasible = true;
                    foreach (samePitch sp in samePitches)
                        if (!sp.feasible(x)) Feasible = false;
                     if (Feasible && oSC.feasible(x))
                    {
                        if (sc.feasible(x))
                        {
                            //run optMethod here
                            double[] xTuned;
                            mass = 0;
                            double fTuned = optMethod.run(x, out xTuned);
                            for (int k = 0; k < gearcount; k++)
                            {
                                mass += stateVars[k, 2];

                            }
                            found = false;
                            if (fTuned< ftemp)
                            {
                                ftemp = fTuned;
                            }
                            found = isCurrentTheGoal(stateVars, udg);
                            if (found == true)
                            {
                                if (mass < massstar)
                                    {
                                        fStar = fTuned;
                                        xStar = (double[])xTuned.Clone();
                                        massstar = mass;
                                        stateVarsStar = (double[,])stateVars.Clone();
                                    }
                            }

                        }
                    }
                }

            } while (currentI < numVars);

            SearchIO.output("final report f = " + c.f0, 3);
            if (gearcount > 2)
            {
                if (massstar == 100)
                fStar = ftemp+50;
            }
            c.f0 = fStar;
            c.f2 = massstar;
            c.f1 = calcInefficiency(stateVarsStar);
            string outputString = "";
            string outputString2 = "";
            double p = 0;
            for (int i = 0; i < gearcount; i++)
            //var order
            //x, y, z, vx, vy, vz, face width, diameter, number of teeth, type ID number
            {//output for gear visualizer!
                outputString += "gear," + (i + 1) + "," + stateVarsStar[i, 3] + "," + stateVarsStar[i, 4] +
                    "," + stateVarsStar[i, 5] + "," + stateVarsStar[i, 6] + "," + stateVarsStar[i, 7] + "," +
                    stateVarsStar[i, 8] + "," + xStar[i * 4 + 2] + "," + (xStar[i * 4] / xStar[i * 4 + 1]) +
                    "," + xStar[i * 4] + "," + stateVarsStar[i, 9] + "\n";
                if (i != 0)
                {
                    if ((stateVarsStar[i, 3] - stateVarsStar[(i - 1), 3] == 0) && (stateVarsStar[i, 4] - stateVarsStar[(i - 1), 4] == 0))
                    {
                        outputString2 += "rod," + (p) + "," + i + "," + (i - 1);//(stateVarsStar[i, 5] - stateVarsStar[(i - 1), 5]);
                        p += 1;
                    }
                }

                for (int j = 1; j < 9; j++)
                {
                    if (c.graph.nodes[i].localVariables.Count <= j)
                        c.graph.nodes[i].localVariables.Add(double.NaN);
                }
                c.graph.nodes[i].localVariables[3] = stateVarsStar[i, 3];
                c.graph.nodes[i].localVariables[4] = stateVarsStar[i, 4];
                c.graph.nodes[i].localVariables[5] = stateVarsStar[i, 5];
                c.graph.nodes[i].localVariables[6] = stateVarsStar[i, 6];
                c.graph.nodes[i].localVariables[7] = stateVarsStar[i, 7];
                c.graph.nodes[i].localVariables[8] = stateVarsStar[i, 8];
            }
            for (int j = 1; j < 9; j++)
            {
                if (c.graph.nodes[gearcount].localVariables.Count <= j)
                    c.graph.nodes[gearcount].localVariables.Add(double.NaN);
            }
            c.graph.nodes[gearcount].localVariables[3] = stateVarsStar[gearcount, 3];
            c.graph.nodes[gearcount].localVariables[4] = stateVarsStar[gearcount, 4];
            c.graph.nodes[gearcount].localVariables[5] = stateVarsStar[gearcount, 5];
            c.graph.nodes[gearcount].localVariables[6] = stateVarsStar[gearcount, 6];
            c.graph.nodes[gearcount].localVariables[7] = stateVarsStar[gearcount, 7];
            c.graph.nodes[gearcount].localVariables[8] = stateVarsStar[gearcount, 8];

            string filename = Program.settings.outputDirectory + "visualizerOutput1.txt";
            FileStream fs = new FileStream(filename, FileMode.Create);
            StreamWriter outputWriter = new StreamWriter(fs);
            outputWriter.WriteLine(outputString);
            outputWriter.WriteLine(outputString2);
            outputWriter.Close();
            fs.Close();
        }
Пример #9
0
        private void reorderNodes(candidate c)
        {
            node inputShaft = null;
            node temp;
            /* find first gear (connected to input shaft) */
            foreach (node n in c.graph.nodes)
                if (n.localLabels.Contains("seed") && n.localLabels.Contains("shaft"))
                {
                    inputShaft = n;
                    break;
                }
            foreach (arc a in inputShaft.arcs)
                if (a.otherNode(inputShaft).localLabels.Contains("gear"))
                {
                    temp = a.otherNode(inputShaft);
                    c.graph.nodes.Remove(temp);
                    c.graph.nodes.Insert(0, temp);
                    break;
                }
            gearcount = 1;
            Boolean foundNextGear;
            do
            {
                foundNextGear = false;
                node gear = c.graph.nodes[gearcount - 1];
                foreach (arc a in gear.arcsFrom)
                    if ((a.otherNode(gear).localLabels.Contains("gear")) || (a.otherNode(gear).localLabels.Contains("gear1")))
                    {
                        temp = a.otherNode(gear);
                        c.graph.nodes.Remove(temp);
                        c.graph.nodes.Insert(gearcount++, temp);
                        foundNextGear = true;
                        break;
                    }
                if (!foundNextGear)
                {
                    // this means that either that was the last gear or we need to traverse thru an idler shaft
                    foreach (arc a in gear.arcsFrom)
                        if (a.otherNode(gear).localLabels.Contains("shaft"))
                        {
                            node shaft = a.otherNode(gear);
                            foreach (arc aa in shaft.arcsFrom)
                                if ((aa.otherNode(shaft).localLabels.Contains("gear")) || (aa.otherNode(shaft).localLabels.Contains("gear1")))
                                {
                                    temp = aa.otherNode(shaft);
                                    c.graph.nodes.Remove(temp);
                                    c.graph.nodes.Insert(gearcount++, temp);
                                    foundNextGear = true;
                                    break;
                                }
                        }
                }

            } while (foundNextGear);
        }
 public override double[] choose(option RC, candidate cand)
 { return null; }
Пример #11
0
 public static void saveToXml(candidate[] candidates, string filename, string outputDir)
 {
     filename = Path.GetFileName(filename).TrimEnd(new char[] { '.', 'x', 'm', 'l' });
     for (int i = 0; i != candidates.GetLength(0); i++)
     {
         string counter = i.ToString();
         counter = counter.PadLeft(3, '0');
         saveToXml(candidates[i], outputDir + filename + counter + ".xml");
     }
 }
 public candidate[] GenerateArrayOfCandidates(int numToCandidates)
 {
     candidate[] candidates = new candidate[numToCandidates];
     int[] numOfCalls = new int[numOfRuleSets];
     for (int i = 0; i != numToCandidates; i++)
     {
         maxNumOfCalls.CopyTo(numOfCalls, 0);
         candidate newCand = seed.copy();
         RecognizeChooseApplyCycle(newCand, seed.activeRuleSetIndex, numOfCalls);
         candidates[i] = newCand;
     }
     return candidates;
 }
Пример #13
0
        public static void runSearchProcess()
        {
            /* Here is where you code goes.
             * You have access to the previous fields and properties.
             * In general, I envision that you will declare three large objects
             * at the beginning of this function (a generation approach, an evaluation
             * approach, and a guidance approach) and initialize them with their
             * important values. */
            /*** here is an example ***/
            output(null, null, "making new generation method", "initializing generation with data");
            Generation.randomChoose GenerationApproach = new Generation.randomChoose(Program.seed,
                Program.rulesets, 50, false, Program.settings.recompileRules, Program.settings.execDir,
                Program.settings.compiledparamRules);

            SearchIO.output("making new evaluation", 2);
            Evaluation.EvaluateSwirls EvaluationApproach = new Evaluation.EvaluateSwirls();

            output("making new guidance", 2);
            Guidance.DoNothingButDisplay GuidanceApproach = new Guidance.DoNothingButDisplay();

            /*start search */
            iteration = 0;
            int iterMax = 50;
            int populationSize = 5;
            candidate[] candidates = new candidate[populationSize];

            do
            {
                iteration++;

                output("", null, "generate", "entering generation",
                    "entering the generation:" + GenerationApproach.GetType().ToString());
                candidates = GenerationApproach.GenerateArrayOfCandidates(populationSize);
                SearchIO.output("leaving generation", 3);

                output(null, null, "evaluate", "entering evaluation",
                    "entering the evaluation:" + EvaluationApproach.GetType().ToString());
                EvaluationApproach.assignSwirlSizeToAllCandidates(candidates);
                output("leaving evaluation", 3);

                output("and now guidance", 2);
                //object misc;
                //GuidanceApproach.displayBiggest(candidates, out misc);
                //miscObject = misc; 
                GuidanceApproach.displayBiggest(candidates);

                /* Some sleep time (25 ms) for the thread will ensure that the display thread 
                 * has time to update itself. This can also happen if the priority is set very
                 * low. Howver, this sleep statement does slow down the process. Comment out if 
                 * there are many iteration (> 10^5). */
                //Thread.Sleep(25);
                /* Additonally, it may be useful to force a garbage collection at the end of each 
                * iteration. Although, since it is time consuming, check to see how memory is 
                * increasing in TaskManager. If it is unaffected by this, then comment out. 
                * It is typical for GraphSynth to require to 50 MB. Essentially, the sleep 
                 statement should give the system time to garbage collect as well. */
                //GC.Collect();

            } while (!terminateRequest && iteration != iterMax); /* also check if population converged
                                                             * some additional boolean functions. */
            addAndShowGraphDisplay(candidates[0].graph, "candidate 0");
            addAndShowGraphDisplay(candidates[1].graph, "candidate 1");
            addAndShowGraphDisplay(candidates[2].graph, "candidate 2");
            addAndShowGraphDisplay(candidates[3].graph, "candidate 3");
            addAndShowGraphDisplay(candidates[4].graph, "candidate 4");
            candidate.saveToXml(candidates, "candidate", settings.outputDirectory);
        }
Пример #14
0
        private static bool isCurrentTheGoal(candidate current, userDefinedGoals udg)
        {
            double xP, y, z, theta1, theta2, theta3;
            int gearcount = 0;
            foreach (node n in current.graph.nodes)
            {
                if ((n.localLabels.Contains("gear")) || (n.localLabels.Contains("gear1")))
                {
                    gearcount = gearcount + 1;
                }
            }
            int i = gearcount;
            xP = current.graph.nodes[gearcount].localVariables[3] - udg.outputLocation[0, 3];
            y = current.graph.nodes[gearcount].localVariables[4] - udg.outputLocation[1, 3];
            z = current.graph.nodes[gearcount].localVariables[5] - udg.outputLocation[2, 3];
            theta1 = Math.Abs(current.graph.nodes[gearcount].localVariables[6]) - Math.Abs(udg.outputLocation[0, 2]);
            theta2 = Math.Abs(current.graph.nodes[gearcount].localVariables[7]) - Math.Abs(udg.outputLocation[1, 2]);
            theta3 = Math.Abs(current.graph.nodes[gearcount].localVariables[8]) - Math.Abs(udg.outputLocation[2, 2]);

            double hVal = Math.Sqrt(xP * xP + y * y + z * z + theta1 * theta1 + theta2 * theta2 + theta3 * theta3);

            if (hVal < .05)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
Пример #15
0
 public void assignSwirlSizeToAllCandidates(candidate[] candidates)
 {
     Random rnd = new Random();
     foreach (candidate c in candidates)
         c.f0 = calcSwirlSize(c);
 }
Пример #16
0
        /* A copy of a candidate is returned. Very similar to designGraph copy.
         * We make sure to not do a shallow copy (ala Clone) since we are unsure
         * how each candidate may be changed in the future. */
        public candidate copy()
        {
            candidate copyOfCand = new candidate();

            copyOfCand.currentState = this.currentState.copy();
            foreach (designGraph d in prevStates)
                copyOfCand.prevStates.Add(d.copy());
            foreach (option rc in recipe)
            {
                option copiedRC = new option();
                copiedRC.ruleSetIndex = rc.ruleSetIndex;
                copiedRC.ruleNumber = rc.ruleNumber;
                copiedRC.rule = rc.rule;
                copiedRC.location = rc.location;
                copyOfCand.recipe.Add(copiedRC);
            }
            foreach (double f in this.performanceParams)
                copyOfCand.performanceParams.Add(f);

            foreach (GenerationStatuses a in this.GenerationStatus)
                copyOfCand.GenerationStatus.Add(a);


            return copyOfCand;
        }
 public RecognizeChooseApply(designGraph _seed, ruleSet[] _rulesets, int[] _maxNumOfCalls, Boolean _display)
 {
     SearchIO.output("initializing generation:", 4);
     this.numOfRuleSets = _rulesets.GetLength(0);
     this.rulesets = new ruleSet[numOfRuleSets];
     for (int i = 0; i != numOfRuleSets; i++)
         rulesets[i] = _rulesets[i].copy();
     SearchIO.output("There are " + numOfRuleSets + " rule sets.", 4);
     this.seed = new candidate(_seed.copy(), numOfRuleSets);
     SearchIO.output("Seed = " + seed.graph.name, 4);
     maxNumOfCalls = _maxNumOfCalls;
     this.display = _display;
     SearchIO.output("It is " + display.ToString() + " that the SearchIO will be displayed.", 4);
 }
Пример #18
0
 public static void saveToXml(candidate c1, string filename)
 {
     StreamWriter candidateWriter = null;
     try
     {
         candidateWriter = new StreamWriter(filename);
         XmlSerializer candidateSerializer = new XmlSerializer(typeof(candidate));
         candidateSerializer.Serialize(candidateWriter, c1);
     }
     catch (Exception ioe)
     {
         MessageBox.Show(ioe.ToString(), "XML Serialization Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     finally
     {
         if (candidateWriter != null) candidateWriter.Close();
     }
 }
        /* Here we outline what an inherited class must contain. Basically it should have 
         * methods for the 2 types of decisions that are made - decisions on what option
         * to invoke and decisions for the variables required for the process. */

        /* Given the list of options and the candidate, determine what option to invoke.
         * Return the integer index of this option from the list. */
        public abstract int choose(List<option> options, candidate cand);
 public override int choose(List<option> options, candidate cand)
 {
     return rnd.Next(-1, options.Count);
 }
 /* Given that the rule has now been chosen, determine the values needed by the
  * rule to properly apply it to the candidate, cand. The array of double is to
  * be determined by parametric apply rules written in complement C# files for 
  * the ruleSet being used. */
 public abstract double[] choose(option RC, candidate cand);
        /* Here is the main Recognize, Choose, and Apply Generation Cycle. It accepts the host candidate
         * (not graph), the index of what ruleSet to invoke, and an array of size equal to the number
         * of ruleSets. At the end of the process, it returns the updated candidate. The three step
         * process may, however exit at any of five places in the loop, these are described below.
         * 1. the ruleSet invoked may not have any calls left. This will cause the GenerationStatus
         *    to be CycleLimit, and the process will execute what is stored in the 3rd position of 
         *    generationSteps, ruleSet->nextGenerationStep[2], either Stop, Loop, GoToPrevious(ruleSet),
         *    GoToNext(ruleSet), or GoToRuleSet#
         * 2. the choice operation has sent a STOP message, or more precisely a negative # or
         *    a number greater than the list of option. This results in a GenerationStatus of Choice
         *    and the execution of ruleSet->nextGenerationStep[1] (any of the options stated above).
         * 3. there are no rules recognized for the graph. This results in a GenerationStatus of
         *    NoRules and the execution of ruleSet->nextGenerationStep[3] (any of the options above).
         * 4. A trigger rule has been applied. This results in a GenerationStatus of TriggerRule
         *    and the execution of ruleSet->nextGenerationStep[4] (any of the options stated above).
         * 5. the recognize, choose, and apply cycle performed as intended - no abnormal activites.
         *    This results in a GenerationStatus of Normal and the execution of 
         *    ruleSet->nextGenerationStep[0] (any of the options stated above).*/
        public void RecognizeChooseApplyCycle(candidate host, int ruleSetIndex, int[] numOfCallsLeft)
        {
            while ((ruleSetIndex >= 0) && (ruleSetIndex < numOfRuleSets))
            {
                host.activeRuleSetIndex = ruleSetIndex;
                SearchIO.output("Active Rule Set = " + ruleSetIndex.ToString(), 4);
                #region terminate immediately if there are no cycles left
                if (numOfCallsLeft[ruleSetIndex] == 0)
                {
                    /* it is possible that another ruleset intends to invoke this one, but your
                     * number of calls for this set has hit its limit. */
                    host.GenerationStatus[ruleSetIndex] = GenerationStatuses.CycleLimit;
                    ruleSetIndex = nextRuleSet(ruleSetIndex, GenerationStatuses.CycleLimit);
                    SearchIO.output("cycle limit reached", 4);
                    continue;
                }
                #endregion

                #region ***** RECOGNIZE *****
                SearchIO.output("begin RCA loop for RuleSet #" + ruleSetIndex.ToString(), 4);
                List<option> options = rulesets[ruleSetIndex].recognize(host.graph);

                SearchIO.output("There are " + options.Count.ToString() + " rule choices.", 4);
                if (options.Count == 0)
                {
                    /* There are no rules to recognize, exit here. */
                    host.GenerationStatus[ruleSetIndex] = GenerationStatuses.NoRules;
                    ruleSetIndex = nextRuleSet(ruleSetIndex, GenerationStatuses.NoRules);
                    continue;
                }
                if (SearchIO.terminateRequest) return;
                #endregion

                #region ***** CHOOSE *****
                if (rulesets[ruleSetIndex].choiceMethod == choiceMethods.Automatic)
                    choice = 0;
                else choice = choose(options, host);
                SearchIO.output("Choice = #" + choice.ToString(), 4);
                if (choice == -1)
                {
                    host.undoLastRule();
                    if (display) SearchIO.addAndShowGraphDisplay(host.graph.copy(),
                        "Revert to after calling " + host.numRulesCalled + " rules");
                    continue;
                }
                if ((choice < 0) || (choice >= options.Count))
                {
                    /* the overloaded choice function may want to communicate to the loop that it
                     * should finish the process. */
                    SearchIO.output("Choice received a STOP request", 4);
                    host.GenerationStatus[ruleSetIndex] = GenerationStatuses.Choice;
                    ruleSetIndex = nextRuleSet(ruleSetIndex, GenerationStatuses.Choice);
                    continue;
                }
                if (SearchIO.terminateRequest) return;
                #endregion

                #region ***** APPLY *****
                host.saveCurrent();
                options[choice].apply(host.graph, choose(options[choice], host));
                host.addToRecipe(options[choice]);
                SearchIO.output("Rule sucessfully applied", 4);

                /* display state? */
                if (display) SearchIO.addAndShowGraphDisplay(host.graph.copy(),
                    "After calling " + host.numRulesCalled + " rules");
                if (SearchIO.terminateRequest) return;
                #endregion

                #region Check to see if loop is done
                /* First thing we do is reduce the number of calls left. Note that if you start with
                 * a negative number, the process will continue to make it more negative - mimicking
                 * no cycle limit. It is safer to use the globalvar, maxRulesToApply though.*/
                numOfCallsLeft[ruleSetIndex]--;
                /* a significant change is made here in Version 1.1.2.0, it is actually the removal of
                 * code. We were checking the numOfCallsLeft here as well as the top, but it has been decided
                 * that it is ambiguous to check in both locations. Later, it may be determined that two
                 * independent cycle limits need to be imposed, but in the mean time, the following code will be 
                 * commented out.
                 * if (numOfCallsLeft[ruleSetIndex] == 0)
                 * {  /* there of no more calls on this ruleset allowed, the limit has been reached.
                 * SearchIO.output("The maximum num of calls has been reached", 4);
                 * host.GenerationStatus[ruleSetIndex] = GenerationStatuses.CycleLimit;
                 * ruleSetIndex = nextRuleSet(ruleSetIndex, GenerationStatuses.CycleLimit);
                 * }
                 * else  */
                if (options[choice].ruleNumber == rulesets[ruleSetIndex].triggerRuleNum)
                {   /* your ruleset loops until a trigger rule and the trigger rule was just called. */
                    SearchIO.output("The trigger rule has been chosen.", 4);
                    host.GenerationStatus[ruleSetIndex] = GenerationStatuses.TriggerRule;
                    ruleSetIndex = nextRuleSet(ruleSetIndex, GenerationStatuses.TriggerRule);
                }
                else
                {  /* Normal operation */
                    SearchIO.output("RCA loop executed normally.", 4);
                    host.GenerationStatus[ruleSetIndex] = GenerationStatuses.Normal;
                    ruleSetIndex = nextRuleSet(ruleSetIndex, GenerationStatuses.Normal);
                }
                #endregion
            }
        }
Пример #23
0
        public static void runSearchProcess()
        {
            userDefinedGoals udg = new userDefinedGoals();
            Form2 inputBox = new Form2(udg);
            //inputBox.ShowDialog();

            ruleSet.loadAndCompileSourceFiles(rulesets, Program.settings.recompileRules, Program.settings.compiledparamRules, Program.settings.execDir);

            List<candidate> candidates = new List<candidate>();
            candidate current = null;
            candidate seedCandidate = new candidate(seed, Program.settings.numOfRuleSets);
            Boolean found = false;
            candidates.Add(seedCandidate);
            GearEvaluator ge = new GearEvaluator(udg);
            Guidance.PNormProportionalPopulationSelection GuidanceApproach
                = new Guidance.PNormProportionalPopulationSelection(0, Guidance.optimize.minimize, true, true, 1);
            int maxPop = 10000;
            while (!found && (candidates.Count != 0))
            {
                current = candidates[0];
                candidates.RemoveAt(0);
                SearchIO.iteration = current.recipe.Count;
                //RECOGNIZE
                List<option> ruleChoices = rulesets[0].recognize(current.graph);
                SearchIO.miscObject = candidates.Count;
                //
                if (current.recipe.Count >= 2)
                {
                    found = isCurrentTheGoal(current, udg);
                    if (found == true)
                    {
                        ge.evalGT(current);
                        break;
                    }
                }
                //else current.f0 = double.PositiveInfinity;

                for (int i = 0; i != ruleChoices.Count; i++)
                {
                    candidate child = current.copy();

                    ruleChoices = rulesets[0].recognize(child.graph);
                    ruleChoices[i].apply(child.graph, null);

                    child.addToRecipe(ruleChoices[i]);
                    child.f0 = double.NaN;
                    child.f1 = double.NaN;
                    child.f2 = double.NaN;
                    ge.evalGT(child);
                    child.f3 = (child.f0)/100 + child.f1;
                    //1 efficiency
                    //2 mass
                    //3 combination
                    addChildToSortedCandList(candidates, child, 3);
                    //candidates.Add(child);
                }

            }
            Program.addAndShowGraphDisplay(current.graph, "Here is your gear train!!!");
            candidate.saveToXml(current, "testTuned", settings.outputDirectory);
        }