コード例 #1
0
        protected void RunFullTPSquared()
        {
            Random r = new Random();

            double[,] desiredPath = { { 1.87,    8 }, { 2.93, 8.46 }, { 2.80, 8.41 },
                                      { 1.99, 8.06 }, { 0.96, 7.46 }, {    0, 6.71 },{ -0.77, 5.93 }, { -1.3, 5.26 }, { -1.60, 4.81 }, { -1.65, 4.75 }, { -1.25, 5.33 }, { 0, 6.71 } };
            double          startAngle = 0;
            double          endAngle   = 2 * Math.PI;
            double          iOmega     = 2;
            double          iAlpha     = 0;
            MechSimulation  sim        = new MechSimulation();
            BoundingBox     bb         = new BoundingBox(sim, 10, 10);
            GrashofCriteria cc         = new GrashofCriteria(sim, 0);

            List <candidate> candidates = new List <candidate>();

            while (true) //notConverged())
            {
                // 1. Generate topologies - calling rulesets - this adds candidates to the candidates list.

                //2. Evaluate  & Param Tuning
                foreach (candidate c in candidates)
                {
                    if (double.IsNaN(c.f0))
                    {
                        sim.Graph = c.graph;
                        NelderMead NMOpt = new NelderMead();
                        NMOpt.Add(sim);
                        //gbu.Add(new GoldenSection(.001, 20));
                        //gbu.Add(new BFGSDirection());
                        NMOpt.Add(new MaxIterationsConvergence(100));
                        double[] x0 = new double[8];
                        for (int i = 0; i < x0.GetLength(0); i++) //since I am going to assign ground pivots as they are
                        {
                            x0[i] = r.NextDouble();
                        }

                        double[] xStar;
                        double   fStar = NMOpt.Run(out xStar, x0);
                        //   double fStar = NMOpt.Run(out xStar,8);
                        c.f0 = fStar;
                    }
                }

                //3. Pruning
                // throw out topologies (candidates) that have bad/large values of f0.

                //4. Guide?
            }
            SearchIO.output("***Completed!***");
        }
