Ejemplo n.º 1
0
    public override string ToString()
    {
        var action = EnumerableUtils.CleanIEnumeratorToString(_action(Current).ToString());

        return($"For each at {_currentIndex} of {_count} total.\n" +
               $"{action}({Current})");
    }
Ejemplo n.º 2
0
        private static void AdjustSpeciesTargetSizesDown(
            Species <T>[] speciesArr,
            int targetSizeDeltaInt,
            IRandomSource rng)
        {
            // We have overshot the required populationSize; remove the required number of allocations to compensate.
            while (targetSizeDeltaInt > 0)
            {
                // Loop through the species in random order, decrementing the target size of each by as we go.
                foreach (var speciesIdx in EnumerableUtils.RangeRandomOrder(0, speciesArr.Length, rng))
                {
                    var stats = speciesArr[speciesIdx].Stats;

                    // We can only decrement non-zero allocations.
                    if (stats.TargetSizeInt > 0)
                    {
                        stats.TargetSizeInt--;
                        if (--targetSizeDeltaInt == 0)
                        {
                            break;
                        }
                    }
                }

                // If we have looped through all species, but the number of target allocations is still too high,
                // then go through species loop again.
                // This is probably a rare execution path, but it's theoretically possible so we cover it.
            }
        }
Ejemplo n.º 3
0
        public static StepFunction <Polynomial> BuildLinearInterpolation(double[] abscissae, double[] values,
                                                                         double leftExtrapolationSlope, double rightExtrapolationSlope)
        {
            var linearInterpol = EnumerableUtils.For(0, abscissae.Length - 1,
                                                     i => StepLinearInterpoler(abscissae[i + 1] - abscissae[i], values[i], values[i + 1]));

            if (Double.IsNaN(rightExtrapolationSlope))
            {
                if (values.Length <= 1)
                {
                    throw new Exception("Linear interpolation : natural extrapolation need at least two values");
                }
                rightExtrapolationSlope = (values[values.Length - 1] - values[values.Length - 2])
                                          / (abscissae[abscissae.Length - 1] - abscissae[abscissae.Length - 2]);
            }
            var rightElem = new Polynomial(values[values.Length - 1], rightExtrapolationSlope);

            if (Double.IsNaN(leftExtrapolationSlope))
            {
                if (values.Length <= 1)
                {
                    throw new Exception("Linear interpolation : natural extrapolation need at least two values");
                }
                leftExtrapolationSlope = (values[1] - values[0]) / (abscissae[1] - abscissae[0]);
            }
            var leftElem = new Polynomial(values[0], leftExtrapolationSlope);

            return(new StepFunction <Polynomial>(abscissae, linearInterpol.Concat(new[] { rightElem }).ToArray(), leftElem));
        }
Ejemplo n.º 4
0
        public async Task <MarginAssetDTO> CreateTestMarginAsset()
        {
            string            url            = ApiPaths.MARGIN_ASSET_BASE_PATH;
            MarginAssetEntity templateEntity = EnumerableUtils.PickRandom(AllMarginAssetsFromDB);
            MarginAssetDTO    createDTO      = this.mapper.Map <MarginAssetDTO>(templateEntity);

            createDTO.Id        += Helpers.Random.Next(1000, 9999).ToString() + GlobalConstants.AutoTest;
            createDTO.IdIssuer  += Helpers.Random.Next(1000, 9999).ToString() + GlobalConstants.AutoTest;
            createDTO.Name      += Helpers.Random.Next(1000, 9999).ToString() + GlobalConstants.AutoTest;
            createDTO.Accuracy   = Helpers.Random.Next(2, 8);
            createDTO.DustLimit  = Helpers.Random.NextDouble();
            createDTO.Multiplier = Helpers.Random.NextDouble();
            string createParam = JsonUtils.SerializeObject(createDTO);

            var response = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, createParam, Method.POST);

            if (response.Status != HttpStatusCode.Created)
            {
                return(null);
            }

            AddOneTimeCleanupAction(async() => await DeleteTestMarginAsset(createDTO.Id));

            return(createDTO);
        }
