// creates the tasks for a single target
        private static IList <CalculationTask> createTargetTasks <T1>(CalculationTarget resolvedTarget, int rowIndex, CalculationFunction <T1> function, IList <Column> columns)
        {
            // create the cells and group them
            ListMultimap <CalculationParameters, CalculationTaskCell> grouped = ArrayListMultimap.create();

            for (int colIndex = 0; colIndex < columns.Count; colIndex++)
            {
                Column  column  = columns[colIndex];
                Measure measure = column.Measure;

                ReportingCurrency   reportingCurrency = column.ReportingCurrency.orElse(ReportingCurrency.NATURAL);
                CalculationTaskCell cell = CalculationTaskCell.of(rowIndex, colIndex, measure, reportingCurrency);
                // group to find cells that can be shared, with same mappings and params (minus reporting currency)
                CalculationParameters @params = column.Parameters.filter(resolvedTarget, measure);
                grouped.put(@params, cell);
            }

            // build tasks
            ImmutableList.Builder <CalculationTask> taskBuilder = ImmutableList.builder();
            foreach (CalculationParameters @params in grouped.Keys)
            {
                taskBuilder.add(CalculationTask.of(resolvedTarget, function, @params, grouped.get(@params)));
            }
            return(taskBuilder.build());
        }
Exemplo n.º 2
0
        public ImmutableList <RateAccrualPeriod> createAccrualPeriods(Schedule accrualSchedule, Schedule paymentSchedule, ReferenceData refData)
        {
            // avoid null stub definitions if there are stubs
            FixedRateStubCalculation  initialStub         = firstNonNull(this.initialStub, FixedRateStubCalculation.NONE);
            FixedRateStubCalculation  finalStub           = firstNonNull(this.finalStub, FixedRateStubCalculation.NONE);
            Optional <SchedulePeriod> scheduleInitialStub = accrualSchedule.InitialStub;
            Optional <SchedulePeriod> scheduleFinalStub   = accrualSchedule.FinalStub;
            // resolve data by schedule
            DoubleArray resolvedRates = rate.resolveValues(accrualSchedule);

            // build accrual periods
            ImmutableList.Builder <RateAccrualPeriod> accrualPeriods = ImmutableList.builder();
            for (int i = 0; i < accrualSchedule.size(); i++)
            {
                SchedulePeriod period       = accrualSchedule.getPeriod(i);
                double         yearFraction = period.yearFraction(dayCount, accrualSchedule);
                // handle stubs
                RateComputation rateComputation;
                if (scheduleInitialStub.Present && scheduleInitialStub.get() == period)
                {
                    rateComputation = initialStub.createRateComputation(resolvedRates.get(i));
                }
                else if (scheduleFinalStub.Present && scheduleFinalStub.get() == period)
                {
                    rateComputation = finalStub.createRateComputation(resolvedRates.get(i));
                }
                else
                {
                    rateComputation = FixedRateComputation.of(resolvedRates.get(i));
                }
                accrualPeriods.add(new RateAccrualPeriod(period, yearFraction, rateComputation));
            }
            return(accrualPeriods.build());
        }
