Ejemplo n.º 1
0
        private static double correct(bool unbiased, WeightType weightType, double sum, double weightSum, double squareSum)
        {
            if (unbiased)
            {
                if (weightType == WeightType.Automatic)
                {
                    if (weightSum > 1 && weightSum.IsInteger(1e-8))
                    {
                        return(sum / (weightSum - 1));
                    }

                    return(sum / (weightSum - (squareSum / weightSum)));
                }
                else if (weightType == WeightType.Fraction)
                {
                    /*
                     * if (Math.Abs(weightSum - 1.0) >= 1e-8)
                     * {
                     *  throw new ArgumentException("An unbiased variance estimate"
                     + " cannot be computed if weights do not sum to one. The"
                     + " given weights sum up to " + squareSum, "weights");
                     + }*/

                    return(sum / (weightSum - (squareSum / weightSum)));
                }
                else if (weightType == WeightType.Repetition)
                {
                    return(sum / (weightSum - (squareSum / weightSum)));
                }
            }

            return(sum / weightSum);
        }
Ejemplo n.º 2
0
        public bool readWeightTest(Behavior behavior)
        {
            _jetTestConnection = new TestJetbusConnection(behavior, ipaddress, "Administrator", "wtx", delegate { return(true); });

            _dseObj = new DSEJet(_jetTestConnection, 100, update);

            _dseObj.Connect(this.OnConnect, 100);

            _dseObj.ProcessData.UpdateData(this, new EventArgs());

            double expGross = 413.96;
            double expNet   = 463.96;
            double expTare  = 50;

            WeightType readWeight = _dseObj.Weight;

            if (readWeight.Gross == expGross && readWeight.Net == expNet && readWeight.Tare == expTare)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 3
0
 public void Clear()
 {
     f      = g = h = 0;
     type   = GridType.Map;
     parent = null;
     weight = WeightType.Level0;
 }
Ejemplo n.º 4
0
        /// <summary>
        /// 发送数据到U9
        /// </summary>
        /// <param name="count">扎数</param>
        /// <param name="Weight">重量</param>
        /// <param name="ExtensionField2">堆位</param>
        /// <param name="ExtensionField3">过磅单号</param>
        /// <param name="ShipmentNumber">采购单</param>
        /// <param name="DepartmentCode">部门代码</param>
        public static bool sendDate(int count, double Weight, string ExtensionField2, string ExtensionField3, string ShipmentNumber, string DepartmentCode)
        {
            try
            {
                LWU9WebReference.LooseWastePaperManagement_v001 lw = new EMEWEQUALITY.LWU9WebReference.LooseWastePaperManagement_v001();

                string OrganizationID = Common.OrganizationID;//公司代号
                LoosePaperTruckLoadU9Type TruckLoad = new LoosePaperTruckLoadU9Type();
                WeightType wt = new WeightType();
                wt.Value = Convert.ToDecimal(Weight);
                WeightUnitType wut = WeightUnitType.kg;

                Weight                        = (double)Weight / (double)1000;
                TruckLoad.Count               = count;           //扎数
                TruckLoad.Weight              = Weight;          //重量
                TruckLoad.ExtensionField2     = ExtensionField2; //堆位
                TruckLoad.ExtensionField3     = ExtensionField3; //过磅单号
                TruckLoad.WorkshopMachineID   = "201311111111";
                TruckLoad.DepartmentCode      = DepartmentCode;  //部门代码
                TruckLoad.BusinessDate        = DateTime.Now;
                TruckLoad.TruckLoadDocumentID = "10";

                RequestHeaderType rht = new RequestHeaderType();
                rht.SourceID     = Common.SourceID;
                lw.Url           = Common.SendURL;
                lw.RequestHeader = rht;//数据源(发起请求应用名)
                LoosePaperContainerShareU9Type[] Distribution = new LoosePaperContainerShareU9Type[1];
                LoosePaperContainerShareU9Type   lpc          = new LoosePaperContainerShareU9Type();
                //必填
                lpc.ContainerID                      = "30";
                lpc.IsGettingShare                   = true;
                lpc.PONumber                         = "20";
                lpc.ShipmentNumber                   = ShipmentNumber;//采购单
                lpc.UnloadPlatform                   = "备注";
                lpc.Memo                             = "20.质检纸";
                lpc.TypeOfWeighedWastePaper          = TypeOfWeighedWastePaperType.BaleLocal;//纸种
                lpc.TypeOfWeighedWastePaperSpecified = true;

                Distribution[0] = lpc;
                string DistributionMemo = "cs1";

                System.Xml.XmlAttribute[] AnyAttr = new System.Xml.XmlAttribute[0];
                lpc.AnyAttr = AnyAttr;

                ReplyMessageType message = lw.RegisterLoosePaperDistribution(OrganizationID, TruckLoad, DistributionMemo, Distribution, AnyAttr);
                if (message.ResultCode.ToString() == "Successful")
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
Ejemplo n.º 5
0
    public void ClickClean()
    {
        startX = startY = targetX = targetY = 0;
        alpha  = 0;
        openList.Clear();
        closeList.Clear();
        parentList.Clear();

        startGrid = null;
        endGrid   = null;
        startRect = null;
        endRect   = null;
        curType   = GridType.Map;
        curColor  = typeColor[(int)WeightType.Level0];
        curWeight = WeightType.Level0;

        for (int x = 0; x < row; x++)
        {
            for (int y = 0; y < colomn; y++)
            {
                grids[x, y].Clear();
                grids[x, y].weight     = (WeightType)MapData[x, y];
                objs[x, y].image.color = typeColor[MapData[x, y]];
            }
        }
        Debug.Log("Clean");
    }
        public int Update(int templateNo, string templateName, WeightType weightType, ReplaceType replaceType, int futuresCopies, double marketCapOpt, string benchmarkId, int userId)
        {
            var dbCommand = _dbHelper.GetStoredProcCommand(SP_Modify);

            _dbHelper.AddInParameter(dbCommand, "@TemplateId", System.Data.DbType.Int32, templateNo);
            _dbHelper.AddInParameter(dbCommand, "@TemplateName", System.Data.DbType.String, templateName);
            _dbHelper.AddInParameter(dbCommand, "@Status", System.Data.DbType.Int32, (int)TemplateStatus.Normal);
            _dbHelper.AddInParameter(dbCommand, "@WeightType", System.Data.DbType.Int32, (int)weightType);
            _dbHelper.AddInParameter(dbCommand, "@ReplaceType", System.Data.DbType.Int32, (int)replaceType);
            _dbHelper.AddInParameter(dbCommand, "@FuturesCopies", System.Data.DbType.Int32, futuresCopies);
            _dbHelper.AddInParameter(dbCommand, "@MarketCapOpt", System.Data.DbType.Decimal, marketCapOpt);
            _dbHelper.AddInParameter(dbCommand, "@BenchmarkId", System.Data.DbType.String, benchmarkId);
            _dbHelper.AddInParameter(dbCommand, "@ModifiedDate", System.Data.DbType.DateTime, DateTime.Now);
            _dbHelper.AddInParameter(dbCommand, "@CreatedUserId", System.Data.DbType.Int32, userId);

            _dbHelper.AddReturnParameter(dbCommand, "@return", System.Data.DbType.Int32);

            int ret        = _dbHelper.ExecuteNonQuery(dbCommand);
            int templateId = -1;

            if (ret > 0)
            {
                templateId = (int)dbCommand.Parameters["@return"].Value;
            }
            return(templateId);
        }
Ejemplo n.º 7
0
            public void AddWeights(params WeightType[] additionalWeights)
            {
                WeightType[] newWeights = new WeightType[this.weights.Length + additionalWeights.Length];

                this.weights.CopyTo(newWeights, 0);
                additionalWeights.CopyTo(newWeights, this.weights.Length);

                this.SetWeights(newWeights);
            }
        public IActionResult Create(int year, string month, int day, int foodId, int mealId)
        {
            // TODO PARSE TRY
            var date = new DateTime(year, int.Parse(month), day);

            ViewData["Date"] = date;

            Food food = _calendarDatabase.Foods.Find(foodId);
            Meal meal = _calendarDatabase.Meals.Find(mealId);

            if (food == null || meal == null)
            {
                TempData["Error"] = "Wrong input";
                return(Redirect(
                           string.Format("/calendarFood/add/{0}/{1}/{2}/{3}",
                                         year, month, day, mealId)));
            }

            // check if already exist and then update it
            CalendarFoodItem foodItem = _calendarDatabase.FoodItems.Where(cfi => cfi.CalendarDate.Date == date.Date && cfi.Meal.MealID == mealId && cfi.Food.FoodID == food.FoodID).SingleOrDefault();

            string     GramUnitName = "gram";
            WeightType gram         = _calendarDatabase.WeightTypes.Where(wt => wt.UnitName == GramUnitName).FirstOrDefault();

            if (foodItem == null)
            {
                foodItem = new CalendarFoodItem()
                {
                    Food         = food,
                    Meal         = meal,
                    Weight       = decimal.ToInt32(food.Weight),
                    CalendarDate = date
                };

                _calendarDatabase.FoodItems.Add(foodItem);
            }
            else
            {
                foodItem.Weight += decimal.ToInt32(food.Weight);
            }

            _calendarDatabase.SaveChanges();

            TempData["Success"] = "Created.";

            return(Redirect(
                       string.Format("/calendarFood/add/{0}/{1}/{2}/{3}",
                                     year, month, day, mealId)));
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Assigns measurement and measurement type.
 /// </summary>
 /// <param name="measurement"></param>
 /// <param name="measurementType"></param>
 internal void AssignMeasurement(double?measurement, WeightType measurementType)
 {
     if (measurement.HasValue)
     {
         //A non null value is being assigned for this type
         _measurement     = measurement;
         _measurementType = measurementType;
     }
     else if ((measurement.HasValue == false) && (_measurementType == measurementType))
     {
         //The measurements are being cleared.
         _measurement     = null;
         _measurementType = null;
     }
 }
        private void initialize(IDensityKernel kernel, double[][] observations,
                                double[] weights, int[] repeats, double[,] smoothing)
        {
            if (smoothing == null)
            {
                smoothing = SilvermanRule(observations, weights, repeats);
            }

            if (kernel == null)
            {
                kernel = new GaussianKernel(Dimension);
            }

            this.kernel      = kernel;
            this.samples     = observations;
            this.smoothing   = smoothing;
            this.determinant = smoothing.Determinant();

            this.weights = weights;
            this.repeats = repeats;

            this.chol = new CholeskyDecomposition(smoothing);


            if (weights != null)
            {
                this.type            = WeightType.Fraction;
                this.numberOfSamples = samples.Length;
                this.sumOfWeights    = weights.Sum();
            }
            else if (repeats != null)
            {
                this.type            = WeightType.Repetition;
                this.numberOfSamples = repeats.Sum();
                this.sumOfWeights    = 1.0;
            }
            else
            {
                this.type            = WeightType.None;
                this.numberOfSamples = samples.Length;
                this.sumOfWeights    = 1.0;
            }

            this.mean       = null;
            this.variance   = null;
            this.covariance = null;
        }
Ejemplo n.º 11
0
        public static void ConvertToPounds(double weight, WeightType type)
        {
            switch (type)
            {
            case WeightType.GRAM:
            {
                double pounds = weight * 2.20462d;
                double ounces = pounds - Math.Floor(pounds);
                pounds -= ounces;
                ounces *= 16;
                Console.WriteLine("{0} lbs and {1} oz.", pounds, ounces);
                break;
            }

            default:
                throw new Exception("Weight type not supported");
            }
        }
Ejemplo n.º 12
0
        public static string GetWeightType(WeightType weightType)
        {
            string weightTypeName = string.Empty;

            switch (weightType)
            {
            case WeightType.ProportionalWeight:
                weightTypeName = "比例权重";
                break;

            case WeightType.AmountWeight:
                weightTypeName = "数量权重";
                break;

            default:
                break;
            }

            return(weightTypeName);
        }
Ejemplo n.º 13
0
        private void initialize(double[] observations, double[] weights, int[] repeats, double?smoothing)
        {
            if (smoothing == null)
            {
                smoothing = SmoothingRule(observations, weights, repeats);
            }

            this.samples   = observations;
            this.weights   = weights;
            this.repeats   = repeats;
            this.smoothing = smoothing.Value;


            if (weights != null)
            {
                this.type            = WeightType.Fraction;
                this.numberOfSamples = samples.Length;
                this.sumOfWeights    = weights.Sum();
                this.constant        = 1.0 / (Constants.Sqrt2PI * this.smoothing);
            }
            else if (repeats != null)
            {
                this.type            = WeightType.Repetition;
                this.numberOfSamples = repeats.Sum();
                this.sumOfWeights    = 1.0;
                this.constant        = 1.0 / (Constants.Sqrt2PI * this.smoothing * numberOfSamples);
            }
            else
            {
                this.type            = WeightType.None;
                this.numberOfSamples = samples.Length;
                this.sumOfWeights    = 1.0;
                this.constant        = 1.0 / (Constants.Sqrt2PI * this.smoothing * numberOfSamples);
            }


            this.mean     = null;
            this.variance = null;
        }
Ejemplo n.º 14
0
        public static WeightModel Create(WeightType weightType)
        {
            switch (weightType)
            {
            case WeightType.ExtraSmall:
                return(new WeightModel(0, 1));

            case WeightType.Small:
                return(new WeightModel(1, 5));

            case WeightType.Medium:
                return(new WeightModel(5, 15));

            case WeightType.Large:
                return(new WeightModel(15, 30));

            case WeightType.ExtraLarge:
                return(new WeightModel(30, float.MaxValue));

            default:
                return(null);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Defines the target font waght.
        /// </summary>
        /// <param name="weight"></param>
        public FontWeightAttribute(WeightType weight)
        {
            switch (weight)
            {
            case WeightType.Thin: Weight = FontWeights.Thin; return;

            case WeightType.ExtraLight: Weight = FontWeights.ExtraLight; return;

            case WeightType.UltraLight: Weight = FontWeights.UltraLight; return;

            case WeightType.Light: Weight = FontWeights.Light; return;

            case WeightType.Normal: Weight = FontWeights.Normal; return;

            case WeightType.Regular: Weight = FontWeights.Regular; return;

            case WeightType.Medium: Weight = FontWeights.Medium; return;

            case WeightType.DemiBold: Weight = FontWeights.DemiBold; return;

            case WeightType.SemiBold: Weight = FontWeights.SemiBold; return;

            case WeightType.Bold: Weight = FontWeights.Bold; return;

            case WeightType.ExtraBold: Weight = FontWeights.ExtraBold; return;

            case WeightType.UltraBold: Weight = FontWeights.UltraBold; return;

            case WeightType.Black: Weight = FontWeights.Black; return;

            case WeightType.Heavy: Weight = FontWeights.Heavy; return;

            case WeightType.ExtraBlack: Weight = FontWeights.ExtraBlack; return;

            case WeightType.UltraBlack: Weight = FontWeights.UltraBlack; return;
            }
        }
Ejemplo n.º 16
0
        static void Main()
        {
            try
            {
                FreightRateService freightRateService = new FreightRateService();
                FreightRateRequest freightRateRequest = new FreightRateRequest();
                RequestType        request            = new RequestType();
                String[]           requestOption      = { "RateChecking Option" };
                request.RequestOption      = requestOption;
                freightRateRequest.Request = request;

                /** ****************ShipFrom******************************* */
                ShipFromType shipFrom             = new ShipFromType();
                AddressType  shipFromAddress      = new AddressType();
                String[]     shipFromAddressLines = { "ShipFrom address" };
                shipFromAddress.AddressLine       = shipFromAddressLines;
                shipFromAddress.City              = "ShipFrom city";
                shipFromAddress.StateProvinceCode = "ShipFrom state province code";
                shipFromAddress.PostalCode        = "ShipFrom postal code";
                shipFromAddress.CountryCode       = "ShipFrom country code";
                shipFrom.Address            = shipFromAddress;
                shipFrom.AttentionName      = "ShipFrom attention name";
                shipFrom.Name               = "ShipFrom Name";
                freightRateRequest.ShipFrom = shipFrom;
                /** ****************ShipFrom******************************* */

                /** ****************ShipTo*************************************** */
                ShipToType  shipTo             = new ShipToType();
                AddressType shipToAddress      = new AddressType();
                String[]    shipToAddressLines = { "ShipTo address line" };
                shipToAddress.AddressLine       = shipToAddressLines;
                shipToAddress.City              = "ShipTo city";
                shipToAddress.StateProvinceCode = "ShipTo state province code";
                shipToAddress.PostalCode        = "ShipTo postal code";
                shipToAddress.CountryCode       = "ShipTo country code";
                shipTo.Address            = shipToAddress;
                shipTo.AttentionName      = "ShipTo attention name";
                shipTo.Name               = "ShipTo Name";
                freightRateRequest.ShipTo = shipTo;
                /** ****************ShipTo*************************************** */

                /** ***************PaymentInformationType************************* */
                PaymentInformationType paymentInfo = new PaymentInformationType();
                PayerType payer = new PayerType();
                payer.AttentionName = "Payer attention name";
                payer.Name          = "Payer name";
                payer.ShipperNumber = "Payer shipper number";
                AddressType payerAddress      = new AddressType();
                String[]    payerAddressLines = { "Payer address line" };
                payerAddress.AddressLine       = payerAddressLines;
                payerAddress.City              = "Payer city";
                payerAddress.StateProvinceCode = "Payer state province code";
                payerAddress.PostalCode        = "Payer postal code";
                payerAddress.CountryCode       = "Payer country code";
                payer.Address     = payerAddress;
                paymentInfo.Payer = payer;
                RateCodeDescriptionType shipBillOption = new RateCodeDescriptionType();
                shipBillOption.Code                   = "Ship bill option";
                shipBillOption.Description            = "Ship bill description";
                paymentInfo.ShipmentBillingOption     = shipBillOption;
                freightRateRequest.PaymentInformation = paymentInfo;
                /** ***************PaymentInformationType************************* */

                //Below code use dummy data for referenced. Please update as required


                /** ***************Service************************************** */
                RateCodeDescriptionType service = new RateCodeDescriptionType();
                service.Code               = "309";
                service.Description        = "UPS Ground Freight";
                freightRateRequest.Service = service;
                /** ***************Service************************************** */


                /** **************Commodity************************************* */
                CommodityType      commodity = new CommodityType();
                CommodityValueType commValue = new CommodityValueType();
                commValue.CurrencyCode   = "USD";
                commValue.MonetaryValue  = "5670";
                commodity.CommodityValue = commValue;
                commodity.NumberOfPieces = "20";

                RateCodeDescriptionType packagingType = new RateCodeDescriptionType();
                packagingType.Code        = "BAG";
                packagingType.Description = "BAG";
                commodity.PackagingType   = packagingType;
                WeightType            weight            = new WeightType();
                UnitOfMeasurementType unitOfMeasurement = new UnitOfMeasurementType();
                unitOfMeasurement.Code        = "LBS";
                unitOfMeasurement.Description = "Pounds";
                weight.UnitOfMeasurement      = unitOfMeasurement;
                weight.Value          = "200";
                commodity.Weight      = weight;
                commodity.Description = "LCD TVS";

                CommodityValueType commodityValue = new CommodityValueType();
                commodityValue.CurrencyCode  = "USD";
                commodityValue.MonetaryValue = "100";
                commodity.CommodityValue     = commodityValue;
                commodity.Description        = "LCD TVS";
                commodity.FreightClass       = "60";
                CommodityType[] commodityArray = { commodity };
                freightRateRequest.Commodity = commodityArray;
                /** **************Commodity************************************* */


                /** **************HandlingUnitOne************************************* */
                HandlingUnitType handUnitType = new HandlingUnitType();
                handUnitType.Quantity = "1";
                RateCodeDescriptionType rateCodeDescType = new RateCodeDescriptionType();
                rateCodeDescType.Code              = "SKD";
                rateCodeDescType.Description       = "SKID";
                handUnitType.Type                  = rateCodeDescType;
                freightRateRequest.HandlingUnitOne = handUnitType;

                /** **************HandlingUnitOne************************************* */


                UPSSecurity upss = new UPSSecurity();
                UPSSecurityServiceAccessToken upsSvcToken = new UPSSecurityServiceAccessToken();
                upsSvcToken.AccessLicenseNumber = "Your License Number";
                upss.ServiceAccessToken         = upsSvcToken;
                UPSSecurityUsernameToken upsSecUsrnameToken = new UPSSecurityUsernameToken();
                upsSecUsrnameToken.Username         = "******";
                upsSecUsrnameToken.Password         = "******";
                upss.UsernameToken                  = upsSecUsrnameToken;
                freightRateService.UPSSecurityValue = upss;

                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
                Console.WriteLine(freightRateRequest);
                FreightRateResponse freightRateResponse = freightRateService.ProcessFreightRate(freightRateRequest);
                Console.WriteLine("Response code: " + freightRateResponse.Response.ResponseStatus.Code);
                Console.WriteLine("Response description: " + freightRateResponse.Response.ResponseStatus.Description);
                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("---------Freight Rate Web Service returns error----------------");
                Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
                Console.WriteLine("SoapException Message= " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
                Console.WriteLine("");
                Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
                Console.WriteLine("");
                Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("--------------------");
                Console.WriteLine("CommunicationException= " + ex.Message);
                Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" General Exception= " + ex.Message);
                Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
            }
            finally
            {
                Console.ReadKey();
            }
        }
Ejemplo n.º 17
0
 public float GetWeight(WeightType t)
 {
     return(_weights[(int)t]);
 }
Ejemplo n.º 18
0
 public void SetWeight(WeightType t, float value)
 {
     _weights[(int)t] = value;
 }
Ejemplo n.º 19
0
 public static double Convert(double value, WeightType fromUnits, WeightType toUnits)
 {
     //Code here to convert units
 }
Ejemplo n.º 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dimensionality">Dimensionality (N) of the problem</param>
        /// <param name="maxgen">Maximum number of generations that the system will run (needed for damping)</param>
        /// <param name="lambda">Number of offspring</param>
        /// <param name="mu">PopulationSize</param>
        /// <param name="weightType">Weighting scheme (for 'selection'): logarithmic, equal, linear</param>
        /// <param name="minSDs">minimum stdevs, last one will apply for all remaining axes</param>
        /// <param name="initialSDs">initial stdevs, last one will apply for all remaining axes</param>
        public CMAParams(
            int dimensionality,
            int maxgen,
            int lambda,
            int mu,
            double[] minSDs,
            double[] initialSDs,
            WeightType weightType = WeightType.Logarithmic)
        {
            N = dimensionality;

            MaxGen = maxgen;

            if (lambda < 2)
            {
                this.Lambda = 4 + (int)(3.0 * Math.Log((double)N));
            }
            else
            {
                this.Lambda = (int)lambda;
            }

            _weightType = weightType;

            if ((mu >= Lambda) || (mu < 1))
            {
                Mu = (int)Math.Floor(Lambda / 2.0);
            }
            else
            {
                Mu = (int)mu;
            }

            Weights = new double[Mu];

            switch (weightType)
            {
            case WeightType.Equal:
                for (int i = 0; i < Weights.Length; ++i)
                {
                    Weights[i] = Mu - i;
                }

                break;

            case WeightType.Linear:
                Weights = Weights.Select(x => 1.0).ToArray();

                break;

            case WeightType.Logarithmic:
            case WeightType.NotSet:
            default:

                for (int i = 0; i < Weights.Length; ++i)
                {
                    Weights[i] = Math.Log(Mu + 1.0) - Math.Log(i + 1.0);
                }

                break;
            }


            /* Normalize weights and set mu_eff */
            double sumw = Weights.Sum();

            MuEff   = sumw * sumw / Weights.Sum(x => x * x);
            Weights = Weights.Select(x => x / sumw).ToArray();

            /* set the others using Nikolaus logic. If you want to tweak, you can parameterize over these defaults */
            MuCov   = MuEff;
            CCumSig = (MuEff + 2.0) / (N + MuEff + 3.0);
            CCumCov = 4.0 / (N + 4);

            double t1 = 2.0 / ((N + 1.4142) * (N + 1.4142));
            double t2 = (2.0 * MuCov - 1.0) / ((N + 2.0) * (N + 2.0) + MuCov);

            t2 = (t2 > 1) ? 1 : t2;
            t2 = (1.0 / MuCov) * t1 + (1.0 - 1.0 / MuCov) * t2;

            CCov = t2;

            Damp = 1 + Math.Max(0.3, (1.0 - (double)N / (double)maxgen))
                   * (1.0 + 2.0 * Math.Max(0.0, Math.Sqrt((MuEff - 1.0) / (N + 1.0)) - 1.0))              /* limit sigma increase */
                   / CCumSig;

            if (minSDs == null)
            {
                minSDs = new double[N];
                for (int i = 0; i < N; i++)
                {
                    minSDs[i] = 0.0;
                }
            }

            if (initialSDs == null)
            {
                initialSDs = new double[N];
                for (int i = 0; i < N; i++)
                {
                    initialSDs[i] = 0.3;
                }
            }

            MinStdDevs     = minSDs;
            InitialStdDevs = initialSDs;
        }
Ejemplo n.º 21
0
 public VertexKey ownerID;//边的拥有者ID
 public Edge(VertexKey ownerID, VertexKey targetID, WeightType weight) : base(targetID, weight)
 {
     this.ownerID = ownerID;
 }
Ejemplo n.º 22
0
        private CommodityType WriteSingleCommidityPackage(IShippable pak, bool ignoreDimensions)
        {
            decimal dGirth  = 0;
            decimal dLength = 0;
            decimal dHeight = 0;
            decimal dwidth  = 0;

            CommodityType      commodity = new CommodityType();
            CommodityValueType commValue = new CommodityValueType();

            commodity.NumberOfPieces = pak.QuantityOfItemsInBox.ToString();

            RateCodeDescriptionType packagingType = new RateCodeDescriptionType();

            packagingType.Code        = ((int)GlobalSettings.DefaultPackaging).ToString();
            packagingType.Description = GlobalSettings.DefaultPackaging.ToString();
            commodity.PackagingType   = packagingType;

            WeightType            weight            = new WeightType();
            UnitOfMeasurementType unitOfMeasurement = new UnitOfMeasurementType();

            unitOfMeasurement.Code        = (pak.BoxWeightType == Hotcakes.Shipping.WeightType.Pounds ? "LBS" : "KGS");
            unitOfMeasurement.Description = (pak.BoxWeightType == Hotcakes.Shipping.WeightType.Pounds ? "LBS" : "KGS");

            weight.UnitOfMeasurement = unitOfMeasurement;
            if (pak.BoxWeight > 0)
            {
                weight.Value = Math.Round(pak.BoxWeight, 1).ToString();
            }
            else
            {
                weight.Value = "1";
            }

            commodity.Weight       = weight;
            commodity.Description  = "Weight";
            commodity.FreightClass = GlobalSettings.FreightClass;


            var dimensions = new List <DimensionAmount>();

            if (pak.BoxLengthType == LengthType.Centimeters)
            {
                dimensions.Add(new DimensionAmount(Conversions.CentimetersToInches(pak.BoxLength)));
                dimensions.Add(new DimensionAmount(Conversions.CentimetersToInches(pak.BoxWidth)));
                dimensions.Add(new DimensionAmount(Conversions.CentimetersToInches(pak.BoxHeight)));
            }
            else
            {
                dimensions.Add(new DimensionAmount(pak.BoxLength));
                dimensions.Add(new DimensionAmount(pak.BoxWidth));
                dimensions.Add(new DimensionAmount(pak.BoxWidth));
            }

            var sorted = (from d in dimensions
                          orderby d.Amount descending
                          select d.Amount).ToList();

            dLength = sorted[0];
            dwidth  = sorted[1];
            dHeight = sorted[2];

            dGirth = dwidth + dwidth + dHeight + dHeight;
            //Dimensions can be skipped in latest UPS specs
            if (!ignoreDimensions)
            {
                if (dLength > 0 | dHeight > 0 | dwidth > 0)
                {
                    DimensionsType commondityDimensions = new DimensionsType();

                    commondityDimensions.Height = Math.Round(dHeight, 2).ToString(CultureInfo.InvariantCulture);
                    commondityDimensions.Width  = Math.Round(dwidth, 2).ToString(CultureInfo.InvariantCulture);
                    commondityDimensions.Length = Math.Round(dLength, 2).ToString(CultureInfo.InvariantCulture);

                    UnitOfMeasurementType unitOfMeasurementDimention = new UnitOfMeasurementType();
                    unitOfMeasurementDimention.Code        = "IN";
                    unitOfMeasurementDimention.Description = "Inch";
                    commondityDimensions.UnitOfMeasurement = unitOfMeasurementDimention;

                    commodity.Dimensions = commondityDimensions;
                }
            }
            return(commodity);
        }
Ejemplo n.º 23
0
        public string EP(ProcedureType Procedure_Type, GenderType Gender, double Weight, WeightType Weight_Units,
                         double Height,
                         HeightType Height_Units, double Total_Blood_Volume, BloodVolumeType Total_Blood_Volume_Override, double FCR,
                         double Initial_Hct,
                         double Target_End_Hct, double Avg_RF_Hct, double Replacement_Volume,
                         ReplacementVolumeType Replacement_Volume_Override,
                         double Target_Depletion_Hct, double Blood_Warmer_Volume, int Flag)
        {
            string Predicted_Error = "None";

            double IP_WB_Volume              = 0;
            double IP_Replaced_Volume        = 0;
            double PD_Replaced_Volume        = 0;
            double Total_Waste_Processed     = 0;
            double RF_Volume                 = 0;
            double FCR_Factor                = 1.085;
            double RBC_Citrate_Concentration = 21.4;
            double Percent_AC_in_RBC         = 2;

            if (Height_Units == HeightType.inc)
            {
                Height = Height / 0.3937008 / 100;
            }
            else
            {
                Height = Height / 100;
            }

            if (Weight_Units == WeightType.lbs)
            {
                Weight = Weight / 2.2046223;
            }

            Initial_Hct = Initial_Hct / 100;
            Avg_RF_Hct  = Avg_RF_Hct / 100;
            double Blood_Prime_Hct = 0;
            double Estimation_Hct  = 0; // Estimation_Hct Estimation_Hct = Estimation_Hct / 100;

            Target_Depletion_Hct = Target_Depletion_Hct / 100;
            Target_End_Hct       = Target_End_Hct / 100;
            FCR = FCR / 100;

            if (Total_Blood_Volume_Override == BloodVolumeType.Nadler)
            {
                // double Estimation_Hct;
                double Low_TBV_Factor = 80;
                if (Weight < 25)
                {
                    Total_Blood_Volume = Weight * Low_TBV_Factor;
                }
                else
                {
                    if (Gender == GenderType.Female)
                    {
                        Total_Blood_Volume = (0.3561 * Math.Pow(Height, 3) + 0.03308 * Weight + 0.1833) * 1000;
                    }
                    else
                    {
                        Total_Blood_Volume = (0.3669 * Math.Pow(Height, 3) + 0.03219 * Weight + 0.6041) * 1000;
                    }
                }
            }

            double Fluid_Balance           = 0;
            double Total_Reinfusion_Volume = 0;


            double IP_Return_Path_Volume = 60 - 15 + Blood_Warmer_Volume;
            double PD_Return_Path_Volume = 60 + Blood_Warmer_Volume;

            double Calculated_CIR_Limit = 1.25 * Weight;

            double Cit_Con_AC = 21.4;

            double Entered_Patient_Volume = Total_Blood_Volume;
            double Entered_Patient_Hct    = Initial_Hct;
            double Entered_Avg_RF_Hct     = Avg_RF_Hct;
            double Entered_Fluid_Balance  = Fluid_Balance;
            double Entered_Max_WB_Rate    = 50;
            double Entered_AC_Ratio       = 12;
            double Entered_CIR            = 1.25;
            string Entered_AC_Type        = "ACD";
            string Entered_Blood_Prime    = "None";
            double Entered_End_Hct        = Target_End_Hct;
            string Entered_Divert_Prime   = "Yes";
            string Entered_Reinfusion     = "No";
            double Entered_FCR            = Math.Exp(Math.Log(FCR) / FCR_Factor) * (Entered_End_Hct / Entered_Patient_Hct) *
                                            ((Entered_Patient_Volume + Entered_Fluid_Balance - Total_Reinfusion_Volume) /
                                             Entered_Patient_Volume);

            double Entered_Depletion_Hct = 0;

            if (Procedure_Type == ProcedureType.Depletion)
            {
                Entered_Depletion_Hct = Entered_End_Hct;
            }
            else
            {
                Entered_Depletion_Hct = Target_Depletion_Hct;
            }
            double Entered_Replacement_Volume = 0;

            if (Replacement_Volume_Override == ReplacementVolumeType.Override)
            {
                Entered_Replacement_Volume = Replacement_Volume;
            }

            Predicted_Error = "None";
            double Predicted_Replacement_Volume = 0;
            double Predicted_Other_RF_Volume    = 0;

            double RF_AC_Fraction    = Percent_AC_in_RBC / 100;
            double Cit_Con_Rep_Fluid = RF_AC_Fraction * RBC_Citrate_Concentration;
            double CIR_Limited_Qrf   = Calculated_CIR_Limit / Cit_Con_Rep_Fluid;

            Cit_Con_AC = 21.4;

            double EqQb = Calculated_CIR_Limit * (Entered_AC_Ratio + 1) / Cit_Con_AC;

            string Divert_Prime      = Entered_Divert_Prime;
            double Max_WB_Rate       = Entered_Max_WB_Rate;
            double AC_Ratio          = Entered_AC_Ratio;
            double Estimation_Volume = Entered_Patient_Volume;

            Estimation_Hct = Entered_Patient_Hct;
            double Estimation_FCR = 1;
            double RF_Used        = 0;

            Avg_RF_Hct     = Entered_Avg_RF_Hct;
            Target_End_Hct = Entered_End_Hct;
            double Target_FCR    = Entered_FCR;
            double Target_Volume = Entered_Patient_Volume + Entered_Fluid_Balance - Total_Reinfusion_Volume;

            if (Target_Volume < 0.9 * Entered_Patient_Volume)
            {
                Predicted_Error = "Increase Target Fluid Blance";
            }

            Target_Depletion_Hct = Entered_Depletion_Hct;
            double Target_Replacement_Volume = Entered_Replacement_Volume;
            double CIR_Limit = Calculated_CIR_Limit;

            double Qwb_Dep = 0;
            double Qwb_Ex  = 0;

            if (Procedure_Type == ProcedureType.Exchange)
            {
                double Qrf_IP = 0;
                double Qwb_IP = Min(CIR_Limited_Qrf * (AC_Ratio + 1) / AC_Ratio, Max_WB_Rate);
                Qwb_IP = Min(Qwb_IP, 50);
                double Qac_IP = Qwb_IP / (AC_Ratio + 1);
                if (Qac_IP < 1.3)
                {
                    Predicted_Error = "AC Ratio Unachievable";
                }
                if (Estimation_Hct > Avg_RF_Hct)
                {
                    Qrf_IP = Qwb_IP - Qac_IP;
                }
                else
                {
                    Qrf_IP = (Estimation_Hct / Avg_RF_Hct) * (Qwb_IP - Qac_IP);
                }
                double   Qp_IP = Qwb_IP - Qac_IP - Qrf_IP;
                double   Remaining_IP_WB_Volume = 105 - IP_WB_Volume;
                double   Est_Mode_Time          = Remaining_IP_WB_Volume / Qwb_IP;
                double   Total_Return_Volume    = (Qrf_IP + Qp_IP) * Est_Mode_Time;
                double   Mode_RF_Volume         = Qrf_IP * Est_Mode_Time;
                double   Mode_Other_RF_Volume   = 0;
                double[] Estimation;
                if (IP_Replaced_Volume < IP_Return_Path_Volume)
                {
                    IP_Return_Path_Volume = IP_Return_Path_Volume - IP_Replaced_Volume;
                    if (IP_Return_Path_Volume > Total_Return_Volume)
                    {
                        IP_Return_Path_Volume = Total_Return_Volume;
                    }
                    double Partial_Time = IP_Return_Path_Volume / (Qwb_IP - Qac_IP);

                    Estimation = RBCXTT(Qwb_IP - Qac_IP, Qrf_IP, Qp_IP, 0, Partial_Time, Estimation_Volume,
                                        Estimation_Hct, Estimation_FCR);

                    Estimation_Volume = Estimation[0];
                    Estimation_Hct    = Estimation[1];
                    Estimation_FCR    = Estimation[2];
                }
                else
                {
                    IP_Return_Path_Volume = 0;
                }

                // TODO: it line can be wrong
                // oroginal kine is If Return_Path_Volume < Total_Return_Volume Then
                // but there is not any
                if (IP_Return_Path_Volume < Total_Return_Volume)
                {
                    double Partial_Time = (Total_Return_Volume - IP_Return_Path_Volume) / (Qwb_IP - Qac_IP);

                    Estimation = RBCXTT(Qwb_IP - Qac_IP, Qrf_IP, Qp_IP, Avg_RF_Hct, Partial_Time, Estimation_Volume,
                                        Estimation_Hct, Estimation_FCR);

                    Estimation_Volume = Estimation[0];
                    Estimation_Hct    = Estimation[1];
                    Estimation_FCR    = Estimation[2];
                }

                Predicted_Replacement_Volume = Mode_RF_Volume;
                Predicted_Other_RF_Volume    = Mode_Other_RF_Volume;

                Qwb_Ex = Max_WB_Rate;
                double Qac_Ex = Qwb_Ex / (AC_Ratio + 1);
                if (Qac_Ex < 1.3)
                {
                    Predicted_Error = "AC Ratio Unachievable";
                }
                if (Replacement_Volume_Override == ReplacementVolumeType.Override)
                {
                    if (Target_Replacement_Volume - RF_Used - Predicted_Replacement_Volume <= 0)
                    {
                        Predicted_Error = "Increase Replacement Volume";
                    }
                    var Calculated_FCR = CalculatedFCRVR(Estimation_Hct, Avg_RF_Hct, Target_End_Hct,
                                                         Target_Volume - Estimation_Volume, Estimation_Volume,
                                                         Target_Replacement_Volume - RF_Used - Predicted_Replacement_Volume, (Qwb_Ex - Qac_Ex), 1);
                    Target_FCR = Calculated_FCR * Estimation_FCR;
                    if (Target_FCR <= 0)
                    {
                        Predicted_Error = "Decrease Replacement Volume";
                    }
                    if (Target_FCR >= Estimation_FCR)
                    {
                        Predicted_Error = "Decrease Target End Hct";
                    }
                }
                else
                {
                    if (Target_FCR <= 0)
                    {
                        Predicted_Error = "Increase Target FCR";
                    }
                    if (Target_FCR >= Estimation_FCR)
                    {
                        Predicted_Error = "Decrease Target FCR";
                    }
                }

                if ((Target_FCR / Estimation_FCR) >= (0.99 + ((Target_Volume - Estimation_Volume) / Estimation_Volume)))
                {
                    Predicted_Error = "Increase Target Fluid Balance";
                }

                double Qrf_Ex = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume, (Target_Volume - Estimation_Volume),
                                              Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR, Avg_RF_Hct, 1);
                double Qp_Ex = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume, (Target_Volume - Estimation_Volume),
                                             Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR, Avg_RF_Hct, 2);
                Est_Mode_Time = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume, (Target_Volume - Estimation_Volume),
                                              Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR, Avg_RF_Hct, 3);
                double Max_Hct            = Max(Estimation_Hct, Target_End_Hct);
                double Plasma_AC_Fraction = 1 / (((1 - Max_Hct) * AC_Ratio) + 1);
                double Estimated_CIR      = (Qrf_Ex * Cit_Con_Rep_Fluid) + (Qp_Ex * Cit_Con_AC * Plasma_AC_Fraction);

                if (Estimated_CIR > CIR_Limit)
                {
                    double CIR_Adjustment = CIR_Limit / Estimated_CIR;
                    Qwb_Ex = Qwb_Ex * CIR_Adjustment;
                    Qac_Ex = Qac_Ex * CIR_Adjustment;
                    if (Qac_Ex < 1.3)
                    {
                        Predicted_Error = "AC Ratio Unachievable";
                    }
                    Qrf_Ex = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume, (Target_Volume - Estimation_Volume),
                                           Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR, Avg_RF_Hct, 1);
                    Qp_Ex = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume, (Target_Volume - Estimation_Volume),
                                          Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR, Avg_RF_Hct, 2);
                    Est_Mode_Time = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume,
                                                  (Target_Volume - Estimation_Volume), Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR,
                                                  Avg_RF_Hct, 3);
                }

                double prbc_Hct    = 0.8;
                double AC_Dilution = AC_Ratio / (AC_Ratio + 1);
                Max_Hct = Max(Estimation_Hct, Target_End_Hct);
                double Hct_ACWB = AC_Dilution * Max_Hct;
                double Qp_max   = Qwb_Ex * (1 - (Hct_ACWB / prbc_Hct));

                if (Qp_Ex > Qp_max)
                {
                    Predicted_Error = "Unable to meet Hct";
                }

                if (Qp_Ex < 1.3)
                {
                    if (Qp_Ex <0 | Qp_Ex> 1E-07)
                    {
                        Predicted_Error = "Decrease Target End Hct";
                    }
                    else
                    {
                        Qp_Ex = 0;
                    }
                }

                if (Qrf_Ex > 150)
                {
                    Predicted_Error = "Decrease Target Fluid Balance";
                }

                if (Qrf_Ex < 1.3)
                {
                    Predicted_Error = "Decrease Target FCR";
                }

                Mode_RF_Volume       = Qrf_Ex * Est_Mode_Time;
                Mode_Other_RF_Volume = 0;

                if (Estimation_Hct > Target_End_Hct)
                {
                    double Plasma_AC_Fraction_Start = 1 / (((1 - Estimation_Hct) * AC_Ratio) + 1);
                    double Plasma_AC_Fraction_End   = 1 / (((1 - Target_End_Hct) * AC_Ratio) + 1);
                    Plasma_AC_Fraction = (Plasma_AC_Fraction_Start + Plasma_AC_Fraction_End) / 2;
                }
                else
                {
                    Plasma_AC_Fraction = 1 / (((1 - Target_End_Hct) * AC_Ratio) + 1);
                }

                // double Mode_Time = Est_Mode_Time;

                Estimation = RBCXTT(Qwb_Ex - Qac_Ex, Qrf_Ex, Qp_Ex, Avg_RF_Hct, Est_Mode_Time, Estimation_Volume,
                                    Estimation_Hct, Estimation_FCR);

                double Current_Patient_Volume = Estimation[0];
                double Current_Patient_Hct    = Estimation[1];
                double Current_FCR            = Estimation[2];

                Estimation_Volume = Current_Patient_Volume;
                Estimation_Hct    = Current_Patient_Hct;
                Estimation_FCR    = Current_FCR;

                Predicted_Replacement_Volume = Predicted_Replacement_Volume + Mode_RF_Volume;
                Predicted_Other_RF_Volume    = Predicted_Other_RF_Volume + Mode_Other_RF_Volume;
            }
            else
            {
                double Qwb_IP = Min(Max_WB_Rate, 50);

                double Qac_IP = Qwb_IP / (AC_Ratio + 1);
                if (Qac_IP < 1.3)
                {
                    Predicted_Error = "AC Ratio Unachievable";
                }
                double Qrf_IP_Est = Qwb_IP - Qac_IP;

                double Remaining_IP_WB_Volume = 105 - IP_WB_Volume;
                double Est_Mode_Time          = Remaining_IP_WB_Volume / Qwb_IP;

                double Mode_RF_Volume       = 0;
                double Mode_Other_RF_Volume = (Qwb_IP - Qac_IP) * Est_Mode_Time;

                double[] Estimation = RBCXTT(Qwb_IP - Qac_IP, Qwb_IP - Qac_IP, 0, 0, Est_Mode_Time, Estimation_Volume,
                                             Estimation_Hct, Estimation_FCR);

                double Current_Patient_Volume = Estimation[0];
                double Current_Patient_Hct    = Estimation[1];
                double Current_FCR            = Estimation[2];

                Estimation_Volume = Current_Patient_Volume;
                Estimation_Hct    = Current_Patient_Hct;
                Estimation_FCR    = Current_FCR;

                Predicted_Replacement_Volume = Mode_RF_Volume;
                Predicted_Other_RF_Volume    = Mode_Other_RF_Volume;

                double Start_Depletion_Hct = Estimation_Hct;
                double Volume_to_Remove    = -Estimation_Volume *Math.Log(Target_Depletion_Hct / Estimation_Hct);

                Qwb_Dep = Min(Max_WB_Rate, EqQb);

                double Qac_Dep = Qwb_Dep / (AC_Ratio + 1);

                if (Qac_Dep < 1.3)
                {
                    Predicted_Error = "AC Ratio Unachievable";
                }

                double prbc_Hct          = 0.8;
                double AC_Dilution       = AC_Ratio / (AC_Ratio + 1);
                double Avg_Depletion_Hct = (Estimation_Hct + Target_Depletion_Hct) / 2;
                double Avg_Hct_ACWB      = AC_Dilution * Avg_Depletion_Hct;
                double Qp_Ideal_Est      = Qwb_Dep * (1 - (Avg_Hct_ACWB / prbc_Hct));

                double Qrf_Dep_Est = Qwb_Dep - Qac_Dep - Qp_Ideal_Est;

                if (Procedure_Type == ProcedureType.DepletionExchange)
                {
                    Volume_to_Remove = Volume_to_Remove - PD_Return_Path_Volume;
                }

                if (Volume_to_Remove < 0)
                {
                    Predicted_Error = "Depletion Target Unachievable";
                }

                Est_Mode_Time = Volume_to_Remove / (Qwb_Dep - Qac_Dep);
                double Est_Depletion_Time = Est_Mode_Time;

                Mode_RF_Volume       = 0;
                Mode_Other_RF_Volume = Qrf_Dep_Est * Est_Mode_Time;

                Estimation = RBCXTT(Qwb_Dep - Qac_Dep, Qwb_Dep - Qac_Dep, 0, 0, Est_Mode_Time, Estimation_Volume,
                                    Estimation_Hct, Estimation_FCR);

                Current_Patient_Volume = Estimation[0];
                Current_Patient_Hct    = Estimation[1];
                Current_FCR            = Estimation[2];

                Estimation_Volume = Current_Patient_Volume;
                Estimation_Hct    = Current_Patient_Hct;
                Estimation_FCR    = Current_FCR;

                Predicted_Replacement_Volume = Predicted_Replacement_Volume + Mode_RF_Volume;
                Predicted_Other_RF_Volume    = Predicted_Other_RF_Volume + Mode_Other_RF_Volume;

                double Plasma_AC_Fraction_Start = 1 / (((1 - Start_Depletion_Hct) * AC_Ratio) + 1);
                double Plasma_AC_Fraction_End   = 1 / (((1 - Estimation_Hct) * AC_Ratio) + 1);
                double Plasma_AC_Fraction       = (Plasma_AC_Fraction_Start + Plasma_AC_Fraction_End) / 2;


                if (Procedure_Type == ProcedureType.DepletionExchange)
                {
                    double Qwb_PD = Max_WB_Rate;

                    double Qac_PD = Qwb_PD / (AC_Ratio + 1);
                    if (Qac_PD < 1.3)
                    {
                        Predicted_Error = "AC Ratio Unachievable";
                    }
                    double PD_FCR;
                    if (Replacement_Volume_Override == ReplacementVolumeType.Override)
                    {
                        if (Target_Replacement_Volume - RF_Used - Predicted_Replacement_Volume <= 0)
                        {
                            Predicted_Error = "Increase_Replacement_Volume";
                        }
                        double Calculated_FCR = CalculatedFCRVR(Estimation_Hct, Avg_RF_Hct, Target_End_Hct,
                                                                Target_Volume - Estimation_Volume, Estimation_Volume,
                                                                Target_Replacement_Volume - RF_Used - Predicted_Replacement_Volume, Qwb_PD - Qac_PD, 1);
                        PD_FCR = Calculated_FCR * Estimation_FCR;

                        if (PD_FCR <= 0)
                        {
                            Predicted_Error = "Decrease Replacement Volume";
                        }
                        if (PD_FCR >= Estimation_FCR)
                        {
                            Predicted_Error = "Decrease Target End Hct";
                        }
                    }
                    else
                    {
                        PD_FCR = Target_FCR;

                        if (PD_FCR <= 0)
                        {
                            Predicted_Error = "Increase Target FCR";
                        }
                        if (PD_FCR >= Estimation_FCR)
                        {
                            Predicted_Error = "Decrease Target FCR";
                        }
                    }

                    if ((PD_FCR / Estimation_FCR) >= (0.99 + ((Target_Volume - Estimation_Volume) / Estimation_Volume)))
                    {
                        Predicted_Error = "Increase_Target_Fluid_Balance";
                    }

                    double Qrf_PD = CalculatedFCR(Qwb_PD - Qac_PD, Estimation_Volume, Target_Volume - Estimation_Volume,
                                                  Estimation_Hct, Estimation_FCR, Target_End_Hct, PD_FCR, Avg_RF_Hct, 1);
                    double Qp_PD = CalculatedFCR(Qwb_PD - Qac_PD, Estimation_Volume, Target_Volume - Estimation_Volume,
                                                 Estimation_Hct, Estimation_FCR, Target_End_Hct, PD_FCR, Avg_RF_Hct, 2);

                    double Max_Hct = Max(Estimation_Hct, Target_End_Hct);
                    Plasma_AC_Fraction = 1 / (((1 - Max_Hct) * AC_Ratio) + 1);
                    double Estimated_CIR = (Qrf_PD * Cit_Con_Rep_Fluid) + (Qp_PD * Cit_Con_AC * Plasma_AC_Fraction);
                    if (Estimated_CIR > CIR_Limit)
                    {
                        double CIR_Adjustment = CIR_Limit / Estimated_CIR;
                        Qwb_PD = Qwb_PD * CIR_Adjustment;
                        Qac_PD = Qac_PD * CIR_Adjustment;
                        if (Qac_PD < 1.3)
                        {
                            Predicted_Error = "AC Ratio Unachievable";
                        }
                        Qrf_PD = CalculatedFCR(Qwb_PD - Qac_PD, Estimation_Volume, Target_Volume - Estimation_Volume,
                                               Estimation_Hct, Estimation_FCR, Target_End_Hct, PD_FCR, Avg_RF_Hct, 1);
                        Qp_PD = CalculatedFCR(Qwb_PD - Qac_PD, Estimation_Volume, Target_Volume - Estimation_Volume,
                                              Estimation_Hct, Estimation_FCR, Target_End_Hct, PD_FCR, Avg_RF_Hct, 2);
                    }

                    prbc_Hct    = 0.8;
                    AC_Dilution = AC_Ratio / (AC_Ratio + 1);
                    Max_Hct     = Max(Estimation_Hct, Target_End_Hct);
                    double Hct_ACWB = AC_Dilution * Max_Hct;
                    double Qp_max   = Qwb_PD * (1 - (Hct_ACWB / prbc_Hct));
                    if (Qp_PD > Qp_max)
                    {
                        Predicted_Error = "Increase Target End Hct";
                    }


                    if (Qp_PD < 1.3)
                    {
                        if (Qp_PD <0 | Qp_PD> 1E-07)
                        {
                            Predicted_Error = "Decrease Target End Hct";
                        }
                        else
                        {
                            Qp_PD = 0;
                        }
                    }

                    if (Qrf_PD > 150)
                    {
                        Predicted_Error = "Decrease Target Fluid Balance";
                    }

                    if (Qrf_PD < 1.3)
                    {
                        Predicted_Error = "Decrease Target FCR";
                    }

                    double PD_Volume_Remaining = PD_Return_Path_Volume - PD_Replaced_Volume;
                    Est_Mode_Time        = PD_Volume_Remaining / (Qrf_PD + Qp_PD);
                    Mode_RF_Volume       = Qrf_PD * Est_Mode_Time;
                    Mode_Other_RF_Volume = 0;

                    if (Estimation_Hct > Target_Depletion_Hct)
                    {
                        Plasma_AC_Fraction_Start = 1 / (((1 - Estimation_Hct) * AC_Ratio) + 1);
                        Plasma_AC_Fraction_End   = 1 / (((1 - Target_Depletion_Hct) * AC_Ratio) + 1);
                        Plasma_AC_Fraction       = (Plasma_AC_Fraction_Start + Plasma_AC_Fraction_End) / 2;
                    }
                    else
                    {
                        Plasma_AC_Fraction = 1 / (((1 - Target_End_Hct) * AC_Ratio) + 1);
                    }

                    Estimation = RBCXTT(Qwb_PD - Qac_PD, Qrf_PD, Qp_PD, 0, Est_Mode_Time, Estimation_Volume,
                                        Estimation_Hct, Estimation_FCR);

                    Current_Patient_Volume = Estimation[0];
                    Current_Patient_Hct    = Estimation[1];
                    Current_FCR            = Estimation[2];

                    Estimation_Volume = Current_Patient_Volume;
                    Estimation_Hct    = Current_Patient_Hct;
                    Estimation_FCR    = Current_FCR;

                    Predicted_Replacement_Volume = Predicted_Replacement_Volume + Mode_RF_Volume;
                    Predicted_Other_RF_Volume    = Predicted_Other_RF_Volume + Mode_Other_RF_Volume;

                    Qwb_Ex = Max_WB_Rate;
                    double Qac_Ex = Qwb_Ex / (AC_Ratio + 1);
                    if (Qac_Ex < 1.3)
                    {
                        Predicted_Error = "AC Ratio Unachievable";
                    }
                    if (Replacement_Volume_Override == ReplacementVolumeType.Override)
                    {
                        if (Target_Replacement_Volume - RF_Used - Predicted_Replacement_Volume <= 0)
                        {
                            Predicted_Error = "Increase Replacement Volume";
                        }
                        double Calculated_FCR = CalculatedFCRVR(Estimation_Hct, Avg_RF_Hct, Target_End_Hct,
                                                                Target_Volume - Estimation_Volume, Estimation_Volume,
                                                                Target_Replacement_Volume - RF_Used - Predicted_Replacement_Volume, (Qwb_Ex - Qac_Ex), 1);
                        Target_FCR = Calculated_FCR * Estimation_FCR;

                        if (Target_FCR < 0)
                        {
                            Predicted_Error = "Decrease Replacement Volume";
                        }
                        if (Target_FCR >= Estimation_FCR)
                        {
                            Predicted_Error = "Decrease Target End Hct";
                        }
                    }
                    else
                    {
                        if (Target_FCR <= 0)
                        {
                            Predicted_Error = "Increase_Target_FCR";
                        }
                        if (Target_FCR >= Estimation_FCR)
                        {
                            Predicted_Error = "Decrease Target FCR";
                        }
                    }

                    if ((Target_FCR / Estimation_FCR) >= (0.99 + ((Target_Volume - Estimation_Volume) / Estimation_Volume)))
                    {
                        Predicted_Error = "Increase Target Fluid Balance";
                    }

                    double Qrf_Ex = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume,
                                                  (Target_Volume - Estimation_Volume), Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR,
                                                  Avg_RF_Hct, 1);
                    double Qp_Ex = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume,
                                                 (Target_Volume - Estimation_Volume), Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR,
                                                 Avg_RF_Hct, 2);
                    Est_Mode_Time = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume,
                                                  (Target_Volume - Estimation_Volume), Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR,
                                                  Avg_RF_Hct, 3);
                    Max_Hct            = Max(Estimation_Hct, Target_End_Hct);
                    Plasma_AC_Fraction = 1 / (((1 - Max_Hct) * AC_Ratio) + 1);
                    Estimated_CIR      = (Qrf_Ex * Cit_Con_Rep_Fluid) + (Qp_Ex * Cit_Con_AC * Plasma_AC_Fraction);

                    if (Estimated_CIR > CIR_Limit)
                    {
                        double CIR_Adjustment = CIR_Limit / Estimated_CIR;
                        Qwb_Ex = Qwb_Ex * CIR_Adjustment;
                        Qac_Ex = Qac_Ex * CIR_Adjustment;
                        if (Qac_Ex < 1.3)
                        {
                            Predicted_Error = "AC Ratio Unachievable";
                        }
                        Qrf_Ex = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume, (Target_Volume - Estimation_Volume),
                                               Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR, Avg_RF_Hct, 1);
                        Qp_Ex = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume, (Target_Volume - Estimation_Volume),
                                              Estimation_Hct, Estimation_FCR, Target_End_Hct, Target_FCR, Avg_RF_Hct, 2);
                        Est_Mode_Time = CalculatedFCR((Qwb_Ex - Qac_Ex), Estimation_Volume,
                                                      (Target_Volume - Estimation_Volume), Estimation_Hct, Estimation_FCR, Target_End_Hct,
                                                      Target_FCR, Avg_RF_Hct, 3);
                    }

                    prbc_Hct    = 0.8;
                    AC_Dilution = AC_Ratio / (AC_Ratio + 1);
                    Max_Hct     = Max(Estimation_Hct, Target_End_Hct);
                    Hct_ACWB    = AC_Dilution * Max_Hct;
                    Qp_max      = Qwb_Ex * (1 - (Hct_ACWB / prbc_Hct));

                    if (Qp_Ex > Qp_max)
                    {
                        Predicted_Error = "Unable to meet Hct";
                    }

                    if (Qp_Ex < 1.3)
                    {
                        if (Qp_Ex <0 | Qp_Ex> 1E-07)
                        {
                            Predicted_Error = "Decrease Target End Hct";
                        }
                        else
                        {
                            Qp_Ex = 0;
                        }
                    }

                    if (Qrf_Ex > 150)
                    {
                        Predicted_Error = "Decrease Target Fluid Balance";
                    }

                    if (Qrf_Ex < 1.3)
                    {
                        Predicted_Error = "Decrease Target FCR";
                    }

                    Mode_RF_Volume       = Qrf_Ex * Est_Mode_Time;
                    Mode_Other_RF_Volume = 0;

                    if (Estimation_Hct > Target_End_Hct)
                    {
                        Plasma_AC_Fraction_Start = 1 / (((1 - Estimation_Hct) * AC_Ratio) + 1);
                        Plasma_AC_Fraction_End   = 1 / (((1 - Target_End_Hct) * AC_Ratio) + 1);
                        Plasma_AC_Fraction       = (Plasma_AC_Fraction_Start + Plasma_AC_Fraction_End) / 2;
                    }
                    else
                    {
                        Plasma_AC_Fraction = 1 / (((1 - Target_End_Hct) * AC_Ratio) + 1);
                    }


                    //double Mode_Time = Est_Mode_Time;

                    Estimation = RBCXTT(Qwb_Ex - Qac_Ex, Qrf_Ex, Qp_Ex, Avg_RF_Hct, Est_Mode_Time, Estimation_Volume,
                                        Estimation_Hct, Estimation_FCR);

                    Current_Patient_Volume = Estimation[0];
                    Current_Patient_Hct    = Estimation[1];
                    Current_FCR            = Estimation[2];

                    Estimation_Volume = Current_Patient_Volume;
                    Estimation_Hct    = Current_Patient_Hct;
                    Estimation_FCR    = Current_FCR;

                    Predicted_Replacement_Volume = Predicted_Replacement_Volume + Mode_RF_Volume;
                    Predicted_Other_RF_Volume    = Predicted_Other_RF_Volume + Mode_Other_RF_Volume;
                }
            }

            double Est_Other_RF = Predicted_Other_RF_Volume;
            double WB_Flow_Rate;

            if (Predicted_Error == "None")
            {
                if (Procedure_Type == ProcedureType.Depletion)
                {
                    WB_Flow_Rate = Qwb_Dep;
                }
                else
                {
                    WB_Flow_Rate = Qwb_Ex;
                }
                if (Replacement_Volume_Override == ReplacementVolumeType.Override)
                {
                    FCR = Estimation_FCR;
                }
                else
                {
                    Replacement_Volume = Predicted_Replacement_Volume;
                }
            }
            else
            {
                if (Replacement_Volume_Override == ReplacementVolumeType.Override)
                {
                    FCR = 0;
                }
                else
                {
                    Replacement_Volume = 0;
                }

                Est_Other_RF = 0;
            }


            if (Flag == 0)
            {
                var r =
                    (Math.Pow(
                         (Estimation_FCR * (Entered_Patient_Volume / Estimation_Volume) * (Entered_Patient_Hct / Estimation_Hct)),
                         (FCR_Factor))) * 100;
                return(r.ToString());
            }
            if (Flag == 1)
            {
                return(Replacement_Volume.ToString());
            }

            if (Flag == 2)
            {
                Est_Other_RF.ToString();
            }
            if (Flag == 3)
            {
                return(Predicted_Error);
            }
            return(null);
        }
 /// <summary>
 /// Assigns measurement and measurement type.
 /// </summary>
 /// <param name="measurement"></param>
 /// <param name="measurementType"></param>
 internal void AssignMeasurement(double? measurement, WeightType measurementType)
 {
     if (measurement.HasValue)
     {
         //A non null value is being assigned for this type
         _measurement = measurement;
         _measurementType = measurementType;
     }
     else if ((measurement.HasValue == false) && (_measurementType == measurementType))
     {
         //The measurements are being cleared.
         _measurement = null;
         _measurementType = null;
     }
 }