Ejemplo n.º 5
0
        protected SqlProvider CreateProvider(SqlSelect statement, QueryParameterBinding extraBinding,
                                             CompilableProvider origin, params ExecutableProvider[] sources)
        {
            var extraBindings = extraBinding != null?EnumerableUtils.One(extraBinding) : null;

            return(CreateProvider(statement, extraBindings, origin, sources));
        }
Ejemplo n.º 6
0
 public async Task RootElementIsNullPrefetchAsyncTest()
 {
     RemoveAllBooks();
     using (var session = Domain.OpenSession()) {
         using (var tx = session.OpenTransaction()) {
             new Model.Book {
                 Title = new Model.Title {
                     Text = "T0"
                 }, Category = "1"
             };
             tx.Complete();
         }
         using (var tx = session.OpenTransaction()) {
             var books = session.Query.All <Model.Book>().AsEnumerable()
                         .Concat(EnumerableUtils.One <Model.Book>(null)).Prefetch(b => b.Title).AsAsync();
             var titleField = Domain.Model.Types[typeof(Model.Book)].Fields["Title"];
             var titleType  = Domain.Model.Types[typeof(Model.Title)];
             var count      = 0;
             foreach (var book in await books)
             {
                 count++;
                 if (book != null)
                 {
                     var titleKey = book.GetReferenceKey(titleField);
                     PrefetchTestHelper.AssertOnlyDefaultColumnsAreLoaded(titleKey, titleType, session);
                 }
             }
             Assert.AreEqual(2, count);
         }
     }
 }