Exemplo n.º 3
0
        static IsdaCompliantIndexCurveCalibratorTest()
        {
            ImmutableList.Builder <StandardId> legalEntityIdsbuilder = ImmutableList.builder();
            ImmutableMarketDataBuilder         marketDataBuilder     = ImmutableMarketData.builder(VALUATION_DATE);
            ImmutableMarketDataBuilder         marketDataPsBuilder   = ImmutableMarketData.builder(VALUATION_DATE);

            for (int?i = 0; i.Value < INDEX_SIZE; ++i)
            {
                StandardId             legalEntityId = StandardId.of("OG", "ABC" + i.ToString());
                LegalEntityInformation information   = DEFAULTED_NAMES.contains(i) ? LegalEntityInformation.isDefaulted(legalEntityId) : LegalEntityInformation.isNotDefaulted(legalEntityId);
                legalEntityIdsbuilder.add(legalEntityId);
                marketDataBuilder.addValue(LegalEntityInformationId.of(legalEntityId), information);
                marketDataPsBuilder.addValue(LegalEntityInformationId.of(legalEntityId), information);
            }
            LEGAL_ENTITIES = legalEntityIdsbuilder.build();
            ImmutableList.Builder <CdsIndexIsdaCreditCurveNode> curveNodesBuilder   = ImmutableList.builder();
            ImmutableList.Builder <CdsIndexIsdaCreditCurveNode> curveNodesPsBuilder = ImmutableList.builder();
            for (int i = 0; i < NUM_PILLARS; ++i)
            {
                QuoteId     id   = QuoteId.of(StandardId.of("OG", INDEX_TENORS[i].ToString()));
                CdsTemplate temp = TenorCdsTemplate.of(INDEX_TENORS[i], CONVENTION);
                curveNodesBuilder.add(CdsIndexIsdaCreditCurveNode.ofPointsUpfront(temp, id, INDEX_ID, LEGAL_ENTITIES, COUPON));
                curveNodesPsBuilder.add(CdsIndexIsdaCreditCurveNode.ofParSpread(temp, id, INDEX_ID, LEGAL_ENTITIES));
                marketDataBuilder.addValue(id, PUF_QUOTES[i]);
                marketDataPsBuilder.addValue(id, PS_QUOTES[i]);
            }
            CURVE_NODES    = curveNodesBuilder.build();
            MARKET_DATA    = marketDataBuilder.build();
            CURVE_NODES_PS = curveNodesPsBuilder.build();
            MARKET_DATA_PS = marketDataPsBuilder.build();
        }
        // variable notional
        private static SwapTrade parseVariableNotional(SwapTrade trade, IList <CsvRow> variableRows)
        {
            // parse notionals
            ImmutableList.Builder <ValueStep> stepBuilder = ImmutableList.builder();
            foreach (CsvRow row in variableRows)
            {
                LocalDate date = LoaderUtils.parseDate(row.getValue(START_DATE_FIELD));
                row.findValue(NOTIONAL_FIELD).map(str => LoaderUtils.parseDouble(str)).ifPresent(notional => stepBuilder.add(ValueStep.of(date, ValueAdjustment.ofReplace(notional))));
            }
            ImmutableList <ValueStep> varNotionals = stepBuilder.build();

            if (varNotionals.Empty)
            {
                return(trade);
            }
            // adjust the trade, inserting the variable notionals
            ImmutableList.Builder <SwapLeg> legBuilder = ImmutableList.builder();
            foreach (SwapLeg swapLeg in trade.Product.Legs)
            {
                RateCalculationSwapLeg leg = (RateCalculationSwapLeg)swapLeg;
                NotionalSchedule       notionalSchedule = leg.NotionalSchedule.toBuilder().amount(ValueSchedule.of(leg.NotionalSchedule.Amount.InitialValue, varNotionals)).build();
                legBuilder.add(leg.toBuilder().notionalSchedule(notionalSchedule).build());
            }
            return(replaceLegs(trade, legBuilder.build()));
        }
        //-------------------------------------------------------------------------
        /// <summary>
        /// Combines two or more instances to form a single sensitivity instance.
        /// <para>
        /// The result will store information about the separate instances allowing it to be <seealso cref="#split()"/> later.
        ///
        /// </para>
        /// </summary>
        /// <param name="marketDataName">  the combined name of the market data that the sensitivity refers to </param>
        /// <param name="sensitivities">  the sensitivity instances to combine, two or more </param>
        /// <returns> the combined sensitivity object </returns>
        public static UnitParameterSensitivity combine <T1>(MarketDataName <T1> marketDataName, params UnitParameterSensitivity[] sensitivities)
        {
            ArgChecker.notEmpty(sensitivities, "sensitivities");
            if (sensitivities.Length < 2)
            {
                throw new System.ArgumentException("At least two sensitivity instances must be specified");
            }
            int size = Stream.of(sensitivities).mapToInt(s => s.ParameterCount).sum();

            double[] combinedSensitivities = new double[size];
            ImmutableList.Builder <ParameterMetadata> combinedMeta = ImmutableList.builder();
            ImmutableList.Builder <ParameterSize>     split        = ImmutableList.builder();
            int count = 0;

            for (int i = 0; i < sensitivities.Length; i++)
            {
                UnitParameterSensitivity sens = sensitivities[i];
                Array.Copy(sens.Sensitivity.toArrayUnsafe(), 0, combinedSensitivities, count, sens.ParameterCount);
                combinedMeta.addAll(sens.ParameterMetadata);
                split.add(ParameterSize.of(sens.MarketDataName, sens.ParameterCount));
                count += sens.ParameterCount;
            }

            return(new UnitParameterSensitivity(marketDataName, combinedMeta.build(), DoubleArray.ofUnsafe(combinedSensitivities), split.build()));
        }
        public virtual void test_volatilities()
        {
            BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification @base = BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification.builder().name(VOL_NAME).currencyPair(GBP_USD).dayCount(ACT_365F).nodes(NODES).timeInterpolator(PCHIP).strikeInterpolator(DOUBLE_QUADRATIC).build();
            LocalDate     date       = LocalDate.of(2017, 9, 25);
            ZonedDateTime dateTime   = date.atStartOfDay().atZone(ZoneId.of("Europe/London"));
            DoubleArray   parameters = DoubleArray.of(0.19, 0.15, 0.13, 0.14, 0.14, 0.11, 0.09, 0.09, 0.11, 0.09, 0.07, 0.07);
            BlackFxOptionSurfaceVolatilities computed = @base.volatilities(dateTime, parameters, REF_DATA);
            DaysAdjustment expOffset = DaysAdjustment.ofBusinessDays(-2, NY_LO);

            double[] expiries = new double[STRIKES.Count * TENORS.Count];
            double[] strikes  = new double[STRIKES.Count * TENORS.Count];
            ImmutableList.Builder <ParameterMetadata> paramMetadata = ImmutableList.builder();
            for (int i = 0; i < TENORS.Count; ++i)
            {
                double expiry = ACT_365F.relativeYearFraction(date, expOffset.adjust(BDA.adjust(SPOT_OFFSET.adjust(date, REF_DATA).plus(TENORS[i]), REF_DATA), REF_DATA));
                for (int j = 0; j < STRIKES.Count; ++j)
                {
                    paramMetadata.add(FxVolatilitySurfaceYearFractionParameterMetadata.of(expiry, SimpleStrike.of(STRIKES[j]), GBP_USD));
                    expiries[STRIKES.Count * i + j] = expiry;
                    strikes[STRIKES.Count * i + j]  = STRIKES[j];
                }
            }
            InterpolatedNodalSurface         surface  = InterpolatedNodalSurface.ofUnsorted(Surfaces.blackVolatilityByExpiryStrike(VOL_NAME.Name, ACT_365F).withParameterMetadata(paramMetadata.build()), DoubleArray.ofUnsafe(expiries), DoubleArray.ofUnsafe(strikes), parameters, GridSurfaceInterpolator.of(PCHIP, DOUBLE_QUADRATIC));
            BlackFxOptionSurfaceVolatilities expected = BlackFxOptionSurfaceVolatilities.of(VOL_NAME, GBP_USD, dateTime, surface);

            assertEquals(computed, expected);
        }
