Пример #1
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 virtual void addMultipleRatesContainingEntryWithNoCommonCurrency()
        {
            LinkedHashMap <CurrencyPair, double> rates = new LinkedHashMap <CurrencyPair, double>();

            rates.put(CurrencyPair.of(GBP, USD), 1.6);
            rates.put(CurrencyPair.of(EUR, USD), 1.4);
            rates.put(CurrencyPair.of(JPY, CAD), 0.01);     // Neither currency linked to one of the others

            assertThrows(() => FxMatrix.builder().addRates(rates).build(), typeof(System.InvalidOperationException));
        }
Пример #3
0
        static Dch客室利用台帳Dbm()
        {
            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_DB_NAME.ToLower(), TABLE_PROPERTY_NAME);
                map.put(DB_NAME_id.ToLower(), PROPERTY_NAME_id);
                map.put(DB_NAME_客室利用コード.ToLower(), PROPERTY_NAME_客室利用コード);
                map.put(DB_NAME_客室コード.ToLower(), PROPERTY_NAME_客室コード);
                map.put(DB_NAME_開始予定日時.ToLower(), PROPERTY_NAME_開始予定日時);
                map.put(DB_NAME_終了予定日時.ToLower(), PROPERTY_NAME_終了予定日時);
                map.put(DB_NAME_開始実績日時.ToLower(), PROPERTY_NAME_開始実績日時);
                map.put(DB_NAME_終了実績日時.ToLower(), PROPERTY_NAME_終了実績日時);
                map.put(DB_NAME_備考.ToLower(), PROPERTY_NAME_備考);
                _dbNamePropertyNameKeyToLowerMap = map;
            }

            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_PROPERTY_NAME.ToLower(), TABLE_DB_NAME);
                map.put(PROPERTY_NAME_id.ToLower(), DB_NAME_id);
                map.put(PROPERTY_NAME_客室利用コード.ToLower(), DB_NAME_客室利用コード);
                map.put(PROPERTY_NAME_客室コード.ToLower(), DB_NAME_客室コード);
                map.put(PROPERTY_NAME_開始予定日時.ToLower(), DB_NAME_開始予定日時);
                map.put(PROPERTY_NAME_終了予定日時.ToLower(), DB_NAME_終了予定日時);
                map.put(PROPERTY_NAME_開始実績日時.ToLower(), DB_NAME_開始実績日時);
                map.put(PROPERTY_NAME_終了実績日時.ToLower(), DB_NAME_終了実績日時);
                map.put(PROPERTY_NAME_備考.ToLower(), DB_NAME_備考);
                _propertyNameDbNameKeyToLowerMap = map;
            }
        }
Пример #4
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void loadParReader(java.net.URL specModelURL, String markingStrategy, String coveredRoot) throws org.maltparser.core.exception.MaltChainedException
        public virtual void loadParReader(URL specModelURL, string markingStrategy, string coveredRoot)
        {
            if (specModelURL == null)
            {
                throw new FeatureException("The URL to the feature specification model is missing or not well-formed. ");
            }
            FeatureSpecReader specReader = null;
            string            urlSuffix  = specModelURL.ToString().Substring(specModelURL.ToString().Length - 3);

            urlSuffix = char.ToUpper(urlSuffix[0]) + urlSuffix.Substring(1);
            try
            {
                Type clazz = Type.GetType("org.maltparser.core.feature.spec.reader." + urlSuffix + "Reader");
                specReader = (FeatureSpecReader)global::System.Activator.CreateInstance(clazz);
            }
            catch (InstantiationException e)
            {
                throw new FeatureException("Could not initialize the feature specification reader to read the specification file: " + specModelURL.ToString(), e);
            }
            catch (IllegalAccessException e)
            {
                throw new FeatureException("Could not initialize the feature specification reader to read the specification file: " + specModelURL.ToString(), e);
            }
            catch (ClassNotFoundException e)
            {
                throw new FeatureException("Could not find the feature specification reader to read the specification file: " + specModelURL.ToString(), e);
            }
            specReaderMap[specModelURL] = specReader;

            if (specReader is ParReader)
            {
                if (markingStrategy.Equals("head", StringComparison.OrdinalIgnoreCase) || markingStrategy.Equals("path", StringComparison.OrdinalIgnoreCase) || markingStrategy.Equals("head+path", StringComparison.OrdinalIgnoreCase))
                {
                    ((ParReader)specReader).Pplifted = true;
                }
                if (markingStrategy.Equals("path", StringComparison.OrdinalIgnoreCase) || markingStrategy.Equals("head+path", StringComparison.OrdinalIgnoreCase))
                {
                    ((ParReader)specReader).Pppath = true;
                }
                if (!coveredRoot.Equals("none", StringComparison.OrdinalIgnoreCase))
                {
                    ((ParReader)specReader).PpcoveredRoot = true;
                }
            }

            specModelKeyMap.put(specModelURL, currentSpecModelURL);
            specReader.load(specModelURL, this);
        }
