Beispiel #1
0
        /// <summary>
        /// Implementation of the linear programming model for the block using the simple gap cost model
        /// </summary>
        /// <param name="weightFunction">Algorith-specific weight function</param>
        /// <param name="blockRow">First index of the block within the grid</param>
        /// <param name="blockCol">Second index of the block within the grid</param>
        /// <param name="lastRow">Last valid row index within the block; rows beyond this index stay uninitialized</param>
        /// <param name="lastCol">Last valid column index within the block; columns beyond this index stay uninitialized</param>
        protected void ComputeBlockSimple(WeightFunction weightFunction, int blockRow, int blockCol, int lastRow, int lastCol)
        {
            int[] foldC = new int[2 * gridStride + 1];

            PopulateFold(cachedRowsC, cachedColsC, foldC, blockRow, blockCol, lastRow, lastCol);

            long startPositionI = Math.BigMul(blockRow, gridStride) - 1;
            long startPositionJ = Math.BigMul(blockCol, gridStride) - 1;

            for (int i = 1; i <= lastRow; i++)
            {
                long globalI = startPositionI + i;

                for (int j = 1, f = gridStride - i, Cij = foldC[f++]; j <= lastCol; j++, f++)
                {
                    long globalJ = startPositionJ + j;

                    // I
                    //int Iij = fold[f - 1] + gapOpenCost;
                    int Iij = Cij + gapOpenCost;

                    // D
                    int Dij = foldC[f + 1] + gapOpenCost;

                    // C
                    Cij = foldC[f] + similarityMatrix[sequenceI[globalI], sequenceJ[globalJ]];

                    Cij = weightFunction(i, j, Iij, Dij, Cij);

                    foldC[f] = Cij;
                }
            }

            WritebackFold(cachedRowsC, cachedColsC, foldC, blockRow, blockCol, lastRow, lastCol);
        }
Beispiel #2
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jo     = JObject.Load(reader);
            var filter = jo.Property("filter")?.Value.ToObject <QueryContainer>(serializer);
            var weight = jo.Property("weight")?.Value.ToObject <double?>();

            ;
            IScoreFunction function = null;

            foreach (var prop in jo.Properties())
            {
                switch (prop.Name)
                {
                case "exp":
                case "gauss":
                case "linear":
                    var properties = prop.Value.Value <JObject>().Properties().ToList();
                    var fieldProp  = properties.First(p => p.Name != "multi_value_mode");
                    var field      = fieldProp.Name;
                    var f          = ReadDecayFunction(prop.Name, fieldProp.Value.Value <JObject>(), serializer);
                    f.Field = field;
                    var mv = properties.FirstOrDefault(p => p.Name == "multi_value_mode")?.Value;
                    if (mv != null)
                    {
                        f.MultiValueMode = serializer.Deserialize <MultiValueMode>(mv.CreateReader());
                    }
                    function = f;

                    break;

                case "random_score":
                    function = FromJson.ReadAs <RandomScoreFunction>(prop.Value.Value <JObject>().CreateReader(), serializer);
                    break;

                case "field_value_factor":
                    function = FromJson.ReadAs <FieldValueFactorFunction>(prop.Value.Value <JObject>().CreateReader(), serializer);
                    break;

                case "script_score":
                    function = FromJson.ReadAs <ScriptScoreFunction>(prop.Value.Value <JObject>().CreateReader(), serializer);
                    break;
                }
            }
            if (function == null && weight.HasValue)
            {
                function = new WeightFunction {
                    Weight = weight
                }
            }
            ;
            else if (function == null)
            {
                return(null);                                   //throw new Exception("error deserializing function score function");
            }
            function.Weight = weight;
            function.Filter = filter;
            return(function);
        }
