Esempio n. 1
0
        public void setUpGraphElementAddButtons()
        {
            var dic = new ResourceDictionary();

            try
            {
                dic.Source = new Uri(GSApp.settings.WorkingDirAbsolute + GSApp.settings.CustomShapesFile,
                                     UriKind.Absolute);
            }
            catch
            {
                SearchIO.output("Custom Shapes File was not found or is invalid.");
            }
            foreach (string k in dic.Keys)
            {
                if (!Application.Current.Resources.Contains(k))
                {
                    Application.Current.Resources.Add(k, XamlWriter.Save(dic[k]));
                }
            }

            var dtNIS    = (DataTemplate)Application.Current.Resources["NodeIconShape"];
            var dtNHS    = (DataTemplate)Application.Current.Resources["HyperArcIconShape"];
            var dtAddBtn = (DataTemplate)Application.Current.Resources["AddButtonTemplate"];

            NodeAddToolbar.Items.Clear();
            ArcAddToolbar.Items.Clear();
            HyperAddToolbar.Items.Clear();
            SelectedAddItems = new List <string>();
            SelectedAddItems.Add("");
            var shortCutKeysList = new List <Key>();

            shortCutKeysList.Add(Key.Escape);
            var temp        = (Button)dtAddBtn.LoadContent();
            var imageLength = temp.Width - 8;

            foreach (object key in Application.Current.Resources.Keys)
            {
                var keyString = key as string;
                try
                {
                    var b     = (Button)dtAddBtn.LoadContent();
                    var s     = (Shape)MyXamlHelpers.Parse((string)Application.Current.Resources[key]);
                    var scStr = "";
                    if (s.Tag != null)
                    {
                        scStr = s.Tag.ToString().Split(new[] { ':' })[0];
                    }
                    var scKey = findShortCut(ref scStr);
                    shortCutKeysList.Add(scKey);
                    SelectedAddItems.Add(keyString);
                    b.Name              = keyString;
                    b.Click            += AddNodeArcButton_Click;
                    b.MouseDoubleClick += AddNodeArcButton_DoubleClick;
                    if (keyString.ToLowerInvariant().Contains("node"))
                    {
                        var NIS     = (Shape)dtNIS.LoadContent();
                        var NISsize = new Size(NIS.Width, NIS.Height);
                        var scale   = imageLength / Math.Max(s.Height, NISsize.Height);
                        s.Height           *= scale;
                        s.Width            *= scale;
                        NIS.Height         *= scale;
                        NIS.Width          *= scale;
                        s.VerticalAlignment = NIS.VerticalAlignment = VerticalAlignment.Top;
                        NIS.Margin          = new Thickness(0, (s.Height - NIS.Height) / 2, 0, 0);
                        b.Tag = scKey;
                        for (var i = 0; i <= NodeAddToolbar.Items.Count; i++)
                        {
                            if (i == NodeAddToolbar.Items.Count)
                            {
                                NodeAddToolbar.Items.Add(b);
                                break;
                            }
                            else if ((int)scKey < (int)((Key)((Button)NodeAddToolbar.Items[i]).Tag))
                            {
                                NodeAddToolbar.Items.Insert(i, b);
                                break;
                            }
                        }
                        ((TextBlock)((Grid)b.Content).Children[0]).Text = scStr;
                        ((TextBlock)((Grid)b.Content).Children[1]).Text = keyString;
                        ((Grid)b.Content).Children.Insert(0, s);
                        ((Grid)b.Content).Children.Insert(1, NIS);
                    }
                    else if (keyString.ToLowerInvariant().Contains("arc"))
                    {
                        ((TextBlock)((Grid)b.Content).Children[0]).Text = scStr;
                        ((TextBlock)((Grid)b.Content).Children[1]).Text = keyString;
                        s.VerticalAlignment = VerticalAlignment.Top;
                        Grid.SetRow(s, 0);
                        ((Grid)b.Content).Children.Add(s);
                        if (s as Path != null)
                        {
                            var pathGeo = ((Path)s).Data;
                            if (pathGeo.IsFrozen)
                            {
                                pathGeo = pathGeo.Clone();
                            }
                            var scale = imageLength /
                                        Math.Max(pathGeo.Bounds.Height, pathGeo.Bounds.Width);
                            pathGeo.Transform = new ScaleTransform(scale, scale);
                        }
                        else
                        {
                            s.Height = s.Width = imageLength;
                        }
                        b.Tag = scKey;
                        for (var i = 0; i <= ArcAddToolbar.Items.Count; i++)
                        {
                            if (i == ArcAddToolbar.Items.Count)
                            {
                                ArcAddToolbar.Items.Add(b);
                                break;
                            }
                            else if ((int)scKey < (int)((Key)((Button)ArcAddToolbar.Items[i]).Tag))
                            {
                                ArcAddToolbar.Items.Insert(i, b);
                                break;
                            }
                        }
                    }
                    else if (keyString.ToLowerInvariant().Contains("hyper"))
                    {
                        ((TextBlock)((Grid)b.Content).Children[0]).Text = scStr;
                        ((TextBlock)((Grid)b.Content).Children[1]).Text = keyString;
                        s.VerticalAlignment = VerticalAlignment.Top;
                        Grid.SetRow(s, 0);
                        ((Grid)b.Content).Children.Add(s);
                        if (s as Path != null)
                        {
                            var pathGeo = ((Path)s).Data;
                            if (pathGeo.IsFrozen)
                            {
                                pathGeo = pathGeo.Clone();
                            }
                            var scale = imageLength /
                                        Math.Max(pathGeo.Bounds.Height, pathGeo.Bounds.Width);
                            pathGeo.Transform = new ScaleTransform(scale, scale);
                        }
                        else
                        {
                            s.Height = s.Width = imageLength;
                        }
                        b.Tag = scKey;
                        for (var i = 0; i <= HyperAddToolbar.Items.Count; i++)
                        {
                            if (i == HyperAddToolbar.Items.Count)
                            {
                                HyperAddToolbar.Items.Add(b);
                                break;
                            }
                            else if ((int)scKey < (int)((Key)((Button)HyperAddToolbar.Items[i]).Tag))
                            {
                                HyperAddToolbar.Items.Insert(i, b);
                                break;
                            }
                        }
                    }
                }
                catch
                {
                    SearchIO.output(keyString + " did not load correctly");
                }
            }
            shortCutKeys = shortCutKeysList.ToArray();
        }