Пример #5
0
 //[MethodImpl(MethodImplOptions.Synchronized)]
 public void put(K key, V value)
 {
     lock (this)
     {
         map.put(key, value);
     }
 }
        static Dch月締確定台帳Dbm()
        {
            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_DB_NAME.ToLower(), TABLE_PROPERTY_NAME);
                map.put(DB_NAME_対象年月.ToLower(), PROPERTY_NAME_対象年月);
                _dbNamePropertyNameKeyToLowerMap = map;
            }

            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_PROPERTY_NAME.ToLower(), TABLE_DB_NAME);
                map.put(PROPERTY_NAME_対象年月.ToLower(), DB_NAME_対象年月);
                _propertyNameDbNameKeyToLowerMap = map;
            }
        }
        static DmyプロシージャDbm()
        {
            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_DB_NAME.ToLower(), TABLE_PROPERTY_NAME);
                map.put(DB_NAME_dummy.ToLower(), PROPERTY_NAME_dummy);
                _dbNamePropertyNameKeyToLowerMap = map;
            }

            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_PROPERTY_NAME.ToLower(), TABLE_DB_NAME);
                map.put(PROPERTY_NAME_dummy.ToLower(), DB_NAME_dummy);
                _propertyNameDbNameKeyToLowerMap = map;
            }
        }
        public void xsetupOuterJoin_Dch客室利用台帳()
        {
            Dch客室利用台帳CQ          cq        = ConditionQueryDch客室利用台帳;
            Map <String, String> joinOnMap = new LinkedHashMap <String, String>();

            joinOnMap.put("客室利用台帳id", "id");
            registerOuterJoin(cq, joinOnMap);
        }
Пример #9
0
        public void xsetupOuterJoin_Mst従業員マスタ()
        {
            Mst従業員マスタCQ          cq        = ConditionQueryMst従業員マスタ;
            Map <String, String> joinOnMap = new LinkedHashMap <String, String>();

            joinOnMap.put("従業員コード", "従業員コード");
            registerOuterJoin(cq, joinOnMap);
        }
Пример #10
0
        public void xsetupOuterJoin_Kbn職位区分()
        {
            Kbn職位区分CQ            cq        = ConditionQueryKbn職位区分;
            Map <String, String> joinOnMap = new LinkedHashMap <String, String>();

            joinOnMap.put("職位コード", "職位コード");
            registerOuterJoin(cq, joinOnMap);
        }
        public virtual void addMultipleRates()
        {
            // Use linked map to force the order of evaluation
            // want to see that builder recovers when
            // encountering a currency pair for 2 unknown
            // currencies but which will appear later
            LinkedHashMap <CurrencyPair, double> rates = new LinkedHashMap <CurrencyPair, double>();

            rates.put(CurrencyPair.of(GBP, USD), 1.6);
            rates.put(CurrencyPair.of(EUR, USD), 1.4);
            rates.put(CurrencyPair.of(CHF, AUD), 1.2);     // Neither currency seen before
            rates.put(CurrencyPair.of(SEK, AUD), 0.16);    // AUD seen before but not added yet
            rates.put(CurrencyPair.of(JPY, CAD), 0.01);    // Neither currency seen before
            rates.put(CurrencyPair.of(EUR, CHF), 1.2);
            rates.put(CurrencyPair.of(JPY, USD), 0.0084);

            FxMatrix matrix = FxMatrix.builder().addRates(rates).build();

            assertThat(matrix.fxRate(GBP, USD)).isEqualTo(1.6);
            assertThat(matrix.fxRate(USD, GBP)).isEqualTo(1 / 1.6);
            assertThat(matrix.fxRate(EUR, USD)).isEqualTo(1.4);
            assertThat(matrix.fxRate(USD, EUR)).isEqualTo(1 / 1.4);
            assertThat(matrix.fxRate(EUR, GBP)).isEqualTo(1.4 / 1.6, TOL);
            assertThat(matrix.fxRate(GBP, EUR)).isEqualTo(1.6 / 1.4, TOL);
            assertThat(matrix.fxRate(EUR, CHF)).isEqualTo(1.2);
        }
