/// <summary>
        ///   Makes the error string.
        /// </summary>
        /// <param name = "Exc">The exc.</param>
        /// <param name = "includeComputerData">if set to <c>true</c> [include computer data].</param>
        /// <returns></returns>
        public static string MakeErrorString(Exception Exc, Boolean includeComputerData)
        {
            var sw = new StringWriter();

            try
            {
                sw.WriteLine("Source    : " + Exc.Source.Trim());
                sw.WriteLine("Method	: "+ Exc.TargetSite.Name);
                if (includeComputerData)
                {
                    sw.WriteLine("Date		: "+ DateTime.Now.ToLongTimeString());
                    sw.WriteLine("Time		: "+ DateTime.Now.ToShortDateString());
                    sw.WriteLine("Computer	: "+ Dns.GetHostName());
                }
                sw.WriteLine("Error		: "+ Exc.Message.Trim());
                sw.WriteLine("Stack Trace	: "+ Exc.StackTrace.Trim());
                var tabString = "";
                while (Exc.InnerException != null)
                {
                    tabString += "\t";
                    Exc        = Exc.InnerException;
                    sw.WriteLine("\n" + tabString + "Inner Exception in : " + Exc.TargetSite.Name);
                    sw.WriteLine(tabString + "Error              : " + Exc.Message.Trim());
                    sw.WriteLine(tabString + "Stack Trace     	: "+ Exc.StackTrace.Trim());
                }
                sw.WriteLine("-------------------------------------------------------------------");
            }
            catch (Exception e)
            {
                SearchIO.output("Error in ErrorLogger (how did this happen?!)"
                                + e);
            }
            return(sw.ToString());
        }
        private void SaveRule(string filename, grammarRule rule, designGraph graphK)
        {
            rule.name = Path.GetFileNameWithoutExtension(filename);

            if (checkRule(rule))
            {
                // progress is now at 13
                var SaveString = BuildXAMLRulePage(rule, graphK);

                /* 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(">", StringComparison.Ordinal),
                                               IgnorableSetup + "Tag=\"Rule\" ");
                /* remove the ending Page tag but put it back at the end. */
                SaveString = SaveString.Replace("</Page>", "");

                /* add the graph data. */
                SaveString += "\n\n" + AddIgnorablePrefix(SerializeRuleToXml(rule)) + "\n\n";
                /* put the closing tag back on. */
                SaveString += "</Page>";
                try
                {
                    File.WriteAllText(filename, SaveString);
                }
                catch (Exception E)
                {
                    SearchIO.output("File Access Exception" + E.Message, 10000, "", "Cancel", false);
                }
                SearchIO.output("**** Rule successfully saved. ****", 2);
            }
        }
Esempio n. 3
0
        /// <summary>
        ///   Opens the rule set.
        /// </summary>
        /// <param name = "filename">The filename.</param>
        /// <returns></returns>
        //public virtual ruleSet OpenRuleSet(string filename)
        //{
        //    ruleSet newRuleSet = null;
        //    StreamReader ruleReader = null;
        //    try
        //    {
        //        ruleReader = new StreamReader(filename);
        //        var ruleDeserializer = new XmlSerializer(typeof(ruleSet));
        //        newRuleSet = (ruleSet)ruleDeserializer.Deserialize(ruleReader);
        //        newRuleSet.rulesDir = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar;
        //        newRuleSet.filer = this;
        //        var numRules = newRuleSet.ruleFileNames.Count;
        //        int numLoaded;
        //        newRuleSet.rules = LoadRulesFromFileNames(newRuleSet.rulesDir,
        //                                                  newRuleSet.ruleFileNames, out numLoaded);

        //        SearchIO.output(Path.GetFileName(filename) + " successfully loaded");
        //        if (numRules == numLoaded) SearchIO.output(" and all (" + numLoaded + ") rules loaded successfully.");
        //        else
        //            SearchIO.output("     but "
        //                            + (numRules - numLoaded) + " rules did not load.");

        //        if ((string.IsNullOrWhiteSpace(newRuleSet.name)) || (newRuleSet.name == "Untitled"))
        //            newRuleSet.name = Path.GetFileNameWithoutExtension(filename);
        //    }
        //    catch (Exception ioe)
        //    {
        //        SearchIO.output("***XML Serialization Error***");
        //        SearchIO.output(ioe.ToString());
        //    }
        //    finally
        //    {
        //        if (ruleReader != null) ruleReader.Close();
        //    }

        //    return newRuleSet;
        //}

        /// <summary>
        ///   Loads the rules from file names.
        /// </summary>
        /// <param name = "ruleDir">The rule dir.</param>
        /// <param name = "ruleFileNames">The rule file names.</param>
        /// <param name = "numLoaded">The num loaded.</param>
        /// <returns></returns>
        protected virtual List <grammarRule> LoadRulesFromFileNames(string ruleDir, List <string> ruleFileNames,
                                                                    out int numLoaded)
        {
            var rules = new List <grammarRule>();

            numLoaded = 0;
            while (numLoaded < ruleFileNames.Count)
            {
                var rulePath = ruleDir + ruleFileNames[numLoaded];
                if (File.Exists(rulePath))
                {
                    SearchIO.output("Loading " + ruleFileNames[numLoaded]);
                    object ruleObj = Open(rulePath);
                    if (ruleObj is grammarRule)
                    {
                        rules.Add((grammarRule)ruleObj);
                    }
                    else if (ruleObj is object[])
                    {
                        rules.AddRange(
                            ((object[])ruleObj).Where(o => o is grammarRule).Cast
                            <grammarRule>());
                    }
                    numLoaded++;
                }
                else
                {
                    SearchIO.output("Rule Not Found: " + ruleFileNames[numLoaded]);
                    ruleFileNames.RemoveAt(numLoaded);
                }
            }
            return(rules);
        }
