Esempio n. 1
0
            public void Add(string key, string value)
            {
                string    dataKey = Attributes.DataKey(key);
                Attribute attr    = new Attribute(dataKey, value);

                enclosingAttributes.Add(dataKey, attr);
            }
Esempio n. 2
0
        /// <summary> Returns the query portion of the URL, broken up into individual key/value
        /// pairs. Does NOT unescape the keys and values.
        /// </summary>
        public virtual LinkedHashMap getParameterMap()
        {
            LinkedHashMap map;

            SupportClass.Tokenizer tokens = new SupportClass.Tokenizer(Query, "?&");             //$NON-NLS-1$
            // multiply by 2 to create a sufficiently large HashMap
            map = new LinkedHashMap(tokens.Count * 2);

            while (tokens.HasMoreTokens())
            {
                String nameValuePair = tokens.NextToken();
                String name          = nameValuePair;
                String value         = "";         //$NON-NLS-1$
                int    equalsIndex   = nameValuePair.IndexOf('=');
                if (equalsIndex != -1)
                {
                    name = nameValuePair.Substring(0, (equalsIndex) - (0));
                    if (name.Length > 0)
                    {
                        value = nameValuePair.Substring(equalsIndex + 1);
                    }
                }
                map.Add(name, value);
            }

            return(map);
        }
        public string predictAccentsWithMultiMatches(string sentence, int nResults, bool getWeight = true)
        {
            LinkedHashMap <string, double> output = new LinkedHashMap <string, double>();
            string @in         = Utils.normaliseString(sentence);
            string lowercaseIn = @in.ToLower();

            string[] words = ("0 " + lowercaseIn + " 0").Split(' ');
            Graph    graph = new VariableGraph();
            Dictionary <int, string> idxWordMap = new Dictionary <int, string>();
            int index = 0;

            int[] numberP = new int[words.Length];

            string[,] possibleChange = new string[words.Length, maxp];

            int[,] indices = new int[words.Length, maxp];
            int nVertex = 0;

            index = buildGraph(words, graph, idxWordMap, index, numberP, possibleChange, indices, nVertex);

            //Yen Algorithm for kShortestPaths
            YenTopKShortestPathsAlg yenAlg = new YenTopKShortestPathsAlg(graph);
            List <Accent.KShortestPaths.Model.Path> shortest_paths_list = yenAlg.get_shortest_paths(graph.get_vertex(0), graph.get_vertex(index - 1), nResults);

            foreach (Accent.KShortestPaths.Model.Path path in shortest_paths_list)
            {
                List <BaseVertex> pathVertex = path.get_vertices();
                string            text       = "";
                for (int i = 1; i < pathVertex.Count - 1; i++)
                {
                    BaseVertex vertext = pathVertex[i];
                    text += idxWordMap[vertext.get_id()] + " ";
                    if (text.Contains("đầm dáng"))
                    {
                        text.Replace("đầm dáng", "đảm đang");
                    }
                    if (text.Contains("chào bán"))
                    {
                        text = Regex.Replace(text, "chào bán", "chào bạn");
                    }
                    if (text.Contains("bị đầu tay"))
                    {
                        text = Regex.Replace(text, "bị đầu tay", "bị đau tay");
                    }
                    if (text.Contains("tay tôi bị đầu"))
                    {
                        text = Regex.Replace(text, "tay tôi bị đầu", "tay tôi bị đau");
                    }
                }
                output.Add(processOutput(@in, text.Trim()), path.get_weight());
            }

            // Không lấy trọng số đo lường cho các trường hợp thêm dấu.
            if (!getWeight)
            {
                return(output.ToString2());
            }

            return(output.ToString());
        }