Пример #12
0
        static Kbn客室利用区分Dbm()
        {
            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_DB_NAME.ToLower(), TABLE_PROPERTY_NAME);
                map.put(DB_NAME_客室利用コード.ToLower(), PROPERTY_NAME_客室利用コード);
                map.put(DB_NAME_客室利用名称.ToLower(), PROPERTY_NAME_客室利用名称);
                _dbNamePropertyNameKeyToLowerMap = map;
            }

            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_PROPERTY_NAME.ToLower(), TABLE_DB_NAME);
                map.put(PROPERTY_NAME_客室利用コード.ToLower(), DB_NAME_客室利用コード);
                map.put(PROPERTY_NAME_客室利用名称.ToLower(), DB_NAME_客室利用名称);
                _propertyNameDbNameKeyToLowerMap = map;
            }
        }
        static Mst権限マスタDbm()
        {
            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_DB_NAME.ToLower(), TABLE_PROPERTY_NAME);
                map.put(DB_NAME_職位コード.ToLower(), PROPERTY_NAME_職位コード);
                map.put(DB_NAME_画面コード.ToLower(), PROPERTY_NAME_画面コード);
                _dbNamePropertyNameKeyToLowerMap = map;
            }

            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_PROPERTY_NAME.ToLower(), TABLE_DB_NAME);
                map.put(PROPERTY_NAME_職位コード.ToLower(), DB_NAME_職位コード);
                map.put(PROPERTY_NAME_画面コード.ToLower(), DB_NAME_画面コード);
                _propertyNameDbNameKeyToLowerMap = map;
            }
        }
        /**
         * @param cb Condition-bean. (NotNull)
         * @param entity Entity. (NotNull)
         * @return The two-way SQL of query update. (NullAllowed: If the set of modified properties is empty, return null.)
         */
        protected String buildQueryUpdateTwoWaySql(ConditionBean cb, Entity entity)
        {
            Map <String, String> columnParameterMap = new LinkedHashMap <String, String>();
            DBMeta dbmeta = DBMetaInstanceHandler.FindDBMeta(entity.TableDbName);

            System.Collections.Generic.IDictionary <String, Object> modifiedPropertyNames = entity.ModifiedPropertyNames;
            if (modifiedPropertyNames.Count == 0)
            {
                return(null);
            }
            String currentPropertyName = null;

            foreach (String propertyName in modifiedPropertyNames.Keys)
            {
                currentPropertyName = propertyName;
                ColumnInfo   columnInfo = dbmeta.FindColumnInfo(propertyName);
                String       columnName = columnInfo.ColumnDbName;
                PropertyInfo getter     = columnInfo.FindProperty();
                Object       value      = getter.GetValue(entity, null);
                if (value != null)
                {
                    columnParameterMap.put(columnName, "/*entity." + propertyName + "*/null");
                }
                else
                {
                    columnParameterMap.put(columnName, "null");
                }
            }
            if (dbmeta.HasVersionNo)
            {
                ColumnInfo columnInfo = dbmeta.VersionNoColumnInfo;
                String     columnName = columnInfo.ColumnDbName;
                columnParameterMap.put(columnName, columnName + " + 1");
            }
            if (dbmeta.HasUpdateDate)
            {
                ColumnInfo   columnInfo = dbmeta.UpdateDateColumnInfo;
                PropertyInfo setter     = columnInfo.FindProperty();
                setter.SetValue(entity, DateTime.Now, null);
                String columnName = columnInfo.ColumnDbName;
                columnParameterMap.put(columnName, "/*entity." + columnInfo.PropertyName + "*/null");
            }
            return(cb.SqlClause.getClauseQueryUpdate(columnParameterMap));
        }
