Exemple #1
0
        public static StringDistribution SubAverageConditional(StringDistribution str, int start, int minLength, int maxLength)
        {
            Argument.CheckIfNotNull(str, "str");
            Argument.CheckIfInRange(start >= 0, "start", "Start index must be non-negative.");
            Argument.CheckIfInRange(minLength >= 0, "minLength", "Min length must be non-negative.");
            Argument.CheckIfInRange(maxLength >= 0, "maxLength", "Max length must be non-negative.");

            if (str.IsPointMass)
            {
                var strPoint = str.Point;
                var alts     = new HashSet <string>();
                for (int length = minLength; length <= maxLength; length++)
                {
                    var s = strPoint.Substring(start, Math.Min(length, strPoint.Length));
                    alts.Add(s);
                }
                return(StringDistribution.OneOf(alts));
            }

            var anyChar    = StringAutomaton.ConstantOnElement(1.0, ImmutableDiscreteChar.Any());
            var transducer = StringTransducer.Consume(StringAutomaton.Repeat(anyChar, minTimes: start, maxTimes: start));

            transducer.AppendInPlace(StringTransducer.Copy(StringAutomaton.Repeat(anyChar, minTimes: minLength, maxTimes: maxLength)));
            transducer.AppendInPlace(StringTransducer.Consume(StringAutomaton.Constant(1.0)));

            return(StringDistribution.FromWeightFunction(transducer.ProjectSource(str.ToAutomaton())));
        }
Exemple #2
0
        public void ProjectSourceLargeAutomaton()
        {
            using (var unlimited = new StringAutomaton.UnlimitedStatesComputation())
            {
                const int StateCount = 100_000;

                var builder = new StringAutomaton.Builder();
                var state   = builder.Start;

                for (var i = 1; i < StateCount; ++i)
                {
                    state = state.AddTransition('a', Weight.One);
                }

                state.SetEndWeight(Weight.One);

                var automaton      = builder.GetAutomaton();
                var point          = new string('a', StateCount - 1);
                var copyTransducer = StringTransducer.Copy();

                var projectedAutomaton = copyTransducer.ProjectSource(automaton);
                var projectedPoint     = copyTransducer.ProjectSource(point);

                StringInferenceTestUtilities.TestValue(projectedAutomaton, 1.0, point);
                StringInferenceTestUtilities.TestValue(projectedPoint, 1.0, point);
            }
        }
Exemple #3
0
        public void Copy()
        {
            StringTransducer copy = StringTransducer.Copy();

            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "important", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "i", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "imp", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "t", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "mpo", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, string.Empty, string.Empty, 1.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, string.Empty, "important", 0.0);

            //// Test that projection on Copy() doesn't change the automaton

            StringAutomaton automaton = StringAutomaton.ConstantOn(2.0, "a", "ab", "ac");

            automaton = automaton.Sum(StringAutomaton.ConstantOn(1.0, "a"));
            automaton = automaton.Sum(StringAutomaton.Constant(2.0));
            automaton = automaton.Product(StringAutomaton.Constant(3.0));

            StringAutomaton automatonClone = copy.ProjectSource(automaton);

            Assert.Equal(automaton, automatonClone);
        }
Exemple #4
0
        public void CopyElement()
        {
            StringTransducer copy = StringTransducer.CopyElement(DiscreteChar.OneOf('a', 'b'));

            StringInferenceTestUtilities.TestTransducerValue(copy, "a", "a", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "b", "b", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "a", "b", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "b", "a", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, string.Empty, string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "bb", "bb", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "bab", "bab", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "bab", "ba", 0.0);

            //// Tests that projection on CopyElement(elements) shrinks the support

            StringAutomaton automaton = StringAutomaton.ConstantOn(2.0, "a", "ab", "ac");

            automaton = automaton.Sum(StringAutomaton.ConstantOn(1.0, "a"));
            automaton = automaton.Sum(StringAutomaton.Constant(2.0));
            automaton = automaton.Product(StringAutomaton.Constant(3.0));

            for (int i = 0; i < 2; ++i)
            {
                StringInferenceTestUtilities.TestValue(automaton, 15, "a");
                StringInferenceTestUtilities.TestValue(automaton, 6.0, "b");
                StringInferenceTestUtilities.TestValue(automaton, i == 0 ? 6.0 : 0.0, string.Empty);
                StringInferenceTestUtilities.TestValue(automaton, i == 0 ? 12.0 : 0.0, "ac", "ab");

                automaton = copy.ProjectSource(automaton);
            }
        }