コード例 #2
0
        protected override void Run()
        {
            Random r = new Random(); //1);



            //  double[,] desiredPath ={{1.87,8},{2.93,8.46},{2.80,8.41},
            //                             {1.99,8.06},{0.96,7.46},{0,6.71},{-0.77,5.93},{-1.3,5.26},{-1.60,4.81},{-1.65,4.75},{-1.25,5.33},{0,6.71}};
            double[,] desiredPath = { { 125, 225 }, { 165.44, 217.76 }, { 189.57, 200.42 }, { 185.89, 178.49 }, { 158.65, 161.92 }, { 109.38, 135.30 }, { 57.997, 101.69 }, { 24.59, 82.07 }, { 0.33, 76.90 }, { -17.03, 91.46 }, { -13.92, 129.10 }, { -0.74, 155.01 }, { 20.73, 180.91 }, { 53.78, 205.65 }, { 88.17, 219.90 } };

            double         startAngle = 0;
            double         endAngle   = 2 * Math.PI;
            double         iOmega     = 2;
            double         iAlpha     = 0;
            MechSimulation sim        = new MechSimulation();


            //Below is a relation for bounding box and also the first point
            double bb_min, bb_max;

            //   bb_min = StarMath.Min(desiredPath);
            //  bb_max = StarMath.Max(desiredPath);

            //now that min and max are obtained - we will form a bounding box using these max and min values

            bb_max = 250;
            bb_min = 250;

            sim.Graph = seedGraph;
            //  designGraph testGraph = this.seedGraph;
            //   ev.c = new candidate(testGraph, 0);
            //  ev.c = this.seedGraph;

            //bounding box - trying to contain the solutions within a particular box
            //      BoundingBox bb = new BoundingBox(sim, bb_max,bb_min);
            //   GrashofCriteria cc = new GrashofCriteria(sim, 0);

            //adding a new objective function which can be taken by the optimization program
            var pathObjFun = new ComparePathWithDesired(seedCandidate, desiredPath, sim);


            //initializing the optimization program
            var optMethod = new NelderMead();

            //var optMethod = new GradientBasedOptimization();

            optMethod.Add(new PowellMethod());
            optMethod.Add(new DSCPowell(0.00001, .5, 1000));


            //     optMethod.Add(new GoldenSection(0.001,300));
            optMethod.Add(new ArithmeticMean(0.001, 0.1, 300));

            //adding simulation
            optMethod.Add(sim);

            //adding objective function to this optimization routine
            optMethod.Add(pathObjFun);

            //we are removing this since we do not have a merit function defined
            optMethod.Add(new squaredExteriorPenalty(optMethod, 1.0));
            //      optMethod.Add(bb);
            //    optMethod.Add(cc);

            // convergence
            optMethod.Add(new MaxIterationsConvergence(100));
            //   optMethod.Add(new DeltaXConvergence(0.01));
            optMethod.Add(new ToKnownBestFConvergence(0.0, 0.1));
            optMethod.Add(new MaxSpanInPopulationConvergence(0.01));

            var n     = 6;
            var dsd   = new DesignSpaceDescription();
            var minX  = StarMath.Min(StarMath.GetColumn(0, desiredPath));
            var maxX  = StarMath.Max(StarMath.GetColumn(0, desiredPath));
            var minY  = StarMath.Min(StarMath.GetColumn(1, desiredPath));
            var maxY  = StarMath.Max(StarMath.GetColumn(1, desiredPath));
            var delta = maxX - minX;

            minX -= delta;
            maxX += delta;
            delta = maxY - minY;
            minY -= delta;
            maxY += delta;

            for (int i = 0; i < n; i++)
            {
                if (i % 2 == 0)
                {
                    dsd.Add(new VariableDescriptor(minX, maxX));
                }
                else
                {
                    dsd.Add(new VariableDescriptor(minY, maxY));
                }
            }
            // dsd.Add(new VariableDescriptor(0,300));
            var LHC        = new LatinHyperCube(dsd, VariablesInScope.BothDiscreteAndReal);
            var initPoints = LHC.GenerateCandidates(null, 100);

            //for each initPoints - generate the fstar value



            //generating random x,y values
            //double[] x0 = new double[8];
            //for (int i = 0; i < x0.GetLength(0); i++) //since I am going to assign ground pivots as they are
            //    x0[i] =  100*r.NextDouble();


            //sim.calculate(x0);

            // double[] xStar;
            // double fStar = optMethod.Run(out xStar, x0);
            //// double fStar = optMethod.Run(out xStar, 8);

            double[]        fStar1 = new double[initPoints.Count];
            List <double[]> xStar1 = new List <double[]>();


            for (int i = 0; i < fStar1.GetLength(0); i++)
            {
                double[] x0 = new double[n];
                x0 = initPoints[i];
                double[] xStar;
                double   fStar = optMethod.Run(out xStar, x0);
                fStar1[i] = fStar;
                xStar1.Add(xStar);
                SearchIO.output("LHC i: " + i);
            }

            int xstarindex;

            SearchIO.output("fStar Min=" + StarMath.Min(fStar1, out xstarindex), 0);
            SearchIO.output("Xstar Values:" + xStar1[xstarindex]);
            SearchIO.output("***Converged by" + optMethod.ConvergenceDeclaredByTypeString, 0);
            SearchIO.output("Rerunning with new x values", 0);

            //     var optMethod1 = new GradientBasedOptimization();
            //     optMethod1.Add(new FletcherReevesDirection());
            //  //   optMethod1.Add(new ArithmeticMean(0.001, 0.1, 300));

            //     optMethod1.Add(new GoldenSection(0.001, 300));
            //     optMethod1.Add(sim);
            //     optMethod1.Add(pathObjFun);
            //     optMethod1.Add(new squaredExteriorPenalty(optMethod, 1.0));
            ////     optMethod1.Add(new MaxIterationsConvergence(100));
            //     optMethod1.Add(new ToKnownBestFConvergence(0.0, 0.1));
            //   //  optMethod.Add(new MaxSpanInPopulationConvergence(0.01))

            //     double[] xStar2;
            //     double fStar2 = optMethod1.Run(out xStar2, xStar1[xstarindex]);

            //     SearchIO.output("New Fstar = " + fStar2, 0);

            //double xstarmin, xstarmax;
            //xstarmax = StarMath.Max(xStar1[xstarindex]);
            //xstarmin = StarMath.Min(xStar1[xstarindex]);

            //var dsd1 = new DesignSpaceDescription();
            //dsd1.Add(new VariableDescriptor(xstarmin, xstarmax));
            //var LHC1 = new LatinHyperCube(dsd1, VariablesInScope.BothDiscreteAndReal);
            //var initPoints1 = LHC.GenerateCandidates(null, 100);
            //double[] fstar1 = new double[initPoints1.Count];
            //List<double[]> xstar_second = new List<double[]>();
            //for (int i = 0; i < fstar1.GetLength(0); i++)
            //{
            //    double[] x0 = new double[n];
            //    x0 = initPoints[i];
            //    double[] xStar;
            //    double fStar = optMethod.Run(out xStar, x0);
            //    fstar1[i] = fStar;
            //    xstar_second.Add(xStar);
            //    SearchIO.output("LHC i: " + i);

            //}



            //SearchIO.output("New fStar = " + StarMath.Min(fstar1), 0);


            //SearchIO.output("***Converged by" + optMethod.ConvergenceDeclaredByTypeString, 0);
        }
