示例#1
0
        //if you pass in the fileName 'ClipBoard', the save is to the windows clipboard
        public static bool Save(NeuronArray theNeuronArray, string fileName)
        {
            Stream file;
            string tempFile      = "";
            bool   fromClipboard = fileName == "ClipBoard";

            if (!fromClipboard)
            {
                //Check for file access
                if (!CanWriteTo(fileName, out string message))
                {
                    MessageBox.Show("Could not save file because: " + message);
                    return(false);
                }

                MainWindow.thisWindow.SetProgress(0, "Saving Network File");

                tempFile = System.IO.Path.GetTempFileName();
                file     = File.Create(tempFile);
            }
            else
            {
                file = new MemoryStream();
            }
            Type[] extraTypes = GetModuleTypes();
            try
            {
                XmlSerializer writer = new XmlSerializer(typeof(NeuronArray), extraTypes);
                writer.Serialize(file, theNeuronArray);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    MessageBox.Show("Xml file write failed because: " + e.InnerException.Message);
                }
                else
                {
                    MessageBox.Show("Xml file write failed because: " + e.Message);
                }
                MainWindow.thisWindow.SetProgress(100, "");
                return(false);
            }
            file.Position = 0;;

            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(file);

            XmlElement root        = xmldoc.DocumentElement;
            XmlNode    neuronsNode = xmldoc.CreateNode("element", "Neurons", "");

            root.AppendChild(neuronsNode);

            for (int i = 0; i < theNeuronArray.arraySize; i++)
            {
                if (!fromClipboard)
                {
                    var progress = i / (float)theNeuronArray.arraySize;
                    progress *= 100;
                    if (MainWindow.thisWindow.SetProgress(progress, ""))
                    {
                        MainWindow.thisWindow.SetProgress(100, "");
                        return(false);
                    }
                }
                Neuron n = theNeuronArray.GetNeuronForDrawing(i);
                if (fromClipboard)
                {
                    n.Owner = theNeuronArray;
                }
                if (n.inUse || n.Label != "" || fromClipboard)
                {
                    n       = theNeuronArray.GetCompleteNeuron(i, fromClipboard);
                    n.Owner = theNeuronArray;
                    string label = n.Label;
                    if (n.ToolTip != "")
                    {
                        label += Neuron.toolTipSeparator + n.ToolTip;
                    }
                    //this is needed bacause inUse is true if any synapse points to this neuron--
                    //we don't need to bother with that if it's the only thing
                    if (n.synapses.Count != 0 || label != "" || n.lastCharge != 0 || n.leakRate != 0.1f ||
                        n.model != Neuron.modelType.IF)
                    {
                        XmlNode neuronNode = xmldoc.CreateNode("element", "Neuron", "");
                        neuronsNode.AppendChild(neuronNode);

                        XmlNode attrNode = xmldoc.CreateNode("element", "Id", "");
                        attrNode.InnerText = n.id.ToString();
                        neuronNode.AppendChild(attrNode);

                        if (n.model != Neuron.modelType.IF)
                        {
                            attrNode           = xmldoc.CreateNode("element", "Model", "");
                            attrNode.InnerText = n.model.ToString();
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.model != Neuron.modelType.Color && n.lastCharge != 0)
                        {
                            attrNode           = xmldoc.CreateNode("element", "LastCharge", "");
                            attrNode.InnerText = n.lastCharge.ToString();
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.model == Neuron.modelType.Color && n.LastChargeInt != 0)
                        {
                            attrNode           = xmldoc.CreateNode("element", "LastCharge", "");
                            attrNode.InnerText = n.LastChargeInt.ToString();
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.leakRate != 0.1f)
                        {
                            attrNode           = xmldoc.CreateNode("element", "LeakRate", "");
                            attrNode.InnerText = n.leakRate.ToString();
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.axonDelay != 0)
                        {
                            attrNode           = xmldoc.CreateNode("element", "AxonDelay", "");
                            attrNode.InnerText = n.axonDelay.ToString();
                            neuronNode.AppendChild(attrNode);
                        }
                        if (label != "")
                        {
                            attrNode           = xmldoc.CreateNode("element", "Label", "");
                            attrNode.InnerText = label;
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.ShowSynapses)
                        {
                            attrNode           = xmldoc.CreateNode("element", "ShowSynapses", "");
                            attrNode.InnerText = "True";
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.RecordHistory && !fromClipboard)
                        {
                            attrNode           = xmldoc.CreateNode("element", "RecordHistory", "");
                            attrNode.InnerText = "True";
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.synapses.Count > 0)
                        {
                            XmlNode synapsesNode = xmldoc.CreateNode("element", "Synapses", "");
                            neuronNode.AppendChild(synapsesNode);
                            foreach (Synapse s in n.synapses)
                            {
                                XmlNode synapseNode = xmldoc.CreateNode("element", "Synapse", "");
                                synapsesNode.AppendChild(synapseNode);

                                if (s.weight != 1)
                                {
                                    attrNode           = xmldoc.CreateNode("element", "Weight", "");
                                    attrNode.InnerText = s.weight.ToString();
                                    synapseNode.AppendChild(attrNode);
                                }

                                attrNode           = xmldoc.CreateNode("element", "TargetNeuron", "");
                                attrNode.InnerText = s.targetNeuron.ToString();
                                synapseNode.AppendChild(attrNode);

                                if (s.model != Synapse.modelType.Fixed)
                                {
                                    attrNode           = xmldoc.CreateNode("element", "Model", "");
                                    attrNode.InnerText = s.model.ToString();
                                    synapseNode.AppendChild(attrNode);
                                }
                            }
                        }
                    }
                }
            }

            file.Position = 0;
            xmldoc.Save(file);
            if (!fromClipboard)
            {
                file.Close();
                try
                {
                    File.Copy(tempFile, fileName, true);
                    File.Delete(tempFile);
                    MainWindow.thisWindow.SetProgress(100, "");
                }
                catch (Exception e)
                {
                    MainWindow.thisWindow.SetProgress(100, "");
                    MessageBox.Show("Could not save file because: " + e.Message);
                    return(false);
                }
            }
            else
            {
                file.Position = 0;
                StreamReader str  = new StreamReader(file);
                string       temp = str.ReadToEnd();
                Clipboard.SetText(temp);
            }

            return(true);
        }
示例#2
0
        public static bool Load(ref NeuronArray theNeuronArray, string fileName)
        {
            FileStream file = File.Open(fileName, FileMode.Open);

            XmlSerializer reader1 = new XmlSerializer(typeof(NeuronArray), GetModuleTypes());

            theNeuronArray = (NeuronArray)reader1.Deserialize(file);
            file.Close();

            //the above automatically loads the content of the neuronArray object but can't load the neurons themselves
            //because of formatting changes
            XmlDocument xmldoc = new XmlDocument();
            XmlNodeList neuronNodes;
            FileStream  fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            xmldoc.Load(fs);
            fs.Close();

            int arraySize = theNeuronArray.arraySize;

            theNeuronArray.Initialize(arraySize);
            neuronNodes = xmldoc.GetElementsByTagName("Neuron");

            for (int i = 0; i < neuronNodes.Count; i++)
            {
                XmlElement  neuronNode = (XmlElement)neuronNodes[i];
                XmlNodeList idNodes    = neuronNode.GetElementsByTagName("Id");
                if (idNodes.Count < 1)
                {
                    continue;
                }
                int id = -1;
                int.TryParse(idNodes[0].InnerText, out id);
                if (id == -1)
                {
                    continue;
                }
                Neuron n = theNeuronArray.GetNeuron(id);
                n.Owner = theNeuronArray;
                n.id    = id;

                foreach (XmlElement node in neuronNode.ChildNodes)
                {
                    string name = node.Name;
                    switch (name)
                    {
                    case "Label":
                        n.label = node.InnerText;
                        break;

                    case "Model":
                        Enum.TryParse(node.InnerText, out Neuron.modelType theModel);
                        n.model = theModel;
                        break;

                    case "LeakRate":
                        float.TryParse(node.InnerText, out float leakRate);
                        n.leakRate = leakRate;
                        break;

                    case "LastCharge":
                        if (n.model != Neuron.modelType.Color)
                        {
                            float.TryParse(node.InnerText, out float lastCharge);
                            n.LastCharge    = lastCharge;
                            n.currentCharge = lastCharge;
                        }
                        else     //is color
                        {
                            int.TryParse(node.InnerText, out int lastChargeInt);
                            n.LastChargeInt = lastChargeInt;
                            n.currentCharge = lastChargeInt;     //current charge is not used on color neurons
                        }
                        break;

                    case "Synapses":
                        theNeuronArray.SetCompleteNeuron(n);
                        XmlNodeList synapseNodess = node.GetElementsByTagName("Synapse");
                        foreach (XmlNode synapseNode in synapseNodess)
                        {
                            Synapse s = new Synapse();
                            foreach (XmlNode synapseAttribNode in synapseNode.ChildNodes)
                            {
                                string name1 = synapseAttribNode.Name;
                                switch (name1)
                                {
                                case "TargetNeuron":
                                    int.TryParse(synapseAttribNode.InnerText, out int target);
                                    s.targetNeuron = target;
                                    break;

                                case "Weight":
                                    float.TryParse(synapseAttribNode.InnerText, out float weight);
                                    s.weight = weight;
                                    break;

                                case "IsHebbian":
                                    bool.TryParse(synapseAttribNode.InnerText, out bool isheb);
                                    s.isHebbian = isheb;

                                    break;
                                }
                            }
                            n.AddSynapse(s.targetNeuron, s.weight, s.isHebbian);
                        }
                        break;
                    }
                }
                theNeuronArray.SetCompleteNeuron(n);
            }
            return(true);
        }
示例#3
0
        //copy the selection to a clipboard
        public void CopyNeurons()
        {
            //get list of neurons to copy
            List <int> neuronsToCopy = theSelection.EnumSelectedNeurons();

            theSelection.GetSelectedBoundingRectangle(out int X1o, out int Y1o, out int X2o, out int Y2o);
            MainWindow.myClipBoard = new NeuronArray();
            NeuronArray myClipBoard;

            myClipBoard = MainWindow.myClipBoard;
            myClipBoard.Initialize((X2o - X1o + 1) * (Y2o - Y1o + 1), (Y2o - Y1o + 1));
            boundarySynapsesOut.Clear();
            boundarySynapsesIn.Clear();

            //copy the neurons
            foreach (int nID in neuronsToCopy)
            {
                int destId = GetClipboardId(X1o, Y1o, nID);
                //copy the source neuron to the clipboard
                Neuron sourceNeuron = MainWindow.theNeuronArray.GetNeuron(nID);
                Neuron destNeuron   = sourceNeuron.Clone();
                destNeuron.Owner = myClipBoard;
                destNeuron.Id    = destId;
                myClipBoard.SetNeuron(destId, destNeuron);
            }

            //copy the synapses (this is two-pass so we make sure all neurons exist prior to copying
            foreach (int nID in neuronsToCopy)
            {
                Neuron sourceNeuron = MainWindow.theNeuronArray.GetNeuron(nID);
                int    destId       = GetClipboardId(X1o, Y1o, nID);
                Neuron destNeuron   = myClipBoard.GetNeuron(destId);
                destNeuron.Owner = myClipBoard;
                if (sourceNeuron.Synapses != null)
                {
                    foreach (Synapse s in sourceNeuron.Synapses)
                    {
                        //only copy synapses with both ends in the selection
                        if (neuronsToCopy.Contains(s.TargetNeuron))
                        {
                            destNeuron.AddSynapse(GetClipboardId(X1o, Y1o, s.TargetNeuron), s.Weight, s.model);
                        }
                        else
                        {
                            string targetName = MainWindow.theNeuronArray.GetNeuron(s.targetNeuron).label;
                            if (targetName != "")
                            {
                                boundarySynapsesOut.Add(new BoundarySynapse
                                {
                                    innerNeuronID = destNeuron.id,
                                    outerNeuronID = s.targetNeuron,
                                    weight        = s.weight,
                                    model         = s.model
                                });
                            }
                        }
                    }
                }
                if (sourceNeuron.SynapsesFrom != null)
                {
                    foreach (Synapse s in sourceNeuron.SynapsesFrom)
                    {
                        if (!neuronsToCopy.Contains(s.TargetNeuron))
                        {
                            string sourceName = MainWindow.theNeuronArray.GetNeuron(s.targetNeuron).label;
                            if (sourceName != "")
                            {
                                boundarySynapsesIn.Add(new BoundarySynapse
                                {
                                    innerNeuronID = destNeuron.id,
                                    outerNeuronID = s.targetNeuron,
                                    weight        = s.weight,
                                    model         = s.model
                                });;
                            }
                        }
                    }
                }
            }

            //copy modules
            foreach (ModuleView mv in MainWindow.theNeuronArray.modules)
            {
                if (theSelection.NeuronInSelection(mv.FirstNeuron) > 0 && theSelection.NeuronInSelection(mv.LastNeuron) > 0)
                {
                    ModuleView newMV = new ModuleView()
                    {
                        FirstNeuron = GetClipboardId(X1o, Y1o, mv.FirstNeuron),
                        TheModule   = mv.TheModule,
                        Color       = mv.Color,
                        Height      = mv.Height,
                        Width       = mv.Width,
                        Label       = mv.Label,
                        CommandLine = mv.CommandLine,
                    };

                    myClipBoard.modules.Add(newMV);
                }
            }
        }