Пример #15
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void add(String subModelName, String featureSpec) throws org.maltparser.core.exception.MaltChainedException
        public virtual void add(string subModelName, string featureSpec)
        {
            if (ReferenceEquals(subModelName, null) || subModelName.Length < 1 || subModelName.ToUpper().Equals("MAIN"))
            {
                if (!subModelMap.containsKey("MAIN"))
                {
                    subModelMap.put("MAIN", new SpecificationSubModel("MAIN"));
                }
                subModelMap.get("MAIN").add(featureSpec);
            }
            else
            {
                if (!subModelMap.containsKey(subModelName.ToUpper()))
                {
                    subModelMap.put(subModelName.ToUpper(), new SpecificationSubModel(subModelName.ToUpper()));
                }
                subModelMap.get(subModelName.ToUpper()).add(featureSpec);
            }
        }
        public void AddParameterType(InternalProcedureParameterType parameterType)
        {
            String name = parameterType.ParameterName;

            parameterTypeMap.put(name.ToLower(), parameterType);
            if (parameterType.IsReturnType)
            {
                _returnType = parameterType.ParameterPropertyType;
            }
        }
Пример #17
0
        private void addNewRate(Currency ccy1, Currency ccy2, double rate)
        {
            Currency existing = currencies.containsKey(ccy1) ? ccy1 : ccy2;
            Currency other    = existing == ccy1 ? ccy2 : ccy1;

            double updatedRate = existing == ccy2 ? 1.0 / rate : rate;
            int    indexRef    = currencies.get(existing);
            int    indexOther  = currencies.size();

            currencies.put(other, indexOther);
            rates[indexOther][indexOther] = 1.0;

            for (int i = 0; i < indexOther; i++)
            {
                double convertedRate = updatedRate * rates[i][indexRef];
                rates[i][indexOther] = convertedRate;
                rates[indexOther][i] = 1.0 / convertedRate;
            }
        }
Пример #18
0
        static Dch宿泊利用台帳Dbm()
        {
            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_DB_NAME.ToLower(), TABLE_PROPERTY_NAME);
                map.put(DB_NAME_客室利用台帳id.ToLower(), PROPERTY_NAME_客室利用台帳id);
                map.put(DB_NAME_会員コード.ToLower(), PROPERTY_NAME_会員コード);
                map.put(DB_NAME_宿泊料金.ToLower(), PROPERTY_NAME_宿泊料金);
                _dbNamePropertyNameKeyToLowerMap = map;
            }

            {
                Map <String, String> map = new LinkedHashMap <String, String>();
                map.put(TABLE_PROPERTY_NAME.ToLower(), TABLE_DB_NAME);
                map.put(PROPERTY_NAME_客室利用台帳id.ToLower(), DB_NAME_客室利用台帳id);
                map.put(PROPERTY_NAME_会員コード.ToLower(), DB_NAME_会員コード);
                map.put(PROPERTY_NAME_宿泊料金.ToLower(), DB_NAME_宿泊料金);
                _propertyNameDbNameKeyToLowerMap = map;
            }
        }
        public virtual void addSimpleMultipleRates()
        {
            // Use linked to force the order of evaluation
            // want to see that builder recovers when
            // encountering a currency pair for 2 unknown
            // currencies but which will appear later
            LinkedHashMap <CurrencyPair, double> rates = new LinkedHashMap <CurrencyPair, double>();

            rates.put(CurrencyPair.of(GBP, USD), 1.6);
            rates.put(CurrencyPair.of(EUR, USD), 1.4);

            FxMatrix matrix = FxMatrix.builder().addRates(rates).build();

            assertThat(matrix.fxRate(GBP, USD)).isEqualTo(1.6);
            assertThat(matrix.fxRate(USD, GBP)).isEqualTo(1 / 1.6);
            assertThat(matrix.fxRate(EUR, USD)).isEqualTo(1.4);
            assertThat(matrix.fxRate(USD, EUR)).isEqualTo(1 / 1.4);
            assertThat(matrix.fxRate(EUR, GBP)).isEqualTo(1.4 / 1.6, TOL);
            assertThat(matrix.fxRate(GBP, EUR)).isEqualTo(1.6 / 1.4, TOL);
        }