コード例 #3
0
        public object[] OpenRuleAndCanvas(string filename)
        {
            XmlReader xR = null;

            try
            {
                xR = XmlReader.Create(filename);
                var xeRule = XElement.Load(xR);


                var shapes = xeRule.Element("{http://schemas.microsoft.com/winfx/2006/xaml/presentation}" + "Border");
                shapes = shapes.Elements().FirstOrDefault();


                var shapesL = (from s in shapes.Elements()
                               where ((s.Attribute("Tag") != null) && (s.Attribute("Tag").Value == "L"))
                               select s).FirstOrDefault();
                if (shapesL != null)
                {
                    shapesL = shapesL.Elements().First();
                }
                else
                {
                    SearchIO.output("No Left Canvas of Shapes found.");
                    shapesL = new XElement("dummyL");
                }

                var shapesR = (from s in shapes.Elements()
                               where ((s.Attribute("Tag") != null) && (s.Attribute("Tag").Value == "R"))
                               select s).FirstOrDefault();
                if (shapesR != null)
                {
                    shapesR = shapesR.Elements().First();
                }
                else
                {
                    SearchIO.output("No Left Canvas of Shapes found.");
                    shapesR = new XElement("dummyL");
                }


                var temp     = xeRule.Element("{ignorableUri}" + "grammarRule");
                var openRule = new grammarRule();
                if (temp != null)
                {
                    openRule = DeSerializeRuleFromXML(RemoveXAMLns(RemoveIgnorablePrefix(temp.ToString())));
                }

                RestoreDisplayShapes(shapesL, openRule.L.nodes, openRule.L.arcs, openRule.L.hyperarcs);
                RestoreDisplayShapes(shapesR, openRule.R.nodes, openRule.R.arcs, openRule.R.hyperarcs);

                return(new object[] { openRule, filename });
            }
            catch
            {
                return(null);
            }
            finally
            {
                xR.Close();
            }
        }