Esempio n. 4
0
        // function GIBBS-ASK(X, e, bn, N) returns an estimate of <b>P</b>(X|e)

        /**
         * The GIBBS-ASK algorithm in Figure 14.16. For answering queries given
         * evidence in a Bayesian Network.
         *
         * @param X
         *            the query variables
         * @param e
         *            observed values for variables E
         * @param bn
         *            a Bayesian network specifying joint distribution
         *            <b>P</b>(X<sub>1</sub>,...,X<sub>n</sub>)
         * @param Nsamples
         *            the total number of samples to be generated
         * @return an estimate of <b>P</b>(X|e)
         */

        public CategoricalDistribution gibbsAsk(RandomVariable[] X,
                                                AssignmentProposition[] e, BayesianNetwork bn, int Nsamples)
        {
            // local variables: <b>N</b>, a vector of counts for each value of X,
            // initially zero
            double[] N = new double[ProbUtil
                                    .expectedSizeOfCategoricalDistribution(X)];
            // Z, the nonevidence variables in bn
            Set <RandomVariable> Z = new Set <RandomVariable>(
                bn.getVariablesInTopologicalOrder());

            foreach (AssignmentProposition ap in e)
            {
                Z.Remove(ap.getTermVariable());
            }
            // <b>x</b>, the current state of the network, initially copied from e
            Map <RandomVariable, Object> x = new LinkedHashMap <RandomVariable, Object>();

            foreach (AssignmentProposition ap in e)
            {
                x.Add(ap.getTermVariable(), ap.getValue());
            }

            // initialize <b>x</b> with random values for the variables in Z
            foreach (RandomVariable Zi in
                     Z)
            {
                x.put(Zi, ProbUtil.randomSample(bn.getNode(Zi), x, randomizer));
            }

            // for j = 1 to N do
            for (int j = 0; j < Nsamples; j++)
            {
                // for each Z<sub>i</sub> in Z do
                foreach (RandomVariable Zi in
                         Z)
                {
                    // set the value of Z<sub>i</sub> in <b>x</b> by sampling from
                    // <b>P</b>(Z<sub>i</sub>|mb(Z<sub>i</sub>))
                    x.put(Zi,
                          ProbUtil.mbRandomSample(bn.getNode(Zi), x, randomizer));
                }
                // Note: moving this outside the previous for loop,
                // as described in fig 14.6, as will only work
                // correctly in the case of a single query variable X.
                // However, when multiple query variables, rare events
                // will get weighted incorrectly if done above. In case
                // of single variable this does not happen as each possible
                // value gets * |Z| above, ending up with the same ratios
                // when normalized (i.e. its still more efficient to place
                // outside the loop).
                //
                // <b>N</b>[x] <- <b>N</b>[x] + 1
                // where x is the value of X in <b>x</b>
                N[ProbUtil.indexOf(X, x)] += 1.0;
            }
            // return NORMALIZE(<b>N</b>)
            return(new ProbabilityTable(N, X).normalize());
        }
		public void Add()
		{
			IDictionary<string, Player> lhm = new LinkedHashMap<string, Player>();
			Fill(lhm);
			lhm.Add("55555", new Player("55555", "Monde Zondeki"));

			Assert.AreEqual(7, lhm.Count);
		}
Esempio n. 6
0
        public void Add()
        {
            IDictionary <string, Player> lhm = new LinkedHashMap <string, Player>();

            Fill(lhm);
            lhm.Add("55555", new Player("55555", "Monde Zondeki"));

            Assert.AreEqual(7, lhm.Count);
        }
        public void GivenASentence_WheAddedToHashTable_ShouldReturnWordFrequency()
        {
            string sentence = "to be or not to be";
            string[] words = sentence.ToLower().Split(" ");

            foreach (string word in words)
            {
                int value = LinkedHashMap.Get(word);
                if (value == default) {
                    value = 1;
                } 
                else value += 1;
                LinkedHashMap.Add(word, value);
            }
            int frequency = LinkedHashMap.Get("to");
            Console.WriteLine(LinkedHashMap);
            Assert.AreEqual(2, frequency);
        }
Esempio n. 8
0
        // function GIBBS-ASK(X, e, bn, N) returns an estimate of <b>P</b>(X|e)
        /**
         * The GIBBS-ASK algorithm in Figure 14.16. For answering queries given
         * evidence in a Bayesian Network.
         * 
         * @param X
         *            the query variables
         * @param e
         *            observed values for variables E
         * @param bn
         *            a Bayesian network specifying joint distribution
         *            <b>P</b>(X<sub>1</sub>,...,X<sub>n</sub>)
         * @param Nsamples
         *            the total number of samples to be generated
         * @return an estimate of <b>P</b>(X|e)
         */

        public CategoricalDistribution gibbsAsk(RandomVariable[] X,
                                                AssignmentProposition[] e, BayesianNetwork bn, int Nsamples)
        {
            // local variables: <b>N</b>, a vector of counts for each value of X,
            // initially zero
            double[] N = new double[ProbUtil
                .expectedSizeOfCategoricalDistribution(X)];
            // Z, the nonevidence variables in bn
            Set<RandomVariable> Z = new Set<RandomVariable>(
                bn.getVariablesInTopologicalOrder());
            foreach (AssignmentProposition ap in e)
            {
                Z.Remove(ap.getTermVariable());
            }
            // <b>x</b>, the current state of the network, initially copied from e
            Map<RandomVariable, Object> x = new LinkedHashMap<RandomVariable, Object>();
            foreach (AssignmentProposition ap in e)
            {
                x.Add(ap.getTermVariable(), ap.getValue());
            }

            // initialize <b>x</b> with random values for the variables in Z
            foreach (RandomVariable Zi in
            Z)
            {
                x.put(Zi, ProbUtil.randomSample(bn.getNode(Zi), x, randomizer));
            }

            // for j = 1 to N do
            for (int j = 0; j < Nsamples; j++)
            {
                // for each Z<sub>i</sub> in Z do
                foreach (RandomVariable Zi in
                Z)
                {
                    // set the value of Z<sub>i</sub> in <b>x</b> by sampling from
                    // <b>P</b>(Z<sub>i</sub>|mb(Z<sub>i</sub>))
                    x.put(Zi,
                          ProbUtil.mbRandomSample(bn.getNode(Zi), x, randomizer));
                }
                // Note: moving this outside the previous for loop,
                // as described in fig 14.6, as will only work
                // correctly in the case of a single query variable X.
                // However, when multiple query variables, rare events
                // will get weighted incorrectly if done above. In case
                // of single variable this does not happen as each possible
                // value gets * |Z| above, ending up with the same ratios
                // when normalized (i.e. its still more efficient to place
                // outside the loop).
                //
                // <b>N</b>[x] <- <b>N</b>[x] + 1
                // where x is the value of X in <b>x</b>
                N[ProbUtil.indexOf(X, x)] += 1.0;
            }
            // return NORMALIZE(<b>N</b>)
            return new ProbabilityTable(N, X).normalize();
        }
 private void AddColumnWithValueOrType(string columnName, object valueOrType)
 {
     if (columns.ContainsKey(columnName))
     {
         throw new ArgumentException(
                   $"The column '{columnName}' has already been added in this SQL builder",
                   nameof(columnName));
     }
     columns.Add(columnName, valueOrType);
 }