示例#4
0
        private static void Cm_Closed(object sender, RoutedEventArgs e)
        {
            if (sender is ContextMenu cm)
            {
                if (!cm.IsOpen)
                {
                    return;
                }
                cm.IsOpen = false;
                if (cmCancelled)
                {
                    MainWindow.Update();
                    return;
                }
                MainWindow.theNeuronArray.SetUndoPoint();
                int    neuronID = (int)cm.GetValue(NeuronIDProperty);
                Neuron n        = MainWindow.theNeuronArray.GetNeuron(neuronID);
                n.AddUndoInfo();

                bool    applyToAll = false;
                Control cc         = Utils.FindByName(cm, "ApplyToSelection");
                if (cc is CheckBox cb)
                {
                    if (cb.IsChecked == true)
                    {
                        applyToAll = true;
                    }
                }

                cc = Utils.FindByName(cm, "Label");
                if (cc is TextBox tb)
                {
                    string newLabel = tb.Text;
                    if (int.TryParse(newLabel, out int dummy))
                    {
                        newLabel = "_" + newLabel;
                    }
                    if (labelChanged)
                    {
                        MainWindow.theNeuronArray.SetUndoPoint();
                        n.Label = newLabel;
                        if (applyToAll)
                        {
                            SetValueInSelectedNeurons(n, "label");
                        }
                    }
                }
                cc = Utils.FindByName(cm, "Model");
                if (cc is ComboBox cb0)
                {
                    ListBoxItem      lbi = (ListBoxItem)cb0.SelectedItem;
                    Neuron.modelType nm  = (Neuron.modelType)System.Enum.Parse(typeof(Neuron.modelType), lbi.Content.ToString());
                    if (modelChanged)
                    {
                        n.model = nm;
                        if (applyToAll)
                        {
                            SetValueInSelectedNeurons(n, "model");
                        }
                    }
                }
                cc = Utils.FindByName(cm, "CurrentCharge");
                if (cc is ComboBox tb1)
                {
                    if (n.model == Neuron.modelType.Color)
                    {
                        try
                        {
                            uint newCharge = Convert.ToUInt32(tb1.Text, 16);
                            if (chargeChanged)
                            {
                                n.SetValueInt((int)newCharge);
                                n.lastCharge = newCharge;
                                if (applyToAll)
                                {
                                    SetValueInSelectedNeurons(n, "currentCharge");
                                }
                                Utils.AddToValues(newCharge, colorValues);
                            }
                        }
                        catch { };
                    }
                    else
                    {
                        float.TryParse(tb1.Text, out float newCharge);
                        if (chargeChanged)
                        {
                            n.SetValue(newCharge);
                            n.lastCharge = newCharge;
                            if (applyToAll)
                            {
                                SetValueInSelectedNeurons(n, "currentCharge");
                            }
                            Utils.AddToValues(newCharge, currentChargeValues);
                        }
                    }
                }
                cc = Utils.FindByName(cm, "LeakRate");
                if (cc is ComboBox tb2)
                {
                    float.TryParse(tb2.Text, out float leakRate);
                    if (leakRateChanged)
                    {
                        n.LeakRate = leakRate;
                        if (applyToAll)
                        {
                            SetValueInSelectedNeurons(n, "leakRate");
                        }
                        if (n.model == Neuron.modelType.LIF)
                        {
                            Utils.AddToValues(leakRate, leakRateValues);
                        }
                        if (n.model == Neuron.modelType.Random)
                        {
                            Utils.AddToValues(leakRate, stdDevValues);
                        }
                        if (n.model == Neuron.modelType.Burst)
                        {
                            Utils.AddToValues(leakRate, axonDelayValues);
                        }
                    }
                }
                else
                {
                    n.leakRate = 0;
                }
                cc = Utils.FindByName(cm, "AxonDelay");
                if (cc is ComboBox tb3)
                {
                    int.TryParse(tb3.Text, out int axonDelay);
                    if (axonDelayChanged)
                    {
                        n.axonDelay = axonDelay;
                        if (applyToAll)
                        {
                            SetValueInSelectedNeurons(n, "axonDelay");
                        }
                        if (n.model == Neuron.modelType.Random)
                        {
                            Utils.AddToValues(axonDelay, meanValues);
                        }
                        else if (n.model == Neuron.modelType.Always)
                        {
                            Utils.AddToValues(axonDelay, alwaysDelayValues);
                        }
                        else if (n.model == Neuron.modelType.Burst)
                        {
                            Utils.AddToValues(axonDelay, alwaysDelayValues);
                        }
                        else
                        {
                            Utils.AddToValues(axonDelay, axonDelayValues);
                        }
                    }
                }
                cc = Utils.FindByName(cm, "Synapses");
                if (cc is CheckBox cb2)
                {
                    if (synapsesChanged)
                    {
                        if (cb2.IsChecked == true)
                        {
                            MainWindow.arrayView.AddShowSynapses(n.id);
                        }
                        else
                        {
                            MainWindow.arrayView.RemoveShowSynapses(n.id);
                        }
                        if (applyToAll)
                        {
                            SetValueInSelectedNeurons(n, "synapses");
                        }
                    }
                }

                cc = Utils.FindByName(cm, "Enabled");
                if (cc is CheckBox cb1)
                {
                    if (enabledChanged)
                    {
                        if (cb1.IsChecked == true)
                        {
                            n.leakRate = Math.Abs(n.leakRate);
                        }
                        else
                        {
                            n.leakRate = Math.Abs(n.leakRate) * -1.0f;
                        }

                        if (applyToAll)
                        {
                            SetValueInSelectedNeurons(n, "enable");
                        }
                    }
                }

                cc = Utils.FindByName(cm, "History");
                if (cc is CheckBox cb3)
                {
                    if (historyChanged)
                    {
                        if (cb3.IsChecked == true)
                        {
                            FiringHistory.AddNeuronToHistoryWindow(n.id);
                            OpenHistoryWindow();
                        }
                        else
                        {
                            FiringHistory.RemoveNeuronFromHistoryWindow(n.id);
                        }
                        if (applyToAll)
                        {
                            SetValueInSelectedNeurons(n, "history");
                        }
                    }
                }
                n.Update();
            }
            MainWindow.Update();
        }
示例#5
0
        public static UIElement GetNeuronView(Neuron n, NeuronArrayView theNeuronArrayViewI, out Label l)
        {
            l = null;
            theNeuronArrayView = theNeuronArrayViewI;

            Point p = dp.pointFromNeuron(n.id);

            SolidColorBrush s1 = GetNeuronColor(n);

            Shape r = null;

            if (dp.ShowNeuronCircles())
            {
                r        = new Ellipse();
                r.Width  = dp.NeuronDisplaySize * ellipseSize;
                r.Height = dp.NeuronDisplaySize * ellipseSize;
            }
            else
            {
                r        = new Rectangle();
                r.Width  = dp.NeuronDisplaySize;
                r.Height = dp.NeuronDisplaySize;
            }
            r.Fill = s1;
            if (dp.ShowNeuronOutlines())
            {
                r.Stroke          = Brushes.Black;
                r.StrokeThickness = 1;
            }

            float offset = (1 - ellipseSize) / 2f;

            Canvas.SetLeft(r, p.X + dp.NeuronDisplaySize * offset);
            Canvas.SetTop(r, p.Y + dp.NeuronDisplaySize * offset);

            if (n.Label != "" || n.model != Neuron.modelType.IF)
            {
                l = new Label();
                //l.Content = n.Label;
                l.FontSize   = dp.NeuronDisplaySize * .25;
                l.Foreground = Brushes.White;
                Canvas.SetLeft(l, p.X + dp.NeuronDisplaySize * offset);
                Canvas.SetTop(l, p.Y + dp.NeuronDisplaySize * offset);
                Canvas.SetZIndex(l, 100);

                string theLabel   = GetNeuronLabel(n);
                string theToolTip = n.ToolTip;
                if (theToolTip != "")
                {
                    r.ToolTip = new ToolTip {
                        Content = theToolTip
                    };
                    l.ToolTip = new ToolTip {
                        Content = theToolTip
                    };
                }
                l.Content = theLabel;
                l.SetValue(NeuronIDProperty, n.id);
                l.SetValue(NeuronArrayView.ShapeType, NeuronArrayView.shapeType.Neuron);
            }
            r.SetValue(NeuronIDProperty, n.id);
            r.SetValue(NeuronArrayView.ShapeType, NeuronArrayView.shapeType.Neuron);
            return(r);
        }
示例#6
0
        static void ProcessIncomingMessages(string message)
        {
            string[] commands = message.Trim().Split(' ');
            string   command  = commands[0];

            switch (command)
            {
            case "PingBack":
                GetSystemTimePreciseAsFileTime(out returnTime);
                pingCount++;
                break;

            case "ServerInfo":
                int index = serverList.FindIndex(x => x.name == commands[2]);
                if (index == -1)
                {
                    Server s = new Server();
                    IPAddress.TryParse(commands[1], out s.ipAddress);
                    s.name = commands[2];
                    int.TryParse(commands[3], out s.firstNeuron);
                    int.TryParse(commands[4], out s.lastNeuron);
                    if (commands.Length > 5)
                    {
                        int.TryParse(commands[5], out s.neuronsInUse);
                    }
                    if (commands.Length > 6)
                    {
                        long.TryParse(commands[6], out s.totalSynapses);
                    }
                    serverList.Add(s);
                    index = serverList.Count - 1;
                }
                break;

            case "Done":
                index = serverList.FindIndex(x => x.name == commands[1]);
                if (index != -1)
                {
                    serverList[index].busy = false;
                    long.TryParse(commands[2], out serverList[index].generation);
                    int.TryParse(commands[3], out serverList[index].firedCount);
                }
                break;

            case "Neuron":
                Neuron n = new Neuron();
                int.TryParse(commands[1], out n.id);
                float.TryParse(commands[2], out n.lastCharge);
                n.label = commands[3].Replace("_", " ");
                bool.TryParse(commands[4], out n.inUse);
                tempNeuron = n;
                break;

            case "Neurons":
                int.TryParse(commands[1], out int count);
                for (int i = 2; i < commands.Length; i += 4)
                {
                    n = new Neuron();
                    int.TryParse(commands[i], out n.id);
                    float.TryParse(commands[i + 1], out n.lastCharge);
                    n.label = commands[i + 2].Replace("_", " ");
                    bool.TryParse(commands[i + 3], out n.inUse);
                    tempNeurons.Add(n);
                }
                break;

            case "Synapses":
                int.TryParse(commands[1], out int neuronID);
                List <Synapse> synapses = new List <Synapse>();
                for (int i = 2; i < commands.Length; i += 3)
                {
                    Synapse s = new Synapse();
                    int.TryParse(commands[i], out s.targetNeuron);
                    float.TryParse(commands[i + 1], out s.weight);
                    int.TryParse(commands[i + 2], out int modelInt);
                    s.model = (Synapse.modelType)modelInt;
                    synapses.Add(s);
                }
                tempSynapses = synapses;
                break;

            case "SynapsesFrom":
                int.TryParse(commands[1], out neuronID);
                synapses = new List <Synapse>();
                for (int i = 2; i < commands.Length; i += 3)
                {
                    Synapse s = new Synapse();
                    int.TryParse(commands[i], out s.targetNeuron);
                    float.TryParse(commands[i + 1], out s.weight);
                    int.TryParse(commands[i + 2], out int modelInt);
                    s.model = (Synapse.modelType)modelInt;
                    synapses.Add(s);
                }
                tempSynapses = synapses;
                break;
            }
        }
