示例#1
0
        public void SetDriver(NetworkEmulatorConfiguration yourConfiguration)
        {
            try
            {
                vc = new NetworkEmulator.VirtualChannelClass();
                lr = new LinkRule();
                fr = new PacketFilterRule();

                //带宽
                lr.BandQueueRule.dbBandwidth = yourConfiguration.dbBandwidth;

                lr.BandQueueRule.queue.QueueType = QueueType.NO_QUEUE;
                //lr.BandQueueRule.queue.dropMode = QueueDropMode.DROP_TAIL;
                //lr.BandQueueRule.queue.QueueMode = QueueMode.QUEUE_MODE_PACKET;
                //lr.BandQueueRule.queue.uiQueueSize = 100;

                //延时
                lr.LatencyRule.LatencyType = LatencyType.FIXED_LATENCY;
                lr.LatencyRule.uLatencyType.FixedLatency.ulLatency = 0;


                if (0 != vc.SetLinkRule(ref lr, ref lr, 1))
                {
                    throw new Exception("Failed to Set LinkRule");
                }

                //NetworkEmulator.PacketFilterRule fr = new PacketFilterRule();

                if (0 != vc.InitFilterRule(ref fr))
                {
                    throw new Exception("Failed initializing FilterRule");
                }

                fr.ipVersion = NetworkType.ALL_NETWORK;

                // Adding FilterRule to the VirtualChannel
                if (0 != vc.AddFilterRule(ref fr))
                {
                    throw new Exception("Failed to add FilterRule");
                }

                // Adding VirtualChannel to the emulation
                if (0 != configurator.SubmitVirtualChannel(vc))
                {
                    throw new Exception("Failed to add VirtualChannel to the emulation");
                }
            }
            catch (Exception e)
            {
                PutErrorMessages("Fail to run test API!");
                Console.WriteLine("Fail to run test API!");
                Console.WriteLine(e);
            }
        }
示例#2
0
        public static string Rule(Rule r)
        {
            StringBuilder buf = new StringBuilder();

            if (r.IsGuarded)
            {
                buf.Append(Guard(r.Guard)).Append(": ");
            }

            if (r is ConsumerRule)
            {
                buf.Append(Multiset((r as ConsumerRule).Lhs)).Append(" -> ");
                switch (r.Type)
                {
                case RuleType.MULTISET_REWRITING: {
                    buf.Append(Multiset((r as RewritingRule).Rhs));
                } break;

                case RuleType.REWRITE_COMMUNICATION: {
                    RewriteCommunicationRule rcr = r as RewriteCommunicationRule;
                    if (!rcr.Rhs.IsEmpty())
                    {
                        buf.Append(Multiset(rcr.Rhs)).Append(", ");
                    }
                    int tCount = rcr.TargetRhs.Count;
                    int i      = 1;
                    foreach (KeyValuePair <IInstanceIdentifier, TargetedMultiset> kv in rcr.TargetRhs)
                    {
                        if (kv.Key is InstanceIdentifier)
                        {
                            if ((kv.Key as InstanceIdentifier).Indicator == InstanceIndicator.TYPE)
                            {
                                buf.AppendFormat("{{{0}}}({1})", Multiset(kv.Value.Multiset), (kv.Key as InstanceIdentifier).Value);
                                if (i < tCount)
                                {
                                    buf.Append(", ");
                                }
                            }
                        }
                    }
                } break;

                case RuleType.MEMBRANE_DISSOLUTION: {
                    buf.Append("#");
                } break;

                case RuleType.MEMBRANE_DIVISION: {
                    DivisionRule dr = r as DivisionRule;
                    foreach (InstanceBlueprint ib in dr.Rhs)
                    {
                        buf.AppendFormat("[{0}]({1})", Multiset(ib.Multiset, true), ib.Type.Name);
                    }
                } break;

                case RuleType.LINK_CREATION: {
                    LinkRule lr = r as LinkRule;
                    if (lr.Target is InstanceIdentifier)
                    {
                        InstanceIdentifier iid = lr.Target as InstanceIdentifier;
                        if (iid.Indicator == InstanceIndicator.TYPE)
                        {
                            buf.AppendFormat("- ({0})", iid.Value);
                        }
                    }
                } break;

                case RuleType.LINK_DESTRUCTION: {
                    LinkRule lr = r as LinkRule;
                    if (lr.Target is InstanceIdentifier)
                    {
                        InstanceIdentifier iid = lr.Target as InstanceIdentifier;
                        if (iid.Indicator == InstanceIndicator.TYPE)
                        {
                            buf.AppendFormat("\\- ({0})", iid.Value);
                        }
                    }
                } break;
                }
            }

            return(buf.ToString());
        }
 public object VisitLinkDestruction(KpLinguaParser.LinkDestructionContext context)
 {
     return(LinkRule.LinkDestroy(new InstanceIdentifier(context.typeReference().Accept(this) as string)));
 }