Пример #20
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void parseParameters(String paramstring, java.util.LinkedHashMap<String, String> libOptions, String allowedLibOptionFlags) throws org.maltparser.core.exception.MaltChainedException
        public virtual void parseParameters(string paramstring, LinkedHashMap <string, string> libOptions, string allowedLibOptionFlags)
        {
            if (ReferenceEquals(paramstring, null))
            {
                return;
            }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String[] argv;
            string[] argv;
            try
            {
                argv = paramstring.Split("[_\\p{Blank}]", true);
            }
            catch (PatternSyntaxException e)
            {
                throw new LibException("Could not split the parameter string '" + paramstring + "'. ", e);
            }
            for (int i = 0; i < argv.Length - 1; i++)
            {
                if (argv[i][0] != '-')
                {
                    throw new LibException("The argument flag should start with the following character '-', not with " + argv[i][0]);
                }
                if (++i >= argv.Length)
                {
                    throw new LibException("The last argument does not have any value. ");
                }
                try
                {
                    int index = allowedLibOptionFlags.IndexOf(argv[i - 1][1]);
                    if (index != -1)
                    {
                        libOptions.put(Convert.ToString(argv[i - 1][1]), argv[i]);
                    }
                    else
                    {
                        throw new LibException("Unknown learner parameter: '" + argv[i - 1] + "' with value '" + argv[i] + "'. ");
                    }
                }
                catch (IndexOutOfRangeException e)
                {
                    throw new LibException("The learner parameter '" + argv[i - 1] + "' could not convert the string value '" + argv[i] + "' into a correct numeric value. ", e);
                }
                catch (FormatException e)
                {
                    throw new LibException("The learner parameter '" + argv[i - 1] + "' could not convert the string value '" + argv[i] + "' into a correct numeric value. ", e);
                }
                catch (NullReferenceException e)
                {
                    throw new LibException("The learner parameter '" + argv[i - 1] + "' could not convert the string value '" + argv[i] + "' into a correct numeric value. ", e);
                }
            }
        }
Пример #21
0
        /** Return map sorted by key */
        public LinkedHashMap <K, V> sort <K, V>(Map <K, V> data)
        {
            LinkedHashMap <K, V> dup  = new LinkedHashMap <K, V>();
            IList <K>            keys = new List <K>();

            keys.addAll(data.keySet());
            Collections.sort(keys);
            foreach (K k in keys)
            {
                dup.put(k, data.get(k));
            }
            return(dup);
        }
        /// <summary>
        /// Splits the array according to the curve order.
        /// <para>
        /// The input array must be of the same size as the total number of parameters.
        /// The result consists of a map of arrays, where each array is the appropriate
        /// section of the input array as defined by the curve order.
        ///
        /// </para>
        /// </summary>
        /// <param name="array">  the array to split </param>
        /// <returns> a map splitting the array by curve name </returns>
        public IDictionary <CurveName, DoubleArray> splitValues(DoubleArray array)
        {
            LinkedHashMap <CurveName, DoubleArray> result = new LinkedHashMap <CurveName, DoubleArray>();
            int start = 0;

            foreach (CurveParameterSize paramSizes in order)
            {
                int size = paramSizes.ParameterCount;
                result.put(paramSizes.Name, array.subArray(start, start + size));
                start += size;
            }
            return(result);
        }
Пример #23
0
	internal virtual void createDictionary()
	{
		for (int i = 0;i < noOfSentences;i++)
		{
			double score = 0;
			for (int j = 0;j < noOfSentences;j++)
			{
				score += intersectionMatrix[i][j];
			}
			dictionary.put(sentences.get(i), score);
			((Sentence)sentences.get(i)).score = score;
		}
	}