Exemplo n.º 7
0
        // create notional exchange events when no FxReset
        private static ImmutableList <SwapPaymentEvent> createStandardEvents(IList <NotionalPaymentPeriod> payPeriods, LocalDate initialExchangePaymentDate, bool initialExchange, bool intermediateExchange, bool finalExchange)
        {
            NotionalPaymentPeriod firstPeriod = payPeriods[0];

            ImmutableList.Builder <SwapPaymentEvent> events = ImmutableList.builder();
            if (initialExchange)
            {
                events.add(NotionalExchange.of(firstPeriod.NotionalAmount.negated(), initialExchangePaymentDate));
            }
            if (intermediateExchange)
            {
                for (int i = 0; i < payPeriods.Count - 1; i++)
                {
                    NotionalPaymentPeriod period1 = payPeriods[i];
                    NotionalPaymentPeriod period2 = payPeriods[i + 1];
                    if (period1.NotionalAmount.Amount != period2.NotionalAmount.Amount)
                    {
                        events.add(NotionalExchange.of(period1.NotionalAmount.minus(period2.NotionalAmount), period1.PaymentDate));
                    }
                }
            }
            if (finalExchange)
            {
                NotionalPaymentPeriod lastPeriod = payPeriods[payPeriods.Count - 1];
                events.add(NotionalExchange.of(lastPeriod.NotionalAmount, lastPeriod.PaymentDate));
            }
            return(events.build());
        }
	  // parses the alternate names
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") private static <R extends Named> com.google.common.collect.ImmutableList<ExtendedEnum<? extends R>> parseChildren(com.opengamma.strata.collect.io.IniFile config, Class<R> enumType)
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
	  private static ImmutableList<ExtendedEnum<R>> parseChildren<R>(IniFile config, Type<R> enumType) where R : Named
	  {

		if (!config.contains(TYPES_SECTION))
		{
		  return ImmutableList.of();
		}
		PropertySet section = config.section(TYPES_SECTION);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: com.google.common.collect.ImmutableList.Builder<ExtendedEnum<? extends R>> builder = com.google.common.collect.ImmutableList.builder();
		ImmutableList.Builder<ExtendedEnum<R>> builder = ImmutableList.builder();
		foreach (string key in section.keys())
		{
		  Type cls;
		  try
		  {
			cls = RenameHandler.INSTANCE.lookupType(key);
		  }
		  catch (Exception ex)
		  {
			throw new System.ArgumentException("Unable to find extended enum class: " + key, ex);
		  }
		  System.Reflection.MethodInfo method;
		  try
		  {
			method = cls.GetMethod("extendedEnum");
		  }
		  catch (Exception ex)
		  {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
			throw new System.ArgumentException("Unable to find extendedEnum() method on class: " + cls.FullName, ex);
		  }
		  if (!method.ReturnType.Equals(typeof(ExtendedEnum)))
		  {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
			throw new System.ArgumentException("Method extendedEnum() does not return ExtendedEnum on class: " + cls.FullName);
		  }
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: ExtendedEnum<?> result;
		  ExtendedEnum<object> result;
		  try
		  {
			result = typeof(ExtendedEnum).cast(method.invoke(null));
		  }
		  catch (Exception ex)
		  {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
			throw new System.ArgumentException("Unable to call extendedEnum() method on class: " + cls.FullName, ex);
		  }
		  if (!enumType.IsAssignableFrom(result.Type))
		  {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
			throw new System.ArgumentException("Method extendedEnum() returned an ExtendedEnum with an incompatible type on class: " + cls.FullName);
		  }
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: builder.add((ExtendedEnum<? extends R>) result);
		  builder.add((ExtendedEnum<R>) result);
		}
		return builder.build();
	  }
        /// <summary>
        /// Obtains an instance from a set of targets, columns and rules, resolving the targets.
        /// <para>
        /// The targets will typically be trades and positions.
        /// The columns represent the measures to calculate.
        /// </para>
        /// <para>
        /// The targets will be resolved if they implement <seealso cref="ResolvableCalculationTarget"/>.
        ///
        /// </para>
        /// </summary>
        /// <param name="rules">  the rules defining how the calculation is performed </param>
        /// <param name="targets">  the targets for which values of the measures will be calculated </param>
        /// <param name="columns">  the columns that will be calculated </param>
        /// <param name="refData">  the reference data to use to resolve the targets </param>
        /// <returns> the calculation tasks </returns>
        public static CalculationTasks of <T1>(CalculationRules rules, IList <T1> targets, IList <Column> columns, ReferenceData refData) where T1 : com.opengamma.strata.basics.CalculationTarget
        {
            // create columns that are a combination of the column overrides and the defaults
            // this is done once as it is the same for all targets
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IList <Column> effectiveColumns = columns.Select(column => column.combineWithDefaults(rules.ReportingCurrency, rules.Parameters)).collect(toImmutableList());

            // loop around the targets, then the columns, to build the tasks
            ImmutableList.Builder <CalculationTask> taskBuilder = ImmutableList.builder();
            for (int rowIndex = 0; rowIndex < targets.Count; rowIndex++)
            {
                CalculationTarget target = resolveTarget(targets[rowIndex], refData);

                // find the applicable function, resolving the target if necessary
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: CalculationFunction<?> fn = target instanceof UnresolvableTarget ? UnresolvableTargetCalculationFunction.INSTANCE : rules.getFunctions().getFunction(target);
                CalculationFunction <object> fn = target is UnresolvableTarget ? UnresolvableTargetCalculationFunction.INSTANCE : rules.Functions.getFunction(target);

                // create the tasks
                IList <CalculationTask> targetTasks = createTargetTasks(target, rowIndex, fn, effectiveColumns);
                taskBuilder.addAll(targetTasks);
            }

            // calculation tasks holds the original user-specified columns, not the derived ones
            return(new CalculationTasks(taskBuilder.build(), columns));
        }
        // variable fixed rate
        private static SwapTrade parseVariableRates(SwapTrade trade, IList <CsvRow> variableRows)
        {
            ImmutableList.Builder <ValueStep> stepBuilder = ImmutableList.builder();
            foreach (CsvRow row in variableRows)
            {
                LocalDate date = LoaderUtils.parseDate(row.getValue(START_DATE_FIELD));
                row.findValue(FIXED_RATE_FIELD).map(str => LoaderUtils.parseDoublePercent(str)).ifPresent(fixedRate => stepBuilder.add(ValueStep.of(date, ValueAdjustment.ofReplace(fixedRate))));
            }
            ImmutableList <ValueStep> varRates = stepBuilder.build();

            if (varRates.Empty)
            {
                return(trade);
            }
            // adjust the trade, inserting the variable rates
            ImmutableList.Builder <SwapLeg> legBuilder = ImmutableList.builder();
            foreach (SwapLeg swapLeg in trade.Product.Legs)
            {
                RateCalculationSwapLeg leg = (RateCalculationSwapLeg)swapLeg;
                if (leg.Calculation is FixedRateCalculation)
                {
                    FixedRateCalculation baseCalc = (FixedRateCalculation)leg.Calculation;
                    FixedRateCalculation calc     = baseCalc.toBuilder().rate(ValueSchedule.of(baseCalc.Rate.InitialValue, varRates)).build();
                    legBuilder.add(leg.toBuilder().calculation(calc).build());
                }
                else
                {
                    legBuilder.add(leg);
                }
            }
            return(replaceLegs(trade, legBuilder.build()));
        }
        //-------------------------------------------------------------------------
        public BoundSurfaceInterpolator bind(DoubleArray xValues, DoubleArray yValues, DoubleArray zValues)
        {
            // single loop around all parameters, collecting data
            int size         = xValues.size();
            int countUniqueX = 0;

            double[] uniqueX = new double[size];
            double[] tempY   = new double[size];
            double[] tempZ   = new double[size];
            ImmutableList.Builder <BoundCurveInterpolator> yInterpBuilder = ImmutableList.builder();
            int i = 0;

            while (i < size)
            {
                double currentX = xValues.get(i);
                uniqueX[countUniqueX] = currentX;
                if (countUniqueX > 0 && uniqueX[countUniqueX - 1] > uniqueX[countUniqueX])
                {
                    throw new System.ArgumentException("Array of x-values must be sorted");
                }
                int countSameX = 0;
                while (i < size && xValues.get(i) == currentX)
                {
                    tempY[countSameX] = yValues.get(i);
                    tempZ[countSameX] = zValues.get(i);
                    if (countSameX > 0 && tempY[countSameX - 1] >= tempY[countSameX])
                    {
                        throw new System.ArgumentException("Array of y-values must be sorted and unique within x-values");
                    }
                    countSameX++;
                    i++;
                }
                // create a curve for the same x-value
                if (countSameX == 1)
                {
                    // when there is only one point, there is not enough data for a curve
                    // so the value must be returned without using the configured interpolator or extrapolator
                    yInterpBuilder.add(new ConstantCurveInterpolator(tempZ[0]));
                }
                else
                {
                    // normal case, where the curve is created
                    DoubleArray yValuesSameX = DoubleArray.ofUnsafe(Arrays.copyOf(tempY, countSameX));
                    DoubleArray zValuesSameX = DoubleArray.ofUnsafe(Arrays.copyOf(tempZ, countSameX));
                    yInterpBuilder.add(yInterpolator.bind(yValuesSameX, zValuesSameX, yExtrapolatorLeft, yExtrapolatorRight));
                }
                countUniqueX++;
            }
            if (countUniqueX == 1)
            {
                throw new System.ArgumentException("Surface interpolator requires at least two different x-values");
            }
            DoubleArray uniqueXArray = DoubleArray.ofUnsafe(Arrays.copyOf(uniqueX, countUniqueX));

            BoundCurveInterpolator[] yInterps = yInterpBuilder.build().toArray(new BoundCurveInterpolator[0]);
            return(new Bound(xInterpolator, xExtrapolatorLeft, xExtrapolatorRight, size, uniqueXArray, yInterps));
        }
 // formats the ASCII table
 private ImmutableList <ImmutableList <string> > formatAsciiTable(R report)
 {
     ImmutableList.Builder <ImmutableList <string> > table = ImmutableList.builder();
     for (int rowIdx = 0; rowIdx < report.RowCount; rowIdx++)
     {
         table.add(formatRow(report, rowIdx, ReportOutputFormat.ASCII_TABLE));
     }
     return(table.build());
 }
 // formats a single row
 private ImmutableList <string> formatRow(R report, int rowIdx, ReportOutputFormat format)
 {
     ImmutableList.Builder <string> tableRow = ImmutableList.builder();
     for (int colIdx = 0; colIdx < report.ColumnCount; colIdx++)
     {
         tableRow.add(formatData(report, rowIdx, colIdx, format));
     }
     return(tableRow.build());
 }
 protected internal static ImmutableList <Period> createNormalEquivMaturities()
 {
     ImmutableList.Builder <Period> builder = ImmutableList.builder();
     for (int i = 0; i < NUM_BLACK_MATURITIES; ++i)
     {
         builder.add(Period.ofYears(CAP_BLACK_END_TIMES[i]));
     }
     return(builder.build());
 }