Esempio n. 4
0
        /// <summary>
        ///   Saves the candidate.
        /// </summary>
        /// <param name = "filename">The filename.</param>
        /// <param name = "c1">The c1.</param>
        protected void SaveCandidate(string filename, candidate c1)
        {
            // c1.graph.checkForRepeatNames();
            StreamWriter candidateWriter = null;

            try
            {
                c1.graphFileName = Path.GetFileNameWithoutExtension(filename) + ".gxml";
                candidateWriter  = new StreamWriter(filename);
                var candidateSerializer = new XmlSerializer(typeof(candidate));
                candidateSerializer.Serialize(candidateWriter, c1);
                Save(Path.GetDirectoryName(filename) + "/" + c1.graphFileName, c1.graph);
            }
            catch (Exception ioe)
            {
                SearchIO.output("***XML Serialization Error***");
                SearchIO.output(ioe.ToString());
            }
            finally
            {
                if (candidateWriter != null)
                {
                    candidateWriter.Close();
                }
            }
        }
Esempio n. 5
0
        public static void LoadPlugins()
        {
            Assembly searchAssembly = null;

            Type[] searchprocesses;
            var    potentialAssemblies = getPotentialAssemblies(settings.SearchDirAbs);

            potentialAssemblies.Add("thisEXE");
            if (potentialAssemblies.Count == 0)
            {
                return;
            }

            foreach (string filepath in potentialAssemblies)
            {
                try
                {
                    if (filepath == "thisEXE")
                    {
                        searchAssembly = Assembly.GetExecutingAssembly();
                    }
                    else
                    {
                        searchAssembly = Assembly.LoadFrom(filepath);
                    }
                    searchprocesses = searchAssembly.GetExportedTypes();
                    foreach (Type spt in searchprocesses)
                    {
                        if (!spt.IsAbstract && SearchProcess.IsInheritedType(spt) &&
                            !SearchAlgorithms.Any(w => w.GetType().FullName.Equals(spt.FullName)))
                        {
                            LoadSearchAlgo(spt);
                        }
                    }
                }
                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);
                    }
                }
            }
            //load from this exe
            searchAssembly  = Assembly.GetExecutingAssembly();
            searchprocesses = searchAssembly.GetExportedTypes();
            foreach (Type spt in searchprocesses)
            {
                if (!spt.IsAbstract && SearchProcess.IsInheritedType(spt) &&
                    !SearchAlgorithms.Any(w => w.GetType().FullName.Equals(spt.FullName)))
                {
                    LoadSearchAlgo(spt);
                }
            }
        }
Esempio n. 6
0
        public static void Main(string[] args)
        {
            InputArgs = new List <string>(args);
            ParseArguments();

            SearchIO.output("Reading in settings file", 3);
            ReadInSettings();
            SearchIO.output("opening files...", 3);
            OpenFiles();

            //SearchIO.output("Checking for update online", 3);
            //var updateThread = new Thread(CheckForUpdate);
            //updateThread.Start();

            SearchIO.output("opening plugins...", 3);
            LoadPlugins();
            SearchIO.output("----- Load in Complete ------", 3);

            if (!ArgContainsPluginCommands || !InvokeArgPlugin())
            {
                PluginDialog();
                //Console.WriteLine("Press any key to close.");
                //Console.ReadKey();
            }
        }
Esempio n. 7
0
        /// <summary>
        ///   Saves the rule.
        /// </summary>
        /// <param name = "filename">The filename.</param>
        /// <param name = "ruleToSave">The rule to save.</param>
        protected void SaveRule(string filename, grammarRule ruleToSave)
        {
            StreamWriter ruleWriter = null;

            try
            {
                ruleToSave.name = Path.GetFileNameWithoutExtension(filename);
                ruleToSave.L.checkForRepeatNames();
                removeNullWhiteSpaceEmptyLabels(ruleToSave.L);
                ruleToSave.R.checkForRepeatNames();
                removeNullWhiteSpaceEmptyLabels(ruleToSave.R);
                ruleToSave.ReorderNodes();
                ruleWriter = new StreamWriter(filename);
                var s = SerializeRuleToXml(ruleToSave);
                if (s != null)
                {
                    ruleWriter.Write(s);
                }
            }
            catch (Exception ioe)
            {
                SearchIO.output("***XML Serialization Error***");
                SearchIO.output(ioe.ToString());
            }
            finally
            {
                if (ruleWriter != null)
                {
                    ruleWriter.Close();
                }
            }
        }