Esempio n. 2
0
        /// <summary>
        ///   Sets up graph layout menu. It would have been better to use the .NET 3.5 pipeline approach
        ///   to add-ins. Was I just lazy? I tried to figure it out for 2 whole weeks. It involves up to 7
        ///   projects and would require GraphGUI to be serialized. However, my view of graph layout is
        ///   to make quick changes to postion of nodes (perhaps specific ones may change shapes and back-
        ///   ground but these will be few). Seeing as how XamlWriter and XamlReader are slow and bottleneck
        ///   the entire application, I thought simply to take this approach. All graph layouts will need
        ///   to be in the GraphSynth.GraphLayout assembly and be derived from the GraphLayoutBaseClass. Each
        ///   one found will be given a slot on the layout menu.
        /// </summary>
        public void setUpGraphLayoutMenu()
        {
            SearchIO.output("Setting Up Graph Layout Algorithms");
            var keyNumOffset = (int)Key.D0;
            var k            = 0;

            GraphLayoutAlgorithms = new List <Type>();
            GraphLayoutCommands   = new List <RoutedUICommand>();
            GraphLayoutSubMenu.Items.Clear();
            var potentialAssemblies = getPotentialAssemblies(GSApp.settings.GraphLayoutDirAbs);

            if (potentialAssemblies.Count == 0)
            {
                return;
            }
            foreach (string filepath in potentialAssemblies)
            {
                Assembly GraphLayoutAssembly = null;
                try
                {
                    GraphLayoutAssembly = Assembly.LoadFrom(filepath);
                    var layouts = GraphLayoutAssembly.GetTypes();
                    foreach (Type lt in layouts)
                    {
                        if (!lt.IsAbstract && GraphLayoutBaseClass.IsInheritedType(lt) &&
                            !GraphLayoutAlgorithms.Any(w => w.FullName.Equals(lt.FullName)))
                        {
                            var newLayAlgo = GraphLayoutBaseClass.Make(lt);
                            if (newLayAlgo != null)
                            {
                                try
                                {
                                    KeyGesture kg = null;
                                    if (k < 10)
                                    {
                                        kg = new KeyGesture((Key)(k + keyNumOffset), ModifierKeys.Alt);
                                    }
                                    else if (k < 20)
                                    {
                                        kg = new KeyGesture((Key)(k + keyNumOffset - 10),
                                                            ModifierKeys.Alt | ModifierKeys.Shift);
                                    }
                                    else if (k < 30)
                                    {
                                        kg = new KeyGesture((Key)(k + keyNumOffset - 20),
                                                            ModifierKeys.Control | ModifierKeys.Alt |
                                                            ModifierKeys.Shift);
                                    }
                                    else
                                    {
                                        MessageBox.Show(
                                            "No shortcut has been assigned to " + newLayAlgo.text +
                                            ". That sure is an awful lot "
                                            +
                                            " of graph layout algorithms! Consider reducing the number included in the plugins directory",
                                            "No ShortCut Assigned", MessageBoxButton.OK);
                                    }
                                    GraphLayoutAlgorithms.Add(lt);
                                    var newGLCommand = new RoutedUICommand(newLayAlgo.text, lt.Name,
                                                                           GetType(),
                                                                           new InputGestureCollection {
                                        kg
                                    });
                                    GraphLayoutCommands.Add(newGLCommand);
                                    CommandBindings.Add(new CommandBinding(newGLCommand, GraphLayoutOnExecuted,
                                                                           GraphLayoutCanExecute));
                                    GraphLayoutSubMenu.Items.Add(new MenuItem {
                                        Command = newGLCommand
                                    });
                                    SearchIO.output("\t" + lt.Name + " loaded successfully.");
                                    k++;
                                }
                                catch (Exception exc)
                                {
                                    SearchIO.output("Unable to load " + lt.Name + ": " + exc.Message);
                                }
                            }
                        }
                    }
                }
                catch
                {
                    // File was either not found are not of the right type.
                }
            }
            if (Directory.Exists(GSApp.settings.GraphLayoutDirAbs))
            {
                glWatcher                       = new FileSystemWatcher(GSApp.settings.GraphLayoutDirAbs, "*.dll");
                glWatcher.Changed              += GraphLayoutDir_Changed;
                glWatcher.Created              += GraphLayoutDir_Changed;
                glWatcher.Deleted              += GraphLayoutDir_Changed;
                glWatcher.Renamed              += GraphLayoutDir_Changed;
                glWatcher.EnableRaisingEvents   = true;
                glWatcher.IncludeSubdirectories = true;
                glWatcher.NotifyFilter          = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                                  | NotifyFilters.FileName;
            }
        }