示例#7
0
        public static void CreateContextMenu(int i, Neuron n, ContextMenu cm)
        {
            cmCancelled = false;

            labelChanged     = false;
            modelChanged     = false;
            enabledChanged   = false;
            historyChanged   = false;
            synapsesChanged  = false;
            chargeChanged    = false;
            leakRateChanged  = false;
            axonDelayChanged = false;

            n = MainWindow.theNeuronArray.AddSynapses(n);
            cm.SetValue(NeuronIDProperty, n.Id);
            cm.Closed         += Cm_Closed;
            cm.Opened         += Cm_Opened;
            cm.PreviewKeyDown += Cm_PreviewKeyDown;
            cmCancelled        = false;
            cm.StaysOpen       = true;

            //The neuron label
            StackPanel sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };

            sp.Children.Add(new Label {
                Content = "ID: " + n.id + "   Label: ", VerticalAlignment = VerticalAlignment.Center, Padding = new Thickness(0)
            });
            TextBox tb = Utils.ContextMenuTextBox(n.Label, "Label", 150);

            tb.TextChanged += Tb_TextChanged;
            sp.Children.Add(tb);
            sp.Children.Add(new Label {
                Content = "Warning:\rDuplicate Label", FontSize = 8, Name = "DupWarn", Visibility = Visibility.Hidden
            });
            //            cm.Items.Add(sp);
            //MenuItem mi = new MenuItem { StaysOpenOnClick = true, Header = new TextBox { Text = "Harry" } };
            cm.Items.Add(new MenuItem {
                StaysOpenOnClick = true, Header = sp
            });

            //The neuron model
            sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };
            sp.Children.Add(new Label {
                Content = "Model: ", Padding = new Thickness(0)
            });
            ComboBox cb = new ComboBox()
            {
                Width = 100, Name = "Model"
            };

            for (int index = 0; index < Enum.GetValues(typeof(Neuron.modelType)).Length; index++)
            {
                Neuron.modelType model = (Neuron.modelType)index;
                cb.Items.Add(new ListBoxItem()
                {
                    Content = model.ToString(),
                    ToolTip = Neuron.modelToolTip[index],
                    Width   = 100,
                });
            }
            cb.SelectedIndex     = (int)n.Model;
            cb.SelectionChanged += Cb_SelectionChanged;
            sp.Children.Add(cb);
            cm.Items.Add(new MenuItem {
                StaysOpenOnClick = true, Header = sp
            });

            cm.Items.Add(new Separator());

            MenuItem mi             = new MenuItem();
            CheckBox cbShowSynapses = new CheckBox
            {
                IsChecked = (n.leakRate > 0) || float.IsPositiveInfinity(1.0f / n.leakRate),
                Content   = "Enabled",
                Name      = "Enabled",
            };

            cbShowSynapses.Checked   += CbCheckedChanged;
            cbShowSynapses.Unchecked += CbCheckedChanged;
            cm.Items.Add(new MenuItem {
                StaysOpenOnClick = true, Header = cbShowSynapses
            });

            cbShowSynapses = new CheckBox
            {
                IsChecked = MainWindow.arrayView.IsShowingSnapses(n.id),
                Content   = "Show Synapses",
                Name      = "Synapses",
            };
            cbShowSynapses.Checked   += CbCheckedChanged;
            cbShowSynapses.Unchecked += CbCheckedChanged;
            cm.Items.Add(new MenuItem {
                StaysOpenOnClick = true, Header = cbShowSynapses
            });

            mi = new MenuItem();
            CheckBox cbHistory = new CheckBox
            {
                IsChecked = FiringHistory.NeuronIsInFiringHistory(n.id),
                Content   = "Record Firing History",
                Name      = "History",
            };

            cbHistory.Checked   += CbCheckedChanged;
            cbHistory.Unchecked += CbCheckedChanged;
            cm.Items.Add(new MenuItem {
                StaysOpenOnClick = true, Header = cbHistory
            });

            mi        = new MenuItem();
            mi.Header = "Synapses Out";
            foreach (Synapse s in n.Synapses)
            {
                string   targetLabel     = MainWindow.theNeuronArray.GetNeuron(s.targetNeuron).Label;
                MenuItem synapseMenuItem = new MenuItem()
                {
                    Header = s.targetNeuron.ToString().PadLeft(8) + s.Weight.ToString("F3").PadLeft(9) + " " + targetLabel, FontFamily = new FontFamily("Courier New")
                };
                synapseMenuItem.Click += Mi_Click;
                synapseMenuItem.PreviewMouseRightButtonDown += SynapseMenuItem_PreviewMouseRightButtonDown;
                synapseMenuItem.ToolTip = "L-click -> target neuron, R-Click -> edit synapse";
                mi.Items.Add(synapseMenuItem);
            }
            cm.Items.Add(mi);

            mi        = new MenuItem();
            mi.Header = "Synapses In";
            foreach (Synapse s in n.SynapsesFrom)
            {
                string   targetLabel     = MainWindow.theNeuronArray.GetNeuron(s.targetNeuron).Label;
                MenuItem synapseMenuItem = new MenuItem()
                {
                    Header = s.targetNeuron.ToString().PadLeft(8) + " " + s.Weight.ToString("F3").PadLeft(9) + " " + targetLabel, FontFamily = new FontFamily("Courier New")
                };
                synapseMenuItem.Click += Mi_Click;
                synapseMenuItem.PreviewMouseRightButtonDown += SynapseFromMenuItem_PreviewMouseRightButtonDown1;
                synapseMenuItem.ToolTip = "L-click -> source neuron, R-Click -> edit synapse";
                mi.Items.Add(synapseMenuItem);;
            }
            cm.Items.Add(mi);

            mi = new MenuItem {
                Header = "Paste Here"
            };
            if (MainWindow.myClipBoard == null)
            {
                mi.IsEnabled = false;
            }
            mi.Click += Mi_Click;
            cm.Items.Add(mi);
            mi = new MenuItem {
                Header = "Move Here"
            };
            if (MainWindow.arrayView.theSelection.selectedRectangles.Count == 0)
            {
                mi.IsEnabled = false;
            }
            mi.Click += Mi_Click;
            cm.Items.Add(mi);


            mi        = new MenuItem();
            mi.Header = "Connect Multiple Synapses";
            mi.Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "From Selection to Here"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "From Here to Selection"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Mutual Suppression"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            cm.Items.Add(mi);

            if (NeuronInSelection(n.id))
            {
                cbShowSynapses = new CheckBox
                {
                    IsChecked = true,
                    Content   = "Apply changes to all neurons in selection",
                    Name      = "ApplyToSelection",
                };
                cbShowSynapses.Checked   += CbCheckedChanged;
                cbShowSynapses.Unchecked += CbCheckedChanged;
                cm.Items.Add(new MenuItem {
                    StaysOpenOnClick = true, Header = cbShowSynapses
                });
            }


            sp = new StackPanel {
                Orientation = Orientation.Horizontal
            };
            Button b0 = new Button {
                Content = "OK", Width = 100, Height = 25, Margin = new Thickness(10)
            };

            b0.Click += B0_Click;
            sp.Children.Add(b0);
            b0 = new Button {
                Content = "Cancel", Width = 100, Height = 25, Margin = new Thickness(10)
            };
            b0.Click += B0_Click;
            sp.Children.Add(b0);

            cm.Items.Add(new MenuItem {
                Header = sp, StaysOpenOnClick = true
            });

            SetCustomCMItems(cm, n, n.model);
        }
示例#8
0
 private static void Cm_Closed(object sender, RoutedEventArgs e)
 {
     if ((Keyboard.GetKeyStates(Key.Escape) & KeyStates.Down) > 0)
     {
         return;
     }
     if (cmCancelled)
     {
         cmCancelled = false;
         return;
     }
     if (sender is ContextMenu cm)
     {
         int     neuronID = (int)cm.GetValue(NeuronIDProperty);
         Neuron  n        = MainWindow.theNeuronArray.GetNeuron(neuronID);
         Control cc       = Utils.FindByName(cm, "Label");
         if (cc is TextBox tb)
         {
             n.Label = tb.Text;
         }
         cc = Utils.FindByName(cm, "CurrentCharge");
         if (cc is TextBox tb1)
         {
             float.TryParse(tb1.Text, out float newCharge);
             n.SetValue(newCharge);
         }
         cc = Utils.FindByName(cm, "LeakRate");
         if (cc is TextBox tb2)
         {
             float.TryParse(tb2.Text, out float leakRate);
             if (n.LeakRate != leakRate)
             {
                 n.LeakRate = leakRate;
                 SetModelAndLeakrate(n);
             }
             n.LeakRate = leakRate;
         }
         cc = Utils.FindByName(cm, "History");
         if (cc is CheckBox cb1)
         {
             bool KeepHistory = (bool)cb1.IsChecked;
             if (!KeepHistory)
             {
                 FiringHistory.RemoveNeuronFromHistoryWindow(n.Id);
                 if (FiringHistory.history.Count == 0 && MainWindow.fwWindow != null && MainWindow.fwWindow.IsVisible)
                 {
                     MainWindow.fwWindow.Close();
                     MainWindow.fwWindow = null;
                 }
             }
             else  //make sure a window is open
             {
                 FiringHistory.AddNeuronToHistoryWindow(n.id);
                 OpenHistoryWindow();
             }
             //if there is a selection, set all the keepHistory values to match
             bool neuronInSelection = false;
             foreach (NeuronSelectionRectangle sr in theNeuronArrayView.theSelection.selectedRectangles)
             {
                 if (sr.NeuronIsInSelection(neuronID))
                 {
                     neuronInSelection = true;
                     break;
                 }
             }
             if (neuronInSelection)
             {
                 theNeuronArrayView.theSelection.EnumSelectedNeurons();
                 for (Neuron n1 = theNeuronArrayView.theSelection.GetSelectedNeuron(); n1 != null; n1 = theNeuronArrayView.theSelection.GetSelectedNeuron())
                 {
                     if (KeepHistory)
                     {
                         FiringHistory.AddNeuronToHistoryWindow(n1.id);
                     }
                     else
                     {
                         FiringHistory.RemoveNeuronFromHistoryWindow(n1.id);
                     }
                 }
                 //n1.KeepHistory = (bool)cb1.IsChecked;
             }
         }
     }
     MainWindow.Update();
 }
示例#9
0
        private static void Mi_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = sender as MenuItem;
            //find out which neuron this context menu is from
            ContextMenu cm = mi.Parent as ContextMenu;

            if (cm == null)
            {
                MenuItem mi2 = mi.Parent as MenuItem;
                if (mi2.Header.ToString().IndexOf("Synapses") == 0)
                {
                    int.TryParse(mi.Header.ToString().Substring(0, 8), out int newID);
                    Neuron n1 = MainWindow.theNeuronArray.GetNeuron(newID);
                    NeuronView.CreateContextMenu(n1.id, n1, new ContextMenu()
                    {
                        IsOpen = true,
                    });
                    return;
                }
                cm = mi2.Parent as ContextMenu;
            }
            int    i = (int)cm.GetValue(NeuronIDProperty);
            Neuron n = MainWindow.theNeuronArray.GetNeuron(i);

            if ((string)mi.Header == "Always Fire")
            {
                if (n.FindSynapse(i) == null)
                {
                    n.AddSynapse(i, 1, MainWindow.theNeuronArray, true);
                }
                else
                {
                    n.DeleteSynapse(i);
                }
            }
            if ((string)mi.Header == "Paste Here")
            {
                theNeuronArrayView.targetNeuronIndex = i;
                theNeuronArrayView.PasteNeurons();
                theNeuronArrayView.targetNeuronIndex = -1;
                cmCancelled = true;
            }
            if ((string)mi.Header == "Move Here")
            {
                theNeuronArrayView.targetNeuronIndex = i;
                theNeuronArrayView.MoveNeurons();
                cmCancelled = true;
            }
            if ((string)mi.Header == "Connect to Here")
            {
                theNeuronArrayView.targetNeuronIndex = i;
                theNeuronArrayView.ConnectToHere();
            }
            if ((string)mi.Header == "Connect from Here")
            {
                theNeuronArrayView.targetNeuronIndex = i;
                theNeuronArrayView.ConnectFromHere();
            }
            if ((string)mi.Header == "Select as Target")
            {
                theNeuronArrayView.targetNeuronIndex = i;
            }
        }
示例#10
0
        public static UIElement GetNeuronView(int i, NeuronArrayView theNeuronArrayViewI, out Label l)
        {
            l = null;
            theNeuronArrayView = theNeuronArrayViewI;
            //this hack makes the GameOfLife display bettern
            if (MainWindow.currentFileName.Contains("Life"))
            {
                int row = i % dp.NeuronRows;
                int col = i / dp.NeuronRows;
                if ((row + 1) % 2 != 0)
                {
                    return(null);
                }
                if (col % 2 != 0)
                {
                    return(null);
                }
            }

            Neuron n = MainWindow.theNeuronArray.GetNeuron(i);
            Point  p = dp.pointFromNeuron(i);

            //if (p.X < -dp.NeuronDisplaySize) return null;
            //if (p.Y < -dp.NeuronDisplaySize) return null;
            //if (p.X > theCanvas.ActualWidth + dp.NeuronDisplaySize) return null;
            //if (p.Y > theCanvas.ActualHeight + dp.NeuronDisplaySize) return null;

            // figure out which color to use
            float value = n.LastCharge;
            Color c     = Colors.Blue;

            if ((n.Model == Neuron.modelType.Std || n.Model == Neuron.modelType.LIF) && value > .99)
            {
                c = Colors.Orange;
            }
            else if ((n.Model == Neuron.modelType.Std || n.Model == Neuron.modelType.LIF) && value != -1)
            {
                c = MapRainbowColor(value, 1, 0);
            }
            else if (n.Model == Neuron.modelType.Color)
            {
                c = Utils.IntToColor((int)n.LastChargeInt);
            }
            SolidColorBrush s1 = new SolidColorBrush(c);

            //   if (n.Label != "" || !n.InUse()) s1.Opacity = .50;
            if (!n.InUse() && n.Model == Neuron.modelType.Std)
            {
                s1.Opacity = .50;
            }

            Shape r = null;

            if (dp.ShowNeuronCircles())
            {
                r        = new Ellipse();
                r.Width  = dp.NeuronDisplaySize * ellipseSize;
                r.Height = dp.NeuronDisplaySize * ellipseSize;
            }
            else
            {
                r        = new Rectangle();
                r.Width  = dp.NeuronDisplaySize;
                r.Height = dp.NeuronDisplaySize;
            }
            r.Fill = s1;
            if (dp.ShowNeuronOutlines())
            {
                r.Stroke          = Brushes.Black;
                r.StrokeThickness = 1;
            }

            r.MouseDown  += theNeuronArrayView.theCanvas_MouseDown;
            r.MouseUp    += theNeuronArrayView.theCanvas_MouseUp;
            r.MouseWheel += theNeuronArrayView.theCanvas_MouseWheel;

            float offset = (1 - ellipseSize) / 2f;

            Canvas.SetLeft(r, p.X + dp.NeuronDisplaySize * offset);
            Canvas.SetTop(r, p.Y + dp.NeuronDisplaySize * offset);
            if (dp.ShowNeuronArrowCursor())
            {
                r.MouseEnter += R_MouseEnter;
                r.MouseLeave += R_MouseLeave;
            }


            if (n.Label != "")
            {
                l            = new Label();
                l.Content    = n.Label;
                l.FontSize   = dp.NeuronDisplaySize * .25;
                l.Foreground = Brushes.White;
                Canvas.SetLeft(l, p.X + dp.NeuronDisplaySize * offset);
                Canvas.SetTop(l, p.Y + dp.NeuronDisplaySize * offset);
                Canvas.SetZIndex(l, 100);

                if (dp.ShowNeuronArrowCursor())
                {
                    l.MouseEnter += R_MouseEnter;
                    l.MouseLeave += R_MouseLeave;
                }
                l.MouseDown += theNeuronArrayView.theCanvas_MouseDown;
                l.MouseUp   += theNeuronArrayView.theCanvas_MouseUp;
                l.MouseMove += theNeuronArrayView.theCanvas_MouseMove;
                //theCanvas.Children.Add(l);
            }
            return(r);
        }
