Click here to Skip to main content
15,881,380 members
Articles / Artificial Intelligence

cn5apinet - ConceptNet5 API Library

Rate me:
Please Sign up or sign in to vote.
4.97/5 (6 votes)
28 Mar 2014GPL35 min read 45.3K   1.2K   19  
Connect to ConceptNet 5's REST API
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using cn5apinet;
using cn5apinet.GraphML;
using System.IO;
using System.Data;
using System.Xml.Schema;
using System.Drawing;

namespace CNAPINetDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        ConceptNetAPI CNClient = new ConceptNetAPI();
        GraphMLFile graphFile = new GraphMLFile();

        private void Form1_Load(object sender, EventArgs e)
        {
            //Select the first item in the Relationship Types ComboBox DropDownList
            cbRelationshipTypes.SelectedIndex = cbRelationshipTypes.Items.Count-1;
            cBoxGetParams.SelectedIndex = 0;

            this.Text = Application.ProductName + " " + Application.ProductVersion;
        }

        private void cbRelationshipTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        private void tbKey_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void tbGetKey_TextChanged(object sender, EventArgs e)
        {
            UpdateGetPreviewbox();
        }

        private void cBoxGetParams_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateGetPreviewbox();
        }

        private void UpdateGetPreviewbox()
        {
            //Skip NODE[no parameter]
            if (cBoxGetParams.SelectedIndex != 0 && 
                cBoxGetParams.Items[cBoxGetParams.SelectedIndex].ToString() != "REMOVELAST")
            {
                //don't do it this is already in there
                if (!tbGetPreview.Text.Contains(cBoxGetParams.Items[cBoxGetParams.SelectedIndex].ToString()))
                {
                    //get the string out of the combobox
                    string urltext = cBoxGetParams.Items[cBoxGetParams.SelectedIndex].ToString();
                    if (tbGetPreview.Text.Contains("?"))
                    {
                        if(urltext != "filter=")
                            tbGetPreview.Text = tbGetPreview.Text + "&" + urltext + txtbVars.Text.Trim();
                    }
                    else
                    {
                        //combine the combobox text with the key
                        if (cBoxGetParams.Items[cBoxGetParams.SelectedIndex].ToString() == "filter=")
                        {
                            // statements submitted by user "rspeer"
                            //The filter parameter lets you see only certain kinds of edges:
                            //filter=core: Only get edges from the ConceptNet 5 Core (not from ShareAlike resources).
                            //filter=core-assertions: We search for edges by default, and there can be many edges representing the same assertion. The core-assertions filter returns one result per assertion, whose weight is the total score of all the included edges. These are represented as virtual edges from the dataset /d/conceptnet/5/combined-core
                            //tbGetPreview.Text = "/" + tbGetKey.Text.Trim().Replace(" ", "_") + "?" + urltext.Trim() + txtbVars.Text.Trim();//book?get=normalized
                            tbGetPreview.Text = @"/contributor/omcs/" + txtbVars.Text.Trim();
                        }
                        else
                        {
                            if (!tbGetPreview.Text.Contains(@"/contributor/omcs/"))
                                tbGetPreview.Text = "/" + tbGetKey.Text.Trim().Replace(" ", "_") + "?" + urltext.Trim() + txtbVars.Text.Trim();//book?limit=5
                        }
                    }
                }

            }
            else if (cBoxGetParams.Items[cBoxGetParams.SelectedIndex].ToString() == "REMOVELAST")
            {
                //REMOVELAST
                //get the last + or &per_page=100
                int iLastPlus = -1;
                iLastPlus = tbGetPreview.Text.LastIndexOf("&");
                if (iLastPlus == -1)
                {
                    //this is the first, remove everything
                    if (!tbGetPreview.Text.Contains(@"/contributor/omcs/"))
                    {
                        iLastPlus = tbGetPreview.Text.LastIndexOf("?");
                        if(iLastPlus != -1)
                            tbGetPreview.Text = tbGetPreview.Text.Remove(iLastPlus);
                    }
                    else
                        tbGetPreview.Text = "/" + tbGetKey.Text.Trim().Replace(" ", "_");
                }

                if (iLastPlus != -1)
                {
                    tbGetPreview.Text = tbGetPreview.Text.Remove(iLastPlus, tbGetPreview.Text.Length - iLastPlus);
                }
                else
                {
                    //maybe remove the ?get=
                    int iLastEq = tbGetPreview.Text.LastIndexOf("?");
                    if (iLastEq != -1)
                    {
                        tbGetPreview.Text = tbGetPreview.Text.Remove(iLastEq, tbGetPreview.Text.Length - iLastEq);
                    }
                }
            }
            else
            {
                //index 0? ; just regular lookup
                tbGetPreview.Text = "/" + tbGetKey.Text.Trim().Replace(" ", "_");
            }

            //add the url
            //tbGetPreview.Text = Common.API_URL + tbGetPreview.Text;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(Common.RESTDOC_URL);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(Application.StartupPath + "\\cn5apinet.chm");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void linkLCN5Wiki_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(Common.RESTDOC_URL);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void chkbSim1_CheckedChanged(object sender, EventArgs e)
        {
            if (chkbSim1.Checked)
                chkbSim2.Checked = false;
        }

        private void chkbSim2_CheckedChanged(object sender, EventArgs e)
        {
            if (chkbSim2.Checked)
                chkbSim1.Checked = false;
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            /*
            //JSON test
            Concept cnreturnsList = CNClient.lookup_json(ReturnTYPE.leftfeature, LANG.en, tbPreview.Text.Trim());
            tbOutput.AppendText("lookup_json response count: " + Convert.ToString(cnreturnsList.Count) + Environment.NewLine);
            tbOutput.AppendText(cnreturnsList.PPrint());

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

            //XML test
            XmlDocument cnXML = new XmlDocument();
            cnXML = CNClient.lookup_xml(ReturnTYPE.leftfeature, LANG.en, tbPreview.Text.Trim());
            tbOutput.AppendText("lookup_xml response : " + Environment.NewLine);
            tbOutput.AppendText(cnXML.InnerXml.ToString());

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

            //Convert Xml To JSON string test
            tbOutput.AppendText("Convert Xml To JSON response : " + Environment.NewLine);
            string json_str = ConceptNetAPI.ConvertToJSON(cnXML);
            tbOutput.AppendText(json_str);

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

            //Convert Xml To JSON Objects test
            tbOutput.AppendText("Convert JSON string to objects : " + Environment.NewLine);
            List<AssertionObj> CNObjList = ConceptNetAPI.ConvertToCNObj(json_str);
            tbOutput.AppendText("ConvertToCNObj response count: " + Convert.ToString(cnreturnsList.Count));

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

            //Using previous CNObjList, test assertions_for_concept DIRECTION.all
            Concept concept = new Concept(tbPreview.Text.Trim().Split('/')[1]);
            concept.AddRange(CNObjList.ToArray<AssertionObj>());
            Concept newconcept = new Concept(tbPreview.Text.Trim().Split('/')[1]);
            newconcept = CNClient.assertions_for_concept(concept, DIRECTION.all);
            tbOutput.AppendText("assertions_for_concept(DIRECTION.all) response count: " + Convert.ToString(newconcept.Count) + Environment.NewLine);
            tbOutput.AppendText(newconcept.PPrint());

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

            //Using previous CNObjList, test assertions_for_concept DIRECTION.forward
            newconcept = new Concept(tbPreview.Text.Trim().Split('/')[1]);
            newconcept = CNClient.assertions_for_concept(concept, DIRECTION.forward);
            tbOutput.AppendText("assertions_for_concept(DIRECTION.forward) response count: " + Convert.ToString(newconcept.Count) + Environment.NewLine);
            tbOutput.AppendText(newconcept.PPrint());

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

            //Using previous CNObjList, test assertions_for_concept DIRECTION.backward
            newconcept = new Concept(tbPreview.Text.Trim().Split('/')[1]);
            newconcept = CNClient.assertions_for_concept(concept, DIRECTION.backward);

            tbOutput.AppendText("assertions_for_concept(DIRECTION.backward) response count: " + Convert.ToString(newconcept.Count) + Environment.NewLine);
            tbOutput.AppendText(newconcept.PPrint());

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

            //lookup_concept_raw test
            cn_concept raw_concept = new cn_concept();
            raw_concept = CNClient.lookup_concept_raw(LANG.en, tbPreview.Text.Trim().Split('/')[1]);
            if (raw_concept != null)
            {
                tbOutput.AppendText("lookup_concept_raw response : " + Environment.NewLine);
                tbOutput.AppendText(raw_concept.PPrint());
            }
            else
                tbOutput.AppendText("null");

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

            //surface_forms_for_concept test
            tbOutput.AppendText("Given a dictionary representing a concept, get a list of its surface forms [surface_forms_for_concept] : " + Environment.NewLine);
            List<SurfaceFormObj> SurfaceObjList = CNClient.surface_forms_for_concept(raw_concept, 10);
            tbOutput.AppendText("SurfaceObjList response count: " + Convert.ToString(SurfaceObjList.Count));

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

            //key.Split('/')[1]
            SurfaceFormObj surface_concept = new SurfaceFormObj();
            surface_concept = CNClient.lookup_concept_from_surface(LANG.en, tbPreview.Text.Trim().Split('/')[1]);//only send the word for surface lookups
            tbOutput.AppendText("lookup_concept_from_surface response : " + Environment.NewLine);
            if (surface_concept != null)
            {
                tbOutput.AppendText(surface_concept.PPrint());
            }
            else
                tbOutput.AppendText("null");

            tbOutput.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);
            tbOutput.AppendText("(If you receive a lot of null values, check your spelling and try again. Or there may be no valid entries in Conceptnet.)");
            */
            Cursor.Current = Cursors.Default;
        }

        /// <summary>
        /// test button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            #region Saxon.Api for easy searching thru xml
            ////Saxon.Api
            //// Create a Processor instance.
            //Processor processor = new Processor();

            //// Load the source document
            //XdmNode input = processor.NewDocumentBuilder().Build(new Uri("file:////" + Application.StartupPath + "/books.xml"));

            //// Create an XPath compiler
            //XPathCompiler xpath = processor.NewXPathCompiler();

            //// Enable caching, so each expression is only compiled once
            //xpath.Caching = true;

            //// Compile and evaluate some XPath expressions
            //foreach (XdmItem item in xpath.Evaluate("//ITEM", input))
            //{
            //    Console.WriteLine("TITLE: " + xpath.EvaluateSingle("string(TITLE)", item));
            //    Console.WriteLine("PRICE: " + xpath.EvaluateSingle("string(PRICE)", item));
            //}

            ////Saxon.Api END
            #endregion

            List<cn5apinet.GraphML.GraphMLNode> nodeList = new List<cn5apinet.GraphML.GraphMLNode>();
            List<cn5apinet.GraphML.GraphMLEdge> edgeList = new List<cn5apinet.GraphML.GraphMLEdge>();

            //CreateGraphMLFile()
            graphFile = new cn5apinet.GraphML.GraphMLFile(Application.StartupPath + "//quicktest.graphml");

            //Create the seed node...
            GraphMLNode node1 = new GraphMLNode(0, new Geometry(30.0, 50.0, 1, 1));//customize the node...
            node1.Text = tbGetKey.Text.Trim();
            node1.FillColor = "#00FF00";//Green
            //Add this node to list
            nodeList.Add(node1);

            //Create second node...
            GraphMLNode node2 = new GraphMLNode(1, new Geometry(30.0, 50.0, node1.Geometry.y + 49, node1.Geometry.x));//customize the node...
            node2.Text = "shelf";
            //Add this node to list
            nodeList.Add(node2);

            //Create the connecting Edge...
            GraphMLEdge edge0 = new GraphMLEdge(0, node1.NodeID, node2.NodeID, "can find on");
            //Add this edge to list
            edgeList.Add(edge0);

            graphFile.Create(nodeList, edgeList, Application.ProductName);

            //Validation
            /*
            XmlTextReader tr = new XmlTextReader(Application.StartupPath + "\\quicktest.graphml");
            XmlValidatingReader vr = new XmlValidatingReader(tr);
            XmlSchemaCollection xsc = new XmlSchemaCollection();
            xsc.Add("urn:xlink-schema", Application.StartupPath + "\\graphml.dtd");
            vr.Schemas.Add(xsc);
            */
            Cursor.Current = Cursors.Default;
        }

        private void btnLookupWithRel_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            tbOutputGet.Clear();
            string ErrMessage = "";

            try
            {
                //Lookuptest
                Lookup lookup_results = CNClient.Lookup(LANG.en, tbGetPreview.Text.Trim().Split('/')[1]);
                if (lookup_results != null)
                {
                    tbOutputGet.AppendText("Lookup response : " + Environment.NewLine);
                    tbOutputGet.AppendText(lookup_results.PPrint());
                }
                else
                    tbOutputGet.AppendText("null");

                tbOutputGet.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

                string[] seperatorsForwardSlash = new string[] { "/" };
                List<edgeLookup> RelList = new List<edgeLookup>();

                if (lookup_results.numFound != -1)
                {
                    string RelWanted = cBoxRelationships.Items[cBoxRelationships.SelectedIndex].ToString();
                    foreach (edgeLookup o in lookup_results.ToEdgeList())
                    {
                        String[] spiltstart = Convert.ToString(o.uri).Split(',');
                        //"/a/[/r/DerivedFrom/,/c/en/toast/v/propose_a_toast_to/,/c/en/salute/n/an_act_of_honor_or_courteous_recognition/]"
                        // [0] = "/a/[/r/DerivedFrom/"
                        // [1] = "/c/en/toast/v/propose_a_toast_to/"
                        // [2] = "/c/en/salute/n/an_act_of_honor_or_courteous_recognition/"
                        string[] Relationshiptext = spiltstart[0].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                        if (Relationshiptext[3] == RelWanted)
                        {
                            RelList.Add(o);
                        }
                    }
                    btnGetLookup.Enabled = false;
                }

                #region GraphML
                List<cn5apinet.GraphML.GraphMLNode> nodeList = new List<cn5apinet.GraphML.GraphMLNode>();
                List<cn5apinet.GraphML.GraphMLEdge> edgeList = new List<cn5apinet.GraphML.GraphMLEdge>();
                if (cBoxGraphML.Checked)
                {
                    //let's look at the edges, nodes and create a graphML

                    //Create the seed node...
                    GraphMLNode node0 = new GraphMLNode(0, new Geometry(30.0, 50.0, 1, 1));//customize the node...
                    node0.Text = tbGetKey.Text.Trim();
                    node0.FillColor = "#00FF00";//Green
                    //Add this node to list
                    nodeList.Add(node0);
                    int i = 1;
                    if (lookup_results.numFound != -1)
                    {
                        foreach (edgeLookup o in RelList)
                        {
                            //need Json to convert o;
                            Dictionary<String, String> startDict = new Dictionary<string, string>();
                            String[] spiltstart = Convert.ToString(o.uri).Replace("]", "").Split(',');
                            //"/a/[/r/DerivedFrom/,/c/en/toast/v/propose_a_toast_to/,/c/en/salute/n/an_act_of_honor_or_courteous_recognition/]"
                            // [0] = "/a/[/r/DerivedFrom/"
                            // [1] = "/c/en/toast/v/propose_a_toast_to/"
                            // [2] = "/c/en/salute/n/an_act_of_honor_or_courteous_recognition/"

                            //= Convert.ToString(((edge)o).key);
                            //Create the connecting Edge...
                            //Add this node
                            GraphMLNode nodeX = new GraphMLNode(i, new Geometry(30.0, 50.0, 1, 0));
                            string[] nodetext = spiltstart[2].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            nodeX.Text = nodetext[nodetext.Length - 1];
                            nodeList.Add(nodeX);

                            //Add this edge to list
                            string[] edgetext = spiltstart[0].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            GraphMLEdge edge0 = new GraphMLEdge(i, node0.NodeID, nodeX.NodeID, edgetext[edgetext.Length - 1] + " " + Convert.ToString(o.score));
                            edgeList.Add(edge0);
                            i = i + 1;

                        }
                    }
                    //Re-arrange the nodes
                    int numofNodes = nodeList.Count;
                    int g = 1;
                    //Draw the nodes around first node[0] in a circle
                    double radius = 100.0;
                    if (numofNodes > 10)
                        radius = (nodeList[0].Geometry.height * 0.45) * numofNodes / 2;

                    for (double h = 0.0; h < 360.0; h += (360 / numofNodes))
                    {
                        if (g >= numofNodes)
                            break;
                        double angle = h * System.Math.PI / 180;
                        if (cBoxQChildren.Checked == true && g < 4)
                        {
                            //push out the top 3 nodes, they should be returned by score in the json
                            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.x + radius * System.Math.Cos(angle)) * 2;
                            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle)) * 2;
                        }
                        else
                        {
                            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.y + radius * System.Math.Cos(angle));
                            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle));
                        }
                        g = g + 1;
                    }

                    graphFile = new cn5apinet.GraphML.GraphMLFile(Application.StartupPath + "//" + node0.Text + ".graphml");
                    graphFile.Create(nodeList, edgeList, Application.ProductName);

                    System.Diagnostics.Process.Start(graphFile.FullPathLocation);
                }
                #endregion GraphML
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ErrMessage);
            }

            Cursor.Current = Cursors.Default;
        }

        private void btnAsk_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            tbOutputGet.Clear();
            string ErrMessage = "";

            try
            {
                //Lookuptest
                Lookup lookup_results = new Lookup();
                lookup_results = CNClient.Lookup(LANG.en, tbKey.Text.Trim());
                //let's update the other tab
                tbGetKey.Text = tbKey.Text.Trim();

                if (lookup_results != null)
                {
                    tbOutputGet.AppendText("Lookup response : " + Environment.NewLine);
                    tbOutputGet.AppendText(lookup_results.PPrint());
                }
                else
                    tbOutputGet.AppendText("null");

                tbOutputGet.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

                string[] seperatorsForwardSlash = new string[] { "/" };
                //List<String> RelList = new List<String>();
                string wantedRel = cbRelationshipTypes.Items[cbRelationshipTypes.SelectedIndex].ToString();
                List<edgeLookup> RelList = new List<edgeLookup>();
                if (lookup_results.numFound != -1)
                {
                    foreach (edgeLookup o in lookup_results.ToEdgeList())
                    {
                        String[] spiltstart = Convert.ToString(o.uri).Split(',');
                        //"/a/[/r/DerivedFrom/,/c/en/toast/v/propose_a_toast_to/,/c/en/salute/n/an_act_of_honor_or_courteous_recognition/]"
                        // [0] = "/a/[/r/DerivedFrom/"
                        // [1] = "/c/en/toast/v/propose_a_toast_to/"
                        // [2] = "/c/en/salute/n/an_act_of_honor_or_courteous_recognition/"
                        string[] Relationshiptext = spiltstart[0].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            string[] Keytext = spiltstart[1].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            string[] Key2text = spiltstart[2].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            if (wantedRel == Relationshiptext[3] && tbKey.Text.Trim().ToLower() == Keytext[2].ToLower() && tbKey2.Text.Trim().ToLower() == Key2text[2].ToLower())
                                RelList.Add(o);
                    }
                    if (RelList.Count != 0)
                    {
                        //get the score and answer (assuming first one is highest score)
                        if (Convert.ToDouble(RelList[0].score) <= 0.0)
                        {
                            lbAnswer.ForeColor = Color.Red;
                            lbAnswer.Text = "No";
                        }
                        else if (Convert.ToDouble(RelList[0].score) <= 1.0)
                        {
                            lbAnswer.ForeColor = Color.Yellow;
                            lbAnswer.Text = "Maybe";
                        }
                        else
                        {
                            lbAnswer.ForeColor = Color.Green;
                            lbAnswer.Text = "Yes";
                        }
                    }
                    else
                    {
                        //No match found, No
                        lbAnswer.ForeColor = Color.Red;
                        lbAnswer.Text = "No";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ErrMessage);
            }

            Cursor.Current = Cursors.Default;
        }

        private void btnGetLookup_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            tbOutputGet.Clear();
            cBoxRelationships.Items.Clear();
            string ErrMessage = "";
            string contributor = "";

            try
            {
                //Lookuptest
                Lookup lookup_results = new Lookup();
                //unforchantly, we need to change it up for a filter by contributor call as it uses a different url pattern
                if (tbGetPreview.Text.Trim().Contains(@"/contributor/"))
                {
                    lookup_results = CNClient.Lookup(LANG.en, tbGetPreview.Text.Trim());
                    contributor = txtbVars.Text.Trim();
                }
                else
                    lookup_results = CNClient.Lookup(LANG.en, tbGetPreview.Text.Trim().Split('/')[1]);

                if (lookup_results != null)
                {
                    tbOutputGet.AppendText("Lookup response : " + Environment.NewLine);
                    tbOutputGet.AppendText(lookup_results.PPrint());
                }
                else
                    tbOutputGet.AppendText("null");

                tbOutputGet.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

                string[] seperatorsForwardSlash = new string[] { "/" };
                //List<String> RelList = new List<String>();

                if (lookup_results.numFound != -1)
                {
                    foreach (edgeLookup o in lookup_results.ToEdgeList())
                    {
                        String[] spiltstart = Convert.ToString(o.uri).Split(',');
                        //"/a/[/r/DerivedFrom/,/c/en/toast/v/propose_a_toast_to/,/c/en/salute/n/an_act_of_honor_or_courteous_recognition/]"
                        // [0] = "/a/[/r/DerivedFrom/"
                        // [1] = "/c/en/toast/v/propose_a_toast_to/"
                        // [2] = "/c/en/salute/n/an_act_of_honor_or_courteous_recognition/"
                        string[] Relationshiptext = spiltstart[0].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                        if (!cBoxRelationships.Items.Contains(Relationshiptext[3]))
                            cBoxRelationships.Items.Add(Relationshiptext[3]);
                        if (cBoxRelationships.Items.Count != 0)
                        {
                            cBoxRelationships.SelectedIndex = 0;
                            cBoxRelationships.Enabled = true;
                            if(contributor == "")
                                btnLookupWithRel.Enabled = true;
                        }
                    }
                    btnGetLookup.Enabled = false;
                }

                #region GraphML
                List<cn5apinet.GraphML.GraphMLNode> nodeList = new List<cn5apinet.GraphML.GraphMLNode>();
                List<cn5apinet.GraphML.GraphMLEdge> edgeList = new List<cn5apinet.GraphML.GraphMLEdge>();
                if (cBoxGraphML.Checked)
                {
                    //let's look at the edges, nodes and create a graphML

                    //Create the seed node...
                    GraphMLNode node0 = new GraphMLNode(0, new Geometry(30.0, 50.0, 1, 1));//customize the node...
                    if (contributor == "")
                        node0.Text = tbGetKey.Text.Trim();
                    else
                        node0.Text = contributor;
                    node0.FillColor = "#00FF00";//Green
                    //Add this node to list
                    nodeList.Add(node0);
                    int i = 1;
                    if (lookup_results.numFound != -1)
                    {
                        foreach (edgeLookup o in lookup_results.ToEdgeList())
                        {
                            //need Json to convert o;
                            Dictionary<String, String> startDict = new Dictionary<string, string>();
                            String[] spiltstart = Convert.ToString(o.uri).Replace("]","").Split(',');
                            //"/a/[/r/DerivedFrom/,/c/en/toast/v/propose_a_toast_to/,/c/en/salute/n/an_act_of_honor_or_courteous_recognition/]"
                            // [0] = "/a/[/r/DerivedFrom/"
                            // [1] = "/c/en/toast/v/propose_a_toast_to/"
                            // [2] = "/c/en/salute/n/an_act_of_honor_or_courteous_recognition/"

                            //= Convert.ToString(((edge)o).key);
                            //Create the connecting Edge...
                            //Add this node
                            GraphMLNode nodeX = new GraphMLNode(i, new Geometry(30.0, 50.0, 1, 0));
                            string[] nodetext = spiltstart[2].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            nodeX.Text = nodetext[nodetext.Length - 1];
                            nodeList.Add(nodeX);
                            if (nodeX.Text == "n")
                                Console.Write("");

                            //Add this edge to list
                            string[] edgetext = spiltstart[0].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            GraphMLEdge edge0 = new GraphMLEdge(i, node0.NodeID, nodeX.NodeID, edgetext[edgetext.Length - 1] + " " + Convert.ToString(o.score));
                            edgeList.Add(edge0);
                            i = i + 1;

                        }
                    }
                    //Re-arrange the nodes
                    int numofNodes = nodeList.Count;
                    int g = 1;
                    //Draw the nodes around first node[0] in a circle
                    double radius = 100.0;
                    if (numofNodes > 10)
                        radius = (nodeList[0].Geometry.height * 0.45) * numofNodes / 2;

                    for (double h = 0.0; h < 360.0; h += (360 / numofNodes))
                    {
                        if (g >= numofNodes)
                            break;
                        double angle = h * System.Math.PI / 180;
                        if (cBoxQChildren.Checked == true && g < 4)
                        {
                            //push out the top 3 nodes, they should be returned by score in the json
                            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.x + radius * System.Math.Cos(angle)) * 2;
                            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle)) * 2;
                        }
                        else
                        {
                            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.y + radius * System.Math.Cos(angle));
                            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle));
                        }
                        g = g + 1;
                    }

                    graphFile = new cn5apinet.GraphML.GraphMLFile(Application.StartupPath + "//" + node0.Text + ".graphml");
                    graphFile.Create(nodeList, edgeList, Application.ProductName);

                    System.Diagnostics.Process.Start(graphFile.FullPathLocation);
                }
                #endregion GraphML


                //order by score [should be pre-sorted so not necessary?]
                /*
                Array.Sort(edge_argList.ToArray(), delegate(edge edge_arg1, edge edge_arg2)
                {
                    return ((double)edge_arg1.score).CompareTo(edge_arg2.score); 
                });

                foreach (edge edge in edge_argList)
                    Console.Write(edge.key.ToString() + edge.score.ToString() + Environment.NewLine);
                 */

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ErrMessage);
            }

            Cursor.Current = Cursors.Default;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            tbOutputGet.Clear();
            string ErrMessage = "";

            try
            {
                //Lookuptest
                string wantedRel = cbRelationshipTypes.Items[cbRelationshipTypes.SelectedIndex].ToString();
                //let's update the other tab
                tbGetKey.Text = tbKey.Text.Trim();
                string end = tbKey2.Text.Trim();
                string start = tbKey.Text.Trim();
                Search search_results = new Search();

                search_results = CNClient.Search(LANG.en, wantedRel, start, end, start, Convert.ToInt16(txtbSearchLimit.Text.Trim()));


                if (search_results != null)
                {
                    tbOutputGet.AppendText("Lookup response : " + Environment.NewLine);
                    tbOutputGet.AppendText(search_results.PPrint());
                }
                else
                    tbOutputGet.AppendText("null");

                tbOutputGet.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

                string[] seperatorsForwardSlash = new string[] { "/" };
                List<edgeSearch> RelList = new List<edgeSearch>();
                if (search_results.numFound != -1)
                {
                    foreach (edgeSearch o in search_results.ToEdgeList())
                    {
                        //check to see if startLemmas was previously added 
                        if (chkbExactMatch.Checked)
                        {
                            if(o.endLemmas.Contains(end.Trim()+" "))
                                RelList.Add(o);
                        }
                        else
                            RelList.Add(o);
                    }
                }

                #region GraphML
                List<cn5apinet.GraphML.GraphMLNode> nodeList = new List<cn5apinet.GraphML.GraphMLNode>();
                List<cn5apinet.GraphML.GraphMLEdge> edgeList = new List<cn5apinet.GraphML.GraphMLEdge>();
                if (cBoxGraphML.Checked)
                {
                    //let's look at the edges, nodes and create a graphML

                    //Create the seed node...
                    GraphMLNode node0 = new GraphMLNode(0, new Geometry(30.0, 50.0, 1, 1));//customize the node...
                    node0.Text = end;
                    node0.FillColor = "#00FF00";//Green
                    //Add this node to list
                    nodeList.Add(node0);
                    int i = 1;
                    if (search_results.numFound != -1)
                    {
                        foreach (edgeSearch o in RelList)
                        {
                            //need Json to convert o;
                            Dictionary<String, String> startDict = new Dictionary<string, string>();
                            String[] spiltstart = Convert.ToString(o.uri).Replace("]", "").Split(',');
                            //Create the connecting Edge...
                            //Add this node
                            GraphMLNode nodeX = new GraphMLNode(i, new Geometry(30.0, 50.0, 1, 0));
                            string[] nodetext = spiltstart[2].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            nodeX.Text = nodetext[nodetext.Length - 1];
                            nodeList.Add(nodeX);

                            //Add this edge to list
                            string[] edgetext = spiltstart[0].Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            GraphMLEdge edge0 = new GraphMLEdge(i, node0.NodeID, nodeX.NodeID, edgetext[edgetext.Length - 1] + " " + Convert.ToString(o.score));
                            edgeList.Add(edge0);
                            i = i + 1;

                        }
                    }
                    //Re-arrange the nodes
                    int numofNodes = nodeList.Count;
                    int g = 1;
                    //Draw the nodes around first node[0] in a circle
                    double radius = 100.0;
                    if (numofNodes > 10)
                        radius = (nodeList[0].Geometry.height * 0.45) * numofNodes / 2;

                    for (double h = 0.0; h < 360.0; h += (360 / numofNodes))
                    {
                        if (g >= numofNodes)
                            break;
                        double angle = h * System.Math.PI / 180;
                        if (cBoxQChildren.Checked == true && g < 4)
                        {
                            //push out the top 3 nodes, they should be returned by score in the json
                            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.x + radius * System.Math.Cos(angle)) * 2;
                            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle)) * 2;
                        }
                        else
                        {
                            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.y + radius * System.Math.Cos(angle));
                            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle));
                        }
                        g = g + 1;
                    }

                    graphFile = new cn5apinet.GraphML.GraphMLFile(Application.StartupPath + "//" + node0.Text + ".graphml");
                    graphFile.Create(nodeList, edgeList, Application.ProductName);

                    System.Diagnostics.Process.Start(graphFile.FullPathLocation);
                }
                #endregion GraphML
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ErrMessage);
            }

            Cursor.Current = Cursors.Default;
        }

        private void btnAssociation_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            tbOutputGet.Clear();
            string ErrMessage = "";

            try
            {
                //Lookuptest
                string wantedRel = cbRelationshipTypes.Items[cbRelationshipTypes.SelectedIndex].ToString();
                //let's update the other tab
                tbGetKey.Text = tbKey.Text.Trim();
                string mainword = ""; 
                string text = ""; 
                //txtbSim2MainWord.Text.Trim()
                if (chkbSim2.Checked)
                {
                    //multi association lookup
                    mainword = txtbSim2MainWord.Text.Trim() + "," + txtbSim2SecondWords.Text.Trim();
                }
                else
                {
                    mainword = txtbSimMainWord.Text.Trim();
                    text = txtbSimSecondWord.Text.Trim();
                }

                Association search_results = new Association();
                if(!chkEnFilter.Checked)
                    search_results = CNClient.Associations(LANG.en, mainword, text, Convert.ToInt16(txtSimLimit.Text.Trim()), chkbSim2.Checked, Convert.ToInt16(txtbSim2Weight.Text.Trim()));
                else
                    search_results = CNClient.Associations(LANG.en, mainword, LANG.en.ToString(), Convert.ToInt16(txtSimLimit.Text.Trim()), chkbSim2.Checked, Convert.ToInt16(txtbSim2Weight.Text.Trim()));
                
                if (search_results != null)
                {
                    tbOutputGet.AppendText("Lookup response : " + Environment.NewLine);
                    tbOutputGet.AppendText(search_results.PPrint());
                }
                else
                    tbOutputGet.AppendText("null");

                tbOutputGet.AppendText(Environment.NewLine + "--------------------" + Environment.NewLine);

                string[] seperatorsForwardSlash = new string[] { "/" };
                List<pair> RelList = new List<pair>();
                if (search_results != null)
                {
                    foreach (pair o in search_results.ToEdgeList())
                    {
                        RelList.Add(o);
                        //pair Pair = new pair();
                        //Pair.URIWord = o.GetValue(0).ToString();
                        //Pair.score = (float)o.GetValue(1);
                        //RelList.Add(Pair);
                    }
                }

                #region GraphML
                List<cn5apinet.GraphML.GraphMLNode> nodeList = new List<cn5apinet.GraphML.GraphMLNode>();
                List<cn5apinet.GraphML.GraphMLEdge> edgeList = new List<cn5apinet.GraphML.GraphMLEdge>();
                if (cBoxGraphML.Checked)
                {
                    //let's look at the edges, nodes and create a graphML

                    //Create the seed node...
                    GraphMLNode node0 = new GraphMLNode(0, new Geometry(30.0, 50.0, 1, 1));//customize the node...
                    node0.Text = mainword;
                    node0.FillColor = "#00FF00";//Green
                    //Add this node to list
                    nodeList.Add(node0);
                    int i = 1;
                    if (search_results != null)
                    {
                        foreach (pair o in RelList)
                        {
                            //need Json to convert o;
                            Dictionary<String, String> startDict = new Dictionary<string, string>();
                            //Create the connecting Edge...
                            //Add this node
                            GraphMLNode nodeX = new GraphMLNode(i, new Geometry(30.0, 50.0, 1, 0));
                            string[] nodetext = o.URIWord.Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            nodeX.Text = nodetext[nodetext.Length - 1];
                            nodeList.Add(nodeX);

                            //Add this edge to list
                            string[] edgetext = o.URIWord.Split(seperatorsForwardSlash, StringSplitOptions.RemoveEmptyEntries);
                            GraphMLEdge edge0 = new GraphMLEdge(i, node0.NodeID, nodeX.NodeID, edgetext[edgetext.Length - 1] + " " + Convert.ToString(o.score));
                            edgeList.Add(edge0);
                            i = i + 1;

                        }
                    }
                    //Re-arrange the nodes
                    int numofNodes = nodeList.Count;
                    int g = 1;
                    //Draw the nodes around first node[0] in a circle
                    double radius = 100.0;
                    if (numofNodes > 10)
                        radius = (nodeList[0].Geometry.height * 0.45) * numofNodes / 2;

                    for (double h = 0.0; h < 360.0; h += (360 / numofNodes))
                    {
                        if (g >= numofNodes)
                            break;
                        double angle = h * System.Math.PI / 180;
                        if (cBoxQChildren.Checked == true && g < 4)
                        {
                            //push out the top 3 nodes, they should be returned by score in the json
                            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.x + radius * System.Math.Cos(angle)) * 2;
                            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle)) * 2;
                        }
                        else
                        {
                            nodeList[g].Geometry.x = (int)(nodeList[0].Geometry.y + radius * System.Math.Cos(angle));
                            nodeList[g].Geometry.y = (int)(nodeList[0].Geometry.y + radius * System.Math.Sin(angle));
                        }
                        g = g + 1;
                    }

                    graphFile = new cn5apinet.GraphML.GraphMLFile(Application.StartupPath + "//" + node0.Text + ".graphml");
                    graphFile.Create(nodeList, edgeList, Application.ProductName);

                    System.Diagnostics.Process.Start(graphFile.FullPathLocation);
                }
                #endregion GraphML
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ErrMessage);
            }

            Cursor.Current = Cursors.Default;
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Chief Technology Officer Earthbotics.com
United States United States
Born in Pennsylvania (USA), just north of Philadelphia. Joe has been programming since he was ten[now much older]. He is entirely self-taught programmer, & he is currently working as an IT Manager in Seattle WA. He was previously U.S. Navy Active Reservist for (SPAWAR)
In '98 was honorably discharged from the USN. He served onboard the USS Carl Vinson (94-98) He was lucky enough to drink President Clinton's leftover wine, promoted by his Captain, and flew in a plane off the flightdeck but not all at the same time. His interests, when time allows, are developing
misc apps and Artificial Intelligence proof-of-concept demos that specifically exhibits human behavior. He is a true sports-a-holic, needs plenty of caffeine, & a coding junkie. He also enjoys alternative music and a big Pearl Jam, Nirvana, new alternative music fan, and the Alison Wonderland.
He is currently working on earthboticsai.net<> which he says is fun and cool. Cool | :cool: :cheers:

Joe is an INTP[
^] personality type. Joe "sees everything in terms of how it could be improved, or what it could be turned into. INTP's live primarily inside their own minds." INTPs also can have the "greatest precision in thought and language. Can readily discern contradictions and inconsistencies. The world exists primarily to be understood. 1% of the total population" [

Comments and Discussions