Esempio n. 10
0
 /// <summary>
 /// </summary>
 /// <param name="sym"></param>
 /// <exception cref="ArgumentException"></exception>
 public virtual void Define(ISymbol sym)
 {
     if (symbols.ContainsKey(sym.GetName()))
     {
         throw new ArgumentException("duplicate symbol " + sym.GetName());
     }
     sym.SetScope(this);
     sym.SetInsertionOrderNumber(symbols.Count); // set to insertion position from 0
     symbols.Add(sym.GetName(), sym);
 }
        public static LinkedHashMap <TB, TA> ReverseHashMap <TA, TB>(this LinkedHashMap <TA, TB> map)
        {
            var reverseMap = new LinkedHashMap <TB, TA>();

            foreach (var pair in map)
            {
                reverseMap.Add(pair.Value, pair.Key);
            }
            return(reverseMap);
        }
Esempio n. 12
0
        // TODO: implement fullyReadInputStream
        //public static void fullyReadInputStream(InputStream is, ByteArrayOutputStream bytes)
        //{
        //    final byte[]
        //    buffer = new byte[0x10000];
        //    try
        //    {
        //        for (; ; )
        //        {
        //            int read = is.read(buffer);
        //            if (read < 0)
        //            {
        //                break;
        //            }
        //            bytes.write(buffer, 0, read);
        //        }
        //    }
        //    finally
        //    {
        //            is.close();
        //    }
        //}

        public static LinkedHashMap <B, A> reverseHashMap <A, B>(LinkedHashMap <A, B> map)
        {
            LinkedHashMap <B, A> reverseMap = new LinkedHashMap <B, A>();

            foreach (A a in map.Keys)
            {
                B b = map[a];
                reverseMap.Add(b, a);
            }
            return(reverseMap);
        }
Esempio n. 13
0
        // function WEIGHTED-SAMPLE(bn, e) returns an event and a weight

        /**
         * The WEIGHTED-SAMPLE function in Figure 14.15.
         *
         * @param e
         *            observed values for variables E
         * @param bn
         *            a Bayesian network specifying joint distribution
         *            <b>P</b>(X<sub>1</sub>,...,X<sub>n</sub>)
         * @return return <b>x</b>, w - an event with its associated weight.
         */

        public Pair <Map <RandomVariable, Object>, Double> weightedSample(
            BayesianNetwork bn, AssignmentProposition[] e)
        {
            // w <- 1;
            double w = 1.0;
            // <b>x</b> <- an event with n elements initialized from e
            Map <RandomVariable, Object> x = new LinkedHashMap <RandomVariable, Object>();

            foreach (AssignmentProposition ap in
                     e)
            {
                x.Add(ap.getTermVariable(), ap.getValue());
            }

            // foreach variable X<sub>i</sub> in X<sub>1</sub>,...,X<sub>n</sub> do
            foreach (RandomVariable Xi in
                     bn.getVariablesInTopologicalOrder())
            {
                // if X<sub>i</sub> is an evidence variable with value x<sub>i</sub>
                // in e
                if (x.ContainsKey(Xi))
                {
                    // then w <- w * P(X<sub>i</sub> = x<sub>i</sub> |
                    // parents(X<sub>i</sub>))
                    w *= bn.getNode(Xi)
                         .getCPD()
                         .getValue(
                        ProbUtil.getEventValuesForXiGivenParents(
                            bn.getNode(Xi), x));
                }
                else
                {
                    // else <b>x</b>[i] <- a random sample from
                    // <b>P</b>(X<sub>i</sub> | parents(X<sub>i</sub>))
                    x.Add(Xi, ProbUtil.randomSample(bn.getNode(Xi), x, randomizer));
                }
            }
            // return <b>x</b>, w
            return(new Pair <Map <RandomVariable, Object>, Double>(x, w));
        }