コード例 #4
0
 private static void CheckForUpdate()
 {
     try
     {
         var xr             = XmlReader.Create("http://www.graphsynth.com/files/install/GraphSynth2_Installer.xml");
         var data           = XElement.Load(xr);
         var onlineVersion  = new Version(data.Element("Version").Value);
         var currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
         var isNewer        = onlineVersion.CompareTo(currentVersion);
         if (isNewer == 1)
         {
             var newChanges = new List <XElement>(data.Elements());
             newChanges.RemoveAt(0);
             var lastPos = newChanges.FindIndex(a => a.Name.LocalName.Equals("Version") &&
                                                currentVersion.CompareTo(new Version(a.Value)) >= 0);
             if (lastPos != -1)
             {
                 newChanges.RemoveRange(lastPos, newChanges.Count - lastPos);
             }
             var changeScript = "";
             var i            = 0;
             foreach (var x in newChanges)
             {
                 if (x.Name.LocalName.Equals("Change"))
                 {
                     changeScript += "  " + (++i) + ". " + x.Value + "\n";
                 }
                 else
                 {
                     changeScript += "since version " + x.Value + "\n";
                 }
             }
             var result =
                 MessageBox.Show(
                     "There is a new version of GraphSynth2 online. You are currently using version " +
                     currentVersion + " and the online version is " + onlineVersion +
                     ".\nHere are the recent updates: \n" + changeScript +
                     "\n\n Would you like to download the updated installer" +
                     " and quit GraphSynth2 now?", "New Version Available!", MessageBoxButton.YesNo,
                     MessageBoxImage.Question, MessageBoxResult.No);
             if (result == MessageBoxResult.Yes)
             {
                 var process = new Process
                 {
                     StartInfo =
                     {
                         FileName        = "http://www.graphsynth.com/files/install/setup.exe",
                         Verb            = "open",
                         UseShellExecute = true
                     }
                 };
                 process.Start();
                 xr.Close();
                 main.Close();
             }
         }
         else
         {
             SearchIO.output("Current version is up to date.");
         }
         xr.Close();
     }
     catch
     {
         SearchIO.output("Unable to check for update.");
     }
 }
コード例 #5
0
        private void SaveGraph(string filename, designGraph graph, CanvasProperty canvProp)
        {
            if (UserCancelled)
            {
                return;
            }
            progress   = 5;
            graph.name = Path.GetFileNameWithoutExtension(filename);
            removeNullWhiteSpaceEmptyLabels(graph);

            if ((graph.checkForRepeatNames()) && !suppressWarnings)
            {
                progWindow.QueryUser("Sorry, but you are not allowed to have repeat names. I have changed" +
                                     " these names to be unique", 5000, "OK", "", false);
            }

            progress = 7;
            if (UserCancelled)
            {
                return;
            }
            progressEnd = 80;
            /* go build the browser page */
            string SaveString = null;

            dispatch.Invoke((ThreadStart) delegate
            {
                var xamlPage = BuildXAMLGraphPage(graph, canvProp);
                progress     = 80;
                SaveString   = XamlWriter.Save(xamlPage);
            });
            progress = 87;
            if (UserCancelled)
            {
                return;
            }
            SaveString = MyXamlHelpers.CleanOutxNulls(SaveString);

            /* A little manipulation is needed to stick the GraphSynth objects within the page. *
             * The IgnorableSetup string ensures that XAML viewers ignore the following      *
             * GraphSynth specific elements: the canvas data, and the graph data. This eff-  *
             * ectively separates the topology and data of the graph from the graphic elements.       */
            SaveString = SaveString.Insert(SaveString.IndexOf(">"),
                                           IgnorableSetup + "Tag=\"Graph\" ");
            /* remove the ending Page tag but put it back at the end. */
            SaveString = SaveString.Replace("</Page>", "");

            /* add the canvas properties. */
            if (canvProp != null)
            {
                dispatch.Invoke(
                    (ThreadStart)
                    delegate { SaveString += "\n\n" + AddIgnorablePrefix(CanvasProperty.SerializeCanvasToXml(canvProp)); });
            }
            progress = 95;
            if (UserCancelled)
            {
                return;
            }
            /* add the graph data. */
            SaveString += "\n\n" + AddIgnorablePrefix(SerializeGraphToXml(graph)) + "\n\n";
            if (UserCancelled)
            {
                return;
            }
            /* put the closing tag back on. */
            SaveString += "</Page>";
            try
            {
                File.WriteAllText(filename, SaveString);
                progress = 100;
                if ((progWindow != null) && !suppressWarnings)
                {
                    progWindow.QueryUser("\n                     **** Graph successfully saved. ****", 1000, "OK", "",
                                         false);
                }
                else
                {
                    SearchIO.output("**** Graph successfully saved. ****", 2);
                }
            }
            catch (Exception E)
            {
                if ((progWindow != null) && !suppressWarnings)
                {
                    progWindow.QueryUser("File Access Exception" + E.Message, 10000, "", "Cancel", false);
                }
                else
                {
                    SearchIO.output("File Access Exception" + E.Message, 2);
                }
            }
        }