Exemplo n.º 15
0
 static IsdaHomogenousCdsIndexProductPricerTest()
 {
     ImmutableList.Builder <StandardId> builder = ImmutableList.builder();
     for (int i = 0; i < 97; ++i)
     {
         builder.add(StandardId.of("OG", i.ToString()));
     }
     LEGAL_ENTITIES = builder.build();
 }
Exemplo n.º 16
0
 /// <summary>
 /// Applies a perturbation to each underlying.
 /// <para>
 /// The updated list of underlying instances is returned.
 ///
 /// </para>
 /// </summary>
 /// @param <R>  the type of the underlying </param>
 /// <param name="underlyingType">  the type of the parameterized data at the specified index </param>
 /// <param name="perturbation">  the perturbation to apply </param>
 /// <returns> a parameterized data instance based on this with the specified parameter altered </returns>
 /// <exception cref="IndexOutOfBoundsException"> if the index is invalid </exception>
 public IList <R> withPerturbation <R>(Type <R> underlyingType, ParameterPerturbation perturbation) where R : ParameterizedData
 {
     ImmutableList.Builder <R> builder = ImmutableList.builder();
     for (int i = 0; i < underlyings.Length; i++)
     {
         builder.add(underlyingWithPerturbation(i, underlyingType, perturbation));
     }
     return(builder.build());
 }
