protected static List <MarginWeighting> CalculateMarginsWeighting(SensitivityCategory category, Dictionary <String, Decimal> thresholdFactors, List <Sensitivity> sensitivities) { if (sensitivities == null) { throw new ArgumentNullException(nameof(sensitivities)); } if (thresholdFactors == null) { throw new ArgumentNullException(nameof(thresholdFactors)); } List <MarginWeighting> weightingMargins = new List <MarginWeighting>(sensitivities.Count); foreach (Sensitivity sensitivity in sensitivities) { Decimal riskWeight = ModelParameters.GetWeightRisk(category, sensitivity); Decimal thresholdFactor = (sensitivity.Subrisk == SensitivitySubrisk.CrossCurrencyBasis) ? 1m : thresholdFactors[sensitivity.Qualifier]; Amount weightingMarginAmount = sensitivity.Amount * riskWeight * thresholdFactor; weightingMargins.Add(MarginWeighting.Of(sensitivity, weightingMarginAmount)); } return(weightingMargins); }
/// <summary> /// Trains a new model /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='modelParameters'> /// The new model parameters /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <Model> TrainNewModelAsync(this IModels operations, ModelParameters modelParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.TrainNewModelWithHttpMessagesAsync(modelParameters, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
private static Amount CalculateCorrelatedSumBuckets(Currency calculationCurrency, SensitivityRisk risk, List <MarginBucket> bucketMargins) { Dictionary <IBucket, Amount> weightingMarginSums = new Dictionary <IBucket, Amount>(); foreach (MarginBucket bucketMargin in bucketMargins) { Amount weightingMarginsSum = Amount.Sum(bucketMargin.Children.Select(x => x.Value), calculationCurrency); Amount bucketMarginAmount = Amount.Max(Amount.Min(weightingMarginsSum, bucketMargin.Value), -bucketMargin.Value); weightingMarginSums[bucketMargin.Bucket] = bucketMarginAmount; } Amount sum = Amount.OfZero(calculationCurrency); foreach (IBucket bucket1 in weightingMarginSums.Keys) { foreach (IBucket bucket2 in weightingMarginSums.Keys) { if (bucket1 != bucket2) { Decimal correlation = MathUtilities.Square(ModelParameters.GetCorrelationBucket(risk, bucket1, bucket2)); sum += weightingMarginSums[bucket1] * weightingMarginSums[bucket2] * correlation; } } } return(sum); }
private static Amount CalculateCorrelatedSumBuckets(Currency calculationCurrency, SensitivityRisk risk, Dictionary <IBucket, Decimal> thresholdFactors, List <MarginBucket> bucketMargins) { Dictionary <IBucket, Amount> weightingMarginSums = new Dictionary <IBucket, Amount>(); foreach (MarginBucket bucketMargin in bucketMargins) { Amount weightingMarginsSum = Amount.Sum(bucketMargin.Children.Select(x => x.Value), calculationCurrency); Amount bucketMarginValue = Amount.Max(Amount.Min(weightingMarginsSum, bucketMargin.Value), -bucketMargin.Value); weightingMarginSums[bucketMargin.Bucket] = bucketMarginValue; } Amount sum = Amount.OfZero(calculationCurrency); foreach (IBucket bucket1 in weightingMarginSums.Keys) { foreach (IBucket bucket2 in weightingMarginSums.Keys) { if (bucket1 != bucket2) { Decimal thresholdFactor1 = thresholdFactors[bucket1]; Decimal thresholdFactor2 = thresholdFactors[bucket2]; Decimal concentration = Math.Min(thresholdFactor1, thresholdFactor2) / Math.Max(thresholdFactor1, thresholdFactor2); Decimal correlationBucket = ModelParameters.GetCorrelationBucket(risk, bucket1, bucket2); Decimal correlation = correlationBucket * concentration; sum += weightingMarginSums[bucket1] * weightingMarginSums[bucket2] * correlation; } } } return(sum); }
private static Amount CalculateCorrelatedSumWeights(Currency calculationCurrency, SensitivityRisk risk, List <MarginWeighting> weightingMargins, Dictionary <String, Decimal> thresholdFactors) { Amount sum = Amount.OfZero(calculationCurrency); foreach (MarginWeighting marginWeighting1 in weightingMargins) { foreach (MarginWeighting marginWeighting2 in weightingMargins) { Sensitivity sensitivity1 = marginWeighting1.Sensitivity; Sensitivity sensitivity2 = marginWeighting2.Sensitivity; if (sensitivity1 != sensitivity2) { Decimal thresholdFactor1 = thresholdFactors[sensitivity1.Qualifier]; Decimal thresholdFactor2 = thresholdFactors[sensitivity2.Qualifier]; Decimal concentration = Math.Min(thresholdFactor1, thresholdFactor2) / Math.Max(thresholdFactor1, thresholdFactor2); Decimal correlationSensitivity = ModelParameters.GetCorrelationSensitivity(risk, sensitivity1, sensitivity2); Decimal correlation = correlationSensitivity * concentration; sum += marginWeighting1.Value * marginWeighting2.Value * correlation; } } } return(sum); }
public async Task <PageResponse <Manufacturer> > GetAsync(ModelParameters modelParam) { var queryParam = new Dictionary <string, string> { ["pageNumber"] = modelParam.PageNumber.ToString() }; var response = await _client.GetAsync(QueryHelpers.AddQueryString("https://localhost:5011/api/manufacturers", queryParam)); var content = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new ApplicationException(content); } var pageResponse = new PageResponse <Manufacturer> { Items = JsonSerializer.Deserialize <List <Manufacturer> >(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }), PageParameters = JsonSerializer.Deserialize <PageParam>(response.Headers.GetValues("X-Pagination").First(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) }; return(pageResponse); }
/// <summary> /// Валидация параметров /// </summary> public void ValidateParameters() { foreach (ParameterType parameterType in Enum.GetValues(typeof(ParameterType))) { if (!ModelParameters.ContainsKey(parameterType)) { throw new ArgumentException( "Не хватает одного из параметров: " + parameterType); } if (ModelParameters[ParameterType.BerthCount].Value * 60 > ModelParameters[ParameterType.MainPartWidth].Value) { throw new ArgumentException( "Ширина кровати слишком мала для указанного количества спальных мест"); } if (ModelParameters[ParameterType.PersonsHeight].Value + 30 > ModelParameters[ParameterType.MainPartLength].Value) { throw new ArgumentException( "Длина кровати слишком мала для указанного роста человека"); } } }
public async Task <PageList <Manufacturer> > GetAllAsync(ModelParameters modelParameters) { var manufacturers = await _context.Manufacturers.ToListAsync(); return(PageList <Manufacturer> .ToPagedList(manufacturers, modelParameters.PageNumber, modelParameters.PageSize)); }
public async Task <IActionResult> Get([FromQuery] ModelParameters modelParameters) { var cars = await _carRepo.GetAllAsync(modelParameters); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(cars.PageParam)); return(Ok(cars)); }
/// <inheritdoc /> public ServerAnimation(EntityModelRenderer.ModelBone bone, ModelParameters initial, ModelParameters target, TimeSpan duration, bool resetAfter) : base(bone) { Start = initial; Duration = duration.TotalSeconds; Target = target; ResetAfter = resetAfter; _finished = false; }
/// <summary> /// Конструктор класса BuilderModel /// </summary> /// <param name="parameters">Параметры модели грифа</param> /// <param name="kompas">Экзепляр Компас 3Д</param> public BuilderModel(ModelParameters parameters, KompasObject kompas) { //Получение параметров модели грифа _modelelParameters = parameters; //Получение объекта KOMPAS 3D _kompasObject = kompas; //Создание модели грифа CreateModel(); }
public async Task <IActionResult> Cart() { string priceCur = ConstClass.priceCurrency; decimal total = 0; List <ModelCart> list; string token = ""; int?customerId = 0; ModelParameters modelParameters = cache.Get <ModelParameters>("globalParams"); if (modelParameters != null) { token = modelParameters.Token; customerId = modelParameters.CustomerId; } ViewBag.Token = token; ViewBag.CustomerId = customerId; if (localizer != null) { ViewData["Title"] = localizer["Title"].Value; ViewBag.CartTitle = localizer["ShoppingCart"].Value; ViewBag.NotFound = localizer["NotFound"].Value; ViewBag.SubmitOrder = localizer["SubmitOrder"].Value; ViewBag.TotalLabel = localizer["Total"].Value; ViewBag.Name = localizer["Name"].Value; ViewBag.Type = localizer["Type"].Value; ViewBag.Days = localizer["Days"].Value; ViewBag.Duration = localizer["Duration"].Value; ViewBag.Price = localizer["Price"].Value; ViewBag.Delete = localizer["Delete"].Value; } try { using (var context = new ApplicationDbContext()) { ApiCartController cartController = new ApiCartController(localizer); //_repository list = await cartController.Get(token); total = list.Sum(p => p.Price); if (logger != null) { logger.LogInformation("ApiCartController result: {0}", list); } ViewBag.Total = total + " " + priceCur; } return(View(list)); } catch (Exception ex) { logger.LogError(ex.Message + "; " + ex.InnerException); ViewBag.StatusMessage = ex.Message + "<br />" + ex.InnerException; return(View()); } }
/// <summary> /// Creates a ModelConfig from the given ConfigNode /// </summary> /// <param name="node">ConfigNode to get the values from</param> public ModelConfig(ConfigNode node) { node.TryGetValue("name", ref _name); node.TryGetValue("diameter", ref _diameter); node.TryGetValue("count", ref _count); node.TryGetValue("maxDiam", ref _maxDiam); ConfigNode chute = new ConfigNode(); if (node.TryGetNode("MAIN", ref chute)) { _main = new ModelParameters(chute); } if (node.TryGetNode("SECONDARY", ref chute)) { _secondary = new ModelParameters(chute); } }
public ActionResult Log() { ModelParameters param = new ModelParameters { PageName = "Log", Info = "Allows user to log amount" }; return(View(param)); }
public ActionResult Index() { ModelParameters param = new ModelParameters { PageName = "Dashboard", Info = "Shows Dashboard of Amount Logs" }; return(View(param)); }
public ActionResult About() { ModelParameters param = new ModelParameters { PageName = "About", Info = "This app logs your stuff. The end. :p" }; return(View(param)); }
public void Test_CalculationMaxLenghtGrip() { var modelParameters = new ModelParameters(); var Handle = 1100; var expected = Handle; modelParameters.Parameter(ParametersName.HandleLength).Value = Handle; modelParameters.CalculationMaxLenghtGrip(); var actual = modelParameters.Parameter(ParametersName.GripLength).MaxValue; Assert.AreEqual(expected, actual, "Метод CalculationMaxLenghtGrip работает некорректно"); }
public void Test_Parameter() { var modelParameters = new ModelParameters(); var result = true; if (modelParameters.Parameter(ParametersName.HandleLength).MinValue != 890 || modelParameters.Parameter(ParametersName.HandleLength).MaxValue != 1100 || modelParameters.Parameter(ParametersName.HandleLength).Value != 890) { result = false; } Assert.IsTrue(result, "Метод Parameter работает некорректно"); }
public async Task <PageList <Car> > GetAllAsync(ModelParameters modelParameters) { var cars = await _context.Cars .Include(a => a.Manufacturer) .Search(modelParameters.SearchTerm) .Sort(modelParameters.OrderBy) .ToListAsync(); return(PageList <Car> .ToPagedList(cars, modelParameters.PageNumber, modelParameters.PageSize)); }
// ModelParameters의 값을 가져와 모델 종류별 index에 따라 대입 private void UpdateCubismParam(ModelParameters model, ModelInfos.Type type) { cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 0]].Value = model.FaceAngleX; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 1]].Value = model.FaceAngleY; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 2]].Value = model.FaceAngleZ; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 3]].Value = model.LEyeOpen; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 4]].Value = model.REyeOpen; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 5]].Value = model.EyeDirX; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 6]].Value = model.EyeDirY; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 7]].Value = model.LEyebrowHeight; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 8]].Value = model.REyebrowHeight; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 9]].Value = model.MouthOpen; cubismModel.Parameters[ModelInfos.paramIndices[(int)type, 10]].Value = model.MouthForm; }
private void cacheData(string token, int customerId) { int?expireTime = 60; MemoryCacheEntryOptions options = new MemoryCacheEntryOptions(); options.AbsoluteExpiration = DateTime.Now.AddMinutes(expireTime.Value); options.SlidingExpiration = TimeSpan.FromMinutes(expireTime.Value); ModelParameters model = new ModelParameters(); model.Token = token; model.CustomerId = customerId; cache.Set("globalParams", model, options); }
public override MarginSensitivity CalculateMargin(Currency calculationCurrency, FxRatesProvider ratesProvider, SensitivityRisk risk, SensitivityCategory category, List <Sensitivity> sensitivities) { if (calculationCurrency == null) { throw new ArgumentNullException(nameof(calculationCurrency)); } if (ratesProvider == null) { throw new ArgumentNullException(nameof(ratesProvider)); } if (!Enum.IsDefined(typeof(SensitivityRisk), risk)) { throw new InvalidEnumArgumentException("Invalid sensitivity risk specified."); } if (!Enum.IsDefined(typeof(SensitivityCategory), category)) { throw new InvalidEnumArgumentException("Invalid sensitivity category specified."); } if (sensitivities == null) { throw new ArgumentNullException(nameof(sensitivities)); } List <IBucket> buckets = sensitivities.Select(x => x.Bucket).Distinct().OrderBy(x => x.Name).ToList(); List <MarginBucket> bucketMargins = new List <MarginBucket>(buckets.Count); foreach (IBucket bucket in buckets) { List <Sensitivity> sensitivitiesByBucket = sensitivities.Where(x => x.Bucket == bucket).ToList(); List <MarginWeighting> weightingMargins = CalculateMarginsWeighting(SensitivityCategory.Curvature, sensitivitiesByBucket); Amount sumSquared = Amount.Sum(weightingMargins.Select(x => Amount.Square(x.Value)), calculationCurrency); Amount sumCorrelated = CalculateCorrelatedSumWeights(calculationCurrency, risk, weightingMargins); Amount bucketMarginAmount = Amount.SquareRoot(sumSquared + sumCorrelated); bucketMargins.Add(MarginBucket.Of(bucket, bucketMarginAmount, weightingMargins)); } Amount marginNonResidual = CalculateMarginByBuckets(calculationCurrency, risk, false, bucketMargins); Amount marginResidual = CalculateMarginByBuckets(calculationCurrency, risk, true, bucketMargins); Amount sensitivityMarginAmount = ModelParameters.GetCurvatureScaleFactor(risk) * (marginNonResidual + marginResidual); return(MarginSensitivity.Of(SensitivityCategory.Curvature, sensitivityMarginAmount, bucketMargins)); }
public static Amount CalculateCurvatureAmount(Sensitivity sensitivity) { if (sensitivity == null) { throw new ArgumentNullException(nameof(sensitivity)); } if (sensitivity.Category != SensitivityCategory.Vega) { throw new ArgumentException("Invalid sensitivity specified.", nameof(sensitivity)); } Decimal days = sensitivity.Tenor.Days; Decimal scaledDays = ModelParameters.GetCurvatureScaledDays(days); return(sensitivity.Amount * scaledDays); }
// 传入DataRow,将其转换为ModelParameters private ModelParameters toModel(DataRow dr) { ModelParameters model = new ModelParameters(); //通过循环为ModelParameters赋值,其中为数据值为空时,DateTime类型的空值为:0001/1/1 0:00:00 int类型得空值为: 0,其余的还没试验 foreach (PropertyInfo propertyInfo in typeof(ModelParameters).GetProperties()) { //如果数据库的字段为空,跳过其赋值 if (dr[propertyInfo.Name].ToString() == "") { continue; } //赋值 model.GetType().GetProperty(propertyInfo.Name).SetValue(model, dr[propertyInfo.Name], null); } return(model); }
/// <summary> /// Creates a ModelConfig from the given ConfigNode /// </summary> /// <param name="node">ConfigNode to get the values from</param> public ModelConfig(ConfigNode node) { node.TryGetValue("name", ref _name); node.TryGetValue("diameter", ref _diameter); node.TryGetValue("count", ref _count); node.TryGetValue("maxDiam", ref _maxDiam); ConfigNode chute = new ConfigNode(); if (node.TryGetNode("MAIN", ref chute)) { _main = new ModelParameters(chute); } if (node.TryGetNode("SECONDARY", ref chute)) { _secondary = new ModelParameters(chute); } }
public void Diffuse() { var id = (ModelParameters.ModelTypeIndex + rand.Next(ModelRepository.PrototypeCount)) % ModelRepository.PrototypeCount; ModelParameters.ModelTypeIndex = id; var angle = ModelParameters.Angle + rand.Next(-15, +15 + 1); ModelParameters.Angle = (short)angle; var scale = ModelParameters.Scale + rand.Next(-15, +15 + 1); ModelParameters.Scale = (short)scale; ModelParameters = ModelRepository.GetMostSimilarTo(ModelParameters); var template = ModelParameters.TryGetTemplate(); this.updateTemplateData(template); }
protected static List <MarginWeighting> CalculateMarginsWeighting(SensitivityCategory category, List <Sensitivity> sensitivities) { if (sensitivities == null) { throw new ArgumentNullException(nameof(sensitivities)); } List <MarginWeighting> weightingMargins = new List <MarginWeighting>(sensitivities.Count); foreach (Sensitivity sensitivity in sensitivities) { Decimal riskWeight = ModelParameters.GetWeightRisk(category, sensitivity); Amount weightingMarginAmount = sensitivity.Amount * riskWeight; weightingMargins.Add(MarginWeighting.Of(sensitivity, weightingMarginAmount)); } return(weightingMargins); }
private static Decimal CalculateThresholdFactor(Currency calculationCurrency, FxRatesProvider ratesProvider, SensitivityRisk risk, SensitivityCategory category, List <Sensitivity> sensitivities) { if ((risk == SensitivityRisk.Rates) && (category == SensitivityCategory.Delta)) { sensitivities = sensitivities.Where(x => x.Subrisk != SensitivitySubrisk.CrossCurrencyBasis).ToList(); if (sensitivities.Count == 0) { return(1m); } } Amount sum = Amount.Abs(Amount.Sum(sensitivities.Select(x => x.Amount), calculationCurrency)); IThresholdIdentifier thresholdIdentifier = sensitivities.Select(y => y.ThresholdIdentifier).Distinct().Single(); Amount threshold = ratesProvider.Convert(ModelParameters.GetThreshold(risk, category, thresholdIdentifier), calculationCurrency); return(Math.Max(1m, MathUtilities.SquareRoot((sum / threshold).Value))); }
public UnitTestOrderController() { Token t = new Token(); token = t.CreateToken(); int customerId = 1; ModelParameters model = new ModelParameters(); model.Token = token; model.CustomerId = customerId; var services = new ServiceCollection(); services.AddMemoryCache(); var serviceProvider = services.BuildServiceProvider(); memoryCache = serviceProvider.GetService <IMemoryCache>(); memoryCache.Set("globalParams", model); }
private static Amount CalculateCorrelatedSumRisks(Currency calculationCurrency, List <MarginRisk> riskMargins) { Amount sum = Amount.OfZero(calculationCurrency); foreach (MarginRisk marginRisk1 in riskMargins) { foreach (MarginRisk marginRisk2 in riskMargins) { SensitivityRisk risk1 = marginRisk1.Risk; SensitivityRisk risk2 = marginRisk2.Risk; if (risk1 != risk2) { Decimal correlation = ModelParameters.GetCorrelationRisk(risk1, risk2); sum += marginRisk1.Value * marginRisk2.Value * correlation; } } } return(sum); }
private static Amount CalculateCorrelatedSumWeights(Currency calculationCurrency, SensitivityRisk risk, List <MarginWeighting> weightingMargins) { Amount sum = Amount.OfZero(calculationCurrency); foreach (MarginWeighting marginWeighting1 in weightingMargins) { foreach (MarginWeighting marginWeighting2 in weightingMargins) { Sensitivity sensitivity1 = marginWeighting1.Sensitivity; Sensitivity sensitivity2 = marginWeighting2.Sensitivity; if (sensitivity1 != sensitivity2) { Decimal correlation = MathUtilities.Square(ModelParameters.GetCorrelationSensitivity(risk, sensitivity1, sensitivity2)); sum += marginWeighting1.Value * marginWeighting2.Value * correlation; } } } return(sum); }
protected ModelParameters DetermineParameters(ModelAction action) { try { ModelParameters allparameters = action.Parameters; ModelParameters choosen = new ModelParameters(); //Loop through the method parameters foreach(ParameterInfo info in action.Method.GetParameters()) { //Find the all parameters assoicated with this param ModelParameters parameters = allparameters.Find(info.Name); //Exclude invalid parameters (if not requested) if(!this.InvalidParameters) parameters = (ModelParameters)parameters.FindFlag((int)ModelItemFlags.Throws, false); if(parameters.Count <= 0) throw new ModelException(this, "Unable to find a ModelParameter for method parameter: '" + info.Name + "'"); //Choose one of the parameters, based upon weight ModelParameter parameter = parameters.Choose(this); parameter.Accessed++; //Note: We cloning the param, since were choosing only one of the values to use this time. parameter = (ModelParameter)parameter.Clone(); //Choose (or generate) one of the values ModelValue value = DetermineParameterValue(parameter); value.Accessed++; //Add it to the array parameter.Value = value; choosen.Add(parameter); } return choosen; } catch(Exception e) { //Make this easier to debug throw new ModelException(this, "DetermineParameters", e); } }