Exemple #5
0
        public void Transpose()
        {
            StringTransducer transducer = StringTransducer.Consume(StringAutomaton.Constant(3.0));
            StringTransducer transpose1 = StringTransducer.Transpose(transducer);
            StringTransducer transpose2 = transducer.Clone();

            transpose2.TransposeInPlace();

            var pairs = new[]
            {
                new[] { "a", string.Empty },
                new[] { string.Empty, string.Empty },
                new[] { "a", "bc" },
                new[] { "a", "a" }
            };

            foreach (string[] valuePair in pairs)
            {
                double referenceValue1 = transducer.GetValue(valuePair[0], valuePair[1]);
                Assert.Equal(referenceValue1, transpose1.GetValue(valuePair[1], valuePair[0]));
                Assert.Equal(referenceValue1, transpose2.GetValue(valuePair[1], valuePair[0]));

                double referenceValue2 = transducer.GetValue(valuePair[1], valuePair[0]);
                Assert.Equal(referenceValue2, transpose1.GetValue(valuePair[0], valuePair[1]));
                Assert.Equal(referenceValue2, transpose2.GetValue(valuePair[0], valuePair[1]));
            }
        }
Exemple #6
0
        public void LargeTransducer()
        {
            StringAutomaton.MaxStateCount = 1200000; // Something big
            var bigAutomatonBuilder = new StringAutomaton.Builder();

            bigAutomatonBuilder.AddStates(StringAutomaton.MaxStateCount - bigAutomatonBuilder.StatesCount);
            Func <Option <DiscreteChar>, Weight, ValueTuple <Option <PairDistribution <char, DiscreteChar> >, Weight> > transitionConverter =
                (dist, weight) => ValueTuple.Create(Option.Some(PairDistribution <char, DiscreteChar> .FromFirstSecond(dist, dist)), weight);

            var bigAutomaton = bigAutomatonBuilder.GetAutomaton();

            Assert.Throws <AutomatonTooLargeException>(() => StringTransducer.FromAutomaton(bigAutomaton, transitionConverter));

            // Shouldn't throw if the maximum number of states is increased
            int prevMaxStateCount = StringTransducer.MaxStateCount;

            try
            {
                StringTransducer.MaxStateCount = StringAutomaton.MaxStateCount;
                StringTransducer.FromAutomaton(bigAutomaton, transitionConverter);
            }
            finally
            {
                StringTransducer.MaxStateCount = prevMaxStateCount;
            }
        }