示例#4
0
        public static string TranslateRule(Rule r, MType container = null)
        {
            StringBuilder buf = new StringBuilder();

            if (r is ConsumerRule)
            {
                ConsumerRule rule = r as ConsumerRule;
                if (r.IsGuarded)
                {
                    buf.Append(TranslateGuard(r.Guard));
                    buf.Append(": ");
                }

                buf.Append(TranslateMultiset(rule.Lhs));
                buf.Append(" -> ");
                switch (r.Type)
                {
                    case RuleType.MULTISET_REWRITING:
                        {
                            buf.Append(TranslateMultiset((r as RewritingRule).Rhs));
                        } break;
                    case RuleType.REWRITE_COMMUNICATION:
                        {
                            RewriteCommunicationRule rcr = r as RewriteCommunicationRule;
                            if (!rcr.Rhs.IsEmpty())
                            {
                                buf.Append(TranslateMultiset(rcr.Rhs));
                                if (rcr.TargetRhs.Count > 0)
                                {
                                    buf.Append(", ");
                                }
                            }
                            buf.Append(TranslateTargetedMultiset(rcr.TargetRhs.Values));
                        } break;
                    case RuleType.MEMBRANE_DISSOLUTION:
                        {
                            buf.Append("#");
                        } break;
                    case RuleType.LINK_CREATION:
                        {
                            LinkRule lr = r as LinkRule;
                            if (lr.Target is InstanceIdentifier)
                            {
                                InstanceIdentifier iid = lr.Target as InstanceIdentifier;
                                if (iid.Indicator == InstanceIndicator.TYPE)
                                {
                                    buf.Append("-(").Append(iid.Value).Append(")");
                                }
                            }
                        } break;
                    case RuleType.LINK_DESTRUCTION:
                        {
                            LinkRule lr = r as LinkRule;
                            if (lr.Target is InstanceIdentifier)
                            {
                                InstanceIdentifier iid = lr.Target as InstanceIdentifier;
                                if (iid.Indicator == InstanceIndicator.TYPE)
                                {
                                    buf.Append("\\-(").Append(iid.Value).Append(")");
                                }
                            }
                        } break;
                    case RuleType.MEMBRANE_DIVISION:
                        {
                            DivisionRule dr = r as DivisionRule;
                            foreach (InstanceBlueprint ib in dr.Rhs)
                            {
                                buf.Append("[");
                                if (!ib.Multiset.IsEmpty())
                                {
                                    buf.Append(TranslateMultiset(ib.Multiset));
                                }
                                buf.Append("]");
                                if (container != null)
                                {
                                    if (container.Name == ib.Type.Name)
                                    {
                                        continue;
                                    }
                                }
                                buf.Append("(").Append(ib.Type.Name).Append(")");
                            }
                        } break;
                }

                buf.Append(" .");
            }

            return buf.ToString();
        }
示例#5
0
        /**
         * Test invoke the API to run the emulator
         */
        public void TestAPI()
        {
            try
            {
                // Creating an IConfigurator object
                NetworkEmulator.INewConfigurator configurator = new NetworkEmulator.NetworkEmulatorClass();

                // Creating a VirtualChannel object
                NetworkEmulator.VirtualChannel vc = new NetworkEmulator.VirtualChannelClass();

                LinkRule lr = new LinkRule();
                if (0 != vc.InitLinkRule(ref lr))
                {
                    throw new Exception("Failed to initialize LinkRule");
                }

                lr.BandQueueRule.dbBandwidth = 1000;

                lr.BandQueueRule.queue.QueueType          = QueueType.NORMAL_QUEUE;
                lr.BandQueueRule.queue.dropMode           = QueueDropMode.DROP_TAIL;
                lr.BandQueueRule.queue.QueueMode          = QueueMode.QUEUE_MODE_PACKET;
                lr.BandQueueRule.queue.uiQueueSize        = 100;
                lr.BandQueueRule.queue.red.QueueMin       = 50;
                lr.BandQueueRule.queue.red.QueueMax       = 100;
                lr.BandQueueRule.queue.red.MeanPacketSize = 500;


                lr.LatencyRule.LatencyType = LatencyType.FIXED_LATENCY;
                lr.LatencyRule.uLatencyType.FixedLatency.ulLatency = 0;

                if (0 != vc.SetLinkRule(ref lr, ref lr, 1))
                {
                    throw new Exception("Failed to Set LinkRule");
                }


                NetworkEmulator.PacketFilterRule fr = new PacketFilterRule();
                if (0 != vc.InitFilterRule(ref fr))
                {
                    throw new Exception("Failed initializing FilterRule");
                }

                fr.ipVersion = NetworkType.ALL_NETWORK;

                // Adding FilterRule to the VirtualChannel
                if (0 != vc.AddFilterRule(ref fr))
                {
                    throw new Exception("Failed to add FilterRule");
                }

                // Adding VirtualChannel to the emulation
                if (0 != configurator.SubmitVirtualChannel(vc))
                {
                    throw new Exception("Failed to add VirtualChannel to the emulation");
                }

                NetworkEmulator.INewController Controller = (INewController)configurator;
                Controller.Start();
                System.Threading.Thread.Sleep(30000);
                Controller.Stop(0, 1000);
            }
            catch (Exception e)
            {
                Console.WriteLine("Fail to run test API!");
                Console.WriteLine(e);
            }
        }