Beispiel #3
0
 /// <summary>
 /// Constructs a RDF calculator that calculates a digitized RDF function.
 /// </summary>
 /// <param name="startCutoff">radial length in Ångstrom at which the RDF starts</param>
 /// <param name="cutoff">radial length in Ångstrom at which the RDF stops</param>
 /// <param name="resolution">width of the bins</param>
 /// <param name="peakWidth">width of the gaussian applied to the peaks in Ångstrom</param>
 /// <param name="weightFunction">the weight function. If null, then an unweighted RDF is calculated</param>
 public RDFCalculator(double startCutoff, double cutoff, double resolution, double peakWidth,
                      WeightFunction weightFunction)
 {
     this.startCutoff    = startCutoff;
     this.cutoff         = cutoff;
     this.resolution     = resolution;
     this.peakWidth      = peakWidth;
     this.weightFunction = weightFunction;
 }
 /// <summary>
 /// Создание квадратурной формулы
 /// </summary>
 /// <param name="n">Количество точек</param>
 /// <param name="a">Левая граница</param>
 /// <param name="b">Правая граница</param>
 /// <param name="function">Функция</param>
 /// <param name="weights">Функция, возвращающая k-ый момент весовой функции</param>
 /// <param name="method">Ньютон-Котес (равноотстоящие узлы) или Гаусс</param>
 /// <param name="type">Простая либо составная квадратурная формула</param>
 /// <param name="parts">Количество участков разбиения составной квадратурной формулы</param>
 public QuadratureFormulas(int n, double a, double b, Function function, WeightFunction weights, QFMethod method, QFType type, int parts = 10)
 {
     this.left     = a;
     this.right    = b;
     this.weights  = weights;
     this.N        = n;
     this.function = function;
     this.type     = type;
     this.method   = method;
     this.parts    = parts;
     SetPolynomialSolver((x, left, right) => Poly.RootsFinding(x, left, right, 1000, 1E-15));
     SetSystemSolver(Infrastructure.GaussSolve);
 }
    /// Get a random item from the list, using a weighting function, Items with 0 or less weight are ignored.
    /// Random is sampled once. If random is null, UnityEngine.Random will be used
    /// WeightFunction will be called twice on each item
    public static T Random <T>(this IList <T> @this, WeightFunction <T> weightFunction, System.Random random = null)
    {
        if (@this.Count == 0)
        {
            return(default(T));
        }

        float maxValue = 0f;

        for (int i = 0; i < @this.Count; i++)
        {
            var val = @this[i];
            maxValue += Mathf.Max(0, weightFunction(val));
        }

        if (maxValue <= 0)
        {
            return(default(T));
        }

        T     output       = default(T);
        float currentValue = 0f;

        float randomVal = (random != null ? (float)random.NextDouble():UnityEngine.Random.value) * (maxValue - Mathf.Epsilon) + Mathf.Epsilon;

        for (int i = 0; i < @this.Count; i++)
        {
            var current = @this[i];
            var weight  = weightFunction(current);
            if (weight <= 0f)
            {
                continue;
            }

            output        = current;
            currentValue += weight;
            if (randomVal <= currentValue)
            {
                break;
            }
        }

        return(output);
    }