Esempio n. 8
0
        private static List <string> getPotentialAssemblies(string directory)
        {
            var potentialAssemblies = Directory.GetFiles(GlobalSettings.ExecDir, "*.dll", SearchOption.TopDirectoryOnly).ToList();

            if (Directory.Exists(GlobalSettings.ExecDir + defaultPluginDir))
            {
                potentialAssemblies.AddRange(Directory.GetFiles(GlobalSettings.ExecDir + defaultPluginDir,
                                                                "*.dll", SearchOption.AllDirectories));
            }
            if (Directory.Exists(directory))
            {
                potentialAssemblies.AddRange(Directory.GetFiles(directory, "*.dll", SearchOption.AllDirectories));
            }
            else
            {
                SearchIO.output("Plugin directory" + directory + " not found.");
            }

            potentialAssemblies.RemoveAll(fs => fs.Contains("/obj/"));
            potentialAssemblies.RemoveAll(fs => fs.Contains("GraphSynth.CustomControls.dll"));
            potentialAssemblies.RemoveAll(fs => fs.Contains("GraphSynth.BaseClasses.dll"));
            potentialAssemblies.RemoveAll(fs => fs.Contains("StarMath.dll"));
            potentialAssemblies.RemoveAll(fs => fs.Contains("OptimizationToolbox.dll"));
            return(potentialAssemblies);
        }
Esempio n. 9
0
        private static Boolean readInSettings(string filePath, out GlobalSettings settings)
        {
            StreamReader streamReader = null;

            try
            {
                streamReader = new StreamReader(filePath);
                var SettingsDeSerializer = new XmlSerializer(typeof(GlobalSettings));
                ConfigDir = Path.GetDirectoryName(filePath) + DS;
                settings  = (GlobalSettings)SettingsDeSerializer.Deserialize(streamReader);

                if (settings == null)
                {
                    throw new Exception("Was not able to find GraphSynthSettings section.");
                }
                SearchIO.output("GraphSynthSettings.gsconfig loaded successfully.");
                return(true);
            }
            catch (Exception e)
            {
                SearchIO.output("The configuration file produced an error:\n" + e);
                settings = null;
                return(false);
            }
            finally { if (streamReader != null)
                      {
                          streamReader.Close();
                      }
            }
        }