示例#6
0
        private void writeRule(Rule rule)
        {
            owt.Write("{");
            bool pItem = writePItem(rule);

            if (!rule.IsEmpty())
            {
                if (pItem)
                {
                    owt.Write(", ");
                }

                if (rule.IsGuarded)
                {
                    owt.Write("\"guard\":");
                    writeGuard(rule.Guard);
                    owt.Write(", ");
                }

                if (rule.Type == RuleType.CONSUMER)
                {
                    owt.Write("\"lhs\":");
                    writeMultiset((rule as ConsumerRule).Lhs);
                }
                else if (rule.Type == RuleType.MULTISET_REWRITING)
                {
                    RewritingRule r = rule as RewritingRule;
                    owt.Write("\"lhs\":");
                    writeMultiset(r.Lhs);
                    owt.Write(", \"rhs\":");
                    writeMultiset(r.Rhs);
                }
                else if (rule.Type == RuleType.REWRITE_COMMUNICATION)
                {
                    RewriteCommunicationRule r = rule as RewriteCommunicationRule;
                    owt.Write("\"lhs\":");
                    writeMultiset(r.Lhs);
                    owt.Write(", \"rhs\":");
                    writeMultiset(r.Rhs);
                    owt.Write(", \"targetRhs\":[");
                    int i = 1;
                    foreach (TargetedMultiset tm in r.TargetRhs.Values)
                    {
                        writeTargetedMultiset(tm);
                        if (i++ < r.TargetRhs.Count)
                        {
                            owt.Write(", ");
                        }
                    }
                    owt.Write("]");
                }
                else if (rule.Type == RuleType.MEMBRANE_DIVISION)
                {
                    DivisionRule r = rule as DivisionRule;
                    owt.Write("\"lhs\":");
                    writeMultiset(r.Lhs);
                    owt.Write(", \"instances\":[");
                    int i = 1;
                    foreach (InstanceBlueprint ib in r.Rhs)
                    {
                        writeInstanceBlueprint(ib);
                        if (i++ < r.Rhs.Count)
                        {
                            owt.Write(", ");
                        }
                    }
                    owt.Write("]");
                }
                else if (rule.Type == RuleType.LINK_CREATION)
                {
                    LinkRule r = rule as LinkRule;
                    owt.Write("\"lhs\":");
                    writeMultiset(r.Lhs);
                    owt.Write(",\"linkCreate\":");
                    writeInstanceIdentifier(r.Target);
                }
                else if (rule.Type == RuleType.LINK_DESTRUCTION)
                {
                    LinkRule r = rule as LinkRule;
                    owt.Write("\"lhs\":");
                    writeMultiset(r.Lhs);
                    owt.Write(",\"linkDestroy\":");
                    writeInstanceIdentifier(r.Target);
                }
                else if (rule.Type == RuleType.MEMBRANE_DISSOLUTION)
                {
                    DissolutionRule r = rule as DissolutionRule;
                    owt.Write("\"lhs\":");
                    writeMultiset(r.Lhs);
                    owt.Write(", \"dissolve\": true");
                }
            }

            owt.Write("}");
        }
示例#7
0
        /// <summary>
        /// 下一个词语
        /// </summary>
        /// <returns></returns>
        public string Next()
        {
            if (length > 0)
            {
                return(Flush());
            }
            //重置联合器
            assoStream.Reset();

            //读取下一个字符
            char c = GetNextChar();

            //如果缓冲区里已经没有内容则终止当前读取
            if (dataLen < bufferIndex)
            {
                return(Flush());
            }

            //将字符放入输出数组
            Push(c);

            //根据首字符的类型选择不同的读取过程
            switch (Char.GetUnicodeCategory(c))
            {
            //如果是数字则读取之后的全部数字直到遇到非数字字符
            case UnicodeCategory.DecimalDigitNumber:
                while (
                    (
                        Char.GetUnicodeCategory(c = GetNextChar()) == UnicodeCategory.DecimalDigitNumber ||
                        c == '.' && buffer[length - 1] != '.'
                    ) &&
                    length < MAX_WORD_LEN
                    )
                {
                    Push(c);
                }
                Back();
                return(Flush().Trim('.'));

            //如果是英文字符则读取之后的全部英文字符直到遇到非英文字符
            case UnicodeCategory.LowercaseLetter:
                while (
                    (
                        Char.GetUnicodeCategory(c = GetNextChar()) == UnicodeCategory.LowercaseLetter ||
                        c == '+' ||
                        c == '#'
                    ) &&
                    length < MAX_WORD_LEN
                    )
                {
                    Push(c);
                }
                Back();
                return(Flush());

            //如果是中文字符则开始中文分词过程
            case UnicodeCategory.OtherLetter:
                if (c > 19967 && c < 40870 || c > 12353 && c < 12436)
                {
                    assoStream.Associate(c);
                    //读取并检测下一个字符是否是中文字符
                    while (Char.GetUnicodeCategory(c = GetNextChar()) == UnicodeCategory.OtherLetter && length < MAX_WORD_LEN)
                    {
                        //通过字典树向下匹配词语直至无法匹配
                        if (!assoStream.IsBegin && assoStream.HasChildren && assoStream.Associate(c))
                        {
                            Push(c);
                            continue;
                        }
                        //如果出现过的匹配成功的词语则昭会上一个词语
                        if (!assoStream.IsWordEnd && assoStream.IsOccurWord)
                        {
                            assoStream.BackToLastWordEnd();
                            bufferIndex = bufferIndex - length + assoStream.Step;
                            offset      = offset - length + assoStream.Step;
                            length      = assoStream.Step;
                        }
                        //如果正好是一个完整的词语则中断处理
                        if (assoStream.IsWordEnd)
                        {
                            Push(c);
                            ClearDifferentMeanings();
                        }
                        //否则进行人名的匹配
                        else
                        {
                            if (!LinkRule.Test(buffer[0]))
                            {
                                Push(c);
                                StrangeWordMacth();
                            }
                            else
                            {
                                bufferIndex = bufferIndex - length;
                                offset      = offset - length;
                                length      = 1;
                                return(Flush());
                            }
                        }
                        break;
                    }
                }
                else
                {
                    while (Char.GetUnicodeCategory(c = GetNextChar()) == UnicodeCategory.OtherLetter && length < MAX_WORD_LEN)
                    {
                        Push(c);
                    }
                }
                Back();
                return(Flush());

            //如果是非可读字符(包括标点符号,空格等)则直接进入下一个处理过程
            default:
                length = 0;
                return(String.Empty);
            }
        }