示例#11
0
        public static void CreateContextMenu(int i, Neuron n, ContextMenu cm)
        {
            n = MainWindow.theNeuronArray.AddSynapses(n);
            cm.SetValue(NeuronIDProperty, n.Id);
            cm.Closed  += Cm_Closed;
            cmCancelled = false;
            StackPanel sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };

            sp.Children.Add(new Label {
                Content = "Charge: ", Padding = new Thickness(0)
            });
            if (n.Model != Neuron.modelType.FloatValue)
            {
                sp.Children.Add(new TextBox {
                    Text = n.LastCharge.ToString("f2"), Width = 60, Name = "CurrentCharge", VerticalAlignment = VerticalAlignment.Center
                });
            }
            else
            {
                sp.Children.Add(new TextBox {
                    Text = n.CurrentCharge.ToString("f2"), Width = 60, Name = "CurrentCharge", VerticalAlignment = VerticalAlignment.Center
                });
            }
            cm.Items.Add(sp);
            if (n.Model == Neuron.modelType.LIF || n.model == Neuron.modelType.Random)
            {
                sp = new StackPanel {
                    Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
                };
                sp.Children.Add(new Label {
                    Content = "Leak Rate: ", Padding = new Thickness(0)
                });
                sp.Children.Add(new TextBox {
                    Text = n.LeakRate.ToString("f4"), Width = 60, Name = "LeakRate", VerticalAlignment = VerticalAlignment.Center
                });
                cm.Items.Add(sp);
            }

            MenuItem mi = new MenuItem();

            mi.Header = "Neuron ID: " + n.Id;
            cm.Items.Add(mi);
            cm.Items.Add(new Separator());
            mi        = new MenuItem();
            mi.Header = "Always Fire";
            mi.Click += Mi_Click;
            cm.Items.Add(mi);
            mi        = new MenuItem();
            mi.Header = "Paste Here";
            mi.Click += Mi_Click;
            cm.Items.Add(mi);
            mi        = new MenuItem();
            mi.Header = "Clipboard";
            mi.Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Paste Here"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Move Here"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Connect to Here"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Connect from Here"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Select as Target"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            cm.Items.Add(mi);
            sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };
            sp.Children.Add(new Label {
                Content = "Label: ", Padding = new Thickness(0)
            });
            sp.Children.Add(new TextBox {
                Text = n.Label, Width = 150, Name = "Label", VerticalAlignment = VerticalAlignment.Center
            });
            cm.Items.Add(sp);

            sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };
            sp.Children.Add(new Label {
                Content = "Model: ", Padding = new Thickness(0)
            });
            ComboBox cb = new ComboBox()
            {
                Width = 100
            };

            for (int index = 0; index < Enum.GetValues(typeof(Neuron.modelType)).Length; index++)
            {
                Neuron.modelType model = (Neuron.modelType)index;
                cb.Items.Add(new ListBoxItem()
                {
                    Content = model.ToString(),
                    ToolTip = Neuron.modelToolTip[index],
                    Width   = 100,
                });
            }
            cb.SelectedIndex     = (int)n.Model;
            cb.SelectionChanged += Cb_SelectionChanged;
            sp.Children.Add(cb);
            cm.Items.Add(sp);
            CheckBox cbHistory = new CheckBox
            {
                IsChecked = FiringHistory.NeuronIsInFiringHistory(n.id),
                Content   = "Record Firing History",
                Name      = "History",
            };

            cbHistory.Checked   += CbHistory_Checked;
            cbHistory.Unchecked += CbHistory_Checked;
            cm.Items.Add(cbHistory);

            mi        = new MenuItem();
            mi.Header = "Synapses";
            foreach (Synapse s in n.Synapses)
            {
                string   targetLabel     = MainWindow.theNeuronArray.GetNeuron(s.targetNeuron).Label;
                MenuItem synapseMenuItem = new MenuItem()
                {
                    Header = s.targetNeuron.ToString().PadLeft(8) + s.Weight.ToString("F3").PadLeft(9) + " " + targetLabel, FontFamily = new FontFamily("Courier New")
                };
                synapseMenuItem.Click += Mi_Click;
                synapseMenuItem.PreviewMouseRightButtonDown += SynapseMenuItem_PreviewMouseRightButtonDown;
                synapseMenuItem.ToolTip = "L-click -> target neuron, R-Click -> edit synapse";
                mi.Items.Add(synapseMenuItem);
            }
            cm.Items.Add(mi);

            mi        = new MenuItem();
            mi.Header = "Synapses In";
            foreach (Synapse s in n.SynapsesFrom)
            {
                string   targetLabel     = MainWindow.theNeuronArray.GetNeuron(s.targetNeuron).Label;
                MenuItem synapseMenuItem = new MenuItem()
                {
                    Header = s.targetNeuron.ToString().PadLeft(8) + " " + s.Weight.ToString("F3").PadLeft(9) + " " + targetLabel, FontFamily = new FontFamily("Courier New")
                };
                synapseMenuItem.Click += Mi_Click;
                synapseMenuItem.PreviewMouseRightButtonDown += SynapseFromMenuItem_PreviewMouseRightButtonDown1;
                synapseMenuItem.ToolTip = "L-click -> source neuron, R-Click -> edit synapse";
                mi.Items.Add(synapseMenuItem);;
            }
            cm.Items.Add(mi);
        }
示例#12
0
        public static void CreateContextMenu(int i, Neuron n, ContextMenu cm)
        {
            cm.SetValue(NeuronIDProperty, n.Id);
            cm.Closed  += Cm_Closed;
            cmCancelled = false;
            StackPanel sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };

            sp.Children.Add(new Label {
                Content = "Charge: ", Padding = new Thickness(0)
            });
            if (n.Model != Neuron.modelType.FloatValue)
            {
                sp.Children.Add(new TextBox {
                    Text = n.LastCharge.ToString("f2"), Width = 60, Name = "CurrentCharge", VerticalAlignment = VerticalAlignment.Center
                });
            }
            else
            {
                sp.Children.Add(new TextBox {
                    Text = n.CurrentCharge.ToString("f2"), Width = 60, Name = "CurrentCharge", VerticalAlignment = VerticalAlignment.Center
                });
            }
            cm.Items.Add(sp);
            if (n.Model == Neuron.modelType.LIF)
            {
                sp = new StackPanel {
                    Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
                };
                sp.Children.Add(new Label {
                    Content = "Leak Rate: ", Padding = new Thickness(0)
                });
                sp.Children.Add(new TextBox {
                    Text = n.LeakRate.ToString("f4"), Width = 60, Name = "LeakRate", VerticalAlignment = VerticalAlignment.Center
                });
                cm.Items.Add(sp);
            }

            MenuItem mi = new MenuItem();

            mi.Header = "Neuron ID: " + n.Id;
            cm.Items.Add(mi);
            cm.Items.Add(new Separator());
            mi        = new MenuItem();
            mi.Header = "Always Fire";
            mi.Click += Mi_Click;
            cm.Items.Add(mi);
            mi        = new MenuItem();
            mi.Header = "Paste Here";
            mi.Click += Mi_Click;
            cm.Items.Add(mi);
            mi        = new MenuItem();
            mi.Header = "Clipboard";
            mi.Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Paste Here"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Move Here"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Connect to Here"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Connect from Here"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            mi.Items.Add(new MenuItem()
            {
                Header = "Select as Target"
            });
            ((MenuItem)mi.Items[mi.Items.Count - 1]).Click += Mi_Click;
            cm.Items.Add(mi);
            sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };
            sp.Children.Add(new Label {
                Content = "Label: ", Padding = new Thickness(0)
            });
            sp.Children.Add(new TextBox {
                Text = n.Label, Width = 150, Name = "Label", VerticalAlignment = VerticalAlignment.Center
            });
            cm.Items.Add(sp);

            sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };
            sp.Children.Add(new Label {
                Content = "Model: ", Padding = new Thickness(0)
            });
            ComboBox cb = new ComboBox()
            {
                Width = 100
            };

            for (int index = 0; index < Enum.GetValues(typeof(Neuron.modelType)).Length; index++)
            {
                Neuron.modelType model = (Neuron.modelType)index;
                cb.Items.Add(new ListBoxItem()
                {
                    Content = model.ToString(),
                    ToolTip = Neuron.modelToolTip[index],
                    Width   = 100,
                });
            }
            cb.SelectedIndex     = (int)n.Model;
            cb.SelectionChanged += Cb_SelectionChanged;
            sp.Children.Add(cb);
            cm.Items.Add(sp);
            CheckBox cbHistory = new CheckBox
            {
                IsChecked = n.KeepHistory,
                Content   = "Record Firing History",
                Name      = "History",
            };

            cbHistory.Checked   += CbHistory_Checked;
            cbHistory.Unchecked += CbHistory_Checked;
            cm.Items.Add(cbHistory);

            mi        = new MenuItem();
            mi.Header = "Synapses";
            mi.Click += Mi_Click;
            if (n.synapses == null)
            {
                n.synapses = new List <Synapse>();
            }
            foreach (Synapse s in n.synapses)
            {
                mi.Items.Add(new MenuItem()
                {
                    Header = s.targetNeuron + " " + s.Weight
                });
            }

            cm.Items.Add(mi);

            mi        = new MenuItem();
            mi.Header = "Synapses In";
            mi.Click += Mi_Click;
            if (n.synapsesFrom == null)
            {
                n.synapsesFrom = new List <Synapse>();
            }
            foreach (Synapse s in n.synapsesFrom)
            {
                mi.Items.Add(new MenuItem()
                {
                    Header = s.targetNeuron + " " + s.Weight
                });
            }
            cm.Items.Add(mi);
        }
示例#13
0
 private static void Mi_Click(object sender, RoutedEventArgs e)
 {
     //Handle delete  & initialize commands
     if (sender is MenuItem mi)
     {
         if ((string)mi.Header == "Cut")
         {
             MainWindow.arrayView.CutNeurons();
             MainWindow.Update();
         }
         if ((string)mi.Header == "Copy")
         {
             MainWindow.arrayView.CopyNeurons();
         }
         if ((string)mi.Header == "Clear Selection")
         {
             MainWindow.arrayView.ClearSelection();
             MainWindow.Update();
         }
         if ((string)mi.Header == "Mutual Suppression")
         {
             MainWindow.arrayView.MutualSuppression();
             MainWindow.Update();
         }
         if ((string)mi.Header == "Delete")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
                 MainWindow.arrayView.DeleteSelection();
             }
             else
             {
                 ModuleView mv = MainWindow.theNeuronArray.Modules[i];
                 foreach (Neuron n in mv.Neurons())
                 {
                     n.Reset();
                     n.DeleteAllSynapes();
                 }
                 MainWindow.theNeuronArray.Modules.RemoveAt(i);
                 deleted = true;
             }
         }
         if ((string)mi.Header == "Initialize")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
             }
             else
             {
                 MainWindow.theNeuronArray.Modules[i].TheModule.Initialize();
             }
         }
         if ((string)mi.Header == "Show Dialog")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
             }
             else
             {
                 MainWindow.theNeuronArray.Modules[i].TheModule.ShowDialog();
             }
         }
         if ((string)mi.Header == "Info...")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
             }
             else
             {
                 ModuleView        m  = MainWindow.theNeuronArray.Modules[i];
                 ModuleBase        m1 = m.TheModule;
                 ModuleDescription md = new ModuleDescription(m1.ShortDescription, m1.LongDescription);
                 md.ShowDialog();
             }
         }
         if ((string)mi.Header == "Reset Hebbian Weights")
         {
             MainWindow.theNeuronArray.SetUndoPoint();
             foreach (NeuronSelectionRectangle sr in MainWindow.arrayView.theSelection.selectedRectangles)
             {
                 foreach (int Id in sr.NeuronInRectangle())
                 {
                     Neuron n = MainWindow.theNeuronArray.GetNeuron(Id);
                     foreach (Synapse s in n.Synapses)
                     {
                         if (s.model != Synapse.modelType.Fixed)
                         {
                             //TODO: Add some UI for this:
                             //s.model = Synapse.modelType.Hebbian2;
                             n.AddSynapseWithUndo(s.targetNeuron, 0, s.model);
                             s.Weight = 0;
                         }
                     }
                 }
             }
             MainWindow.Update();
         }
     }
 }