Ejemplo n.º 7
0
        private static PrettySkeletonPose CombineSkeletonPoses([NotNull, ItemNotNull] IEnumerable <PrettySkeletonPose> poses, [NotNull, ItemNotNull] IEnumerable <PrettySkeleton> skeletons)
        {
            var transformList = new List <RawTransform>();

            foreach (var(pose, skeleton) in EnumerableUtils.Zip(poses, skeletons))
            {
                var transforms = pose.Transforms;
                var ids        = skeleton.NodeIDs;

                Debug.Assert(transforms.Length == ids.Length);

                var len = transforms.Length;

                for (var i = 0; i < len; ++i)
                {
                    if (ids[i] == 0)
                    {
                        if (transformList.Count == 0)
                        {
                            transformList.Add(transforms[i]);
                        }
                    }
                    else
                    {
                        transformList.Add(transforms[i]);
                    }
                }
            }

            var result = new PrettySkeletonPose(transformList.ToArray());

            return(result);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Determines whether the specified difference is relocated.
        /// </summary>
        /// <param name="difference">The difference.</param>
        /// <returns>
        ///  <see langword="true"/> if the specified difference is relocated; otherwise, <see langword="false"/>.
        /// </returns>
        protected virtual bool IsRelocated(Difference difference)
        {
            var nodeDifference = difference as NodeDifference;

            if (nodeDifference == null)
            {
                return(false);
            }
            if ((nodeDifference.MovementInfo & MovementInfo.Relocated) == 0)
            {
                return(false);
            }
            var diffs =
                EnumerableUtils.Unfold(difference, d => d.Parent).Reverse();
            var currentDiffs =
                EnumerableUtils.Unfold(Context.Difference, d => d.Parent).Reverse();
            var commonDiffs = diffs.Zip(currentDiffs).Where(p => p.First == p.Second).Select(p => p.First);
            var newDiffs    = diffs.Except(commonDiffs);
            var query       =
                from diff in newDiffs
                let nodeDiff = diff as NodeDifference
                               where nodeDiff != null && (nodeDiff.MovementInfo & MovementInfo.Changed) != 0
                               select nodeDiff;

            // query = query.ToList();
            return(query.Any());
        }
Ejemplo n.º 9
0
    public IEnumerable <GridEntity2D> Query(Vector2 aabbFrom, Vector2 aabbTo, Func <Vector2, float, bool> filter)
    {
        var from = new Vector2(Mathf.Min(aabbFrom.x, aabbTo.x), Mathf.Min(aabbFrom.y, aabbTo.y));
        var to   = new Vector2(Mathf.Max(aabbFrom.x, aabbTo.x), Mathf.Max(aabbFrom.y, aabbTo.y));

        var fromCoord = PositionInGrid(from);
        var toCoord   = PositionInGrid(to);

        //¡Ojo que clampea a 0,0 el Outside! TODO: Checkear cuando descartar el query si estan del mismo lado
        fromCoord.Clamp(Vector2Int.zero, CellCant);
        toCoord.Clamp(Vector2Int.zero, CellCant);

        if (!InsideGrid(fromCoord) && !InsideGrid(toCoord))
        {
            return(new GridEntity2D[0]);
        }

        var xrows = EnumerableUtils.Generate(fromCoord.x, x => x + 1)
                    .TakeWhile(x => x < CellCant.x && x <= toCoord.x);

        var yrows = EnumerableUtils.Generate(fromCoord.y, y => y + 1)
                    .TakeWhile(y => y < CellCant.y && y <= toCoord.y);

        var cells = xrows.SelectMany(
            xs => yrows.Select(ys => new Vector2Int(xs, ys))
            );

        return(cells
               .SelectMany(cell => buckets[cell.x, cell.y])
               .Where(entity =>
                      from.x <= entity.transform.position.x + entity.radius && entity.transform.position.x - entity.radius <= to.x &&
                      from.y <= entity.transform.position.y + entity.radius && entity.transform.position.y - entity.radius <= to.y
                      ).Where(entity => filter(entity.transform.position, entity.radius)));
    }
Ejemplo n.º 10
0
        public async Task <AssetDTO> CreateTestAsset()
        {
            AssetDTO newAssetDTO = this.mapper.Map <AssetDTO>(EnumerableUtils.PickRandom(AllAssetsFromDB));

            newAssetDTO.Id   += Helpers.Random.Next(1000, 9999).ToString() + GlobalConstants.AutoTest;
            newAssetDTO.Name += Helpers.Random.Next(1000, 9999).ToString() + GlobalConstants.AutoTest;
            newAssetDTO.BlockChainAssetId += Helpers.Random.Next(1000, 9999).ToString() + GlobalConstants.AutoTest;
            newAssetDTO.BlockChainId      += Helpers.Random.Next(1000, 9999).ToString() + GlobalConstants.AutoTest;
            newAssetDTO.Accuracy           = Helpers.Random.Next(2, 6);
            newAssetDTO.MultiplierPower    = Helpers.Random.Next(6, 10);

            string url         = ApiPaths.ASSETS_V2_BASE_PATH;
            string createParam = JsonUtils.SerializeObject(newAssetDTO);

            var response = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, createParam, Method.POST);

            if (response.Status != HttpStatusCode.Created)
            {
                return(null);
            }

            AddOneTimeCleanupAction(async() => await DeleteTestAsset(newAssetDTO.Id));

            return(newAssetDTO);
        }
Ejemplo n.º 11
0
        public async Task <AssetAttributeIdentityDTO> CreateTestAssetAttribute()
        {
            AssetAttributesEntity testAssetAttr = EnumerableUtils.PickRandom(AllAssetAttributesFromDB);

            string url      = ApiPaths.ASSET_ATTRIBUTES_PATH + "/" + testAssetAttr.AssetId;
            string newKey   = testAssetAttr.Key + Helpers.Random.Next(1000, 9999).ToString() + GlobalConstants.AutoTest;
            string newValue = Helpers.Random.Next(1000, 9999).ToString() + "_autotest";

            AssetAttributeDTO createParameter = new AssetAttributeDTO()
            {
                Key = newKey, Value = newValue
            };

            var response = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(createParameter), Method.POST);

            if (response.Status != HttpStatusCode.Created)
            {
                return(null);
            }

            AssetAttributeIdentityDTO returnModel = new AssetAttributeIdentityDTO()
            {
                AssetId = testAssetAttr.AssetId,
                Key     = newKey,
                Value   = newValue
            };

            AddOneTimeCleanupAction(async() => await DeleteTestAssetAttribute(returnModel.AssetId, returnModel.Key));

            return(returnModel);
        }