Esempio n. 14
0
        // function PRIOR-SAMPLE(bn) returns an event sampled from the prior
        // specified by bn
        /**
         * The PRIOR-SAMPLE algorithm in Figure 14.13. A sampling algorithm that
         * generates events from a Bayesian network. Each variable is sampled
         * according to the conditional distribution given the values already
         * sampled for the variable's parents.
         * 
         * @param bn
         *            a Bayesian network specifying joint distribution
         *            <b>P</b>(X<sub>1</sub>,...,X<sub>n</sub>)
         * @return an event sampled from the prior specified by bn
         */

        public Map<RandomVariable, Object> priorSample(BayesianNetwork bn)
        {
            // x <- an event with n elements
            Map<RandomVariable, Object> x = new LinkedHashMap<RandomVariable, Object>();
            // foreach variable X<sub>i</sub> in X<sub>1</sub>,...,X<sub>n</sub> do
            foreach (RandomVariable Xi in bn.getVariablesInTopologicalOrder())
            {
                // x[i] <- a random sample from
                // <b>P</b>(X<sub>i</sub> | parents(X<sub>i</sub>))
                x.Add(Xi, ProbUtil.randomSample(bn.getNode(Xi), x, randomizer));
            }
            // return x
            return x;
        }
Esempio n. 15
0
        // function PRIOR-SAMPLE(bn) returns an event sampled from the prior
        // specified by bn

        /**
         * The PRIOR-SAMPLE algorithm in Figure 14.13. A sampling algorithm that
         * generates events from a Bayesian network. Each variable is sampled
         * according to the conditional distribution given the values already
         * sampled for the variable's parents.
         *
         * @param bn
         *            a Bayesian network specifying joint distribution
         *            <b>P</b>(X<sub>1</sub>,...,X<sub>n</sub>)
         * @return an event sampled from the prior specified by bn
         */

        public Map <RandomVariable, Object> priorSample(BayesianNetwork bn)
        {
            // x <- an event with n elements
            Map <RandomVariable, Object> x = new LinkedHashMap <RandomVariable, Object>();

            // foreach variable X<sub>i</sub> in X<sub>1</sub>,...,X<sub>n</sub> do
            foreach (RandomVariable Xi in bn.getVariablesInTopologicalOrder())
            {
                // x[i] <- a random sample from
                // <b>P</b>(X<sub>i</sub> | parents(X<sub>i</sub>))
                x.Add(Xi, ProbUtil.randomSample(bn.getNode(Xi), x, randomizer));
            }
            // return x
            return(x);
        }
        public void OrderShouldBePreserved()
        {
            var items = new[] {
                KeyValuePair.Create(1, "One"),
                KeyValuePair.Create(3, "Three"),
                KeyValuePair.Create(2, "Two"),
            };

            var linkedHashMap = new LinkedHashMap <int, string>();

            foreach (var item in items)
            {
                linkedHashMap.Add(item);
            }

            using var enumerator = linkedHashMap.GetEnumerator();
            enumerator.MoveNext();
            Assert.AreEqual(1, enumerator.Current.Key);
            enumerator.MoveNext();
            Assert.AreEqual(3, enumerator.Current.Key);
            enumerator.MoveNext();
            Assert.AreEqual(2, enumerator.Current.Key);
            Assert.True(!enumerator.MoveNext());

            var num = 0;

            foreach (var item in linkedHashMap)
            {
                Assert.AreEqual(items[num++], item);
            }

            linkedHashMap[1] = "OneAgain";
            num = 0;
            foreach (var item in linkedHashMap)
            {
                if (num == 2)
                {
                    Assert.AreEqual(1, item.Key);
                }
                else
                {
                    Assert.AreEqual(items[num + 1], item);
                }
                num++;
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Reloads the internal SPI list.
        /// Changes to the service list are visible after the method ends, all
        /// iterators (e.g, from <see cref="AvailableServices"/>,...) stay consistent.
        ///
        /// <para/><b>NOTE:</b> Only new service providers are added, existing ones are
        /// never removed or replaced.
        ///
        /// <para/><em>this method is expensive and should only be called for discovery
        /// of new service providers on the given classpath/classloader!</em>
        /// </summary>
        public void Reload()
        {
            lock (this)
            {
                IDictionary <string, Type> services = new LinkedHashMap <string, Type>(this.services);
                SPIClassIterator <S>       loader   = SPIClassIterator <S> .Get();

                foreach (var service in loader)
                {
                    string clazzName = service.Name;
                    string name      = null;
                    foreach (string suffix in suffixes)
                    {
                        if (clazzName.EndsWith(suffix, StringComparison.Ordinal))
                        {
                            name = clazzName.Substring(0, clazzName.Length - suffix.Length).ToLowerInvariant();
                            break;
                        }
                    }

                    if (name == null)
                    {
                        throw new InvalidOperationException("The class name " + service.Name +
                                                            " has wrong suffix, allowed are: " + Arrays.ToString(suffixes));
                    }
                    // only add the first one for each name, later services will be ignored
                    // this allows to place services before others in classpath to make
                    // them used instead of others
                    //
                    // LUCENETODO: Should we disallow duplicate names here?
                    // Allowing it may get confusing on collisions, as different packages
                    // could contain same factory class, which is a naming bug!
                    // When changing this be careful to allow reload()!
                    if (!services.ContainsKey(name))
                    {
                        services.Add(name, service);
                    }
                }
                this.services = Collections.UnmodifiableMap(services);
            }
        }
Esempio n. 18
0
        // function WEIGHTED-SAMPLE(bn, e) returns an event and a weight
        /**
         * The WEIGHTED-SAMPLE function in Figure 14.15.
         * 
         * @param e
         *            observed values for variables E
         * @param bn
         *            a Bayesian network specifying joint distribution
         *            <b>P</b>(X<sub>1</sub>,...,X<sub>n</sub>)
         * @return return <b>x</b>, w - an event with its associated weight.
         */

        public Pair<Map<RandomVariable, Object>, Double> weightedSample(
            BayesianNetwork bn, AssignmentProposition[] e)
        {
            // w <- 1;
            double w = 1.0;
            // <b>x</b> <- an event with n elements initialized from e
            Map<RandomVariable, Object> x = new LinkedHashMap<RandomVariable, Object>();
            foreach (AssignmentProposition ap in
            e)
            {
                x.Add(ap.getTermVariable(), ap.getValue());
            }

            // foreach variable X<sub>i</sub> in X<sub>1</sub>,...,X<sub>n</sub> do
            foreach (RandomVariable Xi in
            bn.getVariablesInTopologicalOrder())
            {
                // if X<sub>i</sub> is an evidence variable with value x<sub>i</sub>
                // in e
                if (x.ContainsKey(Xi))
                {
                    // then w <- w * P(X<sub>i</sub> = x<sub>i</sub> |
                    // parents(X<sub>i</sub>))
                    w *= bn.getNode(Xi)
                        .getCPD()
                        .getValue(
                            ProbUtil.getEventValuesForXiGivenParents(
                                bn.getNode(Xi), x));
                }
                else
                {
                    // else <b>x</b>[i] <- a random sample from
                    // <b>P</b>(X<sub>i</sub> | parents(X<sub>i</sub>))
                    x.Add(Xi, ProbUtil.randomSample(bn.getNode(Xi), x, randomizer));
                }
            }
            // return <b>x</b>, w
            return new Pair<Map<RandomVariable, Object>, Double>(x, w);
        }
Esempio n. 19
0
 public void setAttribute(string key, string value)
 {
     azzert(key != "style");
     attributes.Add(key, value);
 }
Esempio n. 20
0
 public void setStyle(string key, string value)
 {
     style.Add(key, value);
 }
		public void Performance()
		{
			// Take care with this test because the result is not the same every times

			int numOfRuns = 4;

			int numOfEntries = Int16.MaxValue;

			long[] dictPopulateTicks = new long[numOfRuns];
			long[] dictItemTicks = new long[numOfRuns];

			long[] linkPopulateTicks = new long[numOfRuns];
			long[] linkItemTicks = new long[numOfRuns];

			for (int runIndex = 0; runIndex < numOfRuns; runIndex++)
			{
				string key;
				object value;
				IDictionary<string, object> dictionary = new Dictionary<string, object>();
				IDictionary<string, object> linked = new LinkedHashMap<string, object>();

				long dictStart = DateTime.Now.Ticks;

				for (int i = 0; i < numOfEntries; i++)
				{
					dictionary.Add("test" + i, new object());
				}

				dictPopulateTicks[runIndex] = DateTime.Now.Ticks - dictStart;

				dictStart = DateTime.Now.Ticks;
				for (int i = 0; i < numOfEntries; i++)
				{
					key = "test" + i;
					value = dictionary[key];
				}
				dictItemTicks[runIndex] = DateTime.Now.Ticks - dictStart;

				dictionary.Clear();

				long linkStart = DateTime.Now.Ticks;

				for (int i = 0; i < numOfEntries; i++)
				{
					linked.Add("test" + i, new object());
				}

				linkPopulateTicks[runIndex] = DateTime.Now.Ticks - linkStart;

				linkStart = DateTime.Now.Ticks;
				for (int i = 0; i < numOfEntries; i++)
				{
					key = "test" + i;
					value = linked[key];
				}

				linkItemTicks[runIndex] = DateTime.Now.Ticks - linkStart;

				linked.Clear();
			}

			for (int runIndex = 0; runIndex < numOfRuns; runIndex++)
			{
				decimal linkPopulateOverhead = (linkPopulateTicks[runIndex] / (decimal)dictPopulateTicks[runIndex]);
				decimal linkItemOverhead = (linkItemTicks[runIndex] / (decimal)dictItemTicks[runIndex]);

				string message = string.Format("LinkedHashMap vs Dictionary (Run-{0}) :",runIndex+1);
				message += "\n POPULATE:";
				message += "\n\t linked took " + linkPopulateTicks[runIndex] + " ticks.";
				message += "\n\t dictionary took " + dictPopulateTicks[runIndex] + " ticks.";
				message += "\n\t for an overhead of " + linkPopulateOverhead;
				message += "\n RETRIVE:";
				message += "\n\t linked took " + linkItemTicks[runIndex] + " ticks.";
				message += "\n\t dictionary took " + dictItemTicks[runIndex] + " ticks.";
				message += "\n\t for an overhead of " + linkItemOverhead;

				Console.Out.WriteLine(message);
				Console.Out.WriteLine();
			}
		}
Esempio n. 22
0
        /**
         * Iterate over all possible values assignments for the Random Variables
         * comprising this ProbabilityTable that are not in the fixed set of values.
         * This allows you to iterate over a subset of possible combinations.
         * 
         * @param pti
         *            the ProbabilityTable Iterator to iterate
         * @param fixedValues
         *            Fixed values for a subset of the Random Variables comprising
         *            this Probability Table.
         */

        public void iterateOverTable(Factor.Iterator pti,
                                     params AssignmentProposition[] fixedValues)
        {
            Map<RandomVariable, Object> possibleWorld = new LinkedHashMap<RandomVariable, Object>();
            MixedRadixNumber tableMRN = new MixedRadixNumber(0, radices);
            int[] tableRadixValues = new int[radices.Length];

            // Assert that the Random Variables for the fixed values
            // are part of this probability table and assign
            // all the fixed values to the possible world.
            foreach (AssignmentProposition ap in fixedValues)
            {
                if (!randomVarInfo.ContainsKey(ap.getTermVariable()))
                {
                    throw new ArgumentException("Assignment proposition ["
                                                + ap + "] does not belong to this probability table.");
                }
                possibleWorld.Add(ap.getTermVariable(), ap.getValue());
                RVInfo fixedRVI = randomVarInfo.get(ap.getTermVariable());
                tableRadixValues[fixedRVI.getRadixIdx()] = fixedRVI
                    .getIdxForDomain(ap.getValue());
            }
            // If have assignments for all the random variables
            // in this probability table
            if (fixedValues.Length == randomVarInfo.Count)
            {
                // Then only 1 iteration call is required.
                pti.iterate(possibleWorld, getValue(fixedValues));
            }
            else
            {
                // Else iterate over the non-fixed values
                List<RandomVariable> freeVariables = SetOps.difference(
                    new List<RandomVariable>(randomVarInfo.Keys), new List<RandomVariable>(possibleWorld.Keys));
                Map<RandomVariable, RVInfo> freeVarInfo = new LinkedHashMap<RandomVariable, RVInfo>();
                // Remove the fixed Variables
                foreach (RandomVariable fv in freeVariables)
                {
                    freeVarInfo.put(fv, new RVInfo(fv));
                }
                int[] freeRadixValues = createRadixs(freeVarInfo);
                MixedRadixNumber freeMRN = new MixedRadixNumber(0, freeRadixValues);
                Object fval = null;
                // Iterate through all combinations of the free variables
                do
                {
                    // Put the current assignments for the free variables
                    // into the possible world and update
                    // the current index in the table MRN
                    foreach (RVInfo freeRVI in freeVarInfo.values())
                    {
                        fval = freeRVI.getDomainValueAt(freeMRN
                                                            .getCurrentNumeralValue(freeRVI.getRadixIdx()));
                        possibleWorld.put(freeRVI.getVariable(), fval);

                        tableRadixValues[randomVarInfo.get(freeRVI.getVariable())
                                             .getRadixIdx()] = freeRVI.getIdxForDomain(fval);
                    }
                    pti.iterate(possibleWorld, values[(int) tableMRN
                                                                .getCurrentValueFor(tableRadixValues)]);

                } while (freeMRN.increment());
            }
        }
Esempio n. 23
0
        /**
         * Iterate over all possible values assignments for the Random Variables
         * comprising this ProbabilityTable that are not in the fixed set of values.
         * This allows you to iterate over a subset of possible combinations.
         *
         * @param pti
         *            the ProbabilityTable Iterator to iterate
         * @param fixedValues
         *            Fixed values for a subset of the Random Variables comprising
         *            this Probability Table.
         */

        public void iterateOverTable(Factor.Iterator pti,
                                     params AssignmentProposition[] fixedValues)
        {
            Map <RandomVariable, Object> possibleWorld = new LinkedHashMap <RandomVariable, Object>();
            MixedRadixNumber             tableMRN      = new MixedRadixNumber(0, radices);

            int[] tableRadixValues = new int[radices.Length];

            // Assert that the Random Variables for the fixed values
            // are part of this probability table and assign
            // all the fixed values to the possible world.
            foreach (AssignmentProposition ap in fixedValues)
            {
                if (!randomVarInfo.ContainsKey(ap.getTermVariable()))
                {
                    throw new ArgumentException("Assignment proposition ["
                                                + ap + "] does not belong to this probability table.");
                }
                possibleWorld.Add(ap.getTermVariable(), ap.getValue());
                RVInfo fixedRVI = randomVarInfo.get(ap.getTermVariable());
                tableRadixValues[fixedRVI.getRadixIdx()] = fixedRVI
                                                           .getIdxForDomain(ap.getValue());
            }
            // If have assignments for all the random variables
            // in this probability table
            if (fixedValues.Length == randomVarInfo.Count)
            {
                // Then only 1 iteration call is required.
                pti.iterate(possibleWorld, getValue(fixedValues));
            }
            else
            {
                // Else iterate over the non-fixed values
                List <RandomVariable> freeVariables = SetOps.difference(
                    new List <RandomVariable>(randomVarInfo.Keys), new List <RandomVariable>(possibleWorld.Keys));
                Map <RandomVariable, RVInfo> freeVarInfo = new LinkedHashMap <RandomVariable, RVInfo>();
                // Remove the fixed Variables
                foreach (RandomVariable fv in freeVariables)
                {
                    freeVarInfo.put(fv, new RVInfo(fv));
                }
                int[]            freeRadixValues = createRadixs(freeVarInfo);
                MixedRadixNumber freeMRN         = new MixedRadixNumber(0, freeRadixValues);
                Object           fval            = null;
                // Iterate through all combinations of the free variables
                do
                {
                    // Put the current assignments for the free variables
                    // into the possible world and update
                    // the current index in the table MRN
                    foreach (RVInfo freeRVI in freeVarInfo.values())
                    {
                        fval = freeRVI.getDomainValueAt(freeMRN
                                                        .getCurrentNumeralValue(freeRVI.getRadixIdx()));
                        possibleWorld.put(freeRVI.getVariable(), fval);

                        tableRadixValues[randomVarInfo.get(freeRVI.getVariable())
                                         .getRadixIdx()] = freeRVI.getIdxForDomain(fval);
                    }
                    pti.iterate(possibleWorld, values[(int)tableMRN
                                                      .getCurrentValueFor(tableRadixValues)]);
                } while (freeMRN.increment());
            }
        }
Esempio n. 24
0
        public void Performance()
        {
            // Take care with this test because the result is not the same every times

            int numOfRuns = 4;

            int numOfEntries = Int16.MaxValue;

            long[] dictPopulateTicks = new long[numOfRuns];
            long[] dictItemTicks     = new long[numOfRuns];

            long[] linkPopulateTicks = new long[numOfRuns];
            long[] linkItemTicks     = new long[numOfRuns];

            for (int runIndex = 0; runIndex < numOfRuns; runIndex++)
            {
                string key;
                object value;
                IDictionary <string, object> dictionary = new Dictionary <string, object>();
                IDictionary <string, object> linked     = new LinkedHashMap <string, object>();

                long dictStart = DateTime.Now.Ticks;

                for (int i = 0; i < numOfEntries; i++)
                {
                    dictionary.Add("test" + i, new object());
                }

                dictPopulateTicks[runIndex] = DateTime.Now.Ticks - dictStart;

                dictStart = DateTime.Now.Ticks;
                for (int i = 0; i < numOfEntries; i++)
                {
                    key   = "test" + i;
                    value = dictionary[key];
                }
                dictItemTicks[runIndex] = DateTime.Now.Ticks - dictStart;

                dictionary.Clear();

                long linkStart = DateTime.Now.Ticks;

                for (int i = 0; i < numOfEntries; i++)
                {
                    linked.Add("test" + i, new object());
                }

                linkPopulateTicks[runIndex] = DateTime.Now.Ticks - linkStart;

                linkStart = DateTime.Now.Ticks;
                for (int i = 0; i < numOfEntries; i++)
                {
                    key   = "test" + i;
                    value = linked[key];
                }

                linkItemTicks[runIndex] = DateTime.Now.Ticks - linkStart;

                linked.Clear();
            }

            for (int runIndex = 0; runIndex < numOfRuns; runIndex++)
            {
                decimal linkPopulateOverhead = (linkPopulateTicks[runIndex] / (decimal)dictPopulateTicks[runIndex]);
                decimal linkItemOverhead     = (linkItemTicks[runIndex] / (decimal)dictItemTicks[runIndex]);

                string message = string.Format("LinkedHashMap vs Dictionary (Run-{0}) :", runIndex + 1);
                message += "\n POPULATE:";
                message += "\n\t linked took " + linkPopulateTicks[runIndex] + " ticks.";
                message += "\n\t dictionary took " + dictPopulateTicks[runIndex] + " ticks.";
                message += "\n\t for an overhead of " + linkPopulateOverhead;
                message += "\n RETRIVE:";
                message += "\n\t linked took " + linkItemTicks[runIndex] + " ticks.";
                message += "\n\t dictionary took " + dictItemTicks[runIndex] + " ticks.";
                message += "\n\t for an overhead of " + linkItemOverhead;

                Console.Out.WriteLine(message);
                Console.Out.WriteLine();
            }
        }
Esempio n. 25
0
        void InitFanTable()
        {
            canvas        = new Canvas();
            canvas.Height = chart._contents.ActualHeight;
            canvas.Width  = chart._contents.ActualWidth;

            canvas.MouseEnter += Canvas_MouseEvent;
            canvas.MouseMove  += Canvas_MouseEvent;
            canvas.MouseLeave += Canvas_MouseEvent;

            Rectangle rect = new Rectangle();

            rect.Width   = chart._contents.ActualWidth;
            rect.Height  = chart._contents.ActualHeight;
            rect.Fill    = new SolidColorBrush(Colors.White);
            rect.Opacity = 0.01;
            canvas.Children.Add(rect);
            //Init Lines
            line                 = new LineGraph();
            line.Description     = "Fan";
            line.Stroke          = new SolidColorBrush(Colors.Black);
            line.StrokeThickness = 1;
            //Init TD points
            foreach (TD point in fanTable.points)
            {
                var btn = new Rectangle();
                btn.Width  = 15;
                btn.Height = 15;
                btn.Stroke = new SolidColorBrush(Colors.Black);
                btn.Fill   = new SolidColorBrush(Colors.White);

                btn.AddHandler(FrameworkElement.MouseDownEvent, new MouseButtonEventHandler(Btn_MouseDown));
                btn.AddHandler(FrameworkElement.MouseUpEvent, new MouseButtonEventHandler(Btn_MouseUp));
                btn.AddHandler(FrameworkElement.MouseMoveEvent, new MouseEventHandler(Btn_MouseMove));

                setButtonPos(btn, point);
                canvas.Children.Add(btn);
                Btns.Add(btn, point);
            }
            updateLine();
            Config config = SingleInstanceManager.Instance.cfg;

            //Init FanTable Settings
            setting_panel        = new StackPanel();
            setting_panel.Margin = new Thickness(2);
            //Fixed checkbox
            CheckBox isFixed = new CheckBox();

            isFixed.Click    += IsFixed_Click;
            isFixed.IsChecked = fanTable.isFixed;
            isFixed.Content   = "isFixed";
            TextBlock tooltip = new TextBlock();

            tooltip.Text    = "Set if the FanTable Auto Change Duty base on the circuit power";
            isFixed.ToolTip = tooltip;
            ToolTipService.SetShowDuration(isFixed, 10000);
            setting_panel.Children.Add(isFixed);
            //Cpu proportion
            TextBlock Desc = new TextBlock();

            Desc.Text = "Cpu";
            setting_panel.Children.Add(Desc);
            //TextBox
            TextBox prop = new TextBox();

            prop.Name       = "Cpu";
            prop.Text       = fanTable.CpuProportion.ToString();
            prop.LostFocus += Prop_LostFocus;
            tooltip         = new TextBlock();
            tooltip.Text    = "Set the proportion it takes when calc Fan Duty";
            prop.ToolTip    = tooltip;
            ToolTipService.SetShowDuration(prop, 10000);
            setting_panel.Children.Add(prop);
            if (config.GpuCount >= 1)
            {
                //Gpu_1 proportion
                Desc      = new TextBlock();
                Desc.Text = "Gpu 1";
                setting_panel.Children.Add(Desc);
                //TextBox
                prop            = new TextBox();
                prop.Name       = "Gpu_1";
                prop.Text       = fanTable.Gpu_1_Proportion.ToString();
                prop.LostFocus += Prop_LostFocus;
                tooltip         = new TextBlock();
                tooltip.Text    = "Set the proportion it takes when calc Fan Duty";
                prop.ToolTip    = tooltip;
                ToolTipService.SetShowDuration(prop, 10000);
                setting_panel.Children.Add(prop);
            }
            if (config.GpuCount == 2)
            {
                //Gpu_2 proportion
                Desc      = new TextBlock();
                Desc.Text = "Gpu 2";
                setting_panel.Children.Add(Desc);
                //TextBox
                prop            = new TextBox();
                prop.Name       = "Gpu_2";
                prop.Text       = fanTable.Gpu_2_Proportion.ToString();
                prop.LostFocus += Prop_LostFocus;
                tooltip         = new TextBlock();
                tooltip.Text    = "Set the proportion it takes when calc Fan Duty";
                prop.ToolTip    = tooltip;
                ToolTipService.SetShowDuration(prop, 5000);
                setting_panel.Children.Add(prop);
            }
            //Starting Duty
            Desc      = new TextBlock();
            Desc.Text = "Starting\nDuty";
            setting_panel.Children.Add(Desc);
            //TextBox
            prop            = new TextBox();
            prop.Name       = "StartingDuty";
            prop.Text       = fanTable.StartingDuty.ToString();
            prop.LostFocus += Prop_LostFocus;
            tooltip         = new TextBlock();
            tooltip.Text    = "Set the fan starting duty";
            prop.ToolTip    = tooltip;
            ToolTipService.SetShowDuration(prop, 10000);
            setting_panel.Children.Add(prop);
        }