Ejemplo n.º 25
0
 public Weight(decimal?value, WeightType weightType)
 {
     Value      = value;
     WeightType = weightType;
 }
        private static double correct(bool unbiased, WeightType weightType, double sum, double weightSum, double squareSum)
        {
            if (unbiased)
            {
                if (weightType == WeightType.Automatic)
                {
                    if (weightSum > 1 && weightSum.IsInteger(1e-8))
                        return sum / (weightSum - 1);

                    return sum / (weightSum - (squareSum / weightSum));
                }
                else if (weightType == WeightType.Fraction)
                {
                    /*
                    if (Math.Abs(weightSum - 1.0) >= 1e-8)
                    {
                        throw new ArgumentException("An unbiased variance estimate"
                          + " cannot be computed if weights do not sum to one. The"
                          + " given weights sum up to " + squareSum, "weights");
                    }*/

                    return sum / (weightSum - (squareSum / weightSum));
                }
                else if (weightType == WeightType.Repetition)
                {
                    return sum / (weightSum - (squareSum / weightSum));
                }
            }

            return sum / weightSum;
        }
Ejemplo n.º 27
0
        static void Main()
        {
            try
            {
                FreightShipService freightShipService = new FreightShipService();
                FreightShipRequest freightShipRequest = new FreightShipRequest();
                RequestType        request            = new RequestType();
                String[]           requestOption      = { "1" };
                request.RequestOption      = requestOption;
                freightShipRequest.Request = request;
                ShipmentType shipment = new ShipmentType();

                /** ****************ShipFrom******************************* */
                ShipFromType           shipFrom        = new ShipFromType();
                FreightShipAddressType shipFromAddress = new FreightShipAddressType();
                String[] shipFromAddressLines          = { "ShipFrom address line" };
                shipFromAddress.AddressLine       = shipFromAddressLines;
                shipFromAddress.City              = "Roswell";
                shipFromAddress.StateProvinceCode = "GA";
                shipFromAddress.PostalCode        = "30076";
                shipFromAddress.CountryCode       = "US";
                shipFrom.Address       = shipFromAddress;
                shipFrom.AttentionName = "XYZ Associates";
                shipFrom.Name          = "XYZ Associates";

                FreightShipPhoneType shipFromPhone = new FreightShipPhoneType();
                shipFromPhone.Number    = "123456789";
                shipFromPhone.Extension = "34567";
                shipFrom.Phone          = shipFromPhone;
                shipFrom.EMailAddress   = "*****@*****.**";
                shipment.ShipFrom       = shipFrom;
                /** ****************ShipFrom******************************* */

                shipment.ShipperNumber = "Your shipper number";

                /** ****************ShipTo*************************************** */
                ShipToType             shipTo        = new ShipToType();
                FreightShipAddressType shipToAddress = new FreightShipAddressType();
                String[] shipToAddressLines          = { "ShipTo address line" };
                shipToAddress.AddressLine       = shipToAddressLines;
                shipToAddress.City              = "Roswell";
                shipToAddress.StateProvinceCode = "GA";
                shipToAddress.PostalCode        = "30076";
                shipToAddress.CountryCode       = "US";
                shipTo.Address       = shipFromAddress;
                shipTo.AttentionName = "PQR Associates";
                shipTo.Name          = "PQR";
                FreightShipPhoneType shipToPhone = new FreightShipPhoneType();
                shipToPhone.Number    = "123456789";
                shipToPhone.Extension = "34567";
                shipTo.Phone          = shipToPhone;
                shipTo.EMailAddress   = "*****@*****.**";
                shipment.ShipTo       = shipTo;
                /** ****************ShipTo*************************************** */

                /** ***************PaymentInformationType************************* */
                PaymentInformationType paymentInfo = new PaymentInformationType();
                PayerType payer = new PayerType();
                payer.AttentionName = "Mr. XYZ";
                payer.Name          = "XYZ Associates";
                FreightShipPhoneType payerPhone = new FreightShipPhoneType();
                payerPhone.Number    = "123456789";
                payerPhone.Extension = "3456";
                payer.Phone          = payerPhone;
                payer.ShipperNumber  = "Your Shipper Number";
                payer.EMailAddress   = "*****@*****.**";

                FreightShipAddressType payerAddress = new FreightShipAddressType();
                String[] payerAddressLines          = { "Payer address line" };
                payerAddress.AddressLine       = payerAddressLines;
                payerAddress.City              = "Roswell";
                payerAddress.StateProvinceCode = "GA";
                payerAddress.PostalCode        = "30075";
                payerAddress.CountryCode       = "US";
                payer.Address     = payerAddress;
                paymentInfo.Payer = payer;
                ShipCodeDescriptionType shipBillOption = new ShipCodeDescriptionType();
                shipBillOption.Code               = "10";
                shipBillOption.Description        = "PREPAID";
                paymentInfo.ShipmentBillingOption = shipBillOption;
                shipment.PaymentInformation       = paymentInfo;
                /** ***************PaymentInformationType************************* */

                /** ***************Service************************************** */
                ShipCodeDescriptionType service = new ShipCodeDescriptionType();
                service.Code        = "309";
                service.Description = "UPS Ground Freight";
                shipment.Service    = service;
                /** ***************Service************************************** */

                //Below sample contains dummy data for your reference
                //Please update dummy date as per your requirement
                /** **************Commodity************************************* */
                CommodityType commodity = new CommodityType();
                commodity.NumberOfPieces = "20";
                NMFCCommodityType nmfcCommodity = new NMFCCommodityType();
                nmfcCommodity.PrimeCode = "132680";
                nmfcCommodity.SubCode   = "02";
                commodity.NMFCCommodity = nmfcCommodity;
                commodity.FreightClass  = "77.5";
                ShipCodeDescriptionType packagingType = new ShipCodeDescriptionType();
                packagingType.Code        = "BAG";
                packagingType.Description = "BAG";
                commodity.PackagingType   = packagingType;
                WeightType weight = new WeightType();
                weight.Value = "200";
                FreightShipUnitOfMeasurementType unitOfMeasurement = new FreightShipUnitOfMeasurementType();
                unitOfMeasurement.Code        = "lbs";
                unitOfMeasurement.Description = "pounds";
                weight.UnitOfMeasurement      = unitOfMeasurement;
                commodity.Weight = weight;
                CommodityValueType commodityValue = new CommodityValueType();
                commodityValue.CurrencyCode  = "USD";
                commodityValue.MonetaryValue = "100";
                commodity.CommodityValue     = commodityValue;
                commodity.Description        = "LCD TVS";
                CommodityType[] commodityArray = { commodity };
                shipment.Commodity = commodityArray;
                /** **************Commodity************************************* */

                /** **************HandlingUnitOne************************** */
                HandlingUnitType handlingUnit = new HandlingUnitType();
                handlingUnit.Quantity = "1";
                ShipCodeDescriptionType handlingUnitType = new ShipCodeDescriptionType();
                handlingUnitType.Code        = "SKD";
                handlingUnitType.Description = "SKID";
                handlingUnit.Type            = handlingUnitType;
                shipment.HandlingUnitOne     = handlingUnit;
                /** **************HandlingUnitOne************************** */

                UPSSecurity upss = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = "Your License";
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username           = "******";
                upssUsrNameToken.Password           = "******";
                upss.UsernameToken                  = upssUsrNameToken;
                freightShipService.UPSSecurityValue = upss;

                freightShipRequest.Shipment = shipment;

                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
                Console.WriteLine(freightShipRequest);
                FreightShipResponse freightShipResponse = freightShipService.ProcessShipment(freightShipRequest);
                Console.WriteLine("The transaction was a " + freightShipResponse.Response.ResponseStatus.Description);
                Console.WriteLine("The BOLID of the shipment is: " + freightShipResponse.ShipmentResults.BOLID);
                Console.WriteLine("The Shipment number of the shipment is " + freightShipResponse.ShipmentResults.ShipmentNumber);
                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("---------FreightShip Web Service returns error----------------");
                Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
                Console.WriteLine("SoapException Message= " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
                Console.WriteLine("");
                Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
                Console.WriteLine("");
                Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("--------------------");
                Console.WriteLine("CommunicationException= " + ex.Message);
                Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" Generaal Exception= " + ex.Message);
                Console.WriteLine(" Generaal Exception-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
            }
            finally
            {
                Console.ReadKey();
            }
        }
Ejemplo n.º 28
0
   double GetIncludedWeight(
 WeightType prev_state, WeightType next_state,
 double prev_weight_percent, double next_weight_percent,
 double start_percent, double end_percent,
 double cur_weight_percent)
   {
       if (prev_state == WeightType.UnderStart)
         {
       if (next_state == WeightType.UnderStart)
       {
         return 0.0;
       }
       else if (next_state == WeightType.BetweenStartEnd)
       {
         return next_weight_percent - start_percent;
       }
       else
       {
         return end_percent - start_percent;
       }
         }
         else if (prev_state == WeightType.BetweenStartEnd)
         {
       if (next_state == WeightType.UnderStart)
       {
         logger.Warn("Invalid");
         return 0.0;
       }
       else if (next_state == WeightType.BetweenStartEnd)
       {
         return cur_weight_percent;
       }
       else
       {
         return end_percent - prev_weight_percent;
       }
         }
         else if (prev_state == WeightType.OverEnd)
         {
       return 0;
         }
         else
         {
       logger.Warn("Invalid");
         }
         return 0;
   }
Ejemplo n.º 29
0
        //Returns true if the vertex's matrix node is changed.
        private bool Weight(float value, Vertex3 vertex, WeightType type)
        {
            if (_targetBone == null || _targetBone.Locked)
            {
                return(false);
            }

            Influence  targetInf    = null;
            BoneWeight targetWeight = null;
            float      max          = 1.0f;

            //Get the matrix that influences this vertex
            IMatrixNode node = vertex.GetMatrixNode();

            bool startsAsBone = false;

            //Convert a single bone into an influence so bones can be added to it later
            if (node is MDL0BoneNode)
            {
                startsAsBone = true;
                node         = new Influence(node as MDL0BoneNode);
            }

            //Duplicate the influence if it affects more than just this vertex
            targetInf = node.Users.Count > 1 ?
                        (node as Influence).Clone() :
                        node as Influence;

            //Find or add the current bone to the influence
            List <BoneWeight> weights = targetInf.Weights;
            int selectedIndex         = weights.Select(x => x.Bone).ToArray().IndexOf(TargetBone);

            if (selectedIndex < 0)
            {
                weights.Add(new BoneWeight(TargetBone, 0.0f));
                selectedIndex = weights.Count - 1;
            }

            //Get the weight at the index of the current bone
            targetWeight = targetInf.Weights[selectedIndex];

            //Can't do anything to a locked weight
            if (targetWeight.Locked)
            {
                return(false);
            }

            //Get the sum of all weights that can be edited by subtracting all locked values from 1.0f
            max = 1.0f;
            foreach (BoneWeight b in weights)
            {
                if (b.Locked)
                {
                    max -= b.Weight;
                }
            }

            //Get the new value for the target weight
            //Clamp it between 0.0f and the max value
            switch (type)
            {
            default:
                value = RoundValue(value, max);
                break;

            case WeightType.Add:
                value = RoundValue(targetWeight.Weight + value, max);
                break;

            case WeightType.Multiply:
                value = RoundValue(targetWeight.Weight * value, max);
                break;
            }

            //Nothing to do if there's no change in value
            if (targetWeight.Weight == value)
            {
                return(false);
            }

            //Collect all unlocked weights that are not the current weight
            //These are weights that will be changed to accomodate the current weight edit
            List <int> editableWeights = new List <int>();

            for (int i = 0; i < targetInf.Weights.Count; i++)
            {
                if (!targetInf.Weights[i].Locked && i != selectedIndex)
                {
                    editableWeights.Add(i);
                }
            }

            //Return if nothing can be edited
            if (editableWeights.Count == 0)
            {
                return(false);
            }

            //Set the current weight with the calculated value
            targetWeight.Weight = value;

            //Get the change in value, divide it by all other editable weights,
            //and then add that value to those weights to bring the overall weight sum back to 1.0f
            float perBoneDiff = (targetWeight.Weight - value) / editableWeights.Count;

            if (value < max)
            {
                foreach (int i in editableWeights)
                {
                    targetInf.Weights[i].Weight = RoundValue(targetInf.Weights[i].Weight + perBoneDiff, 1.0f);
                }
            }
            else
            {
                foreach (int i in editableWeights)
                {
                    targetInf.Weights[i].Weight = 0.0f;
                }
            }

            //Normalize the influence just in case, this will scale all weights so they add up to 1.0f
            //Don't let the modified value be normalized, lock it
            bool locked = targetWeight.Locked;

            targetWeight.Locked = true;
            targetInf.Normalize();
            targetWeight.Locked = locked;

            //Clean influence by removing zero weights
            for (int i = 0; i < targetInf.Weights.Count; i++)
            {
                if (targetInf.Weights[i].Weight <= 0.0f)
                {
                    targetInf.Weights.RemoveAt(i--);
                }
            }

            MDL0ObjectNode obj   = vertex.Parent as MDL0ObjectNode;
            MDL0Node       model = obj.Model;
            IMatrixNode    matrixNode;

            //See if the influence is just one bone
            if (targetInf.Weights.Count == 1)
            {
                matrixNode = targetInf.Weights[0].Bone;
                if (!startsAsBone && !_anyConverted.Contains(obj))
                {
                    _anyConverted.Add(obj);
                }
            }
            else
            {
                matrixNode = model._influences.FindOrCreate(targetInf);
                if (startsAsBone && !_anyConverted.Contains(obj))
                {
                    _anyConverted.Add(obj);
                }
            }

            //Move influence to each vertex before modifying the influence of one vertex
            if (obj.MatrixNode != null)
            {
                obj.TryConvertMatrixToVertex();
            }

            vertex.DeferUpdateAssets();
            vertex.MatrixNode = matrixNode;

            return(true);
        }