コード例 #6
0
        internal void RestoreDisplayShapes(XElement shapes, List <node> nodes, List <arc> arcs, List <hyperarc> hyperarcs)
        {
            //
            // how to get to the icons
            //
            var progressStart = progress;
            var progStep      = (double)(progressEnd - progressStart) / (nodes.Count + arcs.Count + hyperarcs.Count);
            var step          = 0;

            foreach (node n in nodes)
            {
                XElement x
                    = shapes.Elements().FirstOrDefault(p => ((p.Attribute("Tag") != null) &&
                                                             p.Attribute("Tag").Value.StartsWith(n.name)));
                if (x != null)
                {
                    n.DisplayShape = new DisplayShape(x.ToString(), ShapeRepresents.Node, n);
                    x.Remove();
                }
                else
                {
                    SearchIO.output("Node: " + n.name + " does not have a shape description in the" +
                                    " file. A default shape is added", 4);
                    dispatch.Invoke((ThreadStart) delegate
                    {
                        n.DisplayShape = new DisplayShape((string)Application.Current.Resources["SmallCircleNode"],
                                                          ShapeRepresents.Node, n);
                        n.DisplayShape.Tag = n.name;
                    });
                }
                if (UserCancelled)
                {
                    return;
                }
                progress = progressStart + (int)(progStep * step++);
            }
            foreach (arc a in arcs)
            {
                XElement x = shapes.Elements().FirstOrDefault(p =>
                                                              ((p.Attribute("Tag") != null) && p.Attribute("Tag").Value.StartsWith(a.name)));
                if (x != null)
                {
                    a.DisplayShape = new DisplayShape(x.ToString(), ShapeRepresents.Arc, a);
                    x.Remove();
                }
                else
                {
                    SearchIO.output("Arc: " + a.name + " does not have a shape description in the" +
                                    " file. A default shape is added", 4);
                    dispatch.Invoke((ThreadStart) delegate
                    {
                        a.DisplayShape =
                            new DisplayShape((string)Application.Current.Resources["StraightArc"],
                                             ShapeRepresents.Arc, a);
                    });
                }
                if (UserCancelled)
                {
                    return;
                }
                progress = progressStart + (int)(progStep * step++);
            }

            foreach (hyperarc h in hyperarcs)
            {
                XElement x = shapes.Elements().FirstOrDefault(p =>
                                                              ((p.Attribute("Tag") != null) && p.Attribute("Tag").Value.StartsWith(h.name)));
                if (x != null)
                {
                    h.DisplayShape = new DisplayShape(x.ToString(), ShapeRepresents.HyperArc, h);
                    x.Remove();
                }
                else
                {
                    SearchIO.output("HyperArc: " + h.name + " does not have a shape description in the" +
                                    " file. A default shape is added", 4);
                    dispatch.Invoke((ThreadStart) delegate
                    {
                        h.DisplayShape =
                            new DisplayShape((string)Application.Current.Resources["StarHyper"],
                                             ShapeRepresents.HyperArc, h);
                    });
                }
                if (UserCancelled)
                {
                    return;
                }
                progress = progressStart + (int)(progStep * step++);
            }
        }