示例#14
0
        public static bool Load(ref NeuronArray theNeuronArray, string fileName)
        {
            bool   fromClipboard = fileName == "ClipBoard";
            Stream file;

            if (!fromClipboard)
            {
                try
                {
                    file = File.Open(fileName, FileMode.Open, FileAccess.Read);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Could not open file because: " + e.Message);
                    RemoveFileFromMRUList(fileName);
                    return(false);
                }

                // first check if the required start tag is present in the file...
                byte[] buffer = new byte[60];
                file.Read(buffer, 0, 60);
                string line = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                if (line.Contains("NeuronArray"))
                {
                    file.Seek(0, SeekOrigin.Begin);
                }
                else
                {
                    file.Close();
                    MessageBox.Show("File is not a valid Brain Simulator II XML file.");
                    return(false);
                }

                MainWindow.thisWindow.SetProgress(0, "Loading Network File");
            }
            else
            {
                file = new MemoryStream();
                StreamWriter sw   = new StreamWriter(file);
                string       temp = Clipboard.GetText();
                sw.Write(temp);
                sw.Flush();
                file.Seek(0, SeekOrigin.Begin);
            }
            theNeuronArray = new NeuronArray();

            XmlSerializer reader1 = new XmlSerializer(typeof(NeuronArray), GetModuleTypes());

            try
            {
                theNeuronArray = (NeuronArray)reader1.Deserialize(file);
            }
            catch (Exception e)
            {
                file.Close();
                MessageBox.Show("Network file load failed, a blank network will be opened. \r\n\r\n" + e.InnerException, "File Load Error",
                                MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
                MainWindow.thisWindow.SetProgress(100, "");
                return(false);
            }

            file.Position = 0;
            //the above automatically loads the content of the neuronArray object but can't load the neurons themselves
            //because of formatting changes
            XmlDocument xmldoc = new XmlDocument();
            XmlNodeList neuronNodes;

            xmldoc.Load(file);
            file.Close();

            int arraySize = theNeuronArray.arraySize;

            theNeuronArray.Initialize(arraySize, theNeuronArray.rows);
            neuronNodes = xmldoc.GetElementsByTagName("Neuron");

            for (int i = 0; i < neuronNodes.Count; i++)
            {
                if (!fromClipboard)
                {
                    var progress = i / (float)neuronNodes.Count;
                    progress *= 100;
                    if (progress != 0 && MainWindow.thisWindow.SetProgress(progress, ""))
                    {
                        MainWindow.thisWindow.SetProgress(100, "");
                        return(false);
                    }
                }
                XmlElement  neuronNode = (XmlElement)neuronNodes[i];
                XmlNodeList idNodes    = neuronNode.GetElementsByTagName("Id");
                int         id         = i; //this is a hack to read obsolete files where all neurons were included but no Id's
                if (idNodes.Count > 0)
                {
                    int.TryParse(idNodes[0].InnerText, out id);
                }
                if (id == -1)
                {
                    continue;
                }

                Neuron n = theNeuronArray.GetNeuron(id);
                n.Owner = theNeuronArray;
                n.id    = id;

                foreach (XmlElement node in neuronNode.ChildNodes)
                {
                    string name = node.Name;
                    switch (name)
                    {
                    case "Label":
                        n.Label = node.InnerText;
                        break;

                    case "Model":
                        Enum.TryParse(node.InnerText, out Neuron.modelType theModel);
                        n.model = theModel;
                        break;

                    case "LeakRate":
                        float.TryParse(node.InnerText, out float leakRate);
                        n.leakRate = leakRate;
                        break;

                    case "AxonDelay":
                        int.TryParse(node.InnerText, out int axonDelay);
                        n.axonDelay = axonDelay;
                        break;

                    case "LastCharge":
                        if (n.model != Neuron.modelType.Color)
                        {
                            float.TryParse(node.InnerText, out float lastCharge);
                            n.LastCharge    = lastCharge;
                            n.currentCharge = lastCharge;
                        }
                        else     //is color
                        {
                            int.TryParse(node.InnerText, out int lastChargeInt);
                            n.LastChargeInt = lastChargeInt;
                            n.currentCharge = lastChargeInt;     //current charge is not used on color neurons
                        }
                        break;

                    case "ShowSynapses":
                        bool.TryParse(node.InnerText, out bool showSynapses);
                        n.ShowSynapses = showSynapses;
                        break;

                    case "RecordHistory":
                        bool.TryParse(node.InnerText, out bool recordHistory);
                        n.RecordHistory = recordHistory;
                        break;

                    case "Synapses":
                        theNeuronArray.SetCompleteNeuron(n);
                        XmlNodeList synapseNodess = node.GetElementsByTagName("Synapse");
                        foreach (XmlNode synapseNode in synapseNodess)
                        {
                            Synapse s = new Synapse();
                            foreach (XmlNode synapseAttribNode in synapseNode.ChildNodes)
                            {
                                string name1 = synapseAttribNode.Name;
                                switch (name1)
                                {
                                case "TargetNeuron":
                                    int.TryParse(synapseAttribNode.InnerText, out int target);
                                    s.targetNeuron = target;
                                    break;

                                case "Weight":
                                    float.TryParse(synapseAttribNode.InnerText, out float weight);
                                    s.weight = weight;
                                    break;

                                case "IsHebbian":         //Obsolete: backwards compatibility
                                    bool.TryParse(synapseAttribNode.InnerText, out bool isheb);
                                    if (isheb)
                                    {
                                        s.model = Synapse.modelType.Hebbian1;
                                    }
                                    else
                                    {
                                        s.model = Synapse.modelType.Fixed;
                                    }
                                    break;

                                case "Model":
                                    Enum.TryParse(synapseAttribNode.InnerText, out Synapse.modelType model);
                                    s.model = model;
                                    break;
                                }
                            }
                            n.AddSynapse(s.targetNeuron, s.weight, s.model);
                        }
                        break;
                    }
                }
                theNeuronArray.SetCompleteNeuron(n);
            }
            if (!fromClipboard)
            {
                MainWindow.thisWindow.SetProgress(100, "");
            }
            return(true);
        }
示例#15
0
        public void theCanvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //set the cursor before checking for busy so the wait cursor can be set
            shapeType theShapeType = SetMouseCursorShape(e, out FrameworkElement theShape);

            if (MainWindow.Busy())
            {
                return;
            }

            if (MainWindow.theNeuronArray == null)
            {
                return;
            }
            MainWindow.theNeuronArray.SetUndoPoint();
            Debug.WriteLine("theCanvas_MouseDown" + MainWindow.theNeuronArray.Generation + theShape + theShapeType);
            Point currentPosition = e.GetPosition(theCanvas);

            LimitMousePostion(ref currentPosition);
            mouseDownNeuronIndex = dp.NeuronFromPoint(currentPosition);

            if (e.RightButton == MouseButtonState.Pressed)
            {
                if (sender is Image img) //TODO: fix this, it should be a selection hit
                {
                    int        i  = (int)img.GetValue(ModuleView.AreaNumberProperty);
                    int        i1 = -i - 1;
                    ModuleView nr = new ModuleView
                    {
                        Label         = "new",
                        Width         = theSelection.selectedRectangles[i1].Width,
                        Height        = theSelection.selectedRectangles[i1].Height,
                        Color         = Utils.ColorToInt(Colors.Aquamarine),
                        ModuleTypeStr = ""
                    };
                    img.ContextMenu = new ContextMenu();
                    ModuleView.CreateContextMenu(i, nr, img, img.ContextMenu);
                    img.ContextMenu.IsOpen = true;
                }
                else if (theShapeType == shapeType.Neuron)
                {
                    OpenNeuronContextMenu(theShape);
                }
                else if (theShapeType == shapeType.Synapse)
                {
                    OpenSynapseContextMenu(theShape);
                }
                else if (theShapeType == shapeType.Selection)
                {
                    OpenSelectionContextMenu(theShape);
                }
                else if (theShapeType == shapeType.Module)
                {
                    OpenModuleContextMenu(theShape);
                }
                return;
            } //end of right-button pressed

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (theShapeType == shapeType.Neuron)
                {
                    Neuron n = null;
                    if (mouseDownNeuronIndex >= 0 && mouseDownNeuronIndex < MainWindow.theNeuronArray.arraySize)
                    {
                        n = MainWindow.theNeuronArray.GetNeuron(mouseDownNeuronIndex) as Neuron;
                    }

                    int clickCount = e.ClickCount;
                    n = NeuronMouseDown(n, clickCount);
                }

                if (theShapeType == shapeType.Synapse)
                {
                    StartSynapseDragging(theShape);
                }

                //start a new selection rectangle drag
                if (theShapeType == shapeType.Canvas && labelCursor == null)
                {
                    currentPosition = StartNewSelectionDrag();
                }

                //either a module or a selection, we're dragging it
                if (theShapeType == shapeType.Module && theCanvas.Cursor == Cursors.ScrollAll)
                {
                    StartaMovingModule(theShape, mouseDownNeuronIndex);
                }
                if (theShapeType == shapeType.Module && theCanvas.Cursor != Cursors.ScrollAll)
                {
                    StartaSizingModule(theShape, mouseDownNeuronIndex);
                }

                if (theShapeType == shapeType.Selection)
                {
                    StartMovingSelection(theShape);
                }
                //starting pan
                if (theCanvas.Cursor == Cursors.Hand)
                {
                    StartPan(e.GetPosition((UIElement)theCanvas.Parent));
                }
                if (currentOperation == CurrentOperation.insertingModule)
                {
                    InsertModule(mouseDownNeuronIndex);
                    Mouse.Capture(null);
                }
                else
                {
                    Mouse.Capture(theCanvas); //if you don't do this, you might lose the mouseup event
                }
            }//end of left-button down
        }
        public void PasteNeurons(bool pasteSynapses = true)
        {
            NeuronArray myClipBoard;

            myClipBoard = MainWindow.myClipBoard;

            if (targetNeuronIndex == -1)
            {
                return;
            }
            if (myClipBoard == null)
            {
                return;
            }
            //We are pasting neurons from the clipboard.
            //The arrays have different sizes so we may by row-col.

            //first check to see if the destination is claar and warn
            List <int> targetNeurons = new List <int>();

            for (int i = 0; i < myClipBoard.arraySize; i++)
            {
                if (myClipBoard.GetNeuron(i) != null)
                {
                    targetNeurons.Add(GetNeuronArrayId(i));
                }
            }

            MainWindow.theNeuronArray.GetNeuronLocation(targetNeuronIndex, out int col, out int row);
            if (col + myClipBoard.Cols > MainWindow.theNeuronArray.Cols ||
                row + myClipBoard.rows > MainWindow.theNeuronArray.rows)
            {
                MessageBoxResult result = MessageBox.Show("Paste would exceed neuron array boundary!", "Error", MessageBoxButton.OK);
                return;
            }

            if (!IsDestinationClear(targetNeurons, 0, true))
            {
                MessageBoxResult result = MessageBox.Show("Some desination is are in use and will be overwritten, continue?", "Continue", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.No)
                {
                    return;
                }
            }

            //now past the neurons
            for (int i = 0; i < myClipBoard.arraySize; i++)
            {
                if (myClipBoard.GetNeuron(i) != null)
                {
                    int destID = GetNeuronArrayId(i);

                    Neuron sourceNeuron = myClipBoard.GetNeuron(i).Clone();
                    sourceNeuron.id = destID;
                    MainWindow.theNeuronArray.SetNeuron(destID, sourceNeuron);
                    //MainWindow.theNeuronArray.GetNeuron(destID).Id = destID;
                    if (pasteSynapses)
                    {
                        foreach (Synapse s in myClipBoard.GetNeuron(i).Synapses)
                        {
                            MainWindow.theNeuronArray.GetNeuron(destID).AddSynapse(GetNeuronArrayId(s.TargetNeuron), s.Weight);
                        }
                    }
                }
            }

            //paste modules
            foreach (ModuleView mv in myClipBoard.modules)
            {
                ModuleView newMV = new ModuleView()
                {
                    FirstNeuron = GetNeuronArrayId(mv.FirstNeuron),
                    TheModule   = mv.TheModule,
                    Color       = mv.Color,
                    Height      = mv.Height,
                    Width       = mv.Width,
                    Label       = mv.Label,
                    CommandLine = mv.CommandLine,
                };

                MainWindow.theNeuronArray.modules.Add(newMV);
            }

            Update();
        }