Пример #24
0
 public virtual Builder ParameterizedWith(string name, TypeReference.Bound bound)
 {
     if (TypeParametersConflict == null)
     {
         TypeParametersConflict = new LinkedHashMap <string, TypeReference.Bound>();
     }
     else if (TypeParametersConflict.containsKey(name))
     {
         throw new System.ArgumentException(name + " defined twice");
     }
     TypeParametersConflict.put(name, bound);
     return(this);
 }
        public override Iterator <Map.Entry <IteratorIndex, SimpleView> > getIterator()
        {
            LinkedHashMap <IteratorIndex, SimpleView> map
                = new LinkedHashMap <IteratorIndex, SimpleView>();

            for (int i = 0; i < _attrList.size(); i++)
            {
                SimpleView view = _attrList.get(i);

                map.put(IteratorIndex.create(view.getNodeName()), view);
            }

            return(map.entrySet().iterator());
        }
Пример #26
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void calculateIndices(org.maltparser.core.syntaxgraph.PhraseStructure phraseStructure) throws org.maltparser.core.exception.MaltChainedException
        private void calculateIndices(PhraseStructure phraseStructure)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.SortedMap<int,int> heights = new java.util.TreeMap<int,int>();
            SortedDictionary <int, int> heights = new SortedDictionary <int, int>();

            foreach (int index in phraseStructure.NonTerminalIndices)
            {
                heights[index] = ((NonTerminalNode)phraseStructure.getNonTerminalNode(index)).Height;
            }

            bool done = false;
            int  h    = 1;
            int  ntid = START_ID_OF_NONTERMINALS;

            nonTerminalIndexMap.clear();
            while (!done)
            {
                done = true;
                foreach (int index in phraseStructure.NonTerminalIndices)
                {
                    if (heights[index] == h)
                    {
                        NonTerminalNode nt = (NonTerminalNode)phraseStructure.getNonTerminalNode(index);
                        nonTerminalIndexMap.put(nt.Index, ntid++);
                        //					nonTerminalIndexMap.put(nt.getIndex(), nt.getIndex()+START_ID_OF_NONTERMINALS-1);
                        done = false;
                    }
                }
                h++;
            }

            //		boolean done = false;
            //		int h = 1;
            ////		int ntid = START_ID_OF_NONTERMINALS;
            ////		nonTerminalIndexMap.clear();
            //		while (!done) {
            //			done = true;
            //			for (int index : phraseStructure.getNonTerminalIndices()) {
            //				if (heights.get(index) == h) {
            //					NonTerminalNode nt = (NonTerminalNode)phraseStructure.getNonTerminalNode(index);
            ////					nonTerminalIndexMap.put(nt.getIndex(), ntid++);
            //					nonTerminalIndexMap.put(nt.getIndex(), nt.getIndex()+START_ID_OF_NONTERMINALS-1);
            //					done = false;
            //				}
            //			}
            //			h++;
            //		}
        }
Пример #27
0
        /// <summary>
        /// Reloads the internal SPI list from the given <seealso cref="ClassLoader"/>.
        /// Changes to the service list are visible after the method ends, all
        /// iterators (e.g., from <seealso cref="#availableServices()"/>,...) stay consistent.
        ///
        /// <para><b>NOTE:</b> Only new service providers are added, existing ones are
        /// never removed or replaced.
        ///
        /// </para>
        /// <para><em>This method is expensive and should only be called for discovery
        /// of new service providers on the given classpath/classloader!</em>
        /// </para>
        /// </summary>
        public void reload(ClassLoader classloader)
        {
            lock (this)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.LinkedHashMap<String,Class> services = new java.util.LinkedHashMap<>(this.services);
                LinkedHashMap <string, Type> services = new LinkedHashMap <string, Type>(this.services);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.apache.lucene.util.SPIClassIterator<S> loader = org.apache.lucene.util.SPIClassIterator.get(clazz, classloader);
                SPIClassIterator <S> loader = SPIClassIterator.get(clazz, classloader);
                while (loader.hasNext())
                {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final Class service = loader.next();
                    Type service = loader.next();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String clazzName = service.getSimpleName();
                    string clazzName = service.SimpleName;
                    string name      = null;
                    foreach (string suffix in suffixes)
                    {
                        if (clazzName.EndsWith(suffix, StringComparison.Ordinal))
                        {
                            name = clazzName.Substring(0, clazzName.Length - suffix.Length).ToLower(Locale.ROOT);
                            break;
                        }
                    }
                    if (name == null)
                    {
                        throw new ServiceConfigurationError("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
                    //
                    // TODO: 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.put(name, service);
                    }
                }
                this.services = Collections.unmodifiableMap(services);
            }
        }