Esempio n. 3
0
        public void setUpSearchProcessMenu()
        {
            SearchIO.output("Setting Up Search Process Algorithms");
            var k = 0;

            SearchCommands   = new List <RoutedUICommand>();
            SearchAlgorithms = new List <SearchProcess>();
            while (DesignDropDown.Items.Count > 14)
            {
                DesignDropDown.Items.RemoveAt(14);
            }

            var potentialAssemblies = getPotentialAssemblies(GSApp.settings.SearchDirAbs);

            potentialAssemblies.Add("thisEXE");

            foreach (string filepath in potentialAssemblies)
            {
                Assembly searchAssembly = null;
                try
                {
                    if (filepath == "thisEXE")
                    {
                        searchAssembly = Assembly.GetExecutingAssembly();
                    }
                    else
                    {
                        searchAssembly = Assembly.LoadFrom(filepath);
                    }
                    var searchprocesses = searchAssembly.GetTypes();
                    foreach (Type spt in searchprocesses)
                    {
                        if (!spt.IsAbstract && SearchProcess.IsInheritedType(spt) &&
                            !SearchAlgorithms.Any(w => w.GetType().FullName.Equals(spt.FullName)))
                        {
                            try
                            {
                                var constructor = spt.GetConstructor(new Type[0]);
                                var searchAlgo  = (SearchProcess)constructor.Invoke(null);
                                searchAlgo.settings = GSApp.settings;
                                KeyGesture kg = null;
                                if (k < endOfFKeys)
                                {
                                    kg = new KeyGesture((Key)(k + keyNumOffset), ModifierKeys.None);
                                }
                                else if (k < 2 * endOfFKeys)
                                {
                                    kg = new KeyGesture((Key)(k + keyNumOffset - endOfFKeys), ModifierKeys.Shift);
                                }
                                else if (k < 3 * endOfFKeys)
                                {
                                    kg = new KeyGesture((Key)(k + keyNumOffset - 2 * endOfFKeys),
                                                        ModifierKeys.Control | ModifierKeys.Shift);
                                }
                                else
                                {
                                    MessageBox.Show(
                                        "No shortcut has been assigned to " + searchAlgo.text +
                                        ". That sure is an awful lot "
                                        +
                                        " of search process algorithms! Consider reducing the number included in the plugins directory",
                                        "No ShortCut Assigned", MessageBoxButton.OK);
                                }
                                SearchAlgorithms.Add(searchAlgo);
                                var newSearchCommand = new RoutedUICommand(searchAlgo.text, spt.Name,
                                                                           GetType(), new InputGestureCollection {
                                    kg
                                });
                                SearchCommands.Add(newSearchCommand);
                                CommandBindings.Add(new CommandBinding(newSearchCommand, RunSearchProcessOnExecuted,
                                                                       RunSearchProcessCanExecute));
                                DesignDropDown.Items.Add(new MenuItem {
                                    Command = newSearchCommand
                                });
                                k++;
                                SearchIO.output("\t" + spt.Name + " loaded successfully.");
                            }
                            catch (Exception exc)
                            {
                                SearchIO.output("Unable to load " + spt.Name + ": " + exc.Message);
                            }
                        }
                    }
                }
                catch (Exception exc)
                {
                    if (searchAssembly == null)
                    {
                        SearchIO.output("Unable to open " + filepath + ": " + exc.Message);
                    }
                    else
                    {
                        SearchIO.output("Unable to open " + searchAssembly.FullName + "(" + filepath + "): " +
                                        exc.Message);
                    }
                }
            }
            if (Directory.Exists(GSApp.settings.SearchDirAbs))
            {
                sWatcher                       = new FileSystemWatcher(GSApp.settings.SearchDirAbs, "*.dll");
                sWatcher.Changed              += SearchDir_Changed;
                sWatcher.Created              += SearchDir_Changed;
                sWatcher.Deleted              += SearchDir_Changed;
                sWatcher.Renamed              += SearchDir_Changed;
                sWatcher.EnableRaisingEvents   = true;
                sWatcher.IncludeSubdirectories = true;
                sWatcher.NotifyFilter          = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                                 | NotifyFilters.FileName;
            }
        }