示例#8
0
        public void RefreshRule()
        {
            var viewer = GetTemplateChild("Viewer") as RichTextBlock;

            if (viewer == null)
            {
                return;
            }
            viewer.Blocks.Clear();
            if (string.IsNullOrWhiteSpace(Content))
            {
                return;
            }
            var items     = LinkRule.Render(Content, Rules, true);
            var paragraph = new Paragraph();

            foreach (var item in items)
            {
                if (item.Type == BlockType.LINE)
                {
                    paragraph.Inlines.Add(new LineBreak());
                    continue;
                }
                if (item.Type == BlockType.TEXT)
                {
                    var run = new Run
                    {
                        Text     = item.Content,
                        FontSize = FontSize,
                    };
                    paragraph.Inlines.Add(run);
                    continue;
                }
                if (item.Type == BlockType.LINK || item.Type == BlockType.USER)
                {
                    var link = new Hyperlink()
                    {
                        // NavigateUri = new Uri(item.Value as string),
                    };
                    link.Click += (Hyperlink sender, HyperlinkClickEventArgs e) =>
                    {
                        RuleTapped?.Invoke(this, new RuleTappedArgs(item));
                    };
                    link.Inlines.Add(new Run()
                    {
                        Text     = item.Content,
                        FontSize = FontSize,
                    });
                    paragraph.Inlines.Add(link);
                    continue;
                }
                if (item.Type == BlockType.IMAGE)
                {
                    var container = new InlineUIContainer();
                    var img       = new Image
                    {
                        Source = ConverterHelper.ToImg(item.Value as string)
                    };
                    img.Width       = 1.5 * FontSize;
                    container.Child = img;
                    paragraph.Inlines.Add(container);
                }
            }
            viewer.TextWrapping = TextWrapping.Wrap;
            viewer.LineHeight   = 2 * FontSize;
            viewer.Blocks.Add(paragraph);
        }
示例#9
0
        //歧义消除
        private void ClearDifferentMeanings()
        {
            int len = length - 1;

            //如果当前词语中含有更短的词语时进行再分词处理,否则继续向后进行歧义检测
            if (assoStream.BackToLastWordEnd())
            {
                int start = assoStream.Step;
                int end   = start;
                assoStream.Reset();

                char c = buffer[end];
                //对多出的词继续进行词语匹配
                while (end < length && assoStream.Associate(c = buffer[end]))
                {
                    Prep(c);
                    end++;
                }

                //如果缓冲区中的内容全部匹配完后继续中文本流中读取
                if (end == length)
                {
                    while (Char.GetUnicodeCategory(c = GetNextChar()) == UnicodeCategory.OtherLetter && assoStream.Associate(c))
                    {
                        Prep(c);
                    }
                }

                //如果预处理的词出现过词语则回朔到最后一个词语
                if (!assoStream.IsWordEnd && assoStream.IsOccurWord)
                {
                    assoStream.BackToLastWordEnd();
                    bufferIndex = bufferIndex - prepLength + assoStream.Step;
                    offset      = offset - prepLength + assoStream.Step;
                    prepLength  = assoStream.Step;
                }

                ///如果存在一个完整的词语并且词语长度比缓冲区中的上一个词语更长时将缓冲区切断至词语长度,并将多余字符放到预读缓冲区,否则回朔本次处理
                if (assoStream.IsWordEnd && (prepLength > len || prepLength > start && len > start + 1 || prepLength >= start && Char.GetUnicodeCategory(c) != UnicodeCategory.OtherLetter))
                {
                    len = start;
                }
                else
                {
                    if (end == length)
                    {
                        bufferIndex = bufferIndex + len - prepLength - start;
                        offset      = offset + len - prepLength - start;
                    }
                    prepLength = 0;
                }
            }
            else if (len == 2)
            {
                //保存词性
                //WordPart wp1 = assoStream.GetWordPart();
                assoStream.Reset();
                char c = buffer[1];
                //从词语的第二个词开始依次进行词语匹配
                if (assoStream.Associate(c) && assoStream.Associate(buffer[2]))
                {
                    Prep(c);
                    Prep(buffer[2]);
                    while (Char.GetUnicodeCategory(c = GetNextChar()) == UnicodeCategory.OtherLetter && assoStream.Associate(c))
                    {
                        Prep(c);
                    }
                    if (!assoStream.IsWordEnd && assoStream.IsOccurWord)
                    {
                        assoStream.BackToLastWordEnd();
                        bufferIndex = bufferIndex - prepLength + assoStream.Step;
                        offset      = offset - prepLength + assoStream.Step;
                        prepLength  = assoStream.Step;
                    }
                    if (assoStream.IsWordEnd)
                    {
                        if (prepLength == 2)
                        {
                            //词性组合规则,尚未实现
                            //WordPart wp2 = assoStream.GetWordPart();
                            //if(WordPart.Combo(wp1, wp2)
                            //    len = 2;
                            //else
                            //    len = 1;

                            //临时方案
                            assoStream.Reset();
                            if (assoStream.Associate(prepBuffer[1]) && assoStream.Associate(c))
                            {
                                char[] tmp = new char[MAX_WORD_LEN];
                                tmp[0] = prepBuffer[1];
                                tmp[1] = c;
                                int tmpLength = 2;
                                while (Char.GetUnicodeCategory(c = GetNextChar()) == UnicodeCategory.OtherLetter && assoStream.Associate(c))
                                {
                                    tmp[tmpLength++] = c;
                                }
                                if (!assoStream.IsWordEnd && assoStream.IsOccurWord)
                                {
                                    assoStream.BackToLastWordEnd();
                                    bufferIndex = bufferIndex - tmpLength + assoStream.Step;
                                    offset      = offset - tmpLength + assoStream.Step;
                                    tmpLength   = assoStream.Step;
                                }
                                if (assoStream.IsWordEnd)
                                {
                                    tmp.CopyTo(prepBuffer, 0);
                                    prepLength = tmpLength;
                                }
                                else
                                {
                                    bufferIndex = bufferIndex - tmpLength;
                                    offset      = offset - tmpLength;
                                    prepLength  = 0;
                                }
                            }
                            else if (LinkRule.Test(buffer[0]))
                            {
                                len = 1;
                            }
                            else
                            {
                                bufferIndex = bufferIndex - prepLength + 1;
                                offset      = offset - prepLength + 1;
                                prepLength  = 0;
                            }
                        }
                        else
                        {
                            len = 1;
                        }
                    }
                    else
                    {
                        bufferIndex = bufferIndex - prepLength + 1;
                        offset      = offset - prepLength + 1;
                        prepLength  = 0;
                    }
                }
            }
            length = len;
        }
        private Rule readRule(XPathNavigator nav)
        {
            ConsumerRule rule = null;

            XPathNavigator rhsNav = nav.SelectSingleNode("rhs");

            if (rhsNav != null)
            {
                Multiset          m = readMultiset(rhsNav);
                XPathNodeIterator div;
                if (m.IsEmpty())
                {
                    //then we can have structure changing rules
                    div = rhsNav.SelectChildren("instance", String.Empty);
                    if (div.Count > 0)
                    {
                        DivisionRule r = new DivisionRule();
                        while (div.MoveNext())
                        {
                            string            mtype = div.Current.GetAttribute("mtype", String.Empty);
                            InstanceBlueprint ib    = null;
                            if (String.IsNullOrEmpty(mtype))
                            {
                                ib = new InstanceBlueprint(currentType);
                            }
                            else
                            {
                                ib = new InstanceBlueprint(kp[mtype]);
                            }
                            readMultiset(div.Current, ib.Multiset);
                            r.Rhs.Add(ib);
                        }
                        rule = r;
                    }
                    else
                    {
                        XPathNavigator v;
                        v = rhsNav.SelectSingleNode("linkCreate");
                        if (v == null)
                        {
                            v = rhsNav.SelectSingleNode("linkDestroy");
                            if (v == null)
                            {
                                v = rhsNav.SelectSingleNode("dissolve");
                                if (v != null)
                                {
                                    rule = new DissolutionRule();
                                }
                            }
                            else
                            {
                                rule = LinkRule.LinkDestroy(readInstanceIdentifier(v));
                            }
                        }
                        else
                        {
                            rule = LinkRule.LinkCreate(readInstanceIdentifier(v));
                        }
                    }
                }

                if (rule == null)
                {
                    div = rhsNav.SelectChildren("target", String.Empty);
                    if (div.Count > 0)
                    {
                        RewriteCommunicationRule rcr = new RewriteCommunicationRule();
                        rcr.Rhs.Add(m);
                        while (div.MoveNext())
                        {
                            TargetedMultiset tm  = readTargetedMultiset(div.Current);
                            TargetedMultiset otm = null;
                            rcr.TargetRhs.TryGetValue(tm.Target, out otm);
                            if (otm == null)
                            {
                                rcr.TargetRhs.Add(tm.Target, tm);
                            }
                            else
                            {
                                otm.Multiset.Add(tm.Multiset);
                            }
                        }
                        rule = rcr;
                    }
                    else if (m != null)
                    {
                        rule = new RewritingRule();
                        (rule as RewritingRule).Rhs.Add(m);
                    }
                }
            }

            if (rule == null)
            {
                rule = new ConsumerRule();
            }
            readPItem(nav, rule);
            rule.Guard = readGuard(nav.SelectSingleNode("guard"));
            readMultiset(nav.SelectSingleNode("lhs"), rule.Lhs);

            return(rule);
        }