Пример #28
0
        public virtual void addTexture(IRenderingEngine re, Texture texture)
        {
            int?    key             = getKey(texture.Addr, texture.ClutAddr, texture.ClutStart, texture.ClutMode);
            Texture previousTexture = cache.get(key);

            if (previousTexture != null)
            {
                previousTexture.deleteTexture(re);
//JAVA TO C# CONVERTER TODO TASK: There is no .NET LinkedList equivalent to the Java 'remove' method:
                vramTextures.remove(previousTexture);
            }
            else
            {
                // Check if the cache is not growing too large
                if (cache.size() >= cacheMaxSize)
                {
                    // Remove the LRU cache entry
                    IEnumerator <KeyValuePair <int, Texture> > it = cache.entrySet().GetEnumerator();
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                    if (it.hasNext())
                    {
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                        KeyValuePair <int, Texture> entry = it.next();
                        Texture lruTexture = entry.Value;
                        lruTexture.deleteTexture(re);
//JAVA TO C# CONVERTER TODO TASK: There is no .NET LinkedList equivalent to the Java 'remove' method:
                        vramTextures.remove(lruTexture);
//JAVA TO C# CONVERTER TODO TASK: .NET enumerators are read-only:
                        it.remove();

                        statistics.entriesRemoved++;
                    }
                }
            }

            cache.put(key, texture);
            if (isVramTexture(texture))
            {
                vramTextures.AddLast(texture);
            }

            if (cache.size() > statistics.maxSizeUsed)
            {
                statistics.maxSizeUsed = cache.size();
            }
        }
Пример #29
0
        private static ICollection <Path> HitsToPaths(ICollection <Hit> depthHits, Node start, Node end, bool stopAsap, int maxResultCount)
        {
            LinkedHashMap <string, Path> paths = new LinkedHashMap <string, Path>();

            foreach (Hit hit in depthHits)
            {
                foreach (Path path in HitToPaths(hit, start, end, stopAsap))
                {
                    paths.put(path.ToString(), path);
                    if (paths.size() >= maxResultCount)
                    {
                        break;
                    }
                }
            }
            return(paths.values());
        }
Пример #30
0
        // END-Factor
        //

        /**
         * Iterate over all the possible value assignments for the Random Variables
         * comprising this ProbabilityTable.
         *
         * @param pti
         *            the ProbabilityTable Iterator to iterate.
         */

        public void iterateOverTable(Factor.Iterator pti)
        {
            Map <RandomVariable, Object> possibleWorld = new LinkedHashMap <RandomVariable, Object>();
            MixedRadixNumber             mrn           = new MixedRadixNumber(0, radices);

            do
            {
                foreach (RVInfo rvInfo in randomVarInfo.Values)
                {
                    possibleWorld.put(rvInfo.getVariable(), rvInfo
                                      .getDomainValueAt(mrn.getCurrentNumeralValue(rvInfo
                                                                                   .
                                                                                   getRadixIdx
                                                                                       ())));
                }
                pti.iterate(possibleWorld, values[mrn.intValue()]);
            } while (mrn.increment());
        }