Esempio n. 4
0
        static void Main()
        {
            /* first a new optimization method in the form of a genetic algorithm is created. */
            var optMethod = new MultiObjectiveGeneticAlgorithm();

            /* The objective function is Rosenbrock's banana function again. */
            optMethod.Add(new polynomialObjFn
            {
                Terms = new List <string>
                {
                    "100*x1^4",
                    "-200*x1^2*x2",
                    "x1^2",
                    "-2*x1",
                    "100*x2^2",
                    "1"
                }
            });

            optMethod.Add(new RoyalRoads());

            /* Now a number of convergerence criteria are added. Again, since these all
             * inherit from the abstractConvergence class, the Add method knows to where
             * to store them. */
            optMethod.Add(new MaxIterationsConvergence(50000));     /* stop after 500 iteration (i.e. generations) */
            optMethod.Add(new MaxAgeConvergence(20, 0.000000001));  /*stop after 20 generations of the best not changing */
            optMethod.Add(new MaxSpanInPopulationConvergence(100)); /*stop if the largest distance is only one unit. */
            optMethod.NumConvergeCriteriaNeeded = 2;                /* two of these three criteria are needed to stop the process. */

            /* The genetic algorithm is for discrete problems. Therefore we need to provide the optimization algorithm
             * and the subsequent generators with the details of the space. The first variable represents the number of
             * passes in our fictitious problem. We set the lower bound to 1 and the upper bound to 20. The third argument
             * is the delta and since only integers are possible we set this to 1. The second and third variables are
             * really continous, but for the purpose of the GA we set a discretization at one-ten-thousandth for the second
             * and one-hundredth in the third. Note that you can provide either the delta or the number of steps. Here
             * 36,001 steps will make increments of one-hundredth. */
            var SpaceDescriptor = new DesignSpaceDescription
            {
                new VariableDescriptor(-100, 100, 0.0001),
                new VariableDescriptor(-100, 100, 0.0001),
                new VariableDescriptor(-100, 100, 0.0001)
            };

            optMethod.Add(SpaceDescriptor);

            /* the genetic algorithm requires some more values to be fully specified. These include initial,
             * crossover, and mutation generators, as well as a selector. A Latin Hyper Cube initial sample is
             * first created to assure the population covers the space well. */
            optMethod.Add(new LatinHyperCube(SpaceDescriptor, VariablesInScope.BothDiscreteAndReal));

            /* the typical bit-string approach to mutation and crossover are adopted here. Note that the
             * mutation rate (per candidate) is increased to 0.4 from the default of 0.1. Which means that
             * 4 in 10 candidates should experience at least one mutation. No new crossover rate is provided
             * therefore the default of 1.7 will be used. This means that between two parents there will likely
             * be 1.7 locations of crossover between them. */
            optMethod.Add(new GAMutationBitString(SpaceDescriptor, 0.4));
            optMethod.Add(new GACrossoverBitString(SpaceDescriptor));

            /* Finally, the selector is added to the population. This RandomPairwiseCompare is often referred to
             * as tournament selection wherein a random selection of two candidates results in the inferior one
             * being removed from the population. It requires the optimization direction: are lower values better
             * (minimize) or larger (maximize)? */
            optMethod.Add(new SkewboidDiversity(optimize.minimize, optimize.minimize));
            optMethod.Add(new RandomPairwiseCompare(optimize.minimize));

            /* for output statements (points in the code where the SearchIO.output(...) function is called, the
             * verbosity is set to 4 which is high. Typical values are between 0 and 4 but higher values (>4)
             * may be used, but this will likely cut into the speed of the search process. */
            Parameters.Verbosity = VerbosityLevels.AboveNormal;

            /* everything is set, we can now run the algorithm and retrieve the f* and x* values. */
            double[] xOptimal;
            var      fOptimal = optMethod.Run(out xOptimal);

            /* since we are curious how the process completed we now output some details. */
            SearchIO.output("f* = " + fOptimal); /* the 0 indicates that this statement has high priority
                                                  * and shouldn't be skipped in printing to the console. */
            SearchIO.output("x* = " + xOptimal.MakePrintString());
            SearchIO.output("The process converged by criteria: " + optMethod.ConvergenceDeclaredByTypeString);
            Console.ReadLine();
        }