Ejemplo n.º 12
0
        private static float Evaluate(Genome genome, bool isRecurrent)
        {
            if (genome.IsNetworkDisconnected)
            {
                return(0);
            }

            const int iterationCount = 10;
            var       maxFitness     = (float)XorTruthTable.Length * iterationCount;
            var       fitness        = maxFitness;


            for (var iteration = 0; iteration < iterationCount; iteration++)
            {
                foreach (var i in EnumerableUtils.RangeRandomOrder(0, XorTruthTable.Length, RandomSource.Rng))
                {
                    var diff = XorTruthTable[i][2] - ActivateAndGetEffector(genome,
                                                                            isRecurrent,
                                                                            XorTruthTable[i][0],
                                                                            XorTruthTable[i][1]);
                    fitness -= diff * diff;
                }
            }

            return(fitness / maxFitness);
        }
        private NeatGenome <T> GetSeedGenome(List <NeatGenome <T> > seedGenomeList, List <NeatGenome <T> > remainingGenomes)
        {
            // Select from a random subset of remainingGenomes rather than the full set, otherwise
            // k-means will have something like O(n^2) scalability
            int subsetCount;

            // For 10 or fewer genomes just select all of them.
            if (remainingGenomes.Count <= 10)
            {
                subsetCount = remainingGenomes.Count;
            }
            else
            {   // For more than ten remainingGenomes we choose a subset size proportional to log(count).
                subsetCount = (int)(Math.Log10(remainingGenomes.Count) * 10.0);
            }

            // Get the indexes of a random subset of remainingGenomes.
            int[] genomeIdxArr = EnumerableUtils.RangeRandomOrder(0, remainingGenomes.Count, _rng).Take(subsetCount).ToArray();

            // Create an array of relative selection probabilities for the candidate genomes.
            double[] pArr = new double[subsetCount];

            for (int i = 0; i < subsetCount; i++)
            {
                // Note. k-means++ assigns a probability that is the squared distance to the nearest existing centroid.
                double distance = GetDistanceFromNearestSeed(seedGenomeList, remainingGenomes[genomeIdxArr[i]]);
                pArr[i] = distance * distance;
            }

            // Select a remaining genome at random based on pArr; remove it from remainingGenomes and return it.
            int selectIdx = new DiscreteDistribution(pArr, _rng).Sample();

            return(GetAndRemove(remainingGenomes, genomeIdxArr[selectIdx]));
        }
Ejemplo n.º 14
0
 private int[] GetUnexpectedTypeIds(string nodeId)
 {
     return((nodeId == WellKnown.DefaultNodeId)
 ? CustomUpgradeHandler.TypeIdPerNode.Values.ToArray()
 : CustomUpgradeHandler.TypeIdPerNode.Where(i => i.Key != nodeId)
            .Select(i => i.Value).Union(EnumerableUtils.One(100)).ToArray());
 }
        public AffineDivCurveUtils(DividendQuote[] dividends,
                                   DiscountCurve discountCurve,
                                   ITimeMeasure time)
        {
            Contract.Requires(EnumerableUtils.IsSorted(dividends.Select(div => div.Date)));

            if (dividends.Length > 0)
            {
                double[] divDates         = dividends.Map(div => time[div.Date]);
                double[] spotYieldGrowths = dividends.Scan(1.0, (prev, div) => prev * (1.0 - div.Yield));
                var      spotYieldGrowth  = new StepFunction(divDates, spotYieldGrowths, 1.0);
                assetGrowth = t => spotYieldGrowth.Eval(t) / discountCurve.Zc(t);

                double[] discountedCashs = dividends.Map(div => div.Cash / assetGrowth(time[div.Date]));
                double[] cashBpvs        = discountedCashs.Scan(0.0, (prev, c) => prev + c);
                cashDivBpv      = new StepFunction(divDates, cashBpvs, 0.0);
                cashBpvIntegral = cashDivBpv.Integral(0.0);

                double[] squareTimeWeightedCashs = discountedCashs.ZipWith(divDates, (c, t) => c * t * t);
                squareTimeWeightedCash = new StepFunction(divDates, squareTimeWeightedCashs, 0.0);
            }
            else
            {
                assetGrowth     = t => 1.0 / discountCurve.Zc(t);
                cashDivBpv      = new StepFunction(new[] { 0.0 }, new[] { 0.0 }, double.NaN);
                cashBpvIntegral = RrFunctions.Zero;

                squareTimeWeightedCash = new StepFunction(new[] { 0.0 }, new[] { 0.0 }, double.NaN);
            }
        }