Пример #31
0
        // END-Factor
        //

        /**
         * Iterate over all the possible value assignments for the Random Variables
         * comprising this ProbabilityTable.
         * 
         * @param pti
         *            the ProbabilityTable Iterator to iterate.
         */

        public void iterateOverTable(Factor.Iterator pti)
        {
            Map<RandomVariable, Object> possibleWorld = new LinkedHashMap<RandomVariable, Object>();
            MixedRadixNumber mrn = new MixedRadixNumber(0, radices);
            do
            {
                foreach (RVInfo rvInfo in randomVarInfo.Values)
                {
                    possibleWorld.put(rvInfo.getVariable(), rvInfo
                                                                .getDomainValueAt(mrn.getCurrentNumeralValue(rvInfo
                                                                                                                 .
                                                                                                                 getRadixIdx
                                                                                                                 ())));
                }
                pti.iterate(possibleWorld, values[mrn.intValue()]);

            } while (mrn.increment());
        }
Пример #32
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());
            }
        }
Пример #33
0
        public ProbabilityTable divideBy(ProbabilityTable divisor)
        {
            if (!randomVarInfo.keySet().containsAll(divisor.randomVarInfo.keySet()))
            {
                throw new IllegalArgumentException(
                    "Divisor must be a subset of the dividend.");
            }

            ProbabilityTable quotient = new ProbabilityTable(new List<RandomVariable>(randomVarInfo.Keys));

            if (1 == divisor.getValues().Length)
            {
                double d = divisor.getValues()[0];
                for (int i = 0; i < quotient.getValues().Length; i++)
                {
                    if (0 == d)
                    {
                        quotient.getValues()[i] = 0;
                    }
                    else
                    {
                        quotient.getValues()[i] = getValues()[i]/d;
                    }
                }
            }
            else
            {
                Set<RandomVariable> dividendDivisorDiff = SetOps
                    .difference(new List<RVInfo>(randomVarInfo.keySet()),
                                new List<RVInfo>(randomVarInfo.keySet()));
                Map<RandomVariable, RVInfo> tdiff = null;
                MixedRadixNumber tdMRN = null;
                if (dividendDivisorDiff.size() > 0)
                {
                    tdiff = new LinkedHashMap<RandomVariable, RVInfo>();
                    foreach (RandomVariable rv in dividendDivisorDiff)
                    {
                        tdiff.put(rv, new RVInfo(rv));
                    }
                    tdMRN = new MixedRadixNumber(0, createRadixs(tdiff));
                }
                Map<RandomVariable, RVInfo> diff = tdiff;
                MixedRadixNumber dMRN = tdMRN;
                int[] qRVs = new int[quotient.radices.Length];
                MixedRadixNumber qMRN = new MixedRadixNumber(0,
                                                             quotient.radices);
                //ProbabilityTable.Iterator divisorIterator = new ProbabilityTable.Iterator() {
                //    public void iterate(Map<RandomVariable, Object> possibleWorld,
                //            double probability) {
                //        foreach (RandomVariable rv in possibleWorld.keySet()) {
                //            RVInfo rvInfo = quotient.randomVarInfo.get(rv);
                //            qRVs[rvInfo.getRadixIdx()] = rvInfo
                //                    .getIdxForDomain(possibleWorld.get(rv));
                //        }
                //        if (null != diff) {
                //            // Start from 0 off the diff
                //            dMRN.setCurrentValueFor(new int[diff.size()]);
                //            do {
                //                for (RandomVariable rv : diff.keySet()) {
                //                    RVInfo drvInfo = diff.get(rv);
                //                    RVInfo qrvInfo = quotient.randomVarInfo.get(rv);
                //                    qRVs[qrvInfo.getRadixIdx()] = dMRN
                //                            .getCurrentNumeralValue(drvInfo
                //                                    .getRadixIdx());
                //                }
                //                updateQuotient(probability);
                //            } while (dMRN.increment());
                //        } else {
                //            updateQuotient(probability);
                //        }
                //    }

                //    //
                //
                //private void updateQuotient(double probability) {
                //    int offset = (int) qMRN.getCurrentValueFor(qRVs);
                //    if (0 == probability) {
                //        quotient.getValues()[offset] = 0;
                //    } else {
                //        quotient.getValues()[offset] += getValues()[offset]
                //                / probability;
                //    }
                //}
                ////// 	};

                //	divisor.iterateOverTable(divisorIterator);
                // TODO
            }

            return quotient;
        }
Пример #34
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();
        }