示例#11
0
        /// <summary>
        /// 对字符序列进行生词检测
        /// </summary>
        /// <param name="word">字符序列</param>
        /// <param name="length">有效字符数量</param>
        /// <returns></returns>
        public static int Match(Char[] word, int length)
        {
            int nStart = 0;

            //姓氏检测
            if (FamilyNameRule.Test(((int)word[0] << 2) + (int)word[1]))
            {
                nStart = 2;
            }
            else if (FamilyNameRule.Test((int)word[0]) && !LinkRule.Test(word[1]))
            {
                nStart = 1;
            }
            else
            {
                AssociateStream assoStream = new AssociateStream();
                //连词检测,如果不是连词则向后进行词语匹配
                if (!LinkRule.Test(word[1]))
                {
                    for (nStart = 1; nStart < length;)
                    {
                        assoStream.Associate(word[nStart++]);
                        if (!assoStream.IsBegin && assoStream.Associate(word[nStart]))
                        {
                            return(nStart - 1);
                        }
                        else
                        {
                            assoStream.Reset();
                        }
                    }
                }
                //地名检测
                for (nStart = 0; nStart < length - 1;)
                {
                    assoStream.Reset();
                    if (!LinkRule.Test(word[nStart++]) && PlaceRule.Test(word[nStart]))
                    {
                        return(nStart + 1);
                    }
                }
                return(1);
            }
            //如果检测到姓氏并且剩余字符数小于3个字符则整个串是一个完整姓名
            if (length - nStart <= 2)
            {
                return(length);
            }
            //如果串的长度大于姓氏的长度则开始检测有效的名字长度
            if (length > nStart)
            {
                int             nEnd       = nStart + 1;
                AssociateStream assoStream = new AssociateStream();

                //如果下一个字是连接字或者当前字符和下一个字无法组合成一个已知词则将当前字被确认为时姓名的一个字
                if (LinkRule.Test(word[nEnd + 1]) || !(assoStream.Associate(word[nEnd]) && assoStream.Associate(word[nEnd + 1])))
                {
                    nEnd++;
                }
                nStart = nEnd;
            }
            return(nStart);
        }