Exemplo n.º 17
0
 public static ImmutableList <AclEntry> ToAclEntries(int[] entries)
 {
     ImmutableList.Builder <AclEntry> b = new ImmutableList.Builder <AclEntry>();
     foreach (int entry in entries)
     {
         AclEntry aclEntry = ToAclEntry(entry);
         b.Add(aclEntry);
     }
     return((ImmutableList <AclEntry>)b.Build());
 }
 /// <summary>
 /// Obtains an instance using a function to create the entries.
 /// <para>
 /// The function is passed the scenario index and returns the value for that index.
 ///
 /// </para>
 /// </summary>
 /// @param <T>  the type of the value </param>
 /// <param name="scenarioCount">  the number of scenarios </param>
 /// <param name="valueFunction">  the function used to obtain each value </param>
 /// <returns> an instance initialized using the function </returns>
 /// <exception cref="IllegalArgumentException"> is size is zero or less </exception>
 public static DefaultScenarioArray <T> of <T>(int scenarioCount, System.Func <int, T> valueFunction)
 {
     ArgChecker.notNegativeOrZero(scenarioCount, "scenarioCount");
     ImmutableList.Builder <T> builder = ImmutableList.builder();
     for (int i = 0; i < scenarioCount; i++)
     {
         builder.add(valueFunction(i));
     }
     return(new DefaultScenarioArray <T>(builder.build()));
 }
