Example #1
0
 public override double[] choose(option RC, candidate cand)
 {
     return(null);
 }
Example #2
0
        /* 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);
Example #3
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string filename;

            try
            {
                filename = getOpenFilename(Program.settings.workingDirectory);
            }
            catch { filename = ""; }
            if (filename != "" && filename != null)
            {
                /* Load the file. */
                XmlDocument doc = new XmlDocument();
                doc.Load(filename);
                /* create prefix<->namespace mappings (if any)  */
                XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
                /* Query the document */
                if (doc.SelectNodes("/grammarRule", nsMgr).Count > 0)
                {
                    grammarRule rule = grammarRule.openRuleFromXml(filename);
                    grammarDisplays.Add(new grammarRuleDisplay(rule, Path.GetFileName(filename)));
                    grammarDisplays[grammarChildCount].Show();
                }
                else if (doc.SelectNodes("/ruleSet", nsMgr).Count > 0)
                {
                    ruleSet rs = ruleSet.openRuleSetFromXml(filename, Program.settings.defaultGenSteps);
                    ruleSetDisplays.Add(new ruleSetDisplay(rs, Path.GetFileName(filename)));
                    ruleSetDisplays[ruleSetChildCount].Show();
                }
                else if (doc.SelectNodes("/designGraph", nsMgr).Count > 0)
                {
                    designGraph graph = designGraph.openGraphFromXml(filename);
                    addAndShowGraphDisplay(graph, Path.GetFileName(filename));
                }
                else if (doc.SelectNodes("/candidate", nsMgr).Count > 0)
                {
                    string    tempString = "";
                    candidate c          = candidate.openCandidateFromXml(filename);
                    SearchIO.output("The candidate found in " + filename, 0);
                    if (c.performanceParams.Count > 0)
                    {
                        tempString = "has the following performance parameters";
                        foreach (double a in c.performanceParams)
                        {
                            tempString += ": " + a.ToString();
                        }
                        SearchIO.output(tempString, 0);
                    }
                    if (c.age > 0)
                    {
                        SearchIO.output("The candidate has existed for " + c.age.ToString() + " iterations.", 0);
                    }
                    SearchIO.output("It's generation ended in RuleSet #" + c.activeRuleSetIndex.ToString(), 0);
                    tempString = "Generation terminated with";
                    foreach (GenerationStatuses a in c.GenerationStatus)
                    {
                        tempString += ": " + a.ToString();
                    }
                    SearchIO.output(tempString, 0);

                    addAndShowGraphDisplay(c.graph, "Candidate in " + Path.GetFileName(filename));
                }
                else
                {
                    MessageBox.Show("The XML files that you have attempted to open contains an unknown" +
                                    "type (not designGraph, grammarRule, ruleSet, or candidate).", "XML Serialization Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Example #4
0
 public override int choose(List <option> options, candidate cand)
 {
     return(rnd.Next(options.Count));
 }
Example #5
0
        /// <summary>
        ///   Recognizes the choose apply cycle. 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).*/
        /// </summary>
        /// <param name = "host">The host.</param>
        /// <param name = "ruleSetIndex">Index of the rule set.</param>
        /// <param name = "numOfCallsLeft">The num of calls left.</param>
        protected void RecognizeChooseApplyCycle(candidate host, int ruleSetIndex, int[] numOfCallsLeft)
        {
            while ((ruleSetIndex >= 0) && (ruleSetIndex < NumOfRuleSets))
            {
                host.activeRuleSetIndex = ruleSetIndex;
                SearchIO.output("Active Rule Set = " + ruleSetIndex, 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, 4);
                var options = Rulesets[ruleSetIndex].recognize(host.graph, InParallel);

                SearchIO.output("There are " + options.Count + " rule choices.", 4);
                if (options.Count == 0)
                {
                    /* There are no rules to recognize, exit here. */
                    host.GenerationStatus[ruleSetIndex] = GenerationStatuses.NoRules;
                    var newRSIndex = nextRuleSet(ruleSetIndex, GenerationStatuses.NoRules);
                    if (newRSIndex == ruleSetIndex)
                    {
                        throw new Exception("Same ruleset chosen when no rules are recognized.");
                    }
                    ruleSetIndex = newRSIndex;
                    continue;
                }
                if (SearchIO.GetTerminateRequest(Thread.CurrentThread.ManagedThreadId))
                {
                    return;
                }

                #endregion

                #region ***** CHOOSE *****

                if (Rulesets[ruleSetIndex].choiceMethod == choiceMethods.Automatic)
                {
                    choice = new[] { 0 }
                }
                ;
                else
                {
                    choice = choose(options, host);
                }
                if (choice[0] == -1)
                {
                    host.undoLastRule();
                    if (Display)
                    {
                        SearchIO.addAndShowGraphWindow(host.graph.copy(),
                                                       "Revert to after calling " + host.numRulesCalled + " rules");
                    }
                    continue;
                }
                if ((choice == null) || (choice[0] < 0) || (choice[0] >= options.Count))
                {
                    SearchIO.output("Choice = #" + IntCollectionConverter.Convert(choice), 4);

                    /* 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.GetTerminateRequest(Thread.CurrentThread.ManagedThreadId))
                {
                    return;
                }

                #endregion

                #region ***** APPLY *****
                host.saveCurrent();
                foreach (var c in choice)
                {
                    options[c].apply(host.graph, choose(options[c], host));
                    host.addToRecipe(options[c]);
                    SearchIO.output("Rule sucessfully applied", 4);
                }
                if (Display && Rulesets[ruleSetIndex].choiceMethod == choiceMethods.Design)
                {
                    SearchIO.addAndShowGraphWindow(host.graph.copy(),
                                                   "After calling " + host.numRulesCalled + " rules");
                }
                if (SearchIO.GetTerminateRequest(Thread.CurrentThread.ManagedThreadId))
                {
                    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.*/
                if (this is LindenmayerChooseRCA)
                {
                    numOfCallsLeft[ruleSetIndex]--;
                }
                else
                {
                    numOfCallsLeft[ruleSetIndex] = numOfCallsLeft[ruleSetIndex] - choice.GetLength(0);
                }

                if (choice.Any(c => (options[c].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
            }
        }
Example #6
0
            //+  виводить кількість однакових елементів серед 2 кандидатів
            public int findr(candidate A)
            {
                int r = 0; // кількість однакових ел. в кандидатах.
                for (int i = 0; i < this.Itemset.Count; i++)
                {
                    for (int j = 0; j < A.Itemset.Count; j++)
                    {
                        if (this.Itemset[i] == A.Itemset[j])
                        {
                            r++;
                        }
                    }
                }

                return r;
            }
        public async Task <HttpResponseMessage> Edit()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var root = HttpContext.Current.Server.MapPath("~/Assets/Uploads");

            Directory.CreateDirectory(root);
            var provider = new CustomMultipartFormDataStreamProvider(root);
            var result   = await Request.Content.ReadAsMultipartAsync(provider);

            if (result.FormData["model"] == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var            model      = result.FormData["model"];
            var            serializer = new JavaScriptSerializer();
            CandidateModel modelToAdd = serializer.Deserialize <CandidateModel>(model);

            string pattern = @"^[A-Za-z ]+$";
            Regex  regex   = new Regex(pattern);

            if (!regex.IsMatch(modelToAdd.name))
            {
                HttpResponseMessage response = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Name must only contains letters and white space");
                throw new HttpResponseException(response);
            }

            if (!regex.IsMatch(modelToAdd.sur_name))
            {
                HttpResponseMessage response = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Surname must only contains letters and white space");
                throw new HttpResponseException(response);
            }

            candidate obj = candidate.GetById(modelToAdd.id);

            if (obj != null)
            {
                obj.name     = modelToAdd.name;
                obj.sur_name = modelToAdd.sur_name;
                obj.position = modelToAdd.position;
            }

            //get the files
            if (result.FileData.Count > 0)
            {
                //TODO: Do something with each uploaded file
                if (obj != null)
                {
                    foreach (var file in result.FileData)
                    {
                        obj.curriculum = Path.GetFileName(file.LocalFileName);
                    }
                    obj.Update();
                }
            }
            else
            {
                obj.Update();
            }

            IEnumerable <candidate> all = candidate.GetAll();

            return(Request.CreateResponse(HttpStatusCode.OK, all));
        }
 public ComparePathWithDesired(candidate c, double[,] desiredPath, MechSimulation sim)
 {
     this.c           = c;
     this.desiredPath = desiredPath;
     this.sim         = sim;
 }
Example #9
0
        // Get Candidates
        public ActionResult Candidates()
        {
            int        all    = 0;
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("http://*****:*****@"""" + s + @"""";
                    prog.dateNaissance = programmeViewModel.dateNaissance;
                    prog.userId        = programmeViewModel.userId;
                    prog.codePostal    = programmeViewModel.codePostal;
                    prog.email         = programmeViewModel.email;
                    prog.role          = programmeViewModel.role;
                    prog.etat          = programmeViewModel.etat;
                    candidates.Add(prog);
                }
                ViewBag.accepted  = candidates;
                ViewBag.naccepted = candidates.Count;
                all = all + candidates.Count;
            }
            else
            {
                ViewBag.result = "erreur";
            }


            //entrevue
            response = client.GetAsync("/MapLevio-web/rest/candidate/CandidateEntrevu").Result;
            if (response.IsSuccessStatusCode)
            {
                ICollection <candidate>      listcandidate          = new List <candidate>();
                IEnumerable <CandidateModel> listcandidateViewModel = response.Content.ReadAsAsync <IEnumerable <CandidateModel> >().Result;
                foreach (CandidateModel programmeViewModel in listcandidateViewModel)
                {
                    candidate prog = new candidate();
                    string    s    = "/Date(" + 1485298353000 + ")/";
                    string    sa   = @"""" + s + @"""";
                    prog.dateNaissance = programmeViewModel.dateNaissance;
                    prog.userId        = programmeViewModel.userId;
                    prog.codePostal    = programmeViewModel.codePostal;
                    prog.email         = programmeViewModel.email;
                    prog.role          = programmeViewModel.role;
                    prog.etat          = programmeViewModel.etat;
                    listcandidate.Add(prog);
                }
                ViewBag.entrevue  = listcandidate;
                ViewBag.nentrevue = listcandidate.Count;
                all = all + listcandidate.Count;
            }
            else
            {
                ViewBag.result = "erreur";
            }

            //entretien
            response = client.GetAsync("/MapLevio-web/rest/candidate/CandidateEntretien").Result;
            if (response.IsSuccessStatusCode)
            {
                ICollection <candidate>      listcandidate          = new List <candidate>();
                IEnumerable <CandidateModel> listcandidateViewModel = response.Content.ReadAsAsync <IEnumerable <CandidateModel> >().Result;
                foreach (CandidateModel programmeViewModel in listcandidateViewModel)
                {
                    candidate prog = new candidate();
                    string    s    = "/Date(" + 1485298353000 + ")/";
                    string    sa   = @"""" + s + @"""";
                    prog.dateNaissance = programmeViewModel.dateNaissance;
                    prog.userId        = programmeViewModel.userId;
                    prog.codePostal    = programmeViewModel.codePostal;
                    prog.email         = programmeViewModel.email;
                    prog.role          = programmeViewModel.role;
                    prog.etat          = programmeViewModel.etat;
                    listcandidate.Add(prog);
                }
                ViewBag.entretien  = listcandidate;
                ViewBag.nentretien = listcandidate.Count;
                all = all + listcandidate.Count;
            }
            else
            {
                ViewBag.result = "erreur";
            }

            //fr
            response = client.GetAsync("/MapLevio-web/rest/candidate/CandidateFr").Result;
            if (response.IsSuccessStatusCode)
            {
                ICollection <candidate>      listcandidate          = new List <candidate>();
                IEnumerable <CandidateModel> listcandidateViewModel = response.Content.ReadAsAsync <IEnumerable <CandidateModel> >().Result;
                foreach (CandidateModel programmeViewModel in listcandidateViewModel)
                {
                    candidate prog = new candidate();
                    string    s    = "/Date(" + 1485298353000 + ")/";
                    string    sa   = @"""" + s + @"""";
                    prog.dateNaissance = programmeViewModel.dateNaissance;
                    prog.userId        = programmeViewModel.userId;
                    prog.codePostal    = programmeViewModel.codePostal;
                    prog.email         = programmeViewModel.email;
                    prog.role          = programmeViewModel.role;
                    prog.etat          = programmeViewModel.etat;
                    listcandidate.Add(prog);
                }
                ViewBag.fr  = listcandidate;
                ViewBag.nfr = listcandidate.Count;
                all         = all + listcandidate.Count;
            }
            else
            {
                ViewBag.result = "erreur";
            }
            ViewBag.all = all;
            return(View());
        }
Example #10
0
 /// <summary>
 ///   Adds the child to sorted candidate list based on the value of f0 (performanceParams[0]).
 ///   The OptimizeDirection is not used as the list is always sorted from lowest to highest.
 /// </summary>
 /// <param name = "candidates">The candidates.</param>
 /// <param name = "child">The child.</param>
 protected void addChildToSortedCandList(List <candidate> candidates, candidate child)
 {
     throw new NotSupportedException("This method is no longer supported. It is more efficient"
                                     +
                                     "to use a SortedList or Dictionary, as this insertion into the list is inefficient.");
 }
Example #11
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();
        }
Example #12
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);
        }
Example #13
0
        public candidate ChooseAndApplyCarboxOption(candidate cand)
        {
            var options = GetCarboxylOptions(cand);

            return(options.Count > 0 ? CopyAndApplyOption(options[Rand.Next(options.Count)], cand, true) : null);
        }
Example #14
0
 /* 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);
Example #15
0
 /// <summary>
 /// Evaluate the fitness of the molecule.
 /// </summary>
 /// <param name="cand"></param>
 /// <returns></returns>
 public static double Evaluate(candidate cand)
 {
     return(0);
 }
Example #16
0
        /* 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
            }
        }
Example #17
0
        public static string GetLinkerName(candidate cand)
        {
            var arr = cand.recipe.Select(x => Convert.ToString(x.optionNumber));

            return(String.Join("-", arr));
        }
Example #18
0
 : NonFuzzyMatchPatternChunk(candidate, patternChunk, punctuationStripped));
Example #19
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);
        }
Example #20
0
 //+
 public bool del2(candidate A)
 {
     bool D = false;
     int r = 0; // кількість однакових ел. в кандидатах.
     for (int i = 0; i < this.Itemset.Count; i++)
     {
         for (int j = 0; j < A.Itemset.Count; j++)
         {
             if (this.Itemset[i] == A.Itemset[j])
             {
                 r++;
             }
         }
     }
     if (r == this.Itemset.Count) { D = true; }
     return D;
 }
Example #21
0
 /// <summary>
 /// Chooses the specified options. Given the list of options and the candidate,
 /// determine what option to invoke. Return the integer index of this option from the list.
 /// </summary>
 /// <param name="options">The options.</param>
 /// <param name="cand">The cand.</param>
 /// <returns></returns>
 public override int[] choose(List <option> options, candidate cand)
 {
     return(new[] { rnd.Next(-1, options.Count) });
 }
Example #22
0
 //СТВОРЕННЯ НОВОГО КАНДИДАТА+
 public candidate newcandidat(candidate A, int[,] B)
 {
     candidate newc = new candidate(new List<int>(), 0);
     for (int i = 0; i < this.Itemset.Count; i++)
     {
         newc.Itemset.Add(this.Itemset[i]);
     }
     for (int i = 0; i < A.Itemset.Count; i++)
     {
         newc.Itemset.Add(A.Itemset[i]);
     }
     newc.cleanItemset();
     newc.support(B);
     return newc;
 }
Example #23
0
        public bool IsTerminalCandidate(candidate cand)
        {
            var numRule = cand.recipe.Count;

            return(cand.recipe[numRule - 1].ruleSetIndex == 1);
        }