Esempio n. 5
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
            }
        }
        private static void Main()
        {
            Parameters.Verbosity = VerbosityLevels.AboveNormal;
            // this next line is to set the Debug statements from OOOT to the Console.
            Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));

            /* In this example, we first present how the details of an optimzation
             * problem can be saved to an XML-file so that it can be read in
             * and solved as opposed to defining all the details in an imperative
             * (code line by code line) way. In the first function, the xml file
             * name "test1.xml" is created. */
            makeAndSaveProblemDefinition();

            /* now we create a series of different optimization methods and test
             * them on the problem. The problem is now opened from the file and
             * the details are stored in an object of class "Problem Definition".*/
            var stream = new FileStream(filename, FileMode.Open);


            ProblemDefinition probTest1 = ProblemDefinition.OpenprobFromXml(stream);
            abstractOptMethod opty;


            /***********Gradient Based Optimization with Steepest Descent****************/
            SearchIO.output("***********Gradient Based Optimization with Steepest Descent****************");
            opty = new GradientBasedOptimization();
            opty.Add(probTest1);
            abstractSearchDirection searchDirMethod = new SteepestDescent();

            opty.Add(searchDirMethod);
            //abstractLineSearch lineSearchMethod = new ArithmeticMean(0.0001, 1, 100);
            //abstractLineSearch lineSearchMethod = new DSCPowell(0.0001, 1, 100);
            abstractLineSearch lineSearchMethod = new GoldenSection(0.0001, 1);

            opty.Add(lineSearchMethod);
            opty.Add(new squaredExteriorPenalty(opty, 10));
            /* since this is not a population-based optimization method, we need to remove the MaxSpan criteria. */
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            double[] xStar;
            var      timer = Stopwatch.StartNew();
            var      fStar = opty.Run(out xStar);

            printResults(opty, xStar, fStar, timer);

            /***********Gradient Based Optimization with Fletcher-Reeves****************/
            SearchIO.output("***********Gradient Based Optimization with Fletcher-Reeves****************");

            /* we don't need to reset (invoke the constructor) for GradientBasedOptimization since we are only
             * change the seaach direction method. */
            searchDirMethod = new FletcherReevesDirection();
            /* you could also try the remaining 3 search direction methods. */
            //searchDirMethod = new CyclicCoordinates();
            //searchDirMethod = new BFGSDirection();
            //searchDirMethod = new PowellMethod(0.001, 6);
            opty.Add(searchDirMethod);

            timer = Stopwatch.StartNew();
            opty.ResetFunctionEvaluationDatabase();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);
            /******************Generalized Reduced Gradient***********************/
            SearchIO.output("******************Generalized Reduced Gradient***********************");
            opty = new GeneralizedReducedGradientActiveSet();
            opty.Add(probTest1);
            opty.Add(new squaredExteriorPenalty(opty, 10));
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);

            /* GRG is the ONLY one here that handles constraints explicity. It find the
             * optimal very quickly and accurately. However, many of the other show a
             * better value of f*, this is because they are using an imperfect penalty
             * function (new squaredExteriorPenalty(opty, 10)). While it seems that GRG
             * includes it as well, it is only used in the the line search method. */


            /******************Random Hill Climbing ***********************/
            SearchIO.output("******************Random Hill Climbing ***********************");
            opty = new HillClimbing();
            opty.Add(probTest1);
            opty.Add(new squaredExteriorPenalty(opty, 8));
            opty.Add(new RandomNeighborGenerator(probTest1.SpaceDescriptor));
            opty.Add(new KeepSingleBest(optimize.minimize));
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            /* the deltaX convergence needs to be removed as well, since RHC will end many iterations
             * at the same point it started. */
            opty.ConvergenceMethods.RemoveAll(a => a is DeltaXConvergence);

            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);



            /******************Exhaustive Hill Climbing ***********************/
            SearchIO.output("******************Exhaustive Hill Climbing ***********************");
            /* Everything else about the Random Hill Climbing stays the same. */
            opty.Add(new ExhaustiveNeighborGenerator(probTest1.SpaceDescriptor));

            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);



            /******************Simulated Annealing***********************/
            SearchIO.output("******************Simulated Annealing***********************");
            opty = new SimulatedAnnealing(optimize.minimize);
            opty.Add(probTest1);
            opty.Add(new squaredExteriorPenalty(opty, 10));
            opty.Add(new RandomNeighborGenerator(probTest1.SpaceDescriptor, 100));
            opty.Add(new SACoolingSangiovanniVincentelli(100));
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            /* the deltaX convergence needs to be removed as well, since RHC will end many iterations
             * at the same point it started. */
            opty.ConvergenceMethods.RemoveAll(a => a is DeltaXConvergence);


            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);


            /******************Exhaustive Search ***********************/
            // SearchIO.output("******************Exhaustive Search ***********************");
            //opty = new ExhaustiveSearch(probTest1.SpaceDescriptor, optimize.minimize);
            //opty.Add(probTest1);

            /* No convergence criteria is needed as the process concludes when all
             * states have been visited but for this problem that is 4 trillion states.*/
            //opty.ConvergenceMethods.Clear();
            /* if you DID KNOW the best, you can include a criteria like...*/
            //opty.ConvergenceMethods.Add(new ToKnownBestXConvergence(new[] { 3.0, 3.0 }, 0.0000001));
            //timer = Stopwatch.StartNew();
            //fStar = opty.Run(out xStar);

            /* you probably will never see this process complete. Even with the added
             * convergence criteria (which is not factored into the estimated time of
             * completion), you are probably looking at 1 to 2 years. */
            //printResults(opty, xStar, fStar, timer);
        }
Esempio n. 7
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();
        }
Esempio n. 8
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);
                }
            }
        }