Beispiel #6
0
        /// <summary>
        /// 构建得分函数
        /// </summary>
        /// <param name="sentence">输入短语</param>
        /// <param name="ranks">排序规则</param>
        /// <returns>返回一个或多个得分函数定义</returns>
        private static IEnumerable <IScoreFunction> BuildScoreFunctions(string sentence, Dictionary <string, int> ranks)
        {
            var scoreFunctions = new List <IScoreFunction>();

            foreach (var rank in ranks)
            {
                var scoreFunction = new WeightFunction()
                {
                    Filter = new MatchQuery()
                    {
                        Field = rank.Key, Query = sentence
                    },
                    Weight = rank.Value
                };

                scoreFunctions.Add(scoreFunction);
            }
            return(scoreFunctions);
        }
        /// <summary>
        /// Implementation of the linear programming model for the block using the affine gap cost model
        /// </summary>
        /// <param name="weightFunction">Algorith-specific weight function</param>
        /// <param name="blockRow">First index of the block within the grid</param>
        /// <param name="blockCol">Second index of the block within the grid</param>
        /// <param name="lastRow">Last valid row index within the block; rows beyond this index stay uninitialized</param>
        /// <param name="lastCol">Last valid column index within the block; columns beyond this index stay uninitialized</param>
        protected void ComputeBlockAffine(WeightFunction weightFunction, int blockRow, int blockCol, int lastRow, int lastCol)
        {
            int[] foldC = new int[2 * gridStride + 1];
            int[] foldD = new int[2 * gridStride + 1];
            int[] foldI = new int[2 * gridStride + 1];

            PopulateFold(cachedRowsC, cachedColsC, foldC, blockRow, blockCol, lastRow, lastCol);
            PopulateFold(cachedRowsD, cachedColsD, foldD, blockRow, blockCol, lastRow, lastCol);
            PopulateFold(cachedRowsI, cachedColsI, foldI, blockRow, blockCol, lastRow, lastCol);

            long startPositionI = Helper.BigMul(blockRow, gridStride) - 1;
            long startPositionJ = Helper.BigMul(blockCol, gridStride) - 1;

            for (int i = 1; i <= lastRow; i++)
            {
                long globalI = startPositionI + i;

                for (int j = 1, f = gridStride - i, Cij = foldC[f++]; j <= lastCol; j++, f++)
                {
                    long globalJ = startPositionJ + j;

                    // I
                    int Iij = Math.Max(foldI[f - 1] + gapExtensionCost, Cij + gapOpenCost);

                    // D
                    int Dij = Math.Max(foldD[f + 1] + gapExtensionCost, foldC[f + 1] + gapOpenCost);

                    // C
                    Cij = foldC[f] + similarityMatrix[sequenceI[globalI], sequenceJ[globalJ]];

                    Cij = weightFunction(i, j, Iij, Dij, Cij);

                    foldC[f] = Cij;
                    foldD[f] = Dij;
                    foldI[f] = Iij;
                }
            }

            WritebackFold(cachedRowsC, cachedColsC, foldC, blockRow, blockCol, lastRow, lastCol);
            WritebackFold(cachedRowsD, cachedColsD, foldD, blockRow, blockCol, lastRow, lastCol);
            WritebackFold(cachedRowsI, cachedColsI, foldI, blockRow, blockCol, lastRow, lastCol);
        }
        /// Chooses a thing from an IEnumerable (Array, List) using weighted randomness
        public static T Choose <T>(IEnumerable <T> spawnOptions, WeightFunction <T> WeightOf, System.Random systemRandom = null)
        {
            float weightSum = 0;

            foreach (T t in spawnOptions)
            {
                weightSum += WeightOf(t);
            }

            if (weightSum == 0)
            {
                return(default(T));
            }

            float choice;

            if (systemRandom != null)
            {
                choice = (float)systemRandom.NextDouble() * weightSum;
            }
            else
            {
                choice = Random.Range(0f, weightSum);
            }
            foreach (T t in spawnOptions)
            {
                choice -= WeightOf(t);
                if (choice <= 0)
                {
                    return(t);
                }
            }

            // Safety fallback, just return first element
            IEnumerator <T> enumerator = spawnOptions.GetEnumerator();

            enumerator.MoveNext();
            return(enumerator.Current);
        }
        void Awake()
        {
            agentState = GetComponent <CharacterState>();
            enemyState = agentState.enemyState;

            agentNavigationHelper = agentState.gameObject.GetComponent <Navigation>();
            enemyNavigationHelper = enemyState.gameObject.GetComponent <Navigation>();

            layerMask            = LayerMask.GetMask("Cover", "Walls");
            wallsLayerMask       = LayerMask.GetMask("Walls");
            healthPacksLayerMask = LayerMask.GetMask("HealthPacks");
            coverLayer           = LayerMask.NameToLayer("Cover");
            wallsLayer           = LayerMask.NameToLayer("Walls");

            // default waypoint processor
            weightFunction = wp =>
            {
                float weight = 0.0f;
                if (wp.isBehindWall)
                {
                    weight = 0.45f;
                }
                else if (wp.isBehindCover)
                {
                    if (wp.isInCover)
                    {
                        weight = 1.0f;
                    }
                    else
                    {
                        weight = 0.66f;
                    }
                }
                return(weight);
            };

            waypoints = GenerateWaypoints();
            CheckWaypointsReachability();
        }
        /// <summary>
        /// Implementation of the linear programming model for the block using the affine gap cost model
        /// </summary>
        /// <param name="weightFunction">Algorith-specific weight function</param>
        /// <param name="blockRow">First index of the block within the grid</param>
        /// <param name="blockCol">Second index of the block within the grid</param>
        /// <param name="lastRow">Last valid row index within the block; rows beyond this index stay uninitialized</param>
        /// <param name="lastCol">Last valid column index within the block; columns beyond this index stay uninitialized</param>
        protected void ComputeBlockAffine(WeightFunction weightFunction, int blockRow, int blockCol, int lastRow, int lastCol)
        {
            int[] foldC = new int[2 * gridStride + 1];
            int[] foldD = new int[2 * gridStride + 1];
            int[] foldI = new int[2 * gridStride + 1];

            PopulateFold(cachedRowsC, cachedColsC, foldC, blockRow, blockCol, lastRow, lastCol);
            PopulateFold(cachedRowsD, cachedColsD, foldD, blockRow, blockCol, lastRow, lastCol);
            PopulateFold(cachedRowsI, cachedColsI, foldI, blockRow, blockCol, lastRow, lastCol);

            long startPositionI = Helper.BigMul(blockRow, gridStride) - 1;
            long startPositionJ = Helper.BigMul(blockCol, gridStride) - 1;

            for (int i = 1; i <= lastRow; i++)
            {
                long globalI = startPositionI + i;

                for (int j = 1, f = gridStride - i, Cij = foldC[f++]; j <= lastCol; j++, f++)
                {
                    long globalJ = startPositionJ + j;

                    // I
                    int Iij = Math.Max(foldI[f - 1] + gapExtensionCost, Cij + gapOpenCost);

                    // D
                    int Dij = Math.Max(foldD[f + 1] + gapExtensionCost, foldC[f + 1] + gapOpenCost);

                    // C
                    Cij = foldC[f] + similarityMatrix[sequenceI[globalI], sequenceJ[globalJ]];

                    Cij = weightFunction(i, j, Iij, Dij, Cij);

                    foldC[f] = Cij;
                    foldD[f] = Dij;
                    foldI[f] = Iij;
                }
            }

            WritebackFold(cachedRowsC, cachedColsC, foldC, blockRow, blockCol, lastRow, lastCol);
            WritebackFold(cachedRowsD, cachedColsD, foldD, blockRow, blockCol, lastRow, lastCol);
            WritebackFold(cachedRowsI, cachedColsI, foldI, blockRow, blockCol, lastRow, lastCol);
        }
Beispiel #11
0
 public Modifier(WeightFunction function)
 {
     this.function = function;
 }
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var jo = JObject.Load(reader);
			QueryContainer filter = jo.Property("filter")?.Value.ToObject<QueryContainer>(serializer);
			double? weight = jo.Property("weight")?.Value.ToObject<double?>(); ;
			IScoreFunction function = null;
			foreach (var prop in jo.Properties())
			{
				switch (prop.Name)
				{
					case "exp":
					case "gauss":
					case "linear":
						var properties = prop.Value.Value<JObject>().Properties().ToList();
						var fieldProp = properties.First(p => p.Name != "multi_value_mode");
						var field = fieldProp.Name;
						var f = this.ReadDecayFunction(prop.Name, fieldProp.Value.Value<JObject>(), serializer);
						f.Field = field;
						var mv = properties.FirstOrDefault(p => p.Name == "multi_value_mode")?.Value;
						if (mv != null)
							f.MultiValueMode = serializer.Deserialize<MultiValueMode>(mv.CreateReader());
						function = f;

						break;
					case "random_score":
						function = FromJson.ReadAs<RandomScoreFunction>(prop.Value.Value<JObject>().CreateReader(), null, null, serializer);
						break;
					case "field_value_factor":
						function = FromJson.ReadAs<FieldValueFactorFunction>(prop.Value.Value<JObject>().CreateReader(), null, null, serializer);
						break;
					case "script_score":
						function = FromJson.ReadAs<ScriptScoreFunction>(prop.Value.Value<JObject>().CreateReader(), null, null, serializer);
						break;
				}
			}
			if (function == null && weight.HasValue) function = new WeightFunction { Weight = weight };
			else if (function == null) return null; //throw new Exception("error deserializing function score function");
			function.Weight = weight;
			function.Filter = filter;
			return function;
		}
 /// <summary>
 /// Forward pass for the block.
 /// </summary>
 /// <param name="weightFunction"></param>
 /// <param name="blockRow"></param>
 /// <param name="blockCol"></param>
 /// <param name="lastRow"></param>
 /// <param name="lastCol"></param>
 protected override void ComputeBlock(WeightFunction weightFunction, int blockRow, int blockCol, int lastRow, int lastCol)
 {
     ComputeBlockSimple(weightFunction, blockRow, blockCol, lastRow, lastCol);
 }
Beispiel #14
0
 /// <summary>
 /// Forward pass for the block.
 /// </summary>
 /// <param name="weightFunction"></param>
 /// <param name="blockRow"></param>
 /// <param name="blockCol"></param>
 /// <param name="lastRow"></param>
 /// <param name="lastCol"></param>
 protected override void ComputeBlock(WeightFunction weightFunction, int blockRow, int blockCol, int lastRow, int lastCol)
 {
     ComputeBlockSimple(weightFunction, blockRow, blockCol, lastRow, lastCol);
 }
 /// <summary>
 /// Forward pass for the block.
 /// Assumes the blocks to the top and right have already been processed.
 /// </summary>
 /// <param name="weightFunction"></param>
 /// <param name="blockRow">First index of the block within the grid</param>
 /// <param name="blockCol">Second index of the block within the grid</param>
 /// <param name="lastRow">Last valid row index within the block; rows beyond this index stay uninitialized</param>
 /// <param name="lastCol">Last valid column index within the block; columns beyond this index stay uninitialized</param>
 protected abstract void ComputeBlock(WeightFunction weightFunction, int blockRow, int blockCol, int lastRow, int lastCol);
Beispiel #16
0
        public IScoreFunction Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
        {
            QueryContainer filter   = null;
            double?        weight   = null;
            IScoreFunction function = null;

            var count = 0;

            while (reader.ReadIsInObject(ref count))
            {
                var propertyName = reader.ReadPropertyNameSegmentRaw();
                if (AutomataDictionary.TryGetValue(propertyName, out var value))
                {
                    switch (value)
                    {
                    case 0:
                        var formatter = formatterResolver.GetFormatter <QueryContainer>();
                        filter = formatter.Deserialize(ref reader, formatterResolver);
                        break;

                    case 1:
                        weight = reader.ReadDouble();
                        break;

                    case 2:
                        var            innerCount     = 0;
                        MultiValueMode?multiValueMode = null;
                        IDecayFunction decayFunction  = null;
                        while (reader.ReadIsInObject(ref innerCount))
                        {
                            var functionPropertyName = reader.ReadPropertyName();
                            if (functionPropertyName == "multi_value_mode")
                            {
                                multiValueMode = formatterResolver.GetFormatter <MultiValueMode>()
                                                 .Deserialize(ref reader, formatterResolver);
                            }
                            else
                            {
                                var name = propertyName.Utf8String();
                                decayFunction       = ReadDecayFunction(ref reader, name, formatterResolver);
                                decayFunction.Field = functionPropertyName;
                            }
                        }

                        if (decayFunction != null)
                        {
                            decayFunction.MultiValueMode = multiValueMode;
                            function = decayFunction;
                        }
                        break;

                    case 3:
                        var randomScoreFormatter = formatterResolver.GetFormatter <RandomScoreFunction>();
                        function = randomScoreFormatter.Deserialize(ref reader, formatterResolver);
                        break;

                    case 4:
                        var fieldValueFormatter = formatterResolver.GetFormatter <FieldValueFactorFunction>();
                        function = fieldValueFormatter.Deserialize(ref reader, formatterResolver);
                        break;

                    case 5:
                        var scriptFormatter = formatterResolver.GetFormatter <ScriptScoreFunction>();
                        function = scriptFormatter.Deserialize(ref reader, formatterResolver);
                        break;
                    }
                }
            }

            if (function == null)
            {
                if (weight.HasValue)
                {
                    function = new WeightFunction();
                }
                else
                {
                    return(null);
                }
            }

            function.Weight = weight;
            function.Filter = filter;
            return(function);
        }
Beispiel #17
0
 public CSG weighted(WeightFunction f)
 {
     return(new Modifier(f).modified(this));
 }
Beispiel #18
0
 /// <summary>Initializes a new instance of the <see cref="Algorithm"/> class.
 /// </summary>
 /// <param name="gaussHermiteIntegrator">The <see cref="GaussHermiteIntegrator"/> object which serves as factory for the current object.</param>
 internal Algorithm(GaussHermiteIntegrator gaussHermiteIntegrator)
 {
     m_IntegratorFactory = gaussHermiteIntegrator;
     WeightFunction      = WeightFunction.Create(x => Math.Exp(-x * x));
 }
Beispiel #19
0
 /// <summary>
 /// Forward pass for the block.
 /// Assumes the blocks to the top and right have already been processed.
 /// </summary>
 /// <param name="weightFunction"></param>
 /// <param name="blockRow">First index of the block within the grid</param>
 /// <param name="blockCol">Second index of the block within the grid</param>
 /// <param name="lastRow">Last valid row index within the block; rows beyond this index stay uninitialized</param>
 /// <param name="lastCol">Last valid column index within the block; columns beyond this index stay uninitialized</param>
 protected abstract void ComputeBlock(WeightFunction weightFunction, int blockRow, int blockCol, int lastRow, int lastCol);
 public void SetWeightFunction(WeightFunction weightFunction)
 {
     this.weightFunction = weightFunction;
 }