示例#17
0
 private static void Mi_Click(object sender, RoutedEventArgs e)
 {
     //Handle delete  & initialize commands
     if (sender is MenuItem mi)
     {
         if ((string)mi.Header == "Delete")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
                 i = -i - 1;
                 MainWindow.arrayView.theSelection.selectedRectangles.RemoveAt(i);
                 deleted = true;
             }
             else
             {
                 ModuleView mv = MainWindow.theNeuronArray.Modules[i];
                 foreach (Neuron n in mv.Neurons())
                 {
                     n.Reset();
                     n.DeleteAllSynapes();
                 }
                 MainWindow.theNeuronArray.Modules.RemoveAt(i);
                 deleted = true;
             }
         }
         if ((string)mi.Header == "Initialize")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
             }
             else
             {
                 MainWindow.theNeuronArray.Modules[i].TheModule.Initialize();
             }
         }
         if ((string)mi.Header == "Show Dialog")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
             }
             else
             {
                 MainWindow.theNeuronArray.Modules[i].TheModule.ShowDialog();
             }
         }
         if ((string)mi.Header == "Info...")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
             }
             else
             {
                 ModuleView        m  = MainWindow.theNeuronArray.Modules[i];
                 ModuleBase        m1 = m.TheModule;
                 ModuleDescription md = new ModuleDescription(m1.ShortDescription, m1.LongDescription);
                 md.ShowDialog();
             }
         }
         if ((string)mi.Header == "Reset Hebbian Weights")
         {
             foreach (NeuronSelectionRectangle sr in MainWindow.arrayView.theSelection.selectedRectangles)
             {
                 foreach (int Id in sr.NeuronInRectangle())
                 {
                     Neuron n = MainWindow.theNeuronArray.GetNeuron(Id);
                     foreach (Synapse s in n.Synapses)
                     {
                         if (s.IsHebbian)
                         {
                             s.Weight = 0;
                         }
                     }
                 }
             }
             MainWindow.Update();
         }
     }
 }
        //copy the selection to a clipboard
        public void CopyNeurons()
        {
            //get list of neurons to copy
            List <int> neuronsToCopy = theSelection.EnumSelectedNeurons();

            theSelection.GetSelectedBoundingRectangle(out int X1o, out int Y1o, out int X2o, out int Y2o);
            myClipBoard = new NeuronArray();
            myClipBoard.Initialize((X2o - X1o + 1) * (Y2o - Y1o + 1), (Y2o - Y1o + 1));
            //by setting neurons to null, we can handle odd-shaped selections
            for (int i = 0; i < myClipBoard.arraySize; i++)
            {
                myClipBoard.SetNeuron(i, null);
            }

            //copy the neurons
            foreach (int nID in neuronsToCopy)
            {
                int destId = GetClipboardId(X1o, Y1o, nID);
                //copy the source neuron to the clipboard
                Neuron sourceNeuron = MainWindow.theNeuronArray.GetNeuron(nID);
                Neuron destNeuron   = sourceNeuron.Clone();
                destNeuron.Id = destId;
                myClipBoard.SetNeuron(destId, destNeuron);
            }
            //copy the synapses (this is two-pass so we make sure all neurons exist prior to copying
            foreach (int nID in neuronsToCopy)
            {
                Neuron sourceNeuron = MainWindow.theNeuronArray.GetNeuron(nID);
                int    destId       = GetClipboardId(X1o, Y1o, nID);
                Neuron destNeuron   = myClipBoard.GetNeuron(destId);
                if (sourceNeuron.synapses != null)
                {
                    foreach (Synapse s in sourceNeuron.synapses)
                    {
                        //only copy synapses with both ends in the selection
                        if (neuronsToCopy.Contains(s.TargetNeuron))
                        {
                            destNeuron.AddSynapse(GetClipboardId(X1o, Y1o, s.TargetNeuron), s.Weight);
                        }
                    }
                }
            }

            //copy modules
            foreach (ModuleView mv in MainWindow.theNeuronArray.modules)
            {
                if (theSelection.NeuronInSelection(mv.FirstNeuron) > 0 && theSelection.NeuronInSelection(mv.LastNeuron) > 0)
                {
                    ModuleView newMV = new ModuleView()
                    {
                        FirstNeuron = GetClipboardId(X1o, Y1o, mv.FirstNeuron),
                        TheModule   = mv.TheModule,
                        Color       = mv.Color,
                        Height      = mv.Height,
                        Width       = mv.Width,
                        Label       = mv.Label,
                        CommandLine = mv.CommandLine,
                    };

                    myClipBoard.modules.Add(newMV);
                }
            }
        }
示例#19
0
        private void MoveModule(FrameworkElement theShape, int currentNeuron)
        {
            Debug.WriteLine("currentNeuron: " + currentNeuron + " prevModuleMouseLocation:" + prevModuleMouseLocation);
            lock (MainWindow.theNeuronArray.modules)
            {
                if (currentNeuron != prevModuleMouseLocation)
                {
                    //which module?
                    int        index            = (int)theShape.GetValue(ModuleView.AreaNumberProperty);
                    ModuleView theCurrentModule = MainWindow.theNeuronArray.modules[index];
                    MainWindow.theNeuronArray.AddModuleUndo(index, theCurrentModule);

                    int delta    = currentNeuron - prevModuleMouseLocation;
                    int newFirst = theCurrentModule.FirstNeuron + delta;
                    int newLast  = theCurrentModule.LastNeuron + delta;
                    MainWindow.theNeuronArray.GetNeuronLocation(newFirst, out int col0, out int row0);
                    MainWindow.theNeuronArray.GetNeuronLocation(newLast, out int col1, out int row1);


                    if (newFirst >= 0 && row1 > row0 && newLast < MainWindow.theNeuronArray.arraySize)
                    {
                        //move all the neurons
                        List <int> neuronsToMove = new List <int>();
                        foreach (Neuron n in theCurrentModule.Neurons)
                        {
                            neuronsToMove.Add(n.id);
                        }
                        if (!IsDestinationClear(neuronsToMove, delta))
                        {
                            MessageBoxResult result1 = MessageBox.Show("Some destination neurons are in use and will be overwritten, continue?", "Continue", MessageBoxButton.YesNo);
                            if (result1 != MessageBoxResult.Yes)
                            {
                                return;
                            }
                        }
                        if (delta > 0) //move all the nuerons...opposite order depending on the direction of the move
                        {
                            for (int i = theCurrentModule.NeuronCount - 1; i >= 0; i--)
                            {
                                Neuron src  = theCurrentModule.GetNeuronAt(i);
                                Neuron dest = MainWindow.theNeuronArray.GetNeuron(src.Id + delta);
                                MainWindow.thisWindow.theNeuronArrayView.MoveOneNeuron(src, dest);
                            }
                        }
                        else
                        {
                            for (int i = 0; i < theCurrentModule.NeuronCount; i++)
                            {
                                Neuron src  = theCurrentModule.GetNeuronAt(i);
                                Neuron dest = MainWindow.theNeuronArray.GetNeuron(src.Id + delta);
                                MainWindow.thisWindow.theNeuronArrayView.MoveOneNeuron(src, dest);
                            }
                        }
                        //move the box
                        theCurrentModule.FirstNeuron += delta;
                        Update();
                        prevModuleMouseLocation = currentNeuron;
                    }
                    else
                    {
                        // MessageBox.Show("Module would be outside neuron array boundary.");
                    }
                }
            }
        }
        //move the neurons from the selected area to the second (start point) and stretch all the synapses
        //!!!will fail if the source and destination areas overlap!!!
        public void MoveNeurons()
        {
            if (theSelection.selectedNeuronIndex == -1)
            {
                return;
            }
            if (theSelection.selectedRectangles.Count == 0)
            {
                return;
            }

            List <int> neuronsToMove = theSelection.EnumSelectedNeurons();
            int        maxCol        = 0;
            int        maxRow        = 0;

            MainWindow.theNeuronArray.GetNeuronLocation(theSelection.selectedRectangles[0].FirstSelectedNeuron, out int col0, out int row0);
            foreach (int id in neuronsToMove)
            {
                MainWindow.theNeuronArray.GetNeuronLocation(id, out int tcol, out int trow);
                if (maxCol < tcol - col0)
                {
                    maxCol = tcol - col0;
                }
                if (maxRow < trow - row0)
                {
                    maxRow = trow - row0;
                }
            }


            MainWindow.theNeuronArray.GetNeuronLocation(targetNeuronIndex, out int col, out int row);
            if (col + maxCol >= MainWindow.theNeuronArray.Cols ||
                row + maxRow >= MainWindow.theNeuronArray.rows)
            {
                MessageBoxResult result = MessageBox.Show("Move would exceed neuron array boundary!", "Error", MessageBoxButton.OK);
                return;
            }

            int offset = targetNeuronIndex - theSelection.selectedRectangles[0].FirstSelectedNeuron;

            if (!IsDestinationClear(neuronsToMove, offset))
            {
                MessageBoxResult result = MessageBox.Show("Some desination is are in use and will be overwritten, continue?", "Continue", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.No)
                {
                    return;
                }
            }

            //change the order of copying to to keep from overwriting ourselves
            if (offset > 0)
            {
                neuronsToMove.Reverse();
            }
            foreach (int source in neuronsToMove)
            {
                Neuron sourceNeuron = MainWindow.theNeuronArray.GetNeuron(source);
                Neuron destNeuron   = MainWindow.theNeuronArray.GetNeuron(source + offset);
                MoveOneNeuron(sourceNeuron, destNeuron);
            }

            foreach (ModuleView mv in MainWindow.theNeuronArray.modules)
            {
                if (theSelection.NeuronInSelection(mv.FirstNeuron) > 0 && theSelection.NeuronInSelection(mv.LastNeuron) > 0)
                {
                    mv.FirstNeuron += offset;
                }
            }

            try
            {
                targetNeuronIndex = -1;
                theSelection.selectedRectangles.Clear();
                Update();
            }
            catch { }
        }
示例#21
0
        public static UIElement GetNeuronView(Neuron n, NeuronArrayView theNeuronArrayViewI, out Label l)
        {
            l = null;
            theNeuronArrayView = theNeuronArrayViewI;

            Point p = dp.pointFromNeuron(n.id);

            SolidColorBrush s1 = GetNeuronColor(n);

            Shape r = null;

            if (dp.ShowNeuronCircles())
            {
                r        = new Ellipse();
                r.Width  = dp.NeuronDisplaySize * ellipseSize;
                r.Height = dp.NeuronDisplaySize * ellipseSize;
            }
            else
            {
                r        = new Rectangle();
                r.Width  = dp.NeuronDisplaySize;
                r.Height = dp.NeuronDisplaySize;
            }
            r.Fill = s1;
            if (dp.ShowNeuronOutlines())
            {
                r.Stroke          = Brushes.Black;
                r.StrokeThickness = 1;
            }

            float offset = (1 - ellipseSize) / 2f;

            Canvas.SetLeft(r, p.X + dp.NeuronDisplaySize * offset);
            Canvas.SetTop(r, p.Y + dp.NeuronDisplaySize * offset);
            if (dp.ShowNeuronArrowCursor())
            {
                r.MouseDown  += theNeuronArrayView.theCanvas_MouseDown;
                r.MouseUp    += theNeuronArrayView.theCanvas_MouseUp;
                r.MouseWheel += theNeuronArrayView.theCanvas_MouseWheel;

                r.MouseEnter += R_MouseEnter;
                r.MouseLeave += R_MouseLeave;
            }


            if (n.Label != "" || n.model != Neuron.modelType.IF)
            {
                l            = new Label();
                l.Content    = n.Label;
                l.FontSize   = dp.NeuronDisplaySize * .25;
                l.Foreground = Brushes.White;
                Canvas.SetLeft(l, p.X + dp.NeuronDisplaySize * offset);
                Canvas.SetTop(l, p.Y + dp.NeuronDisplaySize * offset);
                Canvas.SetZIndex(l, 100);

                if (dp.ShowNeuronArrowCursor())
                {
                    l.MouseEnter += R_MouseEnter;
                    l.MouseLeave += R_MouseLeave;
                }
                l.MouseDown += theNeuronArrayView.theCanvas_MouseDown;
                l.MouseUp   += theNeuronArrayView.theCanvas_MouseUp;
                l.MouseMove += theNeuronArrayView.theCanvas_MouseMove;
                l.Content    = GetNeuronLabel(n);
            }
            return(r);
        }
示例#22
0
 private static void Mi_Click(object sender, RoutedEventArgs e)
 {
     //Handle delete  & initialize commands
     if (sender is MenuItem mi)
     {
         if (mi.Header is StackPanel sp && sp.Children[0] is Label l && l.Content.ToString().StartsWith("Random"))
         {
             if (sp.Children[1] is TextBox tb0)
             {
                 if (int.TryParse(tb0.Text, out int count))
                 {
                     MainWindow.arrayView.CreateRandomSynapses(count);
                     MainWindow.theNeuronArray.ShowSynapses = true;
                     MainWindow.thisWindow.SetShowSynapsesCheckBox(true);
                     MainWindow.Update();
                 }
             }
             return;
         }
         if ((string)mi.Header == "Cut")
         {
             MainWindow.arrayView.CutNeurons();
             MainWindow.Update();
         }
         if ((string)mi.Header == "Copy")
         {
             MainWindow.arrayView.CopyNeurons();
         }
         if ((string)mi.Header == "Clear Selection")
         {
             MainWindow.arrayView.ClearSelection();
             MainWindow.Update();
         }
         if ((string)mi.Header == "Mutual Suppression")
         {
             MainWindow.arrayView.MutualSuppression();
             MainWindow.theNeuronArray.ShowSynapses = true;
             MainWindow.thisWindow.SetShowSynapsesCheckBox(true);
             MainWindow.Update();
         }
         if ((string)mi.Header == "Delete")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
                 MainWindow.arrayView.DeleteSelection();
             }
             else
             {
                 MainWindow.theNeuronArray.SetUndoPoint();
                 MainWindow.theNeuronArray.AddModuleUndo(-1, MainWindow.theNeuronArray.modules[i]);
                 DeleteModule(i);
                 deleted = true;
             }
         }
         if ((string)mi.Header == "Initialize")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
             }
             else
             {
                 {
                     try
                     {
                         MainWindow.theNeuronArray.Modules[i].TheModule.Initialize();
                     }
                     catch (Exception e1)
                     {
                         MessageBox.Show("Initialize failed on module " + MainWindow.theNeuronArray.Modules[i].Label + ".   Message: " + e1.Message);
                     }
                 }
             }
         }
         if ((string)mi.Header == "Show Dialog")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
             }
             else
             {
                 MainWindow.theNeuronArray.Modules[i].TheModule.ShowDialog();
             }
         }
         if ((string)mi.Header == "Info...")
         {
             int i = (int)mi.Parent.GetValue(AreaNumberProperty);
             if (i < 0)
             {
             }
             else
             {
                 ModuleView        m  = MainWindow.theNeuronArray.Modules[i];
                 ModuleBase        m1 = m.TheModule;
                 ModuleDescription md = new ModuleDescription(m1.ShortDescription, m1.LongDescription);
                 md.ShowDialog();
             }
         }
         if ((string)mi.Header == "Reset Hebbian Weights")
         {
             MainWindow.theNeuronArray.SetUndoPoint();
             foreach (SelectionRectangle sr in MainWindow.arrayView.theSelection.selectedRectangles)
             {
                 foreach (int Id in sr.NeuronInRectangle())
                 {
                     Neuron n = MainWindow.theNeuronArray.GetNeuron(Id);
                     foreach (Synapse s in n.Synapses)
                     {
                         if (s.model != Synapse.modelType.Fixed)
                         {
                             //TODO: Add some UI for this:
                             //s.model = Synapse.modelType.Hebbian2;
                             n.AddSynapseWithUndo(s.targetNeuron, 0, s.model);
                             s.Weight = 0;
                         }
                     }
                 }
             }
             MainWindow.Update();
         }
     }
 }