示例#12
0
        internal void build()
        {
            int id;

            MaxLinks        = 0;
            MaxDivisionRate = 0;
            foreach (MInstance instance in mtype.Instances)
            {
                id = nextInstanceId();
                MInstanceMeta im = new MInstanceMeta(this, instance, id);
                iMeta.Add(id, im);
                kpmm.InstanceRegistry.Add(instance, im);
                AddSymbols(instance.Multiset.Objects);
                if (instance.Connections.Count > MaxLinks)
                {
                    MaxLinks = instance.Connections.Count;
                }
            }
            instances = mtype.Instances.ToArray();

            List <Rule>       rs       = new List <Rule>();
            ExecutionStrategy strategy = mtype.ExecutionStrategy;

            while (strategy != null)
            {
                foreach (Rule r in strategy.Rules)
                {
                    id = nextRuleId();
                    RuleMeta rm = new RuleMeta(this, r, id);
                    rMeta.Add(id, rm);
                    rs.Add(r);
                    kpmm.RuleRegistry[r] = rm;
                    if (r.IsGuarded)
                    {
                        extractGuardAlphabet(r.Guard);
                    }

                    switch (r.Type)
                    {
                    case RuleType.MULTISET_REWRITING: {
                        AddSymbols((r as RewritingRule).Lhs.Objects);
                        AddSymbols((r as RewritingRule).Rhs.Objects);
                    } break;

                    case RuleType.REWRITE_COMMUNICATION: {
                        RewriteCommunicationRule rc = r as RewriteCommunicationRule;
                        AddSymbols(rc.Lhs.Objects);
                        AddSymbols(rc.Rhs.Objects);
                        foreach (TargetedMultiset tarm in rc.TargetRhs.Values)
                        {
                            if (tarm.Target is InstanceIdentifier)
                            {
                                InstanceIdentifier iId = tarm.Target as InstanceIdentifier;
                                if (iId.Indicator == InstanceIndicator.TYPE)
                                {
                                    AddSymbols(tarm.Multiset.Objects, iId.Value);
                                    //add interest in this connection
                                    interests.Add(kpmm.GetTypeMetaByName(iId.Value, true));
                                }
                            }
                        }
                    } break;

                    case RuleType.MEMBRANE_DIVISION: {
                        DivisionRule dr = r as DivisionRule;
                        AddSymbols(dr.Lhs.Objects);
                        foreach (InstanceBlueprint ib in dr.Rhs)
                        {
                            AddSymbols(ib.Multiset.Objects, ib.Type.Name);
                            if (ib.Type == MType)
                            {
                                MaxDivisionRate++;
                                divisibleTypes.Add(this);
                            }
                            else
                            {
                                kpmm.GetTypeMetaByName(ib.Type.Name).MaxDivisionRate++;
                                divisibleTypes.Add(kpmm.GetTypeMetaByType(ib.Type));
                            }
                        }
                    } break;

                    default: {
                        if (r is LinkRule)
                        {
                            LinkRule lr = r as LinkRule;
                            AddSymbols(lr.Lhs.Objects);
                            if (lr.Target is InstanceIdentifier)
                            {
                                InstanceIdentifier iid = lr.Target as InstanceIdentifier;
                                if (iid.Indicator == InstanceIndicator.TYPE)
                                {
                                    MTypeMeta mtm = kpmm.GetTypeMetaByName(iid.Value, true);
                                    interests.Add(mtm);
                                    if (lr.Type == RuleType.LINK_CREATION)
                                    {
                                        mayConnectTo.Add(mtm);
                                    }
                                }
                            }
                        }
                        else if (r is ConsumerRule)
                        {
                            AddSymbols((r as ConsumerRule).Lhs.Objects);
                        }
                    } break;
                    }
                    HasCommunication   = HasCommunication || r.Type == RuleType.REWRITE_COMMUNICATION;
                    HasDivision        = HasDivision || r.Type == RuleType.MEMBRANE_DIVISION;
                    HasDissolution     = HasDissolution || r.Type == RuleType.MEMBRANE_DISSOLUTION;
                    HasLinkCreation    = HasLinkCreation || r.Type == RuleType.LINK_CREATION;
                    HasLinkDestruction = HasLinkDestruction || r.Type == RuleType.LINK_DESTRUCTION;
                }
                strategy = strategy.Next;
            }
            rules = rs.ToArray();
        }