Exemplo n.º 19
0
 /// <param name="offset">start endpoint (inclusive)</param>
 /// <param name="length">number of path components</param>
 /// <returns>sub-list of the path</returns>
 public virtual IList <string> GetPath(int offset, int length)
 {
     Preconditions.CheckArgument(offset >= 0 && length >= 0 && offset + length <= path
                                 .Length);
     ImmutableList.Builder <string> components = ImmutableList.Builder();
     for (int i = offset; i < offset + length; i++)
     {
         components.Add(DFSUtil.Bytes2String(path[i]));
     }
     return((ImmutableList <string>)components.Build());
 }
        //-------------------------------------------------------------------------
        /// <summary>
        /// Parses the FpML document extracting the trades.
        /// <para>
        /// This parses the specified FpML root element, using the map of references.
        /// The FpML specification uses references to link one part of the XML to another.
        /// For example, if one part of the XML has {@code <foo id="fooId">}, the references
        /// map will contain an entry mapping "fooId" to the parsed element {@code <foo>}.
        ///
        /// </para>
        /// </summary>
        /// <param name="fpmlRootEl">  the source of the FpML XML document </param>
        /// <param name="references">  the map of id/href to referenced element </param>
        /// <returns> the parsed trades </returns>
        /// <exception cref="RuntimeException"> if a parse error occurred </exception>
        public IList <Trade> parseTrades(XmlElement fpmlRootEl, IDictionary <string, XmlElement> references)
        {
            FpmlDocument       document = new FpmlDocument(fpmlRootEl, references, ourPartySelector, tradeInfoParser, refData);
            IList <XmlElement> tradeEls = document.FpmlRoot.getChildren("trade");

            ImmutableList.Builder <Trade> builder = ImmutableList.builder();
            foreach (XmlElement tradeEl in tradeEls)
            {
                builder.add(parseTrade(document, tradeEl));
            }
            return(builder.build());
        }