示例#23
0
        private static void SetValueInSelectedNeurons(Neuron n, string property)
        {
            bool neuronInSelection = NeuronInSelection(n.id);

            if (neuronInSelection)
            {
                List <int> theNeurons = theNeuronArrayView.theSelection.EnumSelectedNeurons();
                //special case for label because they are auto-incremented,
                //clear all the labels first to avoid collisions
                if (property == "label")
                {
                    for (int i = 0; i < theNeurons.Count; i++)
                    {
                        Neuron n1 = MainWindow.theNeuronArray.GetNeuron(theNeurons[i]);
                        if (n1.id != n.id)
                        {
                            n1.label = "";
                            n1.Update();
                        }
                    }
                }
                for (int i = 0; i < theNeurons.Count; i++)
                {
                    Neuron n1 = MainWindow.theNeuronArray.GetNeuron(theNeurons[i]);
                    n1.AddUndoInfo();
                    switch (property)
                    {
                    case "currentCharge":
                        if (n.model == Neuron.modelType.Color)
                        {
                            n1.SetValueInt(n.LastChargeInt);
                        }
                        else
                        {
                            n1.currentCharge = n.currentCharge;
                            n1.lastCharge    = n.currentCharge;
                        }
                        break;

                    case "leakRate": n1.leakRate = n.leakRate; break;

                    case "axonDelay": n1.axonDelay = n.axonDelay; break;

                    case "model": n1.model = n.model; break;

                    case "enable": n1.leakRate = n.leakRate; break;

                    case "history":
                        if (FiringHistory.NeuronIsInFiringHistory(n.id))
                        {
                            FiringHistory.AddNeuronToHistoryWindow(n1.id);
                            OpenHistoryWindow();
                        }
                        else
                        {
                            FiringHistory.RemoveNeuronFromHistoryWindow(n1.id);
                        }
                        break;

                    case "synapses":
                        if (MainWindow.arrayView.IsShowingSnapses(n.id))
                        {
                            MainWindow.arrayView.AddShowSynapses(n1.id);
                        }
                        else
                        {
                            MainWindow.arrayView.RemoveShowSynapses(n1.id);
                        }
                        break;

                    case "label":
                        if (n.label == "")
                        {
                            n1.label = "";
                        }
                        else if (n.id != n1.id)
                        {
                            string newLabel = n.label;
                            while (MainWindow.theNeuronArray.GetNeuron(newLabel) != null)
                            {
                                int num        = 0;
                                int digitCount = 0;
                                while (Char.IsDigit(newLabel[newLabel.Length - 1]))
                                {
                                    int.TryParse(newLabel[newLabel.Length - 1].ToString(), out int digit);
                                    num = num + (int)Math.Pow(10, digitCount) * digit;
                                    digitCount++;
                                    newLabel = newLabel.Substring(0, newLabel.Length - 1);
                                }
                                num++;
                                newLabel = newLabel + num.ToString();
                            }
                            n1.label = newLabel;
                        }
                        break;
                    }
                    n1.Update();
                }
            }
        }
示例#24
0
        public void MoveOneNeuron(Neuron n, Neuron nNewLocation, bool addUndo = true)
        {
            if (addUndo)
            {
                n.AddUndoInfo();
                nNewLocation.AddUndoInfo();
            }
            if (MainWindow.useServers)
            {
                n.synapses     = NeuronClient.GetSynapses(n.id);
                n.synapsesFrom = NeuronClient.GetSynapsesFrom(n.id);
            }

            //copy the neuron attributes and delete them from the old neuron.
            n.Copy(nNewLocation);
            MainWindow.theNeuronArray.SetCompleteNeuron(nNewLocation);
            //nNewLocation.RecordHistory = n.RecordHistory;
            //n.recordHistory = false;
            //if (FiringHistory.NeuronIsInFiringHistory(n.id))
            //{
            //    FiringHistory.RemoveNeuronFromHistoryWindow(n.id);
            //    FiringHistory.AddNeuronToHistoryWindow(nNewLocation.id);
            //}

            //for all the synapses going out this neuron, change to going from new location
            //don't use a foreach here because the body of the loop may delete a list entry
            for (int k = 0; k < n.Synapses.Count; k++)
            {
                Synapse s = n.Synapses[k];
                if (addUndo)
                {
                    if (s.targetNeuron != n.id)
                    {
                        nNewLocation.AddSynapseWithUndo(s.targetNeuron, s.weight, s.model);
                    }
                    else
                    {
                        nNewLocation.AddSynapseWithUndo(nNewLocation.id, s.weight, s.model);
                    }
                    n.DeleteSynapseWithUndo(n.synapses[k].targetNeuron);
                }
                else
                {
                    if (s.targetNeuron != n.id)
                    {
                        nNewLocation.AddSynapse(s.targetNeuron, s.weight, s.model);
                    }
                    else
                    {
                        nNewLocation.AddSynapse(nNewLocation.id, s.weight, s.model);
                    }
                    n.DeleteSynapse(n.synapses[k].targetNeuron);
                }
            }

            //for all the synapses coming into this neuron, change the synapse target to new location
            for (int k = 0; k < n.SynapsesFrom.Count; k++)
            {
                Synapse reverseSynapse = n.SynapsesFrom[k]; //(from synapses are sort-of backward
                if (reverseSynapse.targetNeuron != -1)      //?
                {
                    Neuron sourceNeuron = MainWindow.theNeuronArray.GetNeuron(reverseSynapse.targetNeuron);
                    sourceNeuron.DeleteSynapseWithUndo(n.id);
                    if (sourceNeuron.id != n.id)
                    {
                        if (addUndo)
                        {
                            sourceNeuron.AddSynapseWithUndo(nNewLocation.id, reverseSynapse.weight, reverseSynapse.model);
                        }
                        else
                        {
                            sourceNeuron.AddSynapse(nNewLocation.id, reverseSynapse.weight, reverseSynapse.model);
                        }
                    }
                }
            }

            n.Clear();
        }
示例#25
0
        public static bool Save(NeuronArray theNeuronArray, string fileName)
        {
            string     tempFile = System.IO.Path.GetTempFileName();
            FileStream file     = File.Create(tempFile);

            Type[]        extraTypes = GetModuleTypes();
            XmlSerializer writer     = new XmlSerializer(typeof(NeuronArray), extraTypes);

            writer.Serialize(file, theNeuronArray);
            file.Position = 0;;

            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(file);

            XmlElement root        = xmldoc.DocumentElement;
            XmlNode    neuronsNode = xmldoc.CreateNode("element", "Neurons", "");

            root.AppendChild(neuronsNode);

            for (int i = 0; i < theNeuronArray.arraySize; i++)
            {
                Neuron n = theNeuronArray.GetCompleteNeuron(i);
                if (n.inUse)
                {
                    string label = theNeuronArray.GetNeuronLabel(n.id);
                    //this is needed bacause inUse is true if any synapse points to this neuron--we don't need to bother with that if it's the only thing
                    if (n.synapses.Count != 0 || label != "" || n.lastCharge != 0 || n.leakRate != 0.1f ||
                        n.model != Neuron.modelType.Std)
                    {
                        XmlNode neuronNode = xmldoc.CreateNode("element", "Neuron", "");
                        neuronsNode.AppendChild(neuronNode);

                        XmlNode attrNode = xmldoc.CreateNode("element", "Id", "");
                        attrNode.InnerText = n.id.ToString();
                        neuronNode.AppendChild(attrNode);

                        if (n.model != Neuron.modelType.Std)
                        {
                            attrNode           = xmldoc.CreateNode("element", "Model", "");
                            attrNode.InnerText = n.model.ToString();
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.model != Neuron.modelType.Color && n.lastCharge != 0)
                        {
                            attrNode           = xmldoc.CreateNode("element", "LastCharge", "");
                            attrNode.InnerText = n.lastCharge.ToString();
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.model == Neuron.modelType.Color && n.LastChargeInt != 0)
                        {
                            attrNode           = xmldoc.CreateNode("element", "LastCharge", "");
                            attrNode.InnerText = n.LastChargeInt.ToString();
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.leakRate != 0.1f)
                        {
                            attrNode           = xmldoc.CreateNode("element", "LeakRate", "");
                            attrNode.InnerText = n.leakRate.ToString();
                            neuronNode.AppendChild(attrNode);
                        }
                        if (label != "")
                        {
                            attrNode           = xmldoc.CreateNode("element", "Label", "");
                            attrNode.InnerText = label;
                            neuronNode.AppendChild(attrNode);
                        }
                        if (n.synapses.Count > 0)
                        {
                            XmlNode synapsesNode = xmldoc.CreateNode("element", "Synapses", "");
                            neuronNode.AppendChild(synapsesNode);
                            foreach (Synapse s in n.synapses)
                            {
                                XmlNode synapseNode = xmldoc.CreateNode("element", "Synapse", "");
                                synapsesNode.AppendChild(synapseNode);

                                if (s.weight != 1)
                                {
                                    attrNode           = xmldoc.CreateNode("element", "Weight", "");
                                    attrNode.InnerText = s.weight.ToString();
                                    synapseNode.AppendChild(attrNode);
                                }

                                attrNode           = xmldoc.CreateNode("element", "TargetNeuron", "");
                                attrNode.InnerText = s.targetNeuron.ToString();
                                synapseNode.AppendChild(attrNode);

                                if (s.isHebbian)
                                {
                                    attrNode           = xmldoc.CreateNode("element", "IsHebbian", "");
                                    attrNode.InnerText = "true";
                                    synapseNode.AppendChild(attrNode);
                                }
                            }
                        }
                    }
                }
            }
            file.Position = 0;
            xmldoc.Save(file);
            file.Close();
            File.Copy(tempFile, fileName, true);
            File.Delete(tempFile);

            return(true);
        }
示例#26
0
        //these aren't added to synapses (for performance) but are built on the fly if the user right-clicks
        public static void CreateContextMenu(int i, Synapse s, ContextMenu cm)
        {
            cmCancelled   = false;
            weightChanged = false;

            //set defaults for next synapse add
            theNeuronArrayView.lastSynapseModel  = s.model;
            theNeuronArrayView.lastSynapseWeight = s.weight;


            cm.SetValue(SourceIDProperty, i);
            cm.SetValue(TargetIDProperty, s.TargetNeuron);
            cm.SetValue(WeightValProperty, s.Weight);
            cm.SetValue(ModelProperty, s.model);

            cm.Closed         += Cm_Closed;
            cm.PreviewKeyDown += Cm_PreviewKeyDown;
            cm.Opened         += Cm_Opened;

            Neuron     nSource = MainWindow.theNeuronArray.GetNeuron(i);
            Neuron     nTarget = MainWindow.theNeuronArray.GetNeuron(s.targetNeuron);
            StackPanel sp      = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };

            sp.Children.Add(new Label {
                Content = "Source: ", Padding = new Thickness(0)
            });
            string source = nSource.id.ToString();

            if (nSource.label != "")
            {
                source = nSource.Label;
            }
            TextBox t0 = Utils.ContextMenuTextBox(source, "Source", 150);

            t0.TextChanged += TextChanged;
            sp.Children.Add(t0);
            cm.Items.Add(new MenuItem {
                Header = sp, StaysOpenOnClick = true
            });

            sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };
            sp.Children.Add(new Label {
                Content = "Target: ", Padding = new Thickness(0)
            });
            string target = nTarget.id.ToString();

            if (nTarget.label != "")
            {
                target = nTarget.Label;
            }
            TextBox t1 = Utils.ContextMenuTextBox(target, "Target", 150);

            t1.TextChanged += TextChanged;
            sp.Children.Add(t1);
            cm.Items.Add(new MenuItem {
                Header = sp, StaysOpenOnClick = true
            });

            //The Synapse model
            sp = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 3, 3)
            };
            sp.Children.Add(new Label {
                Content = "Model: ", Padding = new Thickness(0)
            });
            ComboBox cb = new ComboBox()
            {
                Width = 100,
                Name  = "Model"
            };

            for (int index = 0; index < Enum.GetValues(typeof(Synapse.modelType)).Length; index++)
            {
                Synapse.modelType model = (Synapse.modelType)index;
                cb.Items.Add(new ListBoxItem()
                {
                    Content = model.ToString(),
                    ToolTip = Synapse.modelToolTip[index],
                    Width   = 100,
                });
            }
            cb.SelectedIndex = (int)s.model;
            sp.Children.Add(cb);
            cm.Items.Add(new MenuItem {
                Header = sp, StaysOpenOnClick = true
            });

            cm.Items.Add(Utils.CreateComboBoxMenuItem("SynapseWeight", s.weight, synapseWeightValues, "F3", "Weight: ", 100, ComboBox_ContentChanged));

            MenuItem mi = new MenuItem();

            mi.Header = "Delete";
            mi.Click += DeleteSynapse_Click;
            cm.Items.Add(mi);

            sp = new StackPanel {
                Orientation = Orientation.Horizontal
            };
            Button b0 = new Button {
                Content = "OK", Width = 100, Height = 25, Margin = new Thickness(10), IsDefault = true
            };

            b0.Click += B0_Click;
            sp.Children.Add(b0);
            b0 = new Button {
                Content = "Cancel", Width = 100, Height = 25, Margin = new Thickness(10), IsCancel = true
            };
            b0.Click += B0_Click;
            sp.Children.Add(b0);

            cm.Items.Add(new MenuItem {
                Header = sp, StaysOpenOnClick = true
            });
        }