Esempio n. 10
0
        /// <summary>
        ///   Saves the graph.
        /// </summary>
        /// <param name = "filename">The filename.</param>
        /// <param name = "graph1">The graph1.</param>
        protected void SaveGraph(string filename, designGraph graph1)
        {
            StreamWriter graphWriter = null;

            graph1.name = Path.GetFileNameWithoutExtension(filename);
            graph1.checkForRepeatNames();
            removeNullWhiteSpaceEmptyLabels(graph1);
            try
            {
                graphWriter = new StreamWriter(filename);
                var s = SerializeGraphToXml(graph1);
                if (s != null)
                {
                    graphWriter.Write(s);
                }
            }
            catch (FileNotFoundException fnfe)
            {
                SearchIO.output("***Error Writing to File***");
                SearchIO.output(fnfe.ToString());
            }
            finally
            {
                if (graphWriter != null)
                {
                    graphWriter.Close();
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        ///   Opens the candidate.
        /// </summary>
        /// <param name = "filename">The filename.</param>
        /// <returns></returns>
        public candidate OpenCandidate(string filename)
        {
            candidate    newCandidate    = null;
            StreamReader candidateReader = null;

            try
            {
                candidateReader = new StreamReader(filename);
                var candidateDeserializer = new XmlSerializer(typeof(candidate));
                newCandidate       = (candidate)candidateDeserializer.Deserialize(candidateReader);
                newCandidate.graph = (designGraph)Open(Path.GetDirectoryName(filename)
                                                       + "/" + newCandidate.graphFileName)[0];
            }
            catch (Exception ioe)
            {
                SearchIO.output("***XML Serialization Error***");
                SearchIO.output(ioe.ToString());
            }
            finally
            {
                if (candidateReader != null)
                {
                    candidateReader.Close();
                }
            }
            return(newCandidate);
        }
 /// <summary>
 ///   Catches the specified exception.
 /// </summary>
 /// <param name = "Exc">The exc.</param>
 public static void Catch(Exception Exc)
 {
     try
     {
         if (!File.Exists(ErrorLogFile))
         {
             var fs = new FileStream(ErrorLogFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
             fs.Close();
         }
         var sw = new StreamWriter(ErrorLogFile, true);
         sw.Write(MakeErrorString(Exc, true));
         sw.Flush();
         sw.Close();
         var    r         = new Random();
         string erCaption = counter == ErrorWelcomeCaptions.GetLength(0)
                                ? ErrorWelcomeCaptions[r.Next(ErrorWelcomeCaptions.GetLength(0))]
                                : ErrorWelcomeCaptions[counter++];
         SearchIO.MessageBoxShow("Error found in " + Exc.Source +
                                 "\nError contents can be found in " + ErrorLogFile, erCaption, "Error");
     }
     catch (Exception e)
     {
         SearchIO.output("Error in ErrorLogger (how did this happen?!)"
                         + e);
     }
 }
Esempio n. 13
0
        public static object Parse(string p, ParserContext context = null)
        {
            try
            {
                if (context == null)
                {
                    context = new ParserContext();
                }
                context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                return(XamlReader.Parse(p, context));

                /***** Notice!: If you have crashed Graphsynth here, then
                 * the try-catch failed. This happens due to a setting
                 * in your Visual Studio environment. To fix this:
                 * 1) Go to Debug->Exceptions.
                 * 2) expand Common Language Runtime Exceptions
                 * 3) Scroll Down to System.Windows.Markup.XamlParseException
                 * 4) uncheck the box in the "Thrown" Column. */
            }
            catch (Exception)
            {
                try
                {
                    return(XamlReader.Parse(p));
                }
                catch
                {
                    SearchIO.output("XamlReader.Parse failed to translate the string to an object.");
                    return(null);
                }
            }
        }
Esempio n. 14
0
 /// <summary>
 /// Loads the default seed and rule sets.
 /// </summary>
 public void LoadDefaultSeedAndRuleSets()
 {
     try
     {
         rulesets = new ruleSet[numOfRuleSets];
         SearchIO.output("There are " + numOfRuleSets + " rulesets.");
         var filename = getOpenFilename(InputDirAbs, DefaultSeedFileName);
         if (filename != "")
         {
             var graphAndCanvas = filer.Open(filename, true);
             if (graphAndCanvas == null)
             {
                 seed = null;
                 DefaultSeedFileName = "";
                 SearchIO.MessageBoxShow("The seed graph was not found. Please change to valid file"
                                         + " in settings.", "Seed Graph Not Found.", "Error");
             }
             else
             {
                 seed = (designGraph)graphAndCanvas[0];
                 DefaultSeedFileName = filename;
                 SearchIO.addAndShowGraphWindow(graphAndCanvas,
                                                "SEED: " + Path.GetFileNameWithoutExtension(filename));
                 SearchIO.output("Seed graph, " + Path.GetFileNameWithoutExtension(filename) + " ,successfully opened.");
             }
         }
         for (var i = 0; i < numOfRuleSets; i++)
         {
             var RSFileName = "";
             if (i < defaultRSFileNames.Count)
             {
                 RSFileName = defaultRSFileNames[i];
             }
             filename = getOpenFilename(RulesDirAbs, RSFileName);
             if (filename == "")
             {
                 continue;
             }
             object objRS = filer.Open(filename, true);
             if (objRS == null)
             {
                 rulesets[i]           = null;
                 defaultRSFileNames[i] = "";
                 SearchIO.output("No Rule Set found at #" + i + ".");
             }
             else
             {
                 rulesets[i] = (ruleSet)((object[])objRS)[0];
                 SearchIO.addAndShowRuleSetWindow(new object[] { rulesets[i], filename },
                                                  "RS" + i + ": " + Path.GetFileNameWithoutExtension(filename));
                 // SearchIO.output("Rule Set #" + i + " sucessfully opened.");
             }
         }
     }
     catch (Exception exc)
     {
         ErrorLogger.Catch(exc);
     }
 }
Esempio n. 15
0
        /// <summary>
        ///   Deserialize rule from XML.
        /// </summary>
        /// <param name = "xmlString">The XML string.</param>
        /// <returns></returns>
        protected grammarRule DeSerializeRuleFromXML(string xmlString)
        {
            try
            {
                xmlString = xmlString.Replace("<Rotate>true</Rotate>", "<Rotate>OnlyZ</Rotate>");
                xmlString = xmlString.Replace("<Rotate>false</Rotate>", "<Rotate>Prohibited</Rotate>");
                xmlString = xmlString.Replace("<Rotate >true</Rotate>", "<Rotate>OnlyZ</Rotate>");
                xmlString = xmlString.Replace("<Rotate >false</Rotate>", "<Rotate>Prohibited</Rotate>");
                var stringReader     = new StringReader(xmlString);
                var ruleDeserializer = new XmlSerializer(typeof(grammarRule));
                var newGrammarRule   = (grammarRule)ruleDeserializer.Deserialize(stringReader);
                if (newGrammarRule.L == null)
                {
                    newGrammarRule.L = new designGraph();
                }
                else
                {
                    newGrammarRule.L.RepairGraphConnections();
                }

                if (newGrammarRule.R == null)
                {
                    newGrammarRule.R = new designGraph();
                }
                else
                {
                    newGrammarRule.R.RepairGraphConnections();
                }

                foreach (var er in newGrammarRule.embeddingRules.Where(er => er.oldLabels != null))
                {
                    foreach (var unkXmlElt in er.oldLabels)
                    {
                        /* this doesn't seem like the best place for this, but the double foreach
                         * loop is intended to help load old grammar rules that have the simpler
                         * version of embedding rules. */
                        if ((unkXmlElt.Name == "freeArcLabel") && (unkXmlElt.Value.Length > 0))
                        {
                            er.freeArcLabels.Add(unkXmlElt.Value);
                        }
                        if ((unkXmlElt.Name == "neighborNodeLabel") && (unkXmlElt.Value.Length > 0))
                        {
                            er.neighborNodeLabels.Add(unkXmlElt.Value);
                        }
                    }
                    er.oldLabels = null;
                }
                return(newGrammarRule);
            }
            catch (Exception ioe)
            {
                SearchIO.output("***Error Opening Graph:*** ");
                SearchIO.output(ioe.ToString());
                return(null);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Saves the new settings.
        /// </summary>
        /// <param name="filename">The filename.</param>
        public void saveNewSettings(string filename = "")
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                filename = FilePath;
            }
            if (string.IsNullOrWhiteSpace(filename))
            {
                filename = "GraphSynthSettings.gsconfig";
            }
            if (!Path.IsPathRooted(filename))
            {
                /* if windows machine,the default errorlog location is in the User\AppData\Roaming\GraphSynth */
                if (Environment.OSVersion.Platform.ToString().StartsWith("Win"))
                {
                    var appDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + DS + "GraphSynth";
                    if (!Directory.Exists(appDir))
                    {
                        Directory.CreateDirectory(appDir);
                    }
                    filename = appDir + DS + filename;
                }
                /* otherwise, put it in the executable directory */
                else
                {
                    filename = ExecDir + filename;
                }
            }
            FilePath = filename;
            var tempConfigDir = ConfigDir;

            ConfigDir = Path.GetDirectoryName(filename);
            StreamWriter streamWriter = null;

            try
            {
                streamWriter = new StreamWriter(filename);
                var SettingsSerializer = new XmlSerializer(typeof(GlobalSettings));
                SettingsSerializer.Serialize(streamWriter, this);
                SearchIO.MessageBoxShow("Saved at " + filename, "Settings file saved successfuly.");
            }
            catch (Exception e)
            {
                SearchIO.MessageBoxShow("The configuration file did not save because of error: "
                                        + e,
                                        "Error Saving config file.", "Error");
            }
            finally
            {
                ConfigDir = tempConfigDir;
                if (streamWriter != null)
                {
                    streamWriter.Close();
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Checks the rule with some issues that may have been overlooked.
        /// </summary>
        /// <param name="gR">The grammar rule.</param>
        /// <returns></returns>
        public static Boolean checkRule(grammarRule gR)
        {
            if ((gR.L.checkForRepeatNames()) &&
                !SearchIO.MessageBoxShow("You are not allowed to have repeat names in L. I have changed these " +
                                         "names to be unique, which may have disrupted your context graph, K. Do you want to continue?",
                                         "Repeat names in L", "Information", "YesNo", "Yes"))
            {
                return(false);
            }

            if ((gR.R.checkForRepeatNames()) &&
                !SearchIO.MessageBoxShow("You are not allowed to have repeat names in R. I have changed" +
                                         " these names to be unique, which may have disrupted your context graph, K. Do you" +
                                         " want to continue?", "Repeat names in R", "Information", "YesNo", "Yes"))
            {
                return(false);
            }

            if ((NotExistElementsinKR(gR)) &&
                !SearchIO.MessageBoxShow("There appears to be common elements between "
                                         + "the left and right hand sides of the rule that are indicated as \"Must NOT Exist\""
                                         + " within the left-hand side. This is not allowed. Continue Anyway?", "Improper use of negative elements",
                                         "Error", "YesNo", "No"))
            {
                return(false);
            }

            if ((NumKElements(gR) == 0) &&
                !SearchIO.MessageBoxShow("There appears to be no common elements between " +
                                         "the left and right hand sides of the rule. Is this intentional? If so, click yes to continue.",
                                         "No Context Graph", "Information", "YesNo", "Yes"))
            {
                return(false);
            }

            if ((KarcsChangeDirection(gR) != "") &&
                !SearchIO.MessageBoxShow("It appears that arc(s): " + KarcsChangeDirection(gR) +
                                         " change direction (to = from or vice-versa). Even though the arc(s) might be undirected," +
                                         " this can still lead to problems in the rule application, it is recommended that this is" +
                                         " fixed before saving. Save anyway?", "Change in Arc Direction", "Information", "YesNo", "Yes"))
            {
                return(false);
            }

            if ((!ValidateFreeArcEmbeddingRules(gR)) &&
                !SearchIO.MessageBoxShow("There appears to be invalid references in the free arc embedding rules." +
                                         " Node names used in free arc embedding rules do not exist. Continue Anyway?",
                                         "Invalid Free-Arc References", "Error", "YesNo", "No"))
            {
                return(false);
            }

            gR.ReorderNodes();
            return(true);
        }
Esempio n. 18
0
        public override object[] Open(string filename, Boolean suppressWarnings = false)
        {
            try
            {
                var xR = XmlReader.Create(filename);
                /* Load the file. */
                var doc = new XmlDocument();
                doc.Load(xR);
                xR.Close();
                /* create prefix<->namespace mappings (if any)  */
                var nsMgr = new XmlNamespaceManager(doc.NameTable);
                /* Query the document */
                if (doc.SelectNodes("/designGraph", nsMgr).Count > 0)
                {
                    return new object[] { OpenGraph(filename) }
                }
                ;
                else if (doc.SelectNodes("/grammarRule", nsMgr).Count > 0)
                {
                    return new object[] { OpenRule(filename) }
                }
                ;
                else if (doc.SelectNodes("/candidate", nsMgr).Count > 0)
                {
                    return new object[] { OpenCandidate(filename) }
                }
                ;
                else if (doc.SelectNodes("/ruleSet", nsMgr).Count > 0)
                {
                    return new object[] { OpenRuleSet(filename) }
                }
                ;
                else if (doc.DocumentElement.Attributes["Tag"].Value == "Graph")
                {
                    return(OpenGraphAndCanvas(filename));
                }
                else if (doc.DocumentElement.Attributes["Tag"].Value == "Rule")
                {
                    return(OpenRuleAndCanvas(filename));
                }

                else
                {
                    throw new Exception();
                }
            }
            catch (Exception e)
            {
                SearchIO.output(e.ToString());
            }
            return(null);
        }
Esempio n. 19
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!***");
        }
 private void ReadInSettings()
 {
     /* loadDefaults can be time consuming if there are many ruleSets/rules to load. */
     if (ArgAltConfig)
     {
         settings = GlobalSettings.readInSettings(AlternateConfig);
     }
     else
     {
         settings = GlobalSettings.readInSettings();
     }
     SearchIO.defaultVerbosity = settings.DefaultVerbosity;
     SearchIO.output("Default Verbosity set to " + settings.DefaultVerbosity);
 }
Esempio n. 21
0
 private static void LoadSearchAlgo(Type spt)
 {
     try
     {
         var constructor = spt.GetConstructor(new Type[] { typeof(GlobalSettings) });
         var searchAlgo  = (SearchProcess)constructor.Invoke(new object[] { GSApp.settings });
         SearchAlgorithms.Add(searchAlgo);
         SearchIO.output("\t" + spt.Name + " loaded successfully.", 3);
     }
     catch (Exception exc)
     {
         SearchIO.output("Unable to load " + spt.Name + ": " + exc.Message, 1);
     }
 }
        /// <summary>
        ///   Opens the rule set.
        /// </summary>
        /// <param name = "filename">The filename.</param>
        /// <returns></returns>
        public virtual ruleSet OpenRuleSet(string filename)
        {
            ruleSet      newRuleSet = null;
            StreamReader ruleReader = null;

            try
            {
                ruleReader = new StreamReader(filename);
                var ruleDeserializer = new XmlSerializer(typeof(ruleSet));
                newRuleSet          = (ruleSet)ruleDeserializer.Deserialize(ruleReader);
                newRuleSet.rulesDir = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar;
                newRuleSet.filer    = this;
                var numRules = newRuleSet.ruleFileNames.Count;
                int numLoaded;
                newRuleSet.rules = LoadRulesFromFileNames(newRuleSet.rulesDir,
                                                          newRuleSet.ruleFileNames, out numLoaded);

                SearchIO.output(Path.GetFileName(filename) + " successfully loaded");
                if (numRules == numLoaded)
                {
                    SearchIO.output(" and all (" + numLoaded + ") rules loaded successfully.");
                }
                else
                {
                    SearchIO.output("     but "
                                    + (numRules - numLoaded) + " rules did not load.");
                }

                if ((string.IsNullOrWhiteSpace(newRuleSet.name)) || (newRuleSet.name == "Untitled"))
                {
                    newRuleSet.name = Path.GetFileNameWithoutExtension(filename);
                }
            }
            catch (Exception ioe)
            {
                SearchIO.output("***XML Serialization Error***");
                SearchIO.output(ioe.ToString());
            }
            finally
            {
                if (ruleReader != null)
                {
                    ruleReader.Close();
                }
            }

            return(newRuleSet);
        }
Esempio n. 23
0
        /// <summary>
        /// Reads in the settings.
        /// </summary>
        /// <param name="configPath">The file path.</param>
        /// <returns></returns>
        public static GlobalSettings readInSettings(string configPath = "")
        {
            GlobalSettings settings  = null;
            var            filePaths = GetPotentialFiles(configPath.TrimEnd(DS));
            var            i         = 0;

            while ((i < filePaths.Count) && !readInSettings(filePaths[i], out settings))
            {
                i++;
            }
            if (i == filePaths.Count)
            {
                SearchIO.MessageBoxShow(
                    "Welcome to GraphSynth. This very well might be your first time with this program, " +
                    "since no valid configuration file was found.\n\nPlease review and edit the default "
                    + "Settings in the Edit Drop-Down Menu.",
                    "Welcome to GraphSynth");
                if (Environment.OSVersion.Platform.ToString().StartsWith("Win"))
                {
                    ConfigDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + DS +
                                "GraphSynth" + DS;
                }
                else
                {
                    ConfigDir = ExecDir;
                }
                settings = new GlobalSettings {
                    FilePath = configPath
                };
                settings.LoadDefaults();
                settings.saveNewSettings();
            }
            else
            {
                SearchIO.output("Loaded settings at" + filePaths[i] + ".");
                if (i > 0)
                {
                    SearchIO.output("Found after trying:");
                    for (var j = 0; j < i; j++)
                    {
                        SearchIO.output(j + ". " + filePaths[j]);
                    }
                }
                settings.FilePath = filePaths[i];
            }
            return(settings);
        }
Esempio n. 24
0
        /// <summary>
        ///   Opens the rule.
        /// </summary>
        /// <param name = "filename">The filename.</param>
        /// <returns></returns>
        public grammarRule OpenRule(string filename)
        {
            grammarRule newGrammarRule = null;
            XElement    xmlRule        = null;

            try
            {
                xmlRule = XElement.Load(filename);
            }
            catch (FileLoadException fle)
            {
                SearchIO.output("File was not found or accessible: " + fle);
                filename = "";
            }
            if (!string.IsNullOrWhiteSpace(filename))
            {
                if (!xmlRule.Name.LocalName.Contains("grammarRule"))
                {
                    xmlRule = (from xe in xmlRule.Elements()
                               where xe.Name.LocalName.Contains("grammarRule")
                               select xe).FirstOrDefault();
                }
                if (xmlRule != null)
                {
                    try
                    {
                        newGrammarRule = DeSerializeRuleFromXML(xmlRule.ToString());
                        RestoreDisplayShapes(newGrammarRule.L);
                        RestoreDisplayShapes(newGrammarRule.R);
                        removeNullWhiteSpaceEmptyLabels(newGrammarRule.L);
                        removeNullWhiteSpaceEmptyLabels(newGrammarRule.R);

                        if ((string.IsNullOrWhiteSpace(newGrammarRule.name)) || (newGrammarRule.name == "Untitled"))
                        {
                            newGrammarRule.name = Path.GetFileNameWithoutExtension(filename);
                        }
                    }
                    catch (Exception ioe)
                    {
                        SearchIO.output("***XML Serialization Error***");
                        SearchIO.output(ioe.ToString());
                    }
                }
            }
            return(newGrammarRule);
        }
        /// <summary>
        ///   Reloads the specific rule.
        /// </summary>
        /// <param name = "rs">The rs.</param>
        /// <param name = "i">The i.</param>
        public virtual void ReloadSpecificRule(ruleSet rs, int i)
        {
            var rulePath = rs.rulesDir + rs.ruleFileNames[i];

            SearchIO.output("Loading " + rs.ruleFileNames[i]);
            object ruleObj = Open(rulePath);

            if (ruleObj is grammarRule)
            {
                rs.rules[i] = (grammarRule)ruleObj;
            }
            else if (ruleObj is object[] &&
                     ((object[])ruleObj)[0] is grammarRule)
            {
                rs.rules[i] = ((grammarRule)((object[])ruleObj)[0]);
            }
        }
Esempio n. 26
0
 /// <summary>
 ///   For subsequent instances of GraphSynth, simply get to the original and pass it
 ///   the files that are to be opened - these are passed as the arguments.
 /// </summary>
 /// <param name = "e"><see cref = "T:Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs" />. Contains the command-line arguments of the subsequent application instance and indicates whether the first application instance should be brought to the foreground upon exiting the exception handler.</param>
 protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)
 {
     base.OnStartupNextInstance(e);
     GSApp.InputArgs = new List <string>(e.CommandLine);
     SearchIO.output(StringCollectionConverter.Convert(GSApp.InputArgs));
     GSApp.ParseArguments();
     if (GSApp.ArgAltConfig)
     {
         GSApp.settings =
             GlobalSettings.readInSettings(GSApp.AlternateConfig);
     }
     GSApp.OpenFiles();
     GSApp.main.setUpGraphElementAddButtons();
     GSApp.main.setUpGraphLayoutMenu();
     GSApp.main.setUpSearchProcessMenu();
     GSApp.main.Activate();
 }
Esempio n. 27
0
        //public override ruleSet OpenRuleSet(string filename)
        //{
        //    ruleSet newRuleSet = null;
        //    StreamReader ruleReader = null;
        //    try
        //    {
        //        ruleReader = new StreamReader(filename);
        //        var ruleDeserializer = new XmlSerializer(typeof(ruleSet));
        //        newRuleSet = (ruleSet)ruleDeserializer.Deserialize(ruleReader);
        //        newRuleSet.rulesDir = Path.GetDirectoryName(filename) + "/";
        //        newRuleSet.filer = this;
        //        var numRules = newRuleSet.ruleFileNames.Count;
        //        int numLoaded;
        //        if (progWindow.backgroundWorker.CancellationPending) return null;
        //        progress = -5;
        //        newRuleSet.rules = LoadRulesFromFileNames(newRuleSet.rulesDir, newRuleSet.ruleFileNames,
        //                                                  out numLoaded);

        //        SearchIO.output(Path.GetFileName(filename) + " successfully loaded");
        //        if (numRules == numLoaded) SearchIO.output("     and all rules loaded successfully.");
        //        else
        //            SearchIO.output("     but "
        //                            + (numRules - numLoaded) + " rules did not load.");

        //        newRuleSet.initializeFileWatcher(newRuleSet.rulesDir);
        //        if ((string.IsNullOrWhiteSpace(newRuleSet.name)) || (newRuleSet.name == "Untitled"))
        //            newRuleSet.name = Path.GetFileNameWithoutExtension(filename);
        //    }
        //    catch (Exception ioe)
        //    {
        //        SearchIO.output("***XML Serialization Error***", 0);
        //        SearchIO.output(ioe.ToString());
        //    }
        //    finally
        //    {
        //        if (ruleReader != null) ruleReader.Close();
        //    }

        //    return newRuleSet;
        //}

        protected override List <grammarRule> LoadRulesFromFileNames(string ruleDir, List <string> ruleFileNames,
                                                                     out int numLoaded)
        {
            var progStart = 5;
            var progStep  = (double)(100 - progStart) / ruleFileNames.Count;
            var step      = 0;
            var rules     = new List <grammarRule>();

            numLoaded = 0;
            while (numLoaded < ruleFileNames.Count)
            {
                var rulePath = ruleDir + ruleFileNames[numLoaded];
                if (File.Exists(rulePath))
                {
                    SearchIO.output("Loading " + ruleFileNames[numLoaded]);
                    object ruleObj = OpenRuleAndCanvas(rulePath);
                    if (ruleObj is grammarRule)
                    {
                        rules.Add((grammarRule)ruleObj);
                    }
                    else if (ruleObj is object[])
                    {
                        foreach (object o in (object[])ruleObj)
                        {
                            if (o is grammarRule)
                            {
                                rules.Add((grammarRule)o);
                            }
                        }
                    }
                    numLoaded++;
                }
                else
                {
                    SearchIO.output("Rule Not Found: " + ruleFileNames[numLoaded]);
                    ruleFileNames.RemoveAt(numLoaded);
                }
                if (progWindow.backgroundWorker.CancellationPending)
                {
                    return(null);
                }
                progress = -(progStart + (int)(progStep * step++));
            }
            return(rules);
        }
Esempio n. 28
0
 /// <summary>
 ///   Deserialize graph from XML.
 /// </summary>
 /// <param name = "xmlString">The XML string.</param>
 /// <returns></returns>
 protected designGraph DeSerializeGraphFromXML(string xmlString)
 {
     try
     {
         var stringReader      = new StringReader(xmlString);
         var graphDeserializer = new XmlSerializer(typeof(designGraph));
         var newDesignGraph    = (designGraph)graphDeserializer.Deserialize(stringReader);
         newDesignGraph.RepairGraphConnections();
         removeNullWhiteSpaceEmptyLabels(newDesignGraph);
         return(newDesignGraph);
     }
     catch (Exception ioe)
     {
         SearchIO.output("***Error Opening Graph:*** ");
         SearchIO.output(ioe.ToString());
         return(null);
     }
 }
Esempio n. 29
0
 public override void ReloadSpecificRule(ruleSet rs, int i)
 {
     lock (fileTransfer)
     {
         dispatch.Invoke((ThreadStart) delegate
         {
             var rulePath = rs.rulesDir + rs.ruleFileNames[i];
             SearchIO.output("Loading " + rs.ruleFileNames[i]);
             object ruleObj = Open(rulePath);
             if (ruleObj is grammarRule)
             {
                 rs.rules[i] = (grammarRule)ruleObj;
             }
             else if (ruleObj is object[] &&
                      ((object[])ruleObj)[0] is grammarRule)
             {
                 rs.rules[i] = ((grammarRule)((object[])ruleObj)[0]);
             }
         });
     }
 }
        protected override void OnStartup(StartupEventArgs args)
        {
            base.OnStartup(args);
            ParseArguments();
            /* Printing is done though the usual Console.Writeline, to a textbox. */
            console = new SearchIOToTextWriter();
            Console.SetOut(console);
            var aGS = new AboutGraphSynth(false);

            aGS.Show();

            SearchIO.output("Reading in settings file");
            ReadInSettings();

            SearchIO.output("Reading in default shapes.");
            LoadInShapes();

            SearchIO.output("starting main form...");
            SetUpMainWindow();

            SearchIO.output("opening files...");
            OpenFiles();

            SearchIO.output("Checking for update online");
            var updateThread = new Thread(CheckForUpdate);

            updateThread.Start();

            /* Okay, done with load-in, close self-promo */
            SearchIO.output("Closing Splash...");

            /* set the console.Writeline to the outputTextBox in main since the splash screen
             * is now closed. */
            main.outputTextBox.Text = aGS.outputTextBox.Text;
            console.outputBox       = main.outputTextBox;
            aGS.Close();
            SearchIO.output("----- Load in Complete ------");
            //  main.WindowState = WindowState.Normal; //for some reason with this line intact,
            // the process would never be terminated. (also see commented minimize cmd @line69
        }