コード例 #7
0
        internal void RestoreDisplayShapes(XElement shapes, List <node> nodes, List <arc> arcs, List <hyperarc> hyperarcs)
        {
            //
            // how to get to the icons
            //
            foreach (node n in nodes)
            {
                XElement x
                    = shapes.Elements().FirstOrDefault(p => ((p.Attribute("Tag") != null) &&
                                                             p.Attribute("Tag").Value.StartsWith(n.name)));
                if (x != null)
                {
                    n.DisplayShape = new ShapeData(x.ToString(), n);
                    x.Remove();
                }
                else
                {
                    SearchIO.output("Node: " + n.name + " does not have a shape description in the" +
                                    " file. A default shape is added");
                    n.DisplayShape = new ShapeData(GetShapeReourceString.get("SmallCircleNode"),
                                                   n)
                    {
                        Tag = n.name
                    };
                }
            }
            foreach (arc a in arcs)
            {
                XElement x = shapes.Elements().FirstOrDefault(p =>
                                                              ((p.Attribute("Tag") != null) && p.Attribute("Tag").Value.StartsWith(a.name)));
                if (x != null)
                {
                    a.DisplayShape = new ShapeData(x.ToString(), a);
                    x.Remove();
                }
                else
                {
                    SearchIO.output("Arc: " + a.name + " does not have a shape description in the" +
                                    " file. A default shape is added");
                    a.DisplayShape = new ShapeData(GetShapeReourceString.get("StraightArc"), a)
                    {
                        Tag = a.name
                    };
                }
            }

            foreach (hyperarc h in hyperarcs)
            {
                XElement x = shapes.Elements().FirstOrDefault(p =>
                                                              ((p.Attribute("Tag") != null) && p.Attribute("Tag").Value.StartsWith(h.name)));
                if (x != null)
                {
                    h.DisplayShape = new ShapeData(x.ToString(), h);
                    x.Remove();
                }
                else
                {
                    SearchIO.output("HyperArc: " + h.name + " does not have a shape description in the" +
                                    " file. A default shape is added");
                    h.DisplayShape = new ShapeData(GetShapeReourceString.get("StarHyper"), h)
                    {
                        Tag = h.name
                    };
                }
            }
        }
コード例 #8
0
        private static void PluginDialog()
        {
            var inactiveIndices = new List <int>();
            var numActive       = 0;
            var activeIndex     = 0;

            //if (SearchAlgorithms.Count == 0) SearchIO.output("=== no plugins loaded. ===");
            SearchIO.output("\n========= Plugins ==========");
            for (int i = 0; i < SearchAlgorithms.Count; i++)
            {
                var inactive  = false;
                var s         = SearchAlgorithms[i];
                var numString = (i < 10) ? ((Key)i).ToString().Remove(0, 1) : ((Key)i).ToString();
                Console.Write("{0}. {1}", numString, s.text);
                if (s.RequireSeed && settings.seed == null)
                {
                    inactive = true;
                    Console.Write(" (requires seed)");
                }
                if (s.RequiredNumRuleSets > settings.numOfRuleSets)
                {
                    inactive = true;
                    Console.Write(" (requires {0} rulesets)", s.RequiredNumRuleSets);
                }
                Console.WriteLine();
                if (inactive)
                {
                    inactiveIndices.Add(i);
                }
                else
                {
                    numActive++;
                    activeIndex = i;
                }
            }
            switch (numActive)
            {
            case 0:
                Console.WriteLine("There are no active plugins. Please fix configuration file before rerunning.");
                break;

            case 1:
                SearchIO.output("Push any key to start the single active plugin (F1 for other commands).");
                Console.Write(" >");
                break;

            default:
                SearchIO.output("Push the key of the plugin you would like to run (F1 for other commands).");
                Console.Write(" >");
                break;
            }
            Key response;
            var readKey = Console.ReadKey().Key.ToString();

            readKey = readKey.Replace("D", "");
            int choice = Enum.TryParse(readKey, out response) ? (int)response : -1;

            Console.Write("\n");
            if (choice == 30)
            {
                HelpDialog();
            }
            else if (choice == 31)
            {
                VerbosityDialog();
            }
            else
            {
                if (numActive == 1)
                {
                    choice = activeIndex;
                }
                else if (inactiveIndices.Contains(choice))
                {
                    choice = -1;
                }

                if (choice >= 0 && choice < SearchAlgorithms.Count)
                {
                    SearchAlgorithms[choice].RunSearchProcess();
                }
            }
            if (choice <= 31)
            {
                PluginDialog();
            }
        }