Exemple #7
0
        public void LargeTransducer()
        {
            var largeStatesCount = 1200000; // bigger than default MaxStatesCount in automata

            using (var unlimitedAutomatonStates = new StringAutomaton.UnlimitedStatesComputation())
            {
                var bigAutomatonBuilder = new StringAutomaton.Builder();
                bigAutomatonBuilder.AddStates(largeStatesCount - bigAutomatonBuilder.StatesCount);
                Func <Option <ImmutableDiscreteChar>, Weight, ValueTuple <Option <ImmutablePairDistribution <char, ImmutableDiscreteChar> >, Weight> >
                transitionConverter =
                    (dist, weight) =>
                    ValueTuple.Create(
                        Option.Some(ImmutablePairDistribution <char, ImmutableDiscreteChar> .FromFirstSecond(dist, dist)), weight);

                var bigAutomaton = bigAutomatonBuilder.GetAutomaton();

                Assert.Throws <AutomatonTooLargeException>(() =>
                                                           StringTransducer.FromAutomaton(bigAutomaton, transitionConverter));

                // Shouldn't throw if the maximum number of states is increased
                using (var unlimitedTransducerStates = new StringTransducer.UnlimitedStatesComputation())
                {
                    StringTransducer.FromAutomaton(bigAutomaton, transitionConverter);
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Creates a transducer that replaces escaped argument placeholders with the corresponding arguments.
        /// </summary>
        /// <param name="escapedArgs">The list of arguments.</param>
        /// <param name="transpose">Specifies whether the created transducer should be transposed (useful for backward message computation).</param>
        /// <returns>The created transducer.</returns>
        private static StringTransducer GetPlaceholderReplacingTransducer(IList <StringAutomaton> escapedArgs, bool transpose)
        {
            var alternatives = new List <StringTransducer>();

            for (int i = 0; i < escapedArgs.Count; ++i)
            {
                StringTransducer alternative = StringTransducer.ConsumeElement((char)('0' + i));
                alternative.AppendInPlace(StringTransducer.Produce(escapedArgs[i]), (byte)(i + 1));
                alternatives.Add(alternative);
            }

            StringTransducer result = DisallowBraceReplacersTransducer.Clone();

            result.AppendInPlace(StringTransducer.ConsumeElement(LeftBraceReplacer));
            result.AppendInPlace(StringTransducer.Sum(alternatives));
            result.AppendInPlace(StringTransducer.ConsumeElement(RightBraceReplacer));
            result = StringTransducer.Repeat(result, minTimes: 0);
            result.AppendInPlace(DisallowBraceReplacersTransducer);

            if (transpose)
            {
                result.TransposeInPlace();
            }

            return(result);
        }
Exemple #9
0
        /// <summary>
        /// Tests if a projection of a given automaton onto a given transducer has the desired value on a given sequence.
        /// </summary>
        /// <param name="transducer">The transducer.</param>
        /// <param name="input">The automaton to project.</param>
        /// <param name="str">The sequence to test the projection on.</param>
        /// <param name="trueValue">The desired value of the projection on the sequence.</param>
        public static void TestTransducerProjection(
            StringTransducer transducer, StringAutomaton input, string str, double trueValue)
        {
            // Test ProjectSource(func)
            var result = transducer.ProjectSource(input);

            TestValue(result, trueValue, str);
        }
        /// <summary>
        /// Computes the normalizer via transducers.
        /// </summary>
        /// <param name="automaton">The automaton.</param>
        /// <returns>The logarithm of the normalizer.</returns>
        private static double GetLogNormalizerByGetValueWithTransducers(StringAutomaton automaton)
        {
            var one = StringAutomaton.Constant(1.0);
            StringTransducer transducer = StringTransducer.Consume(automaton);

            transducer.AppendInPlace(StringTransducer.Produce(one));
            return(transducer.ProjectSource(one).GetLogValue("an arbitrary string")); // Now this will be exactly the normalizer
        }
Exemple #11
0
        public void ConsumeElement()
        {
            StringTransducer consume = StringTransducer.ConsumeElement('x');

            StringInferenceTestUtilities.TestTransducerValue(consume, "x", string.Empty, 1.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, "xx", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, string.Empty, string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, string.Empty, "x", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, string.Empty, "xx", 0.0);
        }
Exemple #12
0
        public void ProduceElement()
        {
            StringTransducer produce = StringTransducer.ProduceElement('x');

            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, "x", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, "xx", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, "x", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, "xx", string.Empty, 0.0);
        }
Exemple #13
0
        /// <summary>EP message to <c>str2</c>.</summary>
        /// <param name="concat">Incoming message from <c>concat</c>.</param>
        /// <param name="str1">Incoming message from <c>str1</c>.</param>
        /// <returns>The outgoing EP message to the <c>str2</c> argument.</returns>
        /// <remarks>
        ///   <para>The outgoing message is a distribution matching the moments of <c>str2</c> as the random arguments are varied. The formula is <c>proj[p(str2) sum_(concat,str1) p(concat,str1) factor(concat,str1,str2)]/p(str2)</c>.</para>
        /// </remarks>
        public static StringDistribution Str2AverageConditional(StringDistribution concat, StringDistribution str1)
        {
            Argument.CheckIfNotNull(concat, "concat");
            Argument.CheckIfNotNull(str1, "str1");

            StringTransducer transducer = StringTransducer.Consume(str1.GetProbabilityFunction());

            transducer.AppendInPlace(StringTransducer.Copy());
            return(StringDistribution.FromWorkspace(transducer.ProjectSource(concat)));
        }
Exemple #14
0
 /// <summary>
 /// Tests if a transducer projects each of given strings to a zero function.
 /// </summary>
 /// <param name="transducer">The transducer.</param>
 /// <param name="strings">The strings to test.</param>
 public static void TestIfTransducerRejects(StringTransducer transducer, params string[] strings)
 {
     foreach (string str in strings)
     {
         var res = transducer.ProjectSource(StringAutomaton.ConstantOn(1.0, str));
         Assert.True(res.IsZero());
         var res2 = transducer.ProjectSource(str);
         Assert.True(res2.IsZero());
     }
 }
Exemple #15
0
        /// <include file='FactorDocs.xml' path='factor_docs/message_op_class[@name="StringConcatOp"]/message_doc[@name="Str1AverageConditional(StringDistribution, StringDistribution)"]/*'/>
        public static StringDistribution Str1AverageConditional(StringDistribution concat, StringDistribution str2)
        {
            Argument.CheckIfNotNull(concat, "concat");
            Argument.CheckIfNotNull(str2, "str2");

            StringTransducer transducer = StringTransducer.Copy();

            transducer.AppendInPlace(StringTransducer.Consume(str2.ToAutomaton()));
            return(StringDistribution.FromWeightFunction(transducer.ProjectSource(concat.ToAutomaton())));
        }
        /// <include file='FactorDocs.xml' path='factor_docs/message_op_class[@name="StringConcatOp"]/message_doc[@name="Str1AverageConditional(StringDistribution, StringDistribution)"]/*'/>
        public static StringDistribution Str1AverageConditional(StringDistribution concat, StringDistribution str2)
        {
            Argument.CheckIfNotNull(concat, "concat");
            Argument.CheckIfNotNull(str2, "str2");

            StringTransducer transducer = StringTransducer.Copy();

            transducer.AppendInPlace(StringTransducer.Consume(str2.GetWorkspaceOrPoint()));
            return(StringDistribution.FromWorkspace(transducer.ProjectSource(concat.GetWorkspaceOrPoint())));
        }
Exemple #17
0
        public void ProduceSequence()
        {
            StringTransducer produce = StringTransducer.Produce("abc");

            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, "abc", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, "ab", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, "abcd", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, "abc", string.Empty, 0.0);
        }
Exemple #18
0
        public void ConsumeSequence()
        {
            StringTransducer consume = StringTransducer.Consume("abc");

            StringInferenceTestUtilities.TestTransducerValue(consume, "abc", string.Empty, 1.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, "ab", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, "abcd", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, string.Empty, string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, string.Empty, "abc", 0.0);
        }
Exemple #19
0
        public void ReplaceSequence()
        {
            StringTransducer replace = StringTransducer.Replace("hello", "worlds");

            StringInferenceTestUtilities.TestTransducerValue(replace, "hello", "worlds", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, "worlds", "hello", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, "worlds", "worlds", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, "hello", "hello", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, "hello", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, string.Empty, "worlds", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, string.Empty, string.Empty, 0.0);
        }
Exemple #20
0
        public void Repeat2()
        {
            StringAutomaton  automaton = StringAutomaton.ConstantOn(2.0, "a", string.Empty);
            StringTransducer repeat    = StringTransducer.Repeat(StringTransducer.Copy(automaton), 1, 2);

            StringInferenceTestUtilities.TestTransducerValue(repeat, "a", "a", 10.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "aa", "aa", 4.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, string.Empty, string.Empty, 6.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "aaa", "aaa", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "aa", "a", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, string.Empty, "a", 0.0);
        }
Exemple #21
0
        public void Repeat1()
        {
            StringAutomaton  automaton = StringAutomaton.ConstantOn(2.0, "a");
            StringTransducer repeat    = StringTransducer.Repeat(StringTransducer.Consume(automaton), 1, 3);

            StringInferenceTestUtilities.TestTransducerValue(repeat, "a", string.Empty, 2.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "aa", string.Empty, 4.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "aaa", string.Empty, 8.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "aaaa", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, string.Empty, string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, string.Empty, "aaa", 0.0);
        }
Exemple #22
0
        public void ReplaceElements()
        {
            StringTransducer replace = StringTransducer.Replace(DiscreteChar.Lower(), DiscreteChar.Digit());

            StringInferenceTestUtilities.TestTransducerValue(replace, "hello", "123", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, "w", "1337", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, "w", string.Empty, 1.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, string.Empty, "17", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, string.Empty, string.Empty, 1.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, "123", "worlds", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, "123", "123", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(replace, "1", string.Empty, 0.0);
        }
Exemple #23
0
        /// <summary>
        /// Initializes static members of the <see cref="StringFormatOpBase{TThis}"/> class.
        /// </summary>
        static StringFormatOpBase()
        {
            // More general behavior by default
            RequirePlaceholderForEveryArgument = false;

            DiscreteChar noBraces = DiscreteChar.OneOf('{', '}').Complement();

            DisallowBracesAutomaton  = StringAutomaton.Constant(1.0, noBraces);
            DisallowBracesTransducer = StringTransducer.Copy(noBraces);

            // Make sure that the static constructor of TThis has been invoked so that TThis sets everything up
            new TThis();
        }
Exemple #24
0
        /// <summary>EP message to <c>str</c>.</summary>
        /// <param name="sub">Incoming message from <c>sub</c>.</param>
        /// <param name="start">Constant value for <c>start</c>.</param>
        /// <param name="length">Constant value for <c>length</c>.</param>
        /// <returns>The outgoing EP message to the <c>str</c> argument.</returns>
        /// <remarks>
        ///   <para>The outgoing message is a distribution matching the moments of <c>str</c> as the random arguments are varied. The formula is <c>proj[p(str) sum_(sub) p(sub) factor(sub,str,start,length)]/p(str)</c>.</para>
        /// </remarks>
        public static StringDistribution StrAverageConditional(StringDistribution sub, int start, int length)
        {
            Argument.CheckIfNotNull(sub, "sub");
            Argument.CheckIfInRange(start >= 0, "start", "Start index must be non-negative.");
            Argument.CheckIfInRange(length >= 0, "length", "Length must be non-negative.");

            var anyChar    = StringAutomaton.ConstantOnElement(1.0, DiscreteChar.Any());
            var transducer = StringTransducer.Produce(StringAutomaton.Repeat(anyChar, minTimes: start, maxTimes: start));

            transducer.AppendInPlace(StringTransducer.Copy(StringAutomaton.Repeat(anyChar, minTimes: length, maxTimes: length)));
            transducer.AppendInPlace(StringTransducer.Produce(StringAutomaton.Constant(1.0)));

            return(StringDistribution.FromWorkspace(transducer.ProjectSource(sub)));
        }
Exemple #25
0
        /// <summary>
        /// Creates a transducer that replaces braces surrounding the given argument placeholder
        /// with <see cref="LeftBraceReplacer"/> and <see cref="RightBraceReplacer"/>.
        /// </summary>
        /// <param name="argument">The index of the argument.</param>
        /// <param name="argumentCount">The total number of the arguments.</param>
        /// <param name="transpose">Specifies whether the created transducer should be transposed (useful for backward message computation).</param>
        /// <returns>The created transducer.</returns>
        private static StringTransducer GetArgumentEscapingTransducer(int argument, int argumentCount, bool transpose)
        {
            Debug.Assert(argumentCount >= 1 && argumentCount <= 10, "Up to 10 arguments currently supported.");
            Debug.Assert(argument >= 0 && argument < argumentCount, "Argument index must be less than the number of arguments.");

            List <Pair <StringTransducer, StringTransducer> > argumentToEscapingTransducers;

            if (!ArgumentCountToEscapingTransducers.TryGetValue(argumentCount, out argumentToEscapingTransducers))
            {
                argumentToEscapingTransducers = new List <Pair <StringTransducer, StringTransducer> >(argumentCount);
                ArgumentCountToEscapingTransducers[argumentCount] = argumentToEscapingTransducers;

                for (int i = 0; i < argumentCount; ++i)
                {
                    // Escapes braces in {i}
                    StringTransducer replaceBracesForDigit = StringTransducer.ConsumeElement('{');
                    replaceBracesForDigit.AppendInPlace(StringTransducer.ProduceElement(LeftBraceReplacer));
                    replaceBracesForDigit.AppendInPlace(StringTransducer.CopyElement((char)('0' + i)));
                    replaceBracesForDigit.AppendInPlace(StringTransducer.ConsumeElement('}'));
                    replaceBracesForDigit.AppendInPlace(StringTransducer.ProduceElement(RightBraceReplacer));

                    // Skips any number of placeholders which differ from {i}, with arbitrary intermediate text
                    DiscreteChar     noBraces      = DiscreteChar.UniformOver('{', '}').Complement();
                    StringTransducer braceReplacer = StringTransducer.Copy(noBraces);
                    if (argumentCount > 1)
                    {
                        // Skips every placeholder except {i}
                        StringTransducer skipOtherDigits = StringTransducer.CopyElement('{');
                        skipOtherDigits.AppendInPlace(StringTransducer.CopyElement(AllDigitsExcept(i, argumentCount - 1)));
                        skipOtherDigits.AppendInPlace(StringTransducer.CopyElement('}'));

                        braceReplacer.AppendInPlace(skipOtherDigits);
                        braceReplacer = StringTransducer.Repeat(braceReplacer, minTimes: 0);
                        braceReplacer.AppendInPlace(StringTransducer.Copy(noBraces));
                    }

                    // Skips placeholders, then escapes {i} and skips placeholders
                    StringTransducer escapeAndSkip = replaceBracesForDigit.Clone();
                    escapeAndSkip.AppendInPlace(braceReplacer);
                    StringTransducer transducer = braceReplacer.Clone();
                    transducer.AppendInPlace(escapeAndSkip);  // TODO: use Optional() here if {i} can be omitted

                    StringTransducer transducerTranspose = StringTransducer.Transpose(transducer);
                    argumentToEscapingTransducers.Add(Pair.Create(transducer, transducerTranspose));
                }
            }

            return(transpose ? argumentToEscapingTransducers[argument].Second : argumentToEscapingTransducers[argument].First);
        }
Exemple #26
0
        public void Repeat3()
        {
            StringAutomaton  automaton = StringAutomaton.ConstantOn(2.0, "a", "aa");
            StringTransducer repeat    = StringTransducer.Repeat(StringTransducer.Replace(automaton, automaton), minTimes: 0);

            StringInferenceTestUtilities.TestTransducerValue(repeat, string.Empty, string.Empty, 1.0); // TODO: it's not clear from the definition that this should hold
            StringInferenceTestUtilities.TestTransducerValue(repeat, "a", "a", 4.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "a", "aa", 4.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "aa", "aa", 20.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "aaa", "aa", 32.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "aa", "aaa", 32.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "a", "aaa", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, string.Empty, "a", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(repeat, "b", "b", 0.0);
        }
Exemple #27
0
        public void Optional()
        {
            StringAutomaton  automaton    = StringAutomaton.Constant(1.0, DiscreteChar.Lower());
            StringTransducer copy         = StringTransducer.Copy(automaton);
            StringTransducer copyOptional = StringTransducer.Optional(copy);

            StringInferenceTestUtilities.TestTransducerValue(copy, "abc", "abc", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(copyOptional, "abc", "abc", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, string.Empty, string.Empty, 1.0);
            StringInferenceTestUtilities.TestTransducerValue(copyOptional, string.Empty, string.Empty, 2.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "abc", "ab", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copyOptional, "abc", "ab", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "abc", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copyOptional, "abc", string.Empty, 0.0);
        }
Exemple #28
0
        /// <summary>
        /// Tests if a transducer has the desired value on a given pair of strings.
        /// </summary>
        /// <param name="transducer">The transducer.</param>
        /// <param name="string1">The first string.</param>
        /// <param name="string2">The second string.</param>
        /// <param name="trueValue">The desired value of the transducer on the strings.</param>
        public static void TestTransducerValue(
            StringTransducer transducer, string string1, string string2, double trueValue)
        {
            // Test ProjectSource(sequence)
            var result = transducer.ProjectSource(string1);

            TestValue(result, trueValue, string2);

            // Test ProjectSource(func)
            TestTransducerProjection(transducer, StringAutomaton.ConstantOn(1.0, string1), string2, trueValue);

            // Test GetValue()
            double value = transducer.GetValue(string1, string2);

            Assert.Equal(trueValue, value, LogValueEps);
        }
Exemple #29
0
        public void ProduceAutomaton()
        {
            StringAutomaton automaton = StringAutomaton.Constant(2.0, ImmutableDiscreteChar.Lower());

            automaton = automaton.Sum(StringAutomaton.ConstantOnElement(3.0, 'a'));
            StringTransducer produce = StringTransducer.Produce(automaton);

            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, "aaa", 2.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, "bb", 2.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, "a", 5.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, string.Empty, string.Empty, 2.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, "aaa", "bb", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, "bb", "bb", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, "bb", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(produce, "a", string.Empty, 0.0);
        }
Exemple #30
0
        public void ConsumeAutomaton()
        {
            StringAutomaton automaton = StringAutomaton.Constant(2.0, DiscreteChar.Lower());

            automaton = automaton.Sum(StringAutomaton.ConstantOnElement(3.0, 'a'));
            StringTransducer consume = StringTransducer.Consume(automaton);

            StringInferenceTestUtilities.TestTransducerValue(consume, "aaa", string.Empty, 2.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, "bb", string.Empty, 2.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, "a", string.Empty, 5.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, string.Empty, string.Empty, 2.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, "bb", "aaa", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, "bb", "bb", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, string.Empty, "bb", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(consume, string.Empty, "a", 0.0);
        }