示例#13
0
        public KPsystem Run()
        {
            KpSimulationStep simStep = new KpSimulationStep()
            {
                KPsystem = kp, Step = step
            };

            if (SimulationStarted != null)
            {
                SimulationStarted(kp);
            }

            List <ActiveInstance>    activeInstances  = new List <ActiveInstance>();
            List <ActiveInstance>    targetSelections = new List <ActiveInstance>();
            HashSet <ActiveInstance> deadCells        = new HashSet <ActiveInstance>();

            while (!isHalted && step <= endStep)
            {
                rulesApplied = 0;
                bool advanceStrategyBlock = false;
                bool endStepForInstance   = false;

                bool dissolutionRuleApplied = false;
                bool divisionRuleApplied    = false;
                bool linkRuleApplied        = false;

                activeInstances.AddRange(allOperationalInstances);
                int aiCount = activeInstances.Count;

                while (aiCount > 0)
                {
                    //reset instance flags
                    advanceStrategyBlock = false;
                    endStepForInstance   = false;

                    //select an instance
                    ActiveInstance selectedInstance = activeInstances[rand.Next(aiCount)];

                    ExecutionStrategy ex = selectedInstance.CurrentStrategySegment;

                    //this can only happen if the rule set was set to empty
                    if (selectedInstance.ApplicableRules.Count > 0)
                    {
                        Rule selectedRule     = null;
                        bool isRuleApplicable = true;
                        if (ex.Operator == StrategyOperator.SEQUENCE)
                        {
                            selectedRule = selectedInstance.ApplicableRules.First();
                            if (selectedRule.IsGuarded)
                            {
                                if (!selectedRule.Guard.IsSatisfiedBy(selectedInstance.Instance.Multiset))
                                {
                                    isRuleApplicable = false;
                                }
                                else if (selectedInstance.FlagStructureRuleApplied)
                                {
                                    if (selectedRule.IsStructureChangingRule())
                                    {
                                        isRuleApplicable = false;
                                    }
                                }
                            }
                        }
                        else
                        {
                            int selectedIndex = 0;
                            int arCount       = selectedInstance.ApplicableRules.Count;

                            if (ex.Operator == StrategyOperator.ARBITRARY)
                            {
                                selectedIndex = rand.Next(arCount + 1);
                            }
                            else
                            {
                                selectedIndex = rand.Next(arCount);
                            }

                            if (selectedIndex == arCount)
                            {
                                //this essentially means "skip this block" - always in an arbitrary block, never elsewhere
                                selectedRule     = null;
                                isRuleApplicable = false;
                            }
                            else
                            {
                                selectedRule = selectedInstance.ApplicableRules[selectedIndex];
                                if (selectedInstance.FlagStructureRuleApplied)
                                {
                                    if (selectedRule.IsStructureChangingRule())
                                    {
                                        isRuleApplicable = false;
                                    }
                                }
                            }
                        }

                        if (isRuleApplicable)
                        {
                            if (selectedRule is ConsumerRule)
                            {
                                if ((selectedRule as ConsumerRule).Lhs > selectedInstance.Instance.Multiset)
                                {
                                    isRuleApplicable = false;
                                }
                            }
                        }

                        //At this point, the isRuleApplicable basically confirms that no structure rule has been applied thus far
                        //if the selected rule requires this, if guarded, the guard of the selected rule holds and
                        //the left hand multiset is contained in the instance multiset
                        if (isRuleApplicable)
                        {
                            switch (selectedRule.Type)
                            {
                            case RuleType.REWRITE_COMMUNICATION: {
                                RewriteCommunicationRule rcr = selectedRule as RewriteCommunicationRule;
                                foreach (KeyValuePair <IInstanceIdentifier, TargetedMultiset> kv in rcr.TargetRhs)
                                {
                                    if (kv.Key is InstanceIdentifier)
                                    {
                                        InstanceIdentifier iid = kv.Key as InstanceIdentifier;
                                        if (iid.Indicator == InstanceIndicator.TYPE)
                                        {
                                            IndexedMType targetType = indexedTypesByName[iid.Value];
                                            int          cCount     = selectedInstance.ConnectionCount(targetType);
                                            if (cCount > 0)
                                            {
                                                ActiveInstance selectedTarget = selectedInstance.GetTargetAtIndex(rand.Next(cCount), targetType);
                                                selectedTarget.CommunicatedMultiset = kv.Value.Multiset;
                                                targetSelections.Add(selectedTarget);
                                            }
                                            else
                                            {
                                                isRuleApplicable = false;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (isRuleApplicable)
                                {
                                    selectedInstance.Instance.Multiset.Subtract(rcr.Lhs);
                                    selectedInstance.Buffer.Add(rcr.Rhs);
                                    ruleApplied(selectedRule, selectedInstance.Instance);
                                    foreach (ActiveInstance ai in targetSelections)
                                    {
                                        if (step >= startStep)
                                        {
                                            if (recordTargetSelection)
                                            {
                                                if (TargetSelected != null)
                                                {
                                                    TargetSelected(ai.Instance, ai.Type, selectedRule);
                                                }
                                            }
                                        }
                                        ai.CommitCommunication();
                                    }
                                }
                                else
                                {
                                    foreach (ActiveInstance ai in targetSelections)
                                    {
                                        ai.ResetCommunication();
                                    }
                                }
                                targetSelections.Clear();
                            } break;

                            case RuleType.MULTISET_REWRITING: {
                                ruleApplied(selectedRule, selectedInstance.Instance);
                                selectedInstance.Instance.Multiset.Subtract((selectedRule as ConsumerRule).Lhs);
                                selectedInstance.Buffer.Add((selectedRule as RewritingRule).Rhs);
                            } break;

                            case RuleType.MEMBRANE_DISSOLUTION: {
                                ruleApplied(selectedRule, selectedInstance.Instance);
                                dissolutionRuleApplied         = true;
                                selectedInstance.FlagDissolved = true;
                                selectedInstance.Instance.Multiset.Subtract((selectedRule as ConsumerRule).Lhs);
                            } break;

                            case RuleType.LINK_CREATION: {
                                LinkRule lr = selectedRule as LinkRule;
                                if (lr.Target is InstanceIdentifier)
                                {
                                    string         typeName       = (lr.Target as InstanceIdentifier).Value;
                                    IndexedMType   targetType     = indexedTypesByName[typeName];
                                    ActiveInstance selectedTarget = null;
                                    //check if there is a link-free instance we can connect to
                                    int freeLinkCount = targetType.Instances.Count - selectedInstance.ConnectionCount(targetType);
                                    if (freeLinkCount > 0)
                                    {
                                        int selection = rand.Next(freeLinkCount);
                                        int i         = 0;
                                        foreach (ActiveInstance ai in targetType.Instances)
                                        {
                                            if (!selectedInstance.IsConnectedTo(ai))
                                            {
                                                if (i++ == selection)
                                                {
                                                    selectedTarget = ai;
                                                }
                                            }
                                        }

                                        selectedInstance.Instance.Multiset.Subtract(lr.Lhs);
                                        ruleApplied(selectedRule, selectedInstance.Instance);
                                        linkRuleApplied = true;
                                        //selected target can't be null here
                                        selectedInstance.ConnectionToCreate  = selectedTarget;
                                        selectedInstance.FlagLinkRuleApplied = true;
                                        if (step >= startStep)
                                        {
                                            if (recordTargetSelection)
                                            {
                                                if (TargetSelected != null)
                                                {
                                                    TargetSelected(selectedTarget.Instance, selectedTarget.Type, selectedRule);
                                                }
                                            }
                                        }

                                        //a structure rule can only be applied once per step so remove it
                                        selectedInstance.ApplicableRules.Remove(selectedRule);
                                    }
                                    else
                                    {
                                        isRuleApplicable = false;
                                    }
                                }
                            } break;

                            case RuleType.LINK_DESTRUCTION: {
                                LinkRule lr = selectedRule as LinkRule;
                                if (lr.Target is InstanceIdentifier)
                                {
                                    string       typeName   = (lr.Target as InstanceIdentifier).Value;
                                    IndexedMType targetType = indexedTypesByName[typeName];
                                    int          cCount     = selectedInstance.ConnectionCount(targetType);
                                    if (cCount > 0)
                                    {
                                        ActiveInstance selectedTarget = selectedInstance.GetTargetAtIndex(rand.Next(cCount), targetType);

                                        selectedInstance.Instance.Multiset.Subtract(lr.Lhs);
                                        ruleApplied(selectedRule, selectedInstance.Instance);
                                        linkRuleApplied = true;
                                        //selected target can't be null here
                                        selectedInstance.ConnectionToDestroy = selectedTarget;
                                        selectedInstance.FlagLinkRuleApplied = true;
                                        if (step >= startStep)
                                        {
                                            if (recordTargetSelection)
                                            {
                                                if (TargetSelected != null)
                                                {
                                                    TargetSelected(selectedTarget.Instance, selectedTarget.Type, selectedRule);
                                                }
                                            }
                                        }

                                        //a structure rule can only be applied once per step so remove it
                                        selectedInstance.ApplicableRules.Remove(selectedRule);
                                    }
                                    else
                                    {
                                        isRuleApplicable = false;
                                    }
                                }
                            } break;

                            case RuleType.MEMBRANE_DIVISION: {
                                DivisionRule dr = selectedRule as DivisionRule;
                                selectedInstance.Instance.Multiset.Subtract(dr.Lhs);
                                foreach (InstanceBlueprint ib in dr.Rhs)
                                {
                                    selectedInstance.AddInstanceBlueprint(ib, indexedTypesByName[ib.Type.Name]);
                                }
                                selectedInstance.FlagDivided = true;
                                ruleApplied(selectedRule, selectedInstance.Instance);
                                divisionRuleApplied = true;
                            } break;
                            }
                        }


                        if (selectedInstance.FlagDissolved || selectedInstance.FlagDivided)
                        {
                            allOperationalInstances.Remove(selectedInstance);
                            endStepForInstance = true;
                        }
                        else
                        {
                            switch (ex.Operator)
                            {
                            case StrategyOperator.SEQUENCE: {
                                if (isRuleApplicable)
                                {
                                    selectedInstance.ApplicableRules.Remove(selectedRule);
                                }
                                else
                                {
                                    endStepForInstance = true;
                                }
                            } break;

                            case StrategyOperator.MAX: {
                                if (!isRuleApplicable)
                                {
                                    selectedInstance.ApplicableRules.Remove(selectedRule);
                                }
                            } break;

                            case StrategyOperator.CHOICE: {
                                if (isRuleApplicable)
                                {
                                    advanceStrategyBlock = true;
                                }
                                else
                                {
                                    selectedInstance.ApplicableRules.Remove(selectedRule);
                                }
                            } break;

                            case StrategyOperator.ARBITRARY: {
                                if (!isRuleApplicable)
                                {
                                    if (selectedRule == null)
                                    {
                                        advanceStrategyBlock = true;
                                    }
                                    else
                                    {
                                        selectedInstance.ApplicableRules.Remove(selectedRule);
                                    }
                                }
                            } break;
                            }
                        }
                    }

                    if (endStepForInstance)
                    {
                        activeInstances.Remove(selectedInstance);
                    }
                    else
                    {
                        if (selectedInstance.ApplicableRules.Count == 0)
                        {
                            advanceStrategyBlock = true;
                        }

                        if (advanceStrategyBlock)
                        {
                            ex = ex.Next;

                            //if the next execution block is null, then remove this compartment from the active instance array
                            if (ex == null)
                            {
                                activeInstances.Remove(selectedInstance);
                            }
                            else
                            {
                                selectedInstance.CurrentStrategySegment = ex;
                            }
                        }
                    }

                    aiCount = activeInstances.Count;
                }

                if (rulesApplied == 0)
                {
                    isHalted = true;
                }
                else
                {
                    //Clear buffer for all instances;

                    foreach (ActiveInstance instance in allInstances)
                    {
                        instance.CommitBuffer();

                        if (linkRuleApplied)
                        {
                            if (instance.FlagLinkRuleApplied)
                            {
                                instance.CommitConnectionUpdates();
                            }
                        }
                    }

                    if (dissolutionRuleApplied || divisionRuleApplied)
                    {
                        foreach (ActiveInstance instance in allInstances)
                        {
                            if (instance.FlagDissolved)
                            {
                                instance.Instance.IsDissolved = true;
                                deadCells.Add(instance);
                                instance.CommitDissolution();
                            }
                            else if (instance.FlagDivided)
                            {
                                instance.Instance.IsDivided = true;
                                deadCells.Add(instance);
                                instance.CommitNewInstances(onNewInstanceCreated);
                            }
                        }

                        if (divisionRuleApplied)
                        {
                            foreach (ActiveInstance ai in newInstanceSet)
                            {
                                allInstances.Add(ai);
                            }
                            newInstanceSet.Clear();
                        }
                    }

                    foreach (ActiveInstance instance in deadCells)
                    {
                        //remove from allInstances collection such that a dead instance will never be
                        //considered for updates or any sort of operations
                        allInstances.Remove(instance);
                        //remove this instance from the set of instances associated to its type so
                        //it will never be considered for link creation or destruction
                        instance.IndexedMType.Instances.Remove(instance);
                    }

                    if (deadCells.Count > 0)
                    {
                        deadCells.Clear();
                    }

                    //reset execution strategy to begining
                    //it's important this is done after everthing has been commited, because the guards must be evaluated on the updated multiset
                    //in the instance
                    foreach (ActiveInstance ai in allOperationalInstances)
                    {
                        ai.ResetCurrentStrategySegment();
                    }

                    if (step >= startStep)
                    {
                        if (SimulationParams.RecordConfigurations)
                        {
                            if (StepComplete != null)
                            {
                                simStep.Step = step;
                                StepComplete(simStep);
                            }
                        }
                    }
                    ++step;
                }
            }

            --step;
            if (IsHalted() && SystemHalted != null)
            {
                SystemHalted(step);
            }
            if (SimulationComplete != null)
            {
                SimulationComplete(step);
            }

            return(kp);
        }