Exemplo n.º 21
0
        // parse a single line
        internal static ImmutableList <string> parseLine(string line, int lineNumber, char separator)
        {
            if (line.Length == 0 || line.StartsWith("#", StringComparison.Ordinal) || line.StartsWith(";", StringComparison.Ordinal))
            {
                return(ImmutableList.of());
            }
            ImmutableList.Builder <string> builder = ImmutableList.builder();
            int    start         = 0;
            string terminated    = line + separator;
            int    nextSeparator = terminated.IndexOf(separator, start);

            while (nextSeparator >= 0)
            {
                string possible = terminated.Substring(start, nextSeparator - start).Trim();
                // handle convention where ="xxx" means xxx
                if (possible.StartsWith("=\"", StringComparison.Ordinal))
                {
                    start++;
                    possible = possible.Substring(1);
                }
                // handle quoting where "xxx""yyy" means xxx"yyy
                if (possible.StartsWith("\"", StringComparison.Ordinal))
                {
                    while (true)
                    {
                        if (possible.Substring(1).Replace("\"\"", "").EndsWith("\"", StringComparison.Ordinal))
                        {
                            possible = possible.Substring(1, (possible.Length - 1) - 1).Replace("\"\"", "\"");
                            break;
                        }
                        else
                        {
                            nextSeparator = terminated.IndexOf(separator, nextSeparator + 1);
                            if (nextSeparator < 0)
                            {
                                throw new System.ArgumentException("Mismatched quotes in CSV on line " + lineNumber);
                            }
                            possible = terminated.Substring(start, nextSeparator - start).Trim();
                        }
                    }
                }
                builder.add(possible);
                start         = nextSeparator + 1;
                nextSeparator = terminated.IndexOf(separator, start);
            }
            ImmutableList <string> fields = builder.build();

            if (!hasContent(fields))
            {
                return(ImmutableList.of());
            }
            return(fields);
        }
Exemplo n.º 22
0
 // find the party identifiers
 private static IList <string> findPartyIds(XmlElement party)
 {
     ImmutableList.Builder <string> builder = ImmutableList.builder();
     foreach (XmlElement child in party.getChildren("partyId"))
     {
         if (child.hasContent())
         {
             builder.add(child.Content);
         }
     }
     return(builder.build());
 }
Exemplo n.º 23
0
 //------------------------------------------------------------------------
 // parses the CSV file format
 private static CsvFile parseAll(IList <string> lines, int lineIndex, char separator, ImmutableList <string> headers, ImmutableMap <string, int> searchHeaders)
 {
     ImmutableList.Builder <CsvRow> rows = ImmutableList.builder();
     for (int i = lineIndex; i < lines.Count; i++)
     {
         ImmutableList <string> fields = parseLine(lines[i], i + 1, separator);
         if (!fields.Empty)
         {
             rows.add(new CsvRow(headers, searchHeaders, i + 1, fields));
         }
     }
     return(new CsvFile(headers, searchHeaders, rows.build()));
 }
Exemplo n.º 24
0
        /// <summary>
        /// Returns a list created by repeating the items in the input list multiple times, with each item repeated
        /// in groups.
        /// <para>
        /// For example, given a list [1, 2, 3, 4], total count 12, group size 3 the result is
        /// [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4].
        /// </para>
        /// <para>
        /// This is used when creating scenarios from every possible combination of a set of perturbations.
        ///
        /// </para>
        /// </summary>
        /// <param name="inputs">  an input list whose elements are repeated in the output </param>
        /// <param name="totalCount">  the number of elements in the output list </param>
        /// <param name="groupSize">  the number of times each element should be repeated in each group </param>
        /// @param <T>  the type of the elements </param>
        /// <returns> a list created by repeating the elements of the input list </returns>
        internal static IList <T> repeatItems <T>(IList <T> inputs, int totalCount, int groupSize)
        {
            ImmutableList.Builder <T> builder = ImmutableList.builder();

            for (int i = 0; i < (totalCount / groupSize / inputs.Count); i++)
            {
                foreach (T input in inputs)
                {
                    builder.addAll(Collections.nCopies(groupSize, input));
                }
            }
            return(builder.build());
        }
Exemplo n.º 25
0
        // Converts an FpML 'Schedule' to a {@code ValueSchedule}.
        private ValueSchedule parseSchedule(XmlElement scheduleEl, double initialValue, ValueStepSequence seq, FpmlDocument document)
        {
            IList <XmlElement> stepEls = scheduleEl.getChildren("step");

            ImmutableList.Builder <ValueStep> stepBuilder = ImmutableList.builder();
            foreach (XmlElement stepEl in stepEls)
            {
                LocalDate stepDate  = document.parseDate(stepEl.getChild("stepDate"));
                double    stepValue = document.parseDecimal(stepEl.getChild("stepValue"));
                stepBuilder.add(ValueStep.of(stepDate, ValueAdjustment.ofReplace(stepValue)));
            }
            return(ValueSchedule.builder().initialValue(initialValue).steps(stepBuilder.build()).stepSequence(seq).build());
        }
Exemplo n.º 26
0
        StructType(Program program, StructElement element)
            : base(p)
        {
            super(program, new UserElementMixin(element));

            this.structType = element.type();

            ImmutableList.Builder <Field> fieldsBuilder = ImmutableList.builder();
            for (FieldElement fieldElement : element.fields())
            {
                fieldsBuilder.add(new Field(fieldElement));
            }
            this.fields = fieldsBuilder.build();
        }
Exemplo n.º 27
0
 public static ImmutableList <QuotaByStorageTypeEntry> LoadQuotaByStorageTypeEntries
     (FsImageProto.INodeSection.QuotaByStorageTypeFeatureProto proto)
 {
     ImmutableList.Builder <QuotaByStorageTypeEntry> b = ImmutableList.Builder();
     foreach (FsImageProto.INodeSection.QuotaByStorageTypeEntryProto quotaEntry in proto
              .GetQuotasList())
     {
         StorageType type  = PBHelper.ConvertStorageType(quotaEntry.GetStorageType());
         long        quota = quotaEntry.GetQuota();
         b.Add(new QuotaByStorageTypeEntry.Builder().SetStorageType(type).SetQuota(quota).
               Build());
     }
     return((ImmutableList <QuotaByStorageTypeEntry>)b.Build());
 }
Exemplo n.º 28
0
        //-------------------------------------------------------------------------
        /// <summary>
        /// Converts this schedule to a schedule where all the start and end dates are
        /// adjusted using the specified adjuster.
        /// <para>
        /// The result will have the same number of periods, but each start date and
        /// end date is replaced by the adjusted date as returned by the adjuster.
        /// The unadjusted start date and unadjusted end date of each period will not be changed.
        ///
        /// </para>
        /// </summary>
        /// <param name="adjuster">  the adjuster to use </param>
        /// <returns> the adjusted schedule </returns>
        public Schedule toAdjusted(DateAdjuster adjuster)
        {
            // implementation needs to return 'this' if unchanged to optimize downstream code
            bool adjusted = false;

            ImmutableList.Builder <SchedulePeriod> builder = ImmutableList.builder();
            foreach (SchedulePeriod period in periods)
            {
                SchedulePeriod adjPeriod = period.toAdjusted(adjuster);
                builder.add(adjPeriod);
                adjusted |= (adjPeriod != period);
            }
            return(adjusted ? new Schedule(builder.build(), frequency, rollConvention) : this);
        }
        public ImmutableList <RateAccrualPeriod> createAccrualPeriods(Schedule accrualSchedule, Schedule paymentSchedule, ReferenceData refData)
        {
            // resolve data by schedule
            DoubleArray resolvedGearings = firstNonNull(gearing, ALWAYS_1).resolveValues(accrualSchedule);

            // build accrual periods
            ImmutableList.Builder <RateAccrualPeriod> accrualPeriods = ImmutableList.builder();
            for (int i = 0; i < accrualSchedule.size(); i++)
            {
                SchedulePeriod period = accrualSchedule.getPeriod(i);
                // inflation does not use a day count, so year fraction is 1d
                accrualPeriods.add(new RateAccrualPeriod(period, 1d, createRateComputation(period, i), resolvedGearings.get(i), 0d, NegativeRateMethod.ALLOW_NEGATIVE));
            }
            return(accrualPeriods.build());
        }
Exemplo n.º 30
0
 public ImmutableList <CompressDecompressTester.TesterPair <T, E> > FilterOnAssumeWhat
     (ImmutableList <CompressDecompressTester.TesterPair <T, E> > pairs)
 {
     ImmutableList.Builder <CompressDecompressTester.TesterPair <T, E> > builder = ImmutableList
                                                                                   .Builder();
     foreach (CompressDecompressTester.TesterPair <T, E> pair in pairs)
     {
         if (Org.Apache.Hadoop.IO.Compress.CompressDecompressTester.IsAvailable(pair))
         {
             builder.Add(pair);
         }
     }
     return((ImmutableList <CompressDecompressTester.TesterPair <T, E> >)builder.Build()
            );
 }