示例#27
0
        public void PasteNeurons()
        {
            NeuronArray myClipBoard = MainWindow.myClipBoard;

            if (targetNeuronIndex == -1)
            {
                return;
            }
            if (myClipBoard == null)
            {
                return;
            }

            //We are pasting neurons from the clipboard.
            //The arrays have different sizes so we may by row-col.

            //first check to see if the destination is claar and warn
            List <int> targetNeurons = new List <int>();

            for (int i = 0; i < myClipBoard.arraySize; i++)
            {
                if (myClipBoard.GetNeuron(i) != null)
                {
                    targetNeurons.Add(GetNeuronArrayId(i));
                }
            }

            MainWindow.theNeuronArray.GetNeuronLocation(targetNeuronIndex, out int col, out int row);
            if (col + myClipBoard.Cols > MainWindow.theNeuronArray.Cols ||
                row + myClipBoard.rows > MainWindow.theNeuronArray.rows)
            {
                MessageBoxResult result = MessageBox.Show("Paste would exceed neuron array boundary!", "Error", MessageBoxButton.OK);
                return;
            }

            if (!IsDestinationClear(targetNeurons, 0, true))
            {
                MessageBoxResult result = MessageBox.Show("Some desination neurons are in use and will be overwritten, continue?", "Continue", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.No)
                {
                    return;
                }
            }

            MainWindow.theNeuronArray.SetUndoPoint();
            //now paste the neurons
            for (int i = 0; i < myClipBoard.arraySize; i++)
            {
                if (myClipBoard.GetNeuron(i) != null)
                {
                    int destID = GetNeuronArrayId(i);
                    MainWindow.theNeuronArray.GetNeuron(destID).AddUndoInfo();

                    Neuron sourceNeuron = myClipBoard.GetNeuron(i).Clone();
                    sourceNeuron.id = destID;
                    while (sourceNeuron.label != "" && MainWindow.theNeuronArray.GetNeuron(sourceNeuron.label) != null)
                    {
                        int num        = 0;
                        int digitCount = 0;
                        while (sourceNeuron.Label != "" && Char.IsDigit(sourceNeuron.label[sourceNeuron.label.Length - 1]))
                        {
                            int.TryParse(sourceNeuron.label[sourceNeuron.label.Length - 1].ToString(), out int digit);
                            num = num + (int)Math.Pow(10, digitCount) * digit;
                            digitCount++;
                            sourceNeuron.label = sourceNeuron.label.Substring(0, sourceNeuron.label.Length - 1);
                        }
                        num++;
                        sourceNeuron.label = sourceNeuron.label + num.ToString();
                    }
                    MainWindow.theNeuronArray.SetNeuron(destID, sourceNeuron);

                    foreach (Synapse s in myClipBoard.GetNeuron(i).Synapses)
                    {
                        MainWindow.theNeuronArray.GetNeuron(destID).AddSynapseWithUndo(GetNeuronArrayId(s.TargetNeuron), s.Weight, s.model);
                    }
                }
            }

            //handle boundary synapses
            foreach (BoundarySynapse b in boundarySynapsesOut)
            {
                int    sourceID     = GetNeuronArrayId(b.innerNeuronID);
                Neuron targetNeuron = MainWindow.theNeuronArray.GetNeuron(b.outerNeuronID);
                if (targetNeuron != null)
                {
                    MainWindow.theNeuronArray.GetNeuron(sourceID).AddSynapseWithUndo(targetNeuron.id, b.weight, b.model);
                }
            }
            foreach (BoundarySynapse b in boundarySynapsesIn)
            {
                int    targetID     = GetNeuronArrayId(b.innerNeuronID);
                Neuron sourceNeuron = MainWindow.theNeuronArray.GetNeuron(b.outerNeuronID);
                if (sourceNeuron != null)
                {
                    sourceNeuron.AddSynapseWithUndo(targetID, b.weight, b.model);
                }
            }

            //paste modules
            foreach (ModuleView mv in myClipBoard.modules)
            {
                ModuleView newMV = new ModuleView()
                {
                    FirstNeuron = GetNeuronArrayId(mv.FirstNeuron),
                    TheModule   = mv.TheModule,
                    Color       = mv.Color,
                    Height      = mv.Height,
                    Width       = mv.Width,
                    Label       = mv.Label,
                    CommandLine = mv.CommandLine,
                };

                MainWindow.theNeuronArray.modules.Add(newMV);
            }

            Update();
        }
示例#28
0
        private static void Cm_Closed(object sender, RoutedEventArgs e)
        {
            if (sender is ContextMenu cm)
            {
                if (cmCancelled || (Keyboard.GetKeyStates(Key.Escape) & KeyStates.Down) > 0)
                {
                    cm.IsOpen = false;
                    MainWindow.Update();
                    return;
                }
                int    sourceID    = (int)cm.GetValue(SourceIDProperty);
                int    targetID    = (int)cm.GetValue(TargetIDProperty);
                Neuron nSource     = MainWindow.theNeuronArray.GetNeuron(sourceID);
                Neuron nTarget     = MainWindow.theNeuronArray.GetNeuron(targetID);
                int    newSourceID = sourceID;
                int    newTargetID = targetID;

                Control cc = Utils.FindByName(cm, "Target");
                if (cc is TextBox tb)
                {
                    string targetLabel = tb.Text;
                    if (nTarget.label != targetLabel)
                    {
                        if (!int.TryParse(tb.Text, out newTargetID))
                        {
                            newTargetID = targetID;
                            Neuron n = MainWindow.theNeuronArray.GetNeuron(targetLabel);
                            if (n != null)
                            {
                                newTargetID = n.id;
                            }
                        }
                    }
                }
                cc = Utils.FindByName(cm, "Source");
                if (cc is TextBox tb1)
                {
                    string sourceLabel = tb1.Text;
                    if (nSource.label != sourceLabel)
                    {
                        if (!int.TryParse(tb1.Text, out newSourceID))
                        {
                            newSourceID = sourceID;
                            Neuron n = MainWindow.theNeuronArray.GetNeuron(sourceLabel);
                            if (n != null)
                            {
                                newSourceID = n.id;
                            }
                        }
                    }
                }
                if (newSourceID < 0 || newSourceID >= MainWindow.theNeuronArray.arraySize ||
                    newTargetID < 0 || newTargetID >= MainWindow.theNeuronArray.arraySize
                    )
                {
                    MessageBox.Show("Neuron outside array boundary!");
                    return;
                }
                cc = Utils.FindByName(cm, "SynapseWeight");
                if (cc is ComboBox tb2)
                {
                    float.TryParse(tb2.Text, out float newWeight);
                    if (weightChanged)
                    {
                        theNeuronArrayView.lastSynapseWeight = newWeight;
                        Utils.AddToValues(newWeight, synapseWeightValues);
                    }
                }
                cc = Utils.FindByName(cm, "Model");
                if (cc is ComboBox cb0)
                {
                    ListBoxItem       lbi = (ListBoxItem)cb0.SelectedItem;
                    Synapse.modelType sm  = (Synapse.modelType)System.Enum.Parse(typeof(Synapse.modelType), lbi.Content.ToString());
                    theNeuronArrayView.lastSynapseModel = sm;
                }

                if (newSourceID != sourceID || newTargetID != targetID)
                {
                    MainWindow.theNeuronArray.SetUndoPoint();
                    MainWindow.theNeuronArray.GetNeuron((int)cm.GetValue(SourceIDProperty)).DeleteSynapseWithUndo((int)cm.GetValue(TargetIDProperty));
                }
                Neuron nNewSource = MainWindow.theNeuronArray.GetNeuron(newSourceID);
                nNewSource.AddSynapseWithUndo(newTargetID, theNeuronArrayView.lastSynapseWeight, theNeuronArrayView.lastSynapseModel);
                cm.IsOpen = false;
                MainWindow.Update();
            }
        }
示例#29
0
        //move the neurons from the selected area to the second (start point) and stretch all the synapses
        public void MoveNeurons(bool dragging = false)
        {
            if (theSelection.selectedNeuronIndex == -1)
            {
                return;
            }
            if (theSelection.selectedRectangles.Count == 0)
            {
                return;
            }

            List <int> neuronsToMove = theSelection.EnumSelectedNeurons();
            int        maxCol        = 0;
            int        maxRow        = 0;

            MainWindow.theNeuronArray.GetNeuronLocation(theSelection.selectedRectangles[0].FirstSelectedNeuron, out int col0, out int row0);
            foreach (int id in neuronsToMove)
            {
                MainWindow.theNeuronArray.GetNeuronLocation(id, out int tcol, out int trow);
                if (maxCol < tcol - col0)
                {
                    maxCol = tcol - col0;
                }
                if (maxRow < trow - row0)
                {
                    maxRow = trow - row0;
                }
            }

            int offset = targetNeuronIndex - theSelection.selectedRectangles[0].FirstSelectedNeuron;

            if (offset == 0)
            {
                return;
            }

            MainWindow.theNeuronArray.GetNeuronLocation(targetNeuronIndex, out int col, out int row);
            if (col + maxCol >= MainWindow.theNeuronArray.Cols ||
                row + maxRow >= MainWindow.theNeuronArray.rows ||
                row < 0 ||
                col < 0)
            {
                if (!dragging)
                {
                    MessageBox.Show("Move would exceed neuron array boundary!", "Error", MessageBoxButton.OK);
                }
                return;
            }

            if (!IsDestinationClear(neuronsToMove, offset))
            {
                MessageBoxResult result = MessageBox.Show("Some desination neurons are in use and will be overwritten, continue?\n\nYou can also right-click the final destination neuron and select 'Move Here.'", "Continue", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.No)
                {
                    return;
                }
            }

            if (!dragging)
            {
                MainWindow.theNeuronArray.SetUndoPoint();
                MainWindow.theNeuronArray.AddSelectionUndo();
            }
            //change the order of copying to keep from overwriting ourselves
            if (offset > 0)
            {
                neuronsToMove.Reverse();
            }
            foreach (int source in neuronsToMove)
            {
                Neuron sourceNeuron = MainWindow.theNeuronArray.GetNeuron(source);
                Neuron destNeuron   = MainWindow.theNeuronArray.GetNeuron(source + offset);
                MoveOneNeuron(sourceNeuron, destNeuron);
                if (MainWindow.arrayView.IsShowingSnapses(source))
                {
                    MainWindow.arrayView.RemoveShowSynapses(source);
                    MainWindow.arrayView.AddShowSynapses(source + offset);
                }
            }

            foreach (ModuleView mv in MainWindow.theNeuronArray.modules)
            {
                if (theSelection.NeuronInSelection(mv.FirstNeuron) > 0 && theSelection.NeuronInSelection(mv.LastNeuron) > 0)
                {
                    mv.FirstNeuron += offset;
                }
            }

            try
            {
                targetNeuronIndex = -1;
                foreach (NeuronSelectionRectangle nsr in theSelection.selectedRectangles)
                {
                    nsr.FirstSelectedNeuron += offset;
                }
                Update();
            }
            catch { }
        }
示例#30
0
 private static void SynapseEntry_MouseDown(object sender, MouseButtonEventArgs e)
 {
     if (sender is TextBlock tb0)
     {
         if (tb0.Parent is StackPanel sp)
         {
             if (sp.Parent is MenuItem mi)
             {
                 if (mi.Parent is ContextMenu cm)
                 {
                     if (tb0.Name == "weight")
                     {
                         int sourceID = (int)cm.GetValue(NeuronIDProperty);
                         if (sp.Children.Count > 1 && sp.Children[1] is TextBlock tb1)
                         {
                             int.TryParse(tb1.Text.Substring(0, 8), out int targetID);
                             if (mi.Header.ToString().Contains("In"))
                             {
                                 int temp = targetID;
                                 targetID = sourceID;
                                 sourceID = temp;
                             }
                             ContextMenu newCm = new ContextMenu();
                             Neuron      n     = MainWindow.theNeuronArray.GetNeuron(sourceID);
                             Synapse     s     = n.FindSynapse(targetID);
                             if (s != null)
                             {
                                 SynapseView.CreateContextMenu(sourceID, s, newCm);
                                 newCm.IsOpen = true;
                                 e.Handled    = true;
                             }
                         }
                     }
                     if (tb0.Name == "neuron")
                     {
                         int.TryParse(tb0.Text.Substring(0, 8), out int targetID);
                         Neuron      n1  = MainWindow.theNeuronArray.GetNeuron(targetID);
                         ContextMenu cm1 = NeuronView.CreateContextMenu(n1.id, n1, new ContextMenu()
                         {
                             IsOpen = true,
                         });
                         MainWindow.arrayView.targetNeuronIndex = targetID;
                         Point loc = dp.pointFromNeuron(targetID);
                         if (loc.X < 0 || loc.X > theCanvas.ActualWidth - cm.ActualWidth ||
                             loc.Y < 0 || loc.Y > theCanvas.ActualHeight - cm.ActualHeight)
                         {
                             MainWindow.arrayView.PanToNeuron(targetID);
                             loc = dp.pointFromNeuron(targetID);
                         }
                         loc.X += dp.NeuronDisplaySize / 2;
                         loc.Y += dp.NeuronDisplaySize / 2;
                         loc    = MainWindow.arrayView.theCanvas.PointToScreen(loc);
                         cm1.PlacementRectangle = new Rect(loc.X, loc.Y, 0, 0);
                         cm1.Placement          = System.Windows.Controls.Primitives.PlacementMode.AbsolutePoint;
                     }
                 }
             }
         }
         e.Handled = true;
     }
 }