Ejemplo n.º 16
0
        public AutocallPathFlow(CouponPathFlow[] underlyingPathFlows,
                                CouponPathFlow[] redemptionPathFlows,
                                FixingFuncPathValue[] triggers,
                                int[] underlyingCallIndexes)
        {
            Contract.Requires(redemptionPathFlows.Length == triggers.Length);
            Contract.Requires(underlyingCallIndexes.Length == triggers.Length);

            this.underlyingPathFlows   = underlyingPathFlows;
            this.redemptionPathFlows   = redemptionPathFlows;
            this.triggers              = triggers;
            this.underlyingCallIndexes = underlyingCallIndexes;

            var underlyingFixings = underlyingPathFlows.Map(pf => pf.PayoffPathValues.FixingFunction.Fixings);
            var redemptionFixings = redemptionPathFlows.Map(pf => pf.PayoffPathValues.FixingFunction.Fixings);
            var triggerFixings    = triggers.Map(pf => pf.FixingFunction.Fixings);

            Fixings = EnumerableUtils.Merge(underlyingFixings)
                      .MergeWith(redemptionFixings)
                      .MergeWith(triggerFixings);

            var underlyingLabels = underlyingPathFlows.Map(pf => pf.CouponLabel);
            var redemptionLabels = redemptionPathFlows.Map(pf => pf.CouponLabel);

            labels = EnumerableUtils.Append(underlyingLabels, redemptionLabels);

            var underlyingPayments = underlyingLabels.Map(l => l.Payment);
            var redemptionPayments = redemptionLabels.Map(l => l.Payment);

            Payments = EnumerableUtils.Append(underlyingPayments, redemptionPayments);
        }
Ejemplo n.º 17
0
        public void ScrambledEquals_SimpleTypes_Test()
        {
            Assert.True(EnumerableUtils.ScrambledEquals(new[] { 1, 2, 3, 4, 5, 6 },
                                                        new[] { 1, 2, 3, 4, 5, 6 }),
                        "Equal int[]");

            Assert.True(EnumerableUtils.ScrambledEquals(new[] { "1", "2", "3", "4", "5" },
                                                        new[] { "1", "2", "3", "4", "5" }),
                        "Equal string[]");

            Assert.True(EnumerableUtils.ScrambledEquals(new[] { true, false, true },
                                                        new[] { true, false, true }),
                        "Equal bool[]");

            Assert.False(EnumerableUtils.ScrambledEquals(new[] { 1, 2, 3, 4 },
                                                         new[] { 1, 2, 2 }),
                         "Not equal int[]");

            Assert.False(EnumerableUtils.ScrambledEquals(new[] { "23", "3", "4" },
                                                         new[] { "34", "3", " " }),
                         "Not equal string[]");

            Assert.True(EnumerableUtils.ScrambledEquals(new[] { 1, 2, 3 },
                                                        new List <int> {
                1, 2, 3
            }),
                        "Equal List and array");
        }
Ejemplo n.º 18
0
    public static IEnumerable <Tuple <Node, IEnumerable <Node> > > Run <Node>
    (
        Node start,
        Func <Node, bool> satisfies,
        Func <Node, float> heuristic,
        Func <Node, IEnumerable <Tuple <Node, float> > > expand
    )
    {
        var open    = new MinHeap <Node, float>();
        var closed  = new HashSet <Node>();
        var previus = new Dictionary <Node, Node>();
        var gs      = new Dictionary <Node, float>();

        open.Insert(start, 0);
        gs[start] = 0f;

        bool done = false;

        while (!done && !open.IsEmpty)
        {
            var candidate = open.Pop();

            if (satisfies(candidate))
            {
                done = true;
                yield return(Tuple.Create <Node, IEnumerable <Node> >(
                                 candidate,
                                 EnumerableUtils.Generate(candidate, n => previus[n])
                                 .TakeWhile(n => n != null && previus.ContainsKey(n))
                                 .Reverse()
                                 ));
            }
            else
            {
                closed.Add(candidate);
                var transitions = expand(candidate);
                var gc          = gs[candidate];
                foreach (var t in transitions)
                {
                    var node = t.Item1;
                    if (closed.Contains(node))
                    {
                        continue;
                    }

                    var gn = gc + t.Item2;
                    if (gs.ContainsKey(node) && gn >= gs[node])
                    {
                        continue;
                    }

                    previus[node] = candidate;
                    gs[node]      = gn;
                    open.Insert(node, gn + heuristic(node));
                }
                yield return(Tuple.Create <Node, IEnumerable <Node> >(candidate, null));
            }
        }
    }
Ejemplo n.º 19
0
        private static IEnumerable <KeyValuePair <string, DType> > LanguageCodeSuggestion(TryGetEnumSymbol tryGetEnumSymbol, bool suggestUnqualifedEnums, DType scopeType, int argumentIndex, out bool requiresSuggestionEscaping)
        {
            Contracts.Assert(scopeType.IsValid);
            Contracts.Assert(0 <= argumentIndex);

            requiresSuggestionEscaping = false;
            return(argumentIndex == 1 ? GetLanguageCodeSuggestions() : EnumerableUtils.Yield <KeyValuePair <string, DType> >());
        }
Ejemplo n.º 20
0
 public AssetForwardCurve(double spot, DividendQuote[] dividends, DiscountCurve assetFinancingCurve,
                          ITimeMeasure time)
 {
     Contract.Requires(EnumerableUtils.IsSorted(dividends.Select(div => div.Date)));
     this.time     = time;
     Spot          = spot;
     divCurveUtils = new AffineDivCurveUtils(dividends, assetFinancingCurve, time);
 }
Ejemplo n.º 21
0
 public RegularGridAffineInterpol(RealInterval support, int size, double[] f)
 {
     Contract.Requires(f.Length == size);
     this.f = f;
     inf    = support.Inf;
     step   = support.Length / (f.Length - 1);
     df     = EnumerableUtils.For(0, f.Length - 1, i => f[i + 1] - f[i]);
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Gets a list of involved <see cref="IZincElement"/> instances that are the children of
 /// this <see cref="IZincElement"/>.
 /// </summary>
 /// <returns>
 /// An <see cref="T:System.Collections.Generic.IEnumerable`1"/> instance of
 /// <see cref="IZincElement"/> that are the childrens of this <see cref="IZincBox"/> instance.
 /// </returns>
 public override IEnumerable <IZincElement> Children()
 {
     return(EnumerableUtils.Append(new IEnumerable <IZincElement>[] {
         this.annotations,
         this.typeInstExpressions,
         base.Children()
     }));
 }
 private IEnumerable <Customer> GetExpectedCustomerAsSequence()
 {
     if (StorageProviderInfo.Instance.CheckProviderIs(StorageProvider.Firebird))
     {
         return(EnumerableUtils.One(Session.Query.All <Customer>().OrderBy(c => c.CustomerId).AsEnumerable().First()));
     }
     return(EnumerableUtils.One(Customers.First()));
 }
 /// <summary>
 /// Safely adds one value to sequence.
 /// </summary>
 /// <typeparam name="T">The type of enumerated items.</typeparam>
 /// <param name="source">Source sequence.</param>
 /// <param name="value">Value to add to sequence.</param>
 /// <returns>New sequence with both <paramref name="source"/> and <paramref name="value"/> items inside without duplicates.</returns>
 /// <remarks>If source sequence is null, it's equals to empty sequence. If value is null, it will not added to result sequence.</remarks>
 public static IEnumerable <T> AddOne <T>(this IEnumerable <T> source, T value)
 {
     source = source ?? EnumerableUtils <T> .Empty;
     if (!ReferenceEquals(value, null))
     {
         source = source.Concat(EnumerableUtils.One(value));
     }
     return(source);
 }
Ejemplo n.º 25
0
 public Coupon[] Decomposition()
 {
     Coupon[][] weightedCoupons = weights.ZipWith(decomposables, (w, d) =>
     {
         var coupons = d.Decomposition();
         return(coupons.Map(cpn => new Coupon(cpn.PaymentInfo, new WeightedFixingFunction(w, cpn.Payoff))));
     });
     return(EnumerableUtils.Append(weightedCoupons));
 }
Ejemplo n.º 26
0
 public override string ToString()
 {
     return(EnumerableUtils.ToObjectString(new string[]
     {
         $"{nameof(DotNet)}: {DotNet}",
         $"{nameof(NSpec)}: {NSpec}",
         $"{nameof(UnknownArgs)}: {EnumerableUtils.ToArrayString(UnknownArgs)}",
     }, true));
 }
Ejemplo n.º 27
0
 public CouponArrayPathFlow(CouponPathFlow[] couponPathFlows)
 {
     this.couponPathFlows = couponPathFlows;
     labels   = couponPathFlows.Map(l => l.CouponLabel);
     Payments = couponPathFlows.Map(cpnCoord => cpnCoord.CouponLabel.Payment);
     Fixings  = EnumerableUtils.Merge(couponPathFlows.Map(c => c.PayoffPathValues.FixingFunction.Fixings))
                .OrderBy(f => f.Date)
                .ToArray();
 }
Ejemplo n.º 28
0
 public void TestTake()
 {
     testEqual(new char[] { 'H', 'e', 'l', 'l', 'o' }, EnumerableUtils.Take("Hello World!", 5));
     testEqual(new int[] { 1, 2, 3 }, EnumerableUtils.Take(new int[] { 1, 2, 3, 4, 5 }, 3));
     testEqual(new int[] { 1, 2 }, EnumerableUtils.Take(new int[] { 1, 2 }, 3));
     testEqual(new int[] { }, EnumerableUtils.Take(new int[] { }, 3));
     testEqual(new int[] { }, EnumerableUtils.Take(new int[] { 1, 2 }, -1));
     testEqual(new int[] { }, EnumerableUtils.Take(new int[] { 1, 2 }, 0));
 }
Ejemplo n.º 29
0
 public void TestDrop()
 {
     testEqual(new char[] { 'W', 'o', 'r', 'l', 'd', '!' }, EnumerableUtils.Drop("Hello World!", 6));
     testEqual(new int[] { 4, 5 }, EnumerableUtils.Drop(new int[] { 1, 2, 3, 4, 5 }, 3));
     testEqual(new int[] { }, EnumerableUtils.Drop(new int[] { 1, 2 }, 3));
     testEqual(new int[] { }, EnumerableUtils.Drop(new int[] { }, 3));
     testEqual(new int[] { 1, 2 }, EnumerableUtils.Drop(new int[] { 1, 2 }, -1));
     testEqual(new int[] { 1, 2 }, EnumerableUtils.Drop(new int[] { 1, 2 }, 0));
 }
Ejemplo n.º 30
0
    public static IEnumerable <Tuple <bool, Node, IEnumerable <Node> > > Run <Node>
    (
        Node start,
        Func <Node, bool> satisfies,
        Func <Node, List <Tuple <Node, float> > > expand,
        Func <Node, float> heuristic
    )
    {
        var open = new PriorityQueue <Node>();

        open.Enqueue(start, 0);

        var closed = new HashSet <Node>();

        var parents = new Dictionary <Node, Node>();

        var costs = new Dictionary <Node, float>();

        costs[start] = 0;

        while (!open.IsEmpty)
        {
            var current = open.Dequeue();

            yield return(Tuple.Create(
                             satisfies(current),
                             current,
                             EnumerableUtils.GeneratePath(current, parents)
                             ));

            var currentCost = costs[current];
            closed.Add(current);

            foreach (var childPair in expand(current))
            {
                var child     = childPair.Item1;
                var childCost = childPair.Item2;

                if (closed.Contains(child))
                {
                    continue;
                }

                var tentativeCost = currentCost + childCost;
                if (costs.ContainsKey(child) && tentativeCost > costs[child])
                {
                    continue;
                }

                parents[child] = current;

                costs[child] = tentativeCost;
                open.Enqueue(child, tentativeCost + heuristic(child));
            }
        }
    }