Example #1
0
        /// <summary>
        /// Computes an exponential moving average
        /// </summary>
        /// <param name="prices">Prices for which the average should be computed</param>
        /// <param name="terms">A period in days</param>
        /// <returns>Values of the exponential moving average</returns>
        public static IList <IndicatorValue> ExpotentialMovingAverage(IList <Price> prices, int terms)
        {
            if (prices == null || prices.Count < terms || terms < 1 || !CheckDates(prices.Select(price => price.Date).ToList()))
            {
                throw new IndicatorArgumentException();
            }
            IList <IndicatorValue> averages = new List <IndicatorValue>();
            var ema = SimpleMovingAverage(prices.Take(terms).ToList());

            averages.Add(ema);
            var alpha = 2.0m / (terms + 1);
            var p     = 1 - alpha;

            for (var i = terms; i < prices.Count; i++)
            {
                var nextEma = new IndicatorValue
                {
                    Date  = prices[i].Date,
                    Value = prices[i].ClosePrice * alpha + ema.Value * p
                };
                ema = nextEma;
                averages.Add(ema);
            }
            return(averages);
        }
        public override TimeBaseValue Calculate(int forIndex)
        {
            CheckCreateMaIndicator();

            DateTime dt = GetTime(forIndex);

            if (forIndex < Length)
            {
                IndicatorValue nullValue = new IndicatorValue()
                {
                    Time = dt, Value = double.NaN, Source = GetValueBySource(forIndex)
                };
                ResultCore.Add(nullValue);
                IndicatorValue val = (IndicatorValue)MaIndicator.Calculate(forIndex);
                MaIndicator.Result.Add(val);
                return(nullValue);
            }

            double         tr    = CalculateCore(forIndex);
            IndicatorValue value = new IndicatorValue()
            {
                Time = dt, Value = tr, Source = GetValueBySource(forIndex)
            };

            ResultCore.Add(value);
            IndicatorValue signal = (IndicatorValue)MaIndicator.Calculate(forIndex);

            MaIndicator.Result.Add(signal);
            return(signal);
        }
Example #3
0
        public override TimeBaseValue Calculate(int forIndex)
        {
            CheckCreateInnerIndicators();

            FastEmaIndicator.Result.Add(FastEmaIndicator.Calculate(forIndex));
            SlowEmaIndicator.Result.Add(SlowEmaIndicator.Calculate(forIndex));

            if (forIndex < SlowLength)
            {
                IndicatorValue nullValue = new IndicatorValue()
                {
                    Time = GetTime(forIndex), Value = double.NaN, Source = GetValueBySource(forIndex)
                };
                Result.Push(nullValue);
                SignalMaIndicator.Result.Add(SignalMaIndicator.Calculate(forIndex));
                Result.Pop();
                return(nullValue);
            }

            IndicatorValue value = new IndicatorValue()
            {
                Time = GetTime(forIndex), Value = ((IndicatorValue)FastEmaIndicator.Result[forIndex]).Value - ((IndicatorValue)SlowEmaIndicator.Result[forIndex]).Value, Source = GetValueBySource(forIndex)
            };

            Result.Push(value);
            IndicatorValue signal = (IndicatorValue)SignalMaIndicator.Calculate(forIndex);

            SignalMaIndicator.Result.Add(signal);
            Result.Pop();
            return(value);
        }
Example #4
0
        public override void OnUpdateValue(int index)
        {
            IndicatorValue fast  = (IndicatorValue)FastEmaIndicator.Calculate(index);
            IndicatorValue slow  = (IndicatorValue)SlowEmaIndicator.Calculate(index);
            double         value = fast.Value - slow.Value;

            ((IndicatorValue)Result[index]).Value = value;
            IndicatorValue signal = (IndicatorValue)SignalMaIndicator.Calculate(index);

            ((IndicatorValue)SignalMaIndicator.Result[index]).Value = signal.Value;
        }
 public TechnicalIndicatorClass(string name, string shortname, IndicatorValue value, List<int> values, IndicatorType type, double upperlimit = double.MaxValue, double lowerlimit = double.MinValue, double maxvalue = double.MaxValue, double minvalue = double.MinValue)
 {
     this.Name = name;
     this.Defaultvalues = values == null ? new List<int>() : values;
     this.ShortName = shortname;
     this.Value = value;
     this.Type = type;
     this.UpperLimit = upperlimit;
     this.LowerLimit = lowerlimit;
     this.MaxVal = maxvalue;
     this.MinVal = minvalue;
 }
Example #6
0
        public override void OnUpdateValue(int index)
        {
            IndicatorValue max = (IndicatorValue)MaxIndicator.Calculate(index);
            IndicatorValue min = (IndicatorValue)MinIndicator.Calculate(index);

            double k = (GetValueBySource(index) - min.Value) / (max.Value - min.Value) * 100;

            ((StochasticValue)Result[index]).K = k;

            IndicatorValue ma = (IndicatorValue)MaIndicator.Calculate(index);

            ((StochasticValue)Result[index]).D = ma.Value;
        }
        public override void OnUpdateValue(int index)
        {
            base.OnUpdateValue(index);
            if (index < Length)
            {
                return;
            }
            double value = CalculateCore(index);

            ((IndicatorValue)ResultCore[index]).Value = value;
            IndicatorValue signal = (IndicatorValue)MaIndicator.Calculate(index);

            ((IndicatorValue)MaIndicator.Result[index]).Value = signal.Value;
            Result[index].Value = signal.Value;
        }
Example #8
0
        public void KazakhstanValuesEditByYearIndicator(int Year, int IndicatorId)
        {
            Indicator             indicator        = _context.Indicator.AsNoTracking().FirstOrDefault(i => i.Id == IndicatorId);
            List <IndicatorValue> indicatorValues  = _context.IndicatorValue.AsNoTracking().Include(i => i.Region).Where(i => i.Region.Year == Year && i.IndicatorId == indicator.Id).ToList();
            IndicatorValue        indicatorValueKZ = _context.IndicatorValue
                                                     .Include(i => i.Region)
                                                     .FirstOrDefault(i => i.Region.Year == Year && i.IndicatorId == indicator.Id && string.IsNullOrEmpty(i.Region.Coordinates) && i.Region.Code == Startup.Configuration["KazakhstanCode"]);

            if (indicatorValueKZ != null && indicatorValues.Count() > 0)
            {
                indicatorValueKZ.SourceId = indicatorValues.FirstOrDefault().SourceId;
                indicatorValueKZ.Value    = indicatorValues.Average(i => i.Value);
                _context.Update(indicatorValueKZ);
            }
            _context.SaveChanges();
        }
        private IList <IndicatorValue> SubstractLongEmaFromShortEma(IList <IndicatorValue> shortEma,
                                                                    IList <IndicatorValue> longEma)
        {
            var difference = LongTerm - ShortTerm;
            IList <IndicatorValue> values = new List <IndicatorValue>();

            for (var i = difference; i < shortEma.Count; i++)
            {
                var val = new IndicatorValue
                {
                    Date  = shortEma[i].Date,
                    Value = shortEma[i].Value - longEma[i - difference].Value
                };
                values.Add(val);
            }
            return(values);
        }
Example #10
0
        public void PassesOnDuplicateTimes()
        {
            var target = new TestIndicator();

            var time = DateTime.UtcNow;

            const double value1 = 1d;
            var          data   = new IndicatorValue(value1);

            target.Update(time, data);
            Assert.AreEqual(value1, target.Current.Value);

            // this won't update because we told it to ignore duplicate
            // data based on time
            target.Update(time, data);
            Assert.AreEqual(value1, target.Current.Value);
        }
Example #11
0
        public async Task <AddIndicatorValueStatus> InsertAsync(IndicatorValue entity)
        {
            using (var context = new ControlSystemContext.ControlSystemContext())
            {
                var isExists = await IsDeviceIndicatorExist(entity.DeviceIndicatorId);

                if (!isExists)
                {
                    return(AddIndicatorValueStatus.DeviceIndicatorNotExists);
                }

                await context.AddAsync(entity);

                await context.SaveChangesAsync();

                return(AddIndicatorValueStatus.Success);
            }
        }
Example #12
0
        private static IList <IndicatorValue> ExponentialMovingAverageInternal(IList <IndicatorValue> values, int terms, decimal alpha)
        {
            IList <IndicatorValue> averages = new List <IndicatorValue>();
            var ema = SimpleMovingAverage(values.Take(terms).ToList());

            averages.Add(ema);
            for (var i = terms; i < values.Count; i++)
            {
                var nextEma = new IndicatorValue
                {
                    Date  = values[i].Date,
                    Value = ema.Value + alpha * (values[i].Value - ema.Value)
                };
                ema = nextEma;
                averages.Add(ema);
            }
            return(averages);
        }
Example #13
0
        public void UpdatesProperly()
        {
            // we want to make sure the initialized value is the default value
            // for a datapoint, and also verify the our indicator updates as we
            // expect it to, in this case, it should return identity
            var target = new TestIndicator();

            Assert.AreEqual(0, target.CurrentTime);
            Assert.AreEqual(0d, target.Current.Value);

            var time = DateTime.UtcNow;
            var data = new IndicatorValue(1d);

            target.Update(time, data);
            Assert.AreEqual(1d, target.Current.Value);

            target.Update(time.AddMilliseconds(1), new IndicatorValue(2d));
            Assert.AreEqual(2d, target.Current.Value);
        }
Example #14
0
        public override TimeBaseValue Calculate(int forIndex)
        {
            IndicatorValue max = (IndicatorValue)MaxIndicator.Calculate(forIndex);

            MaxIndicator.Result.Add(max);
            IndicatorValue min = (IndicatorValue)MinIndicator.Calculate(forIndex);

            MinIndicator.Result.Add(min);

            IndicatorValue ma = null;

            if (forIndex < Length)
            {
                StochasticValue nullValue = new StochasticValue()
                {
                    Time = GetTime(forIndex), K = double.NaN, D = double.NaN, Source = GetValueBySource(forIndex)
                };
                Result.Push(nullValue);
                ma = (IndicatorValue)MaIndicator.Calculate(forIndex);
                MaIndicator.Result.Add(ma);
                Result.Pop();
                return(nullValue);
            }

            double          k   = (GetValueBySource(forIndex) - min.Value) / (max.Value - min.Value) * 100;
            StochasticValue res = new StochasticValue()
            {
                Time   = GetTime(forIndex),
                K      = k,
                D      = 0,
                Source = GetValueBySource(forIndex)
            };

            Result.Push(res);
            ma = (IndicatorValue)MaIndicator.Calculate(forIndex);
            MaIndicator.Result.Add(ma);
            res.D = ma.Value;
            Result.Pop();

            return(res);
        }
Example #15
0
        /// <summary>
        /// Computes a smoothed sum
        /// </summary>
        /// <param name="indicatorValues">Indicator values for which the sum should be computed</param>
        /// <param name="terms">A period in days</param>
        /// <returns>Values of the smoothed sum</returns>
        public static IList <IndicatorValue> SmoothedSum(IList <IndicatorValue> indicatorValues, int terms)
        {
            var values = new List <IndicatorValue>();
            var prev   = new IndicatorValue()
            {
                Date  = indicatorValues[terms - 1].Date,
                Value = indicatorValues.Take(terms).Sum(x => x.Value)
            };

            values.Add(prev);
            for (int i = terms; i < indicatorValues.Count; i++)
            {
                var newVal = new IndicatorValue()
                {
                    Date  = indicatorValues[i].Date,
                    Value = prev.Value - (prev.Value / terms) + indicatorValues[i].Value
                };
                values.Add(newVal);
                prev = newVal;
            }
            return(values);
        }
Example #16
0
        /// <summary>
        /// Computes a smoothed moving average (SSMA)
        /// </summary>
        /// <param name="indicatorValues">Indicator values for which the average should be computed</param>
        /// <param name="terms">A period in days</param>
        /// <returns>Values of the smoothed moving average</returns>
        public static IList <IndicatorValue> SmoothedMovingAverage2(IList <IndicatorValue> indicatorValues, int terms)
        {
            var values = new List <IndicatorValue>();
            var prev   = new IndicatorValue()
            {
                Date  = indicatorValues[terms - 1].Date,
                Value = indicatorValues.Take(terms).Average(x => x.Value)
            };

            values.Add(prev);
            for (int i = terms; i < indicatorValues.Count; i++)
            {
                var newVal = new IndicatorValue()
                {
                    Date  = indicatorValues[i].Date,
                    Value = (prev.Value * (terms - 1) + indicatorValues[i].Value) / terms
                };
                values.Add(newVal);
                prev = newVal;
            }
            return(values);
        }
Example #17
0
        public void KazakhstanValuesCreateByYearIndicator(int Year, int IndicatorId)
        {
            KazakhstanRegionsCreateByYear(Year);
            Indicator             indicator       = _context.Indicator.AsNoTracking().FirstOrDefault(i => i.Id == IndicatorId);
            List <IndicatorValue> indicatorValues = _context.IndicatorValue.AsNoTracking().Include(i => i.Region).Where(i => i.Region.Year == Year && i.IndicatorId == indicator.Id).ToList();
            int indicatorValueKZCount             = _context.IndicatorValue
                                                    .Include(i => i.Region)
                                                    .Count(i => i.Region.Year == Year && i.IndicatorId == indicator.Id && string.IsNullOrEmpty(i.Region.Coordinates) && i.Region.Code == Startup.Configuration["KazakhstanCode"]);

            if (indicatorValueKZCount == 0 && indicatorValues.Count() > 0)
            {
                IndicatorValue indicatorValueKZ = new IndicatorValue()
                {
                    IndicatorId = indicator.Id,
                    RegionId    = _context.Region.AsNoTracking().FirstOrDefault(r => r.Year == Year && string.IsNullOrEmpty(r.Coordinates) && r.Code == Startup.Configuration["KazakhstanCode"]).Id,
                    SourceId    = indicatorValues.FirstOrDefault().SourceId,
                    Year        = indicatorValues.FirstOrDefault().Region.Year,
                    Value       = indicatorValues.Average(i => i.Value)
                };
                _context.Add(indicatorValueKZ);
            }
            _context.SaveChanges();
        }
        public override TimeBaseValue Calculate(int forIndex)
        {
            if (forIndex < Length + 1)
            {
                return new IndicatorValue()
                       {
                           Time = GetTime(forIndex), Value = double.NaN, Source = GetValueBySource(forIndex)
                       }
            }
            ;
            IndicatorValue prev = (IndicatorValue)Result[forIndex - 1];

            if (double.IsNaN(prev.Value))
            {
                prev.Value = ((IndicatorValue)base.Calculate(forIndex - 1)).Value;
            }
            double value = prev.Value + Koeff * (GetValueBySource(forIndex) - prev.Value);

            return(new IndicatorValue()
            {
                Time = GetTime(forIndex), Value = value, Source = GetValueBySource(forIndex)
            });
        }
    }
Example #19
0
        public override void SelectIndicatorValues()
        {
            this.IndicatorValues.ClearOnUI();

            this.Temperature.ClearOnUI();
            this.TemperaturePerCore.ClearOnUI();

            this.Load.ClearOnUI();
            this.LoadPerCore.ClearOnUI();

            try
            {
                // Name
                var name = (from p in this.Indicators
                            where p.Name == "ProcessorName"
                            from q in p.IndicatorValues
                            orderby q.Timestamp descending
                            select q).FirstOrDefault();
                if (name != null)
                {
                    this.Name = name.Value as string;
                }
                else
                {
                    this.Name = " - ";
                }
            }
            catch (Exception)
            {
                Console.WriteLine("CPU VIS PLUGIN: Problem at getting ProcessorName");
                this.Name = " - ";
            }

            try
            {
                var temperatures = (from p in this.Indicators
                                    where p.Name == "Temperature"
                                    from q in p.IndicatorValues
                                    orderby q.Timestamp descending
                                    select new IndicatorValue(Convert.ToByte(q.Value), q.DataType, q.Timestamp, q.MappingState));
                ExtendedObservableCollection <IndicatorValue> filteredTemps = DiagramHelper.filterDiagramValues(temperatures);
                Temperature.BeginAddRange(filteredTemps);


                // this adds all values to the diagram, way too much for wpf toolkit diagrams
                // Temperature
                //this.Temperature.BeginAddRange(from p in this.Indicators
                //                               where p.Name == "Temperature"
                //                               from q in p.IndicatorValues
                //                               select new IndicatorValue(Convert.ToByte(q.Value), q.DataType, q.Timestamp, q.MappingState));
            }
            catch (Exception)
            {
                Console.WriteLine("CPU VIS PLUGIN: Problem at getting Temperature");
            }

            try
            {
                // Temperature Per Core
                var temperatures = from p in this.Indicators
                                   where p.Name == "TemperaturePerCore"
                                   from q in p.IndicatorValues
                                   select q;
                if (temperatures.Count() > 0)
                {
                    IndicatorValue first = null;
                    int            z     = 0;
                    while (first == null)
                    {
                        if (!temperatures.ElementAt(z).Value.ToString().Equals(""))
                        {
                            first = temperatures.ElementAt(z);
                        }
                        z++;
                    }

                    for (int i = 0; i < first.Value.ToString().Split(';').Length; i++)
                    {
                        ExtendedObservableCollection <IndicatorValue> rawValues = new ExtendedObservableCollection <IndicatorValue>();
                        ExtendedObservableCollection <IndicatorValue> filteredValues;

                        foreach (IndicatorValue tempValue in temperatures)
                        {
                            string[] temps = tempValue.Value.ToString().Split(';');
                            if (temps.Length > 0 && temps.Length == first.Value.ToString().Split(';').Length&& !temps[i].Equals(""))
                            {
                                rawValues.Add(new IndicatorValue(Convert.ToByte(temps[i]), tempValue.DataType, tempValue.Timestamp, tempValue.MappingState));
                            }
                        }
                        filteredValues = DiagramHelper.filterDiagramValues(rawValues);
                        this.TemperaturePerCore.BeginAddOnUI(filteredValues);
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("CPU VIS PLUGIN: Problem at getting TemperaturePerCore");
            }


            try
            {
                // Load
                var load = (from p in this.Indicators
                            where p.Name == "Load"
                            from q in p.IndicatorValues
                            select new IndicatorValue(Convert.ToByte(q.Value), q.DataType, q.Timestamp, q.MappingState));
                this.Load.BeginAddRange(DiagramHelper.filterDiagramValues(load));
            }
            catch (Exception)
            {
                Console.WriteLine("CPU VIS PLUGIN: Problem at getting Load");
            }

            try
            {
                // Load Per Core
                var loadValues = from p in this.Indicators
                                 where p.Name == "LoadPerCore"
                                 from q in p.IndicatorValues
                                 select q;

                if (loadValues.Count() > 0)
                {
                    IndicatorValue first = null;
                    int            z     = 0;
                    while (first == null)
                    {
                        if (!loadValues.ElementAt(z).Value.ToString().Equals(""))
                        {
                            first = loadValues.ElementAt(z);
                        }
                        z++;
                    }

                    for (int i = 0; i < first.Value.ToString().Split(';').Length; i++)
                    {
                        ExtendedObservableCollection <IndicatorValue> rawValues = new ExtendedObservableCollection <IndicatorValue>();
                        ExtendedObservableCollection <IndicatorValue> filteredValues;

                        foreach (IndicatorValue value in loadValues)
                        {
                            string[] loads = value.Value.ToString().Split(';');
                            if (loads.Length > 0 && loads.Length == (first.Value as string).Split(';').Length&& !loads[i].Equals(""))
                            {
                                rawValues.Add(new IndicatorValue(Convert.ToByte(loads[i]), value.DataType, value.Timestamp, value.MappingState));
                            }
                        }
                        filteredValues = DiagramHelper.filterDiagramValues(rawValues);
                        this.LoadPerCore.BeginAddOnUI(filteredValues);
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("CPU VIS PLUGIN: Problem at getting LoadPerCore");
            }
        }
        private static string Combine(IndicatorValue existingInd, IndicatorValue newInd)
        {
            if (string.IsNullOrEmpty(existingInd.DynamicValue) && string.IsNullOrEmpty(newInd.DynamicValue))
                return null;
            if (string.IsNullOrEmpty(existingInd.DynamicValue))
                return newInd.DynamicValue;
            if (string.IsNullOrEmpty(newInd.DynamicValue))
                return existingInd.DynamicValue;

            if (existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Multiselect || existingInd.Indicator.DataTypeId == (int)IndicatorDataType.DiseaseMultiselect ||
                existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Partners)
            {
                var vals = existingInd.DynamicValue.Split('|').ToList();
                var newVals = newInd.DynamicValue.Split('|');
                foreach (string newVal in newVals)
                    if (!vals.Contains(newVal))
                        vals.Add(newVal);

                return string.Join("|", vals.ToArray()); 
            }
            else
                return existingInd.DynamicValue + " " + newInd.DynamicValue;
        }
        private static string MergeDropdown(IndicatorValue existingInd, IndicatorValue newInd, List<IndicatorDropdownValue> dropdownOptions, IndicatorEntityType entityType)
        {
            if (string.IsNullOrEmpty(existingInd.DynamicValue) && string.IsNullOrEmpty(newInd.DynamicValue))
                return "";
            if (string.IsNullOrEmpty(newInd.DynamicValue))
                return existingInd.DynamicValue;
            if (string.IsNullOrEmpty(existingInd.DynamicValue))
                return newInd.DynamicValue;
            // Training category other rule
            if (existingInd.DynamicValue == newInd.DynamicValue)
                return newInd.DynamicValue;

            var ind1option = dropdownOptions.FirstOrDefault(i => i.IndicatorId == newInd.IndicatorId && i.EntityType == entityType
                && i.TranslationKey == newInd.DynamicValue);
            var ind2option = dropdownOptions.FirstOrDefault(i => i.IndicatorId == existingInd.IndicatorId && i.EntityType == entityType
                && i.TranslationKey == existingInd.DynamicValue);
            if (ind1option == null)
                return existingInd.DynamicValue;
            if (ind2option == null)
                return newInd.DynamicValue;

            if (newInd.Indicator.MergeRuleId == (int)MergingRule.BestCase)
            {
                if (ind1option.WeightedValue <= ind2option.WeightedValue)
                    return newInd.DynamicValue;
                else
                    return existingInd.DynamicValue;
            }
            if (newInd.Indicator.MergeRuleId == (int)MergingRule.WorstCase)
            {
                if (ind1option.WeightedValue >= ind2option.WeightedValue)
                    return newInd.DynamicValue;
                else
                    return existingInd.DynamicValue;
            }

            return TranslationLookup.GetValue("NA", "NA"); ;
        }
        private static string MergeNumber(IndicatorValue existingInd, IndicatorValue newInd, int ruleId)
        {
            double i1 = 0, i2 = 0;
            if (!Double.TryParse(existingInd.DynamicValue, out i1) && !Double.TryParse(newInd.DynamicValue, out i2))
                return "";
            if (!Double.TryParse(existingInd.DynamicValue, out i1))
                return newInd.DynamicValue;
            if (!Double.TryParse(newInd.DynamicValue, out i2))
                return existingInd.DynamicValue;

            if (ruleId == (int)MergingRule.Min)
            {
                if (i1 >= i2)
                    return newInd.DynamicValue;
                else
                    return existingInd.DynamicValue;
            }
            else if (ruleId == (int)MergingRule.Max)
            {
                if (i1 >= i2)
                    return existingInd.DynamicValue;
                else
                    return newInd.DynamicValue;
            }
            else if (ruleId == (int)MergingRule.Average)
            {
                if (i1 == 0)
                    return i2.ToString();
                if (i2 == 0)
                    return i1.ToString();
                return ((i1 + i2) / 2).ToString();
            }
            else // default sum
                return (i1 + i2).ToString();
        }
        private static string MergeDate(IndicatorValue existingInd, IndicatorValue newInd, int ruleId)
        {
            if (string.IsNullOrEmpty(existingInd.DynamicValue) && string.IsNullOrEmpty(newInd.DynamicValue))
                return "";
            if (string.IsNullOrEmpty(existingInd.DynamicValue))
                return newInd.DynamicValue;
            if (string.IsNullOrEmpty(newInd.DynamicValue))
                return existingInd.DynamicValue;

            DateTime newDate = DateTime.ParseExact(newInd.DynamicValue, "MM/dd/yyyy", CultureInfo.InvariantCulture);
            DateTime existing = DateTime.ParseExact(existingInd.DynamicValue, "MM/dd/yyyy", CultureInfo.InvariantCulture);

            if (ruleId == (int)MergingRule.Max)
            {
                if (existing >= newDate)
                    return existing.ToString("MM/dd/yyyy");
                else
                    return newDate.ToString("MM/dd/yyyy");
            }
            else
            {
                if (newDate <= (DateTime)existing)
                    return newDate.ToString("MM/dd/yyyy");
                else
                    return existing.ToString("MM/dd/yyyy");
            }
        }
 public object GetParamValue(EquipmentConnectorCfg equipment, IndicatorConnectorCfg indicator, IndicatorValue value)
 {
     return(lambda0.Value.DynamicInvoke(equipment, indicator, value));
 }
        public static IndicatorValue Merge(IndicatorValue existingInd, IndicatorValue newInd, List<IndicatorDropdownValue> dropdownOptions,
            IndicatorEntityType entityType)
        {
            newInd.CalcByRedistrict = true;
            newInd.Indicator = existingInd.Indicator;
            newInd.IndicatorId = existingInd.IndicatorId;
            if (existingInd.Indicator.MergeRuleId == (int)MergingRule.CaseFindingStrategy)
                newInd.DynamicValue = MergeCaseFindingStrategy(existingInd, newInd);
            else if ((existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Number || existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Year || existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Month || existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Integer)
                && (existingInd.Indicator.MergeRuleId == (int)MergingRule.Average || existingInd.Indicator.MergeRuleId == (int)MergingRule.Min ||
                existingInd.Indicator.MergeRuleId == (int)MergingRule.Max || existingInd.Indicator.MergeRuleId == (int)MergingRule.Sum))
                newInd.DynamicValue = MergeNumber(existingInd, newInd, existingInd.Indicator.MergeRuleId);
            else if (existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Date &&
                (existingInd.Indicator.MergeRuleId == (int)MergingRule.Min || existingInd.Indicator.MergeRuleId == (int)MergingRule.Max))
                newInd.DynamicValue = MergeDate(existingInd, newInd, existingInd.Indicator.MergeRuleId);
            else if (existingInd.Indicator.MergeRuleId == (int)MergingRule.ListAll)
                newInd.DynamicValue = Combine(existingInd, newInd);
            else if (existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Dropdown &&
                (existingInd.Indicator.MergeRuleId == (int)MergingRule.WorstCase || existingInd.Indicator.MergeRuleId == (int)MergingRule.BestCase || existingInd.Indicator.MergeRuleId == (int)MergingRule.Other))
                newInd.DynamicValue = MergeDropdown(existingInd, newInd, dropdownOptions, entityType);
            else //defaultblank/tbd/leaveblank53/leaveblank59
                newInd.DynamicValue = "";

            return newInd;
        }
        private static string SplitByPercentAndRoundToNearestInt(IndicatorValue existingValue, double percentage)
        {
            double i1 = 0;
            if (!Double.TryParse(existingValue.DynamicValue, out i1))
                return "";

            return ((int)Math.Round(i1 * percentage)).ToString();
        }
        private static string SplitByPercent(IndicatorValue existingValue, double percentage)
        {
            double i1 = 0;
            if (!Double.TryParse(existingValue.DynamicValue, out i1))
                return "";

            return (i1 * percentage).ToString();
        }
        public static IndicatorValue Redistribute(IndicatorValue existingInd, double percentage)
        {
            IndicatorValue result = new IndicatorValue { CalcByRedistrict = true };
            result.Indicator = existingInd.Indicator;
            result.IndicatorId = existingInd.IndicatorId;
            if (existingInd.Indicator.RedistrictRuleId == (int)RedistrictingRule.Duplicate)
                result.DynamicValue = existingInd.DynamicValue;
            else if (existingInd.Indicator.RedistrictRuleId == (int)RedistrictingRule.SplitByPercent && existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Number)
                result.DynamicValue = SplitByPercent(existingInd, percentage);
            else if (existingInd.Indicator.RedistrictRuleId == (int)RedistrictingRule.SplitByPercent && existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Integer)
                result.DynamicValue = SplitByPercentAndRoundToNearestInt(existingInd, percentage);
            else // defaultblank/TBD
                result.DynamicValue = "";

            return result;
        }
Example #29
0
        public List <IndicatorValue> CalculateIndicatorValues(string Formula, int IndicatorId)
        {
            List <IndicatorValue> indicatorValues = new List <IndicatorValue>();
            string        formula_test            = Formula;
            List <Region> regions = _context.Region.ToList();

            foreach (var region in regions)
            {
                IndicatorValue indicatorValue = _context.IndicatorValue.AsNoTracking().FirstOrDefault(iv => iv.RegionId == region.Id && iv.IndicatorId == IndicatorId);
                if (indicatorValue == null)
                {
                    indicatorValue = new IndicatorValue()
                    {
                        Id          = 0,
                        IndicatorId = IndicatorId
                    };
                }
                indicatorValue.RegionId = region.Id;
                indicatorValue.Region   = region;
                indicatorValue.Year     = region.Year;
                indicatorValues.Add(indicatorValue);
            }
            // => calculate values
            string code = $"decimal?[] r = new decimal?[{indicatorValues.Count().ToString()}];";

            for (int i = 0; i < indicatorValues.Count(); i++)
            {
                code += @"
                        ";
                string formula_code = formula_test;
                while (formula_code.IndexOf("Area") >= 0)
                {
                    formula_code = formula_code.Replace("Area", indicatorValues[i].Region.Area.ToString());
                }
                while (formula_code.IndexOf("Population") >= 0)
                {
                    formula_code = formula_code.Replace("Population", indicatorValues[i].Region.Area.ToString());
                }
                while (formula_code.IndexOf("$") >= 0)
                {
                    DollarRate dollarRate      = _context.DollarRate.AsNoTracking().FirstOrDefault(d => d.Year == indicatorValues[i].Region.Year);
                    decimal?   dollarRateValue = dollarRate == null ? null : dollarRate.Value;
                    formula_code = formula_code.Replace("$", dollarRateValue == null ? "null" : dollarRateValue.ToString());
                }
                while (formula_code.IndexOf("Min") >= 0)
                {
                    int M = formula_code.IndexOf("Min"),
                        I = formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"], M),
                        d = formula_code.IndexOf(Startup.Configuration["FormulaIdLastChar"], I);
                    int            indicatorId    = Convert.ToInt32(formula_code.Substring(I + 1, d - I - 1));
                    ReferencePoint referencePoint = _context.ReferencePoint
                                                    .FirstOrDefault(r => r.IndicatorId == indicatorId);
                    decimal referencePointValue = referencePoint != null ? referencePoint.Min : 0;
                    formula_code = formula_code.Remove(M, d - M + 1 + 1);
                    formula_code = formula_code.Insert(M, referencePointValue.ToString());
                }
                while (formula_code.IndexOf("Max") >= 0)
                {
                    int M = formula_code.IndexOf("Max"),
                        I = formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"], M),
                        d = formula_code.IndexOf(Startup.Configuration["FormulaIdLastChar"], I);
                    int            indicatorId    = Convert.ToInt32(formula_code.Substring(I + 1, d - I - 1));
                    ReferencePoint referencePoint = _context.ReferencePoint
                                                    .FirstOrDefault(r => r.IndicatorId == indicatorId);
                    decimal referencePointValue = referencePoint != null ? referencePoint.Max : 0;
                    formula_code = formula_code.Remove(M, d - M + 1 + 1);
                    formula_code = formula_code.Insert(M, referencePointValue.ToString());
                }
                while (formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"]) >= 0)
                {
                    int I = formula_code.IndexOf(Startup.Configuration["FormulaIdFirstChar"]),
                        d = formula_code.IndexOf(Startup.Configuration["FormulaIdLastChar"]);
                    int            indicatorId    = Convert.ToInt32(formula_code.Substring(I + 1, d - I - 1));
                    IndicatorValue indicatorValue = _context.IndicatorValue
                                                    .AsNoTracking()
                                                    .FirstOrDefault(iv => iv.IndicatorId == indicatorId && iv.RegionId == indicatorValues[i].RegionId && iv.Year == indicatorValues[i].Year);
                    decimal?indicatorValueValue       = indicatorValue != null ? indicatorValue.Value : null;
                    string  indicatorValueValueString = indicatorValueValue != null?indicatorValueValue.ToString() : "null";

                    formula_code = formula_code.Remove(I, d - I + 1);
                    formula_code = formula_code.Insert(I, indicatorValueValueString);
                }
                formula_code = formula_code.Replace(',', '.');
                for (int j = formula_code.Length - 1; j >= 0; j--)
                {
                    bool insert = false;
                    if (Char.IsDigit(formula_code[j]))
                    {
                        insert = true;
                    }
                    if (j != formula_code.Length - 1)
                    {
                        if (formula_code[j + 1] == '.' || Char.IsDigit(formula_code[j + 1]))
                        {
                            insert = false;
                        }
                    }
                    if (insert)
                    {
                        formula_code = formula_code.Insert(j + 1, "M");
                    }
                }
                if (formula_code.Contains("null"))
                {
                    formula_code = "null";
                }
                code += $"r[{i.ToString()}] = null;" + "try{" + $"r[{i.ToString()}] = (decimal?)({formula_code});" + "} catch { }";
            }
            string     codeToCompile = @"using System;
                    namespace RoslynCompile
                    {
                        public class Calculator
                        {
                            public decimal?[] Calculate()
                            {
                                " + code + @"
                                return r;
                            }
                        }
                    }";
            SyntaxTree syntaxTree    = CSharpSyntaxTree.ParseText(codeToCompile);
            string     assemblyName  = Path.GetRandomFileName();

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location)
            };
            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);
                if (!result.Success)
                {
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);
                    indicatorValues = new List <IndicatorValue>();
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly   assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
                    var        type     = assembly.GetType("RoslynCompile.Calculator");
                    var        instance = assembly.CreateInstance("RoslynCompile.Calculator");
                    var        meth     = type.GetMember("Calculate").First() as MethodInfo;
                    decimal?[] r        = meth.Invoke(instance, null) as decimal?[];
                    for (int i = 0; i < indicatorValues.Count(); i++)
                    {
                        indicatorValues[i].Value = r[i];
                    }
                }
            }
            // <=
            return(indicatorValues);
        }
Example #30
0
        private void DrawValueIndicator(SKCanvas canvas, int width, int height)
        {
            if (IndicatorValue < Minimum || IndicatorValue > Maximum)
            {
                return;
            }

            float indicatorPosition = (height - guageWidth * 2) * (1f - (IndicatorValue - Minimum) / (Maximum - Minimum)) + guageWidth;
            float verticalMargin    = guageWidth / 2 + regularStrokeWidth / 2;

            //Draw Indicator Line
            var start = new SKPoint(IndicatorDirection == "Right" ? guageWidth + 10 : width - guageWidth - 10, indicatorPosition);
            var end   = new SKPoint(IndicatorDirection == "Right" ? guageWidth + 40 : width - guageWidth - 40, indicatorPosition);

            canvas.DrawLine(start, end, indicatorStrokePaint);

            //Draw Value Label
            using (var textPaint = new SKPaint())
            {
                textPaint.TextSize    = (Device.RuntimePlatform == Device.Android) ? 36 : 20;
                textPaint.IsAntialias = true;
                textPaint.Color       = strokeColor;
                textPaint.IsStroke    = false;

                var indicatorText = IndicatorValue.ToString("0.0") + (!String.IsNullOrEmpty(IndicatorValueUnit) ? " " + IndicatorValueUnit : "");

                if (IndicatorDirection == "Right")
                {
                    canvas.DrawText(indicatorText, guageWidth + 40 + 10, indicatorPosition + 14, textPaint);
                }
                else
                {
                    float textWidth = textPaint.MeasureText(indicatorText);

                    canvas.DrawText(indicatorText, width - guageWidth - 40 - 10 - textWidth, indicatorPosition + 14, textPaint);
                }
            }

            //Fill the guage
            using (SKPath containerPath = new SKPath())
            {
                switch (IndicatorDirection)
                {
                case "Right":
                    containerPath.MoveTo(regularStrokeWidth / 2, indicatorPosition);
                    containerPath.LineTo(guageWidth + regularStrokeWidth / 2, indicatorPosition);
                    containerPath.LineTo(guageWidth + regularStrokeWidth / 2, height - verticalMargin);
                    containerPath.ArcTo(guageWidth / 2, guageWidth / 2, 0, SKPathArcSize.Large, SKPathDirection.Clockwise, regularStrokeWidth / 2, height - verticalMargin);
                    containerPath.Close();
                    break;

                case "Left":
                    containerPath.MoveTo(width - guageWidth - regularStrokeWidth / 2, indicatorPosition);
                    containerPath.LineTo(width - regularStrokeWidth / 2, indicatorPosition);
                    containerPath.LineTo(width - regularStrokeWidth / 2, height - verticalMargin);
                    containerPath.ArcTo(guageWidth / 2, guageWidth / 2, 0, SKPathArcSize.Large, SKPathDirection.Clockwise, width - guageWidth - regularStrokeWidth / 2, height - verticalMargin);
                    containerPath.Close();
                    break;
                }

                canvas.DrawPath(containerPath, fillPaint);
            }
        }
Example #31
0
 protected static void AddValueParam(OleDbCommand command, IndicatorValue val)
 {
     if (val.Indicator.DataTypeId == (int)IndicatorDataType.LargeText)
     {
         command.Parameters.Add(OleDbUtil.CreateNullableParam("@DynamicValue", string.Empty));
         command.Parameters.Add(OleDbUtil.CreateNullableParam("@MemoValue", val.DynamicValue));
     }
     else
     {
         command.Parameters.Add(OleDbUtil.CreateNullableParam("@DynamicValue", val.DynamicValue));
         command.Parameters.Add(OleDbUtil.CreateNullableParam("@MemoValue", string.Empty));
     }
 }
        private static string MergeCaseFindingStrategy(IndicatorValue existingInd, IndicatorValue newInd)
        {
            if (string.IsNullOrEmpty(existingInd.DynamicValue) && string.IsNullOrEmpty(newInd.DynamicValue))
                return "";
            if (string.IsNullOrEmpty(existingInd.DynamicValue))
                return newInd.DynamicValue;
            if (string.IsNullOrEmpty(newInd.DynamicValue))
                return existingInd.DynamicValue;

            if (existingInd.DynamicValue == "Passive" || existingInd.DynamicValue == TranslationLookup.GetValue("Passive", "Passive") &&
                newInd.DynamicValue == "Passive" || newInd.DynamicValue == TranslationLookup.GetValue("Passive", "Passive"))
                return existingInd.DynamicValue;
            if (existingInd.DynamicValue == "Active" || existingInd.DynamicValue == TranslationLookup.GetValue("Active", "Active") &&
                newInd.DynamicValue == "Active" || newInd.DynamicValue == TranslationLookup.GetValue("Active", "Active"))
                return existingInd.DynamicValue;

            if (existingInd.Indicator.DataTypeId == (int)IndicatorDataType.Dropdown)
                return "Combined";
            else
                return existingInd.DynamicValue + ", " + newInd.DynamicValue;
        }
Example #33
0
        private void AddDepartmentIndicatorValueByCalculation(Guid dlSourceSystemId, DateTime addTime)
        {
            using (ImsDbContext context = new ImsDbContext())
            {
                //1 由项目来源部门找出管属项目

                var indicatorItems = context.Indicators.Where(i => i.DataSourceSystemID != null && i.DataSourceSystemID == dlSourceSystemId).OrderBy(i => i.Name).ToList();
                foreach (var indicator in indicatorItems)
                {
                    //2 管属项目找到对应的科室类别项目映射表,找到对应科室类别
                    var departmentCategoryIndicators = indicator.DepartmentCategoryIndicatorMaps.ToList();
                    //列举出对应的科室类别,再由此找到每个科室
                    foreach (var categoryIndicator in departmentCategoryIndicators)
                    {
                        //3 通过科室类别找到管辖的科室,逐一与项目组合,添加到科室项目值表
                        var departmentCategory = categoryIndicator.DepartmentCategory;
                        if (departmentCategory == null)
                        {
                            continue;
                        }
                        //var departments = departmentCategory.Departments;
                        //列出该科室负责的填报项目,再逐步添加到值表中。

                        foreach (var department in departmentCategory.Departments)
                        {
                            //需先查重,如果已经该项目已存在于数据库,不添加
                            //检查下一项
                            var query = context.DepartmentIndicatorValues.Where(d => d.DepartmentID == department.DepartmentID && d.IndicatorID == indicator.IndicatorID &&
                                                                                d.Time.Year == addTime.Year && d.Time.Month == addTime.Month).FirstOrDefault();
                            if (query != null)
                            {
                                //需计算出该结果值
                                //相当于一个Update
                                IndicatorValue indicatorValue = new IndicatorValue();
                                var            valueReturned  = indicatorValue.GetDepartmentIndicatorValueByCalculate(query.DepartmentID, query.IndicatorID, addTime);
                                //根据项目值单位,如果是“百分比”,需乘以100
                                if (indicator.Unit == "百分比")
                                {
                                    valueReturned *= 100;
                                }
                                query.Value = valueReturned;

                                #region Client win context.SaveChanges();
                                bool saveFailed;
                                do
                                {
                                    saveFailed = false;
                                    try
                                    {
                                        context.SaveChanges();
                                    }
                                    catch (DbUpdateConcurrencyException ex)
                                    {
                                        saveFailed = true;

                                        // Update original values from the database
                                        var entry = ex.Entries.Single();
                                        entry.OriginalValues.SetValues(entry.GetDatabaseValues());
                                    }
                                } while (saveFailed);
                                #endregion
                            }
                            else
                            {
                                //不存在该项目,需添加到数据库
                                IMS.Models.DepartmentIndicatorValue item = new IMS.Models.DepartmentIndicatorValue();
                                item.DepartmentID = department.DepartmentID;
                                item.IndicatorID  = indicator.IndicatorID;
                                item.Time         = addTime;
                                item.ID           = System.Guid.NewGuid();
                                //从计算获取该值
                                IndicatorValue indicatorValue = new IndicatorValue();
                                var            valueReturned  = indicatorValue.GetDepartmentIndicatorValueByCalculate(item.DepartmentID, item.IndicatorID, addTime);
                                //根据项目值单位,如果是“百分比”,需乘以100
                                if (indicator.Unit == "百分比")
                                {
                                    valueReturned *= 100;
                                }
                                item.Value = valueReturned;
                                context.DepartmentIndicatorValues.Add(item);
                                context.SaveChanges();
                            }
                        }
                    }
                }
            }
        }
Example #34
0
        protected override Gui.Mesh Redraw()
        {
            var meshes   = new List <Gui.Mesh>();
            var interior = Rect;

            if (DrawFrame)
            {
                meshes.Add(Gui.Mesh.Quad()
                           .Scale(Rect.Width, Rect.Height)
                           .Translate(Rect.X, Rect.Y)
                           .Colorize(MouseIsOver
                        ? new Vector4(1, 0.5f, 0.5f, 1)
                        : (Hilite ? new Vector4(1, 0, 0, 1) : BackgroundColor))
                           .Texture(Root.GetTileSheet(Background.Sheet).TileMatrix(Background.Tile)));
                interior = Rect.Interior(4, 4, 4, 4);
            }

            if (Icon != null)
            {
                var iconSheet = Root.GetTileSheet(Icon.Sheet);

                if (interior.Width > iconSheet.TileWidth)
                {
                    meshes.Add(Gui.Mesh.Quad()
                               .Scale(iconSheet.TileWidth, iconSheet.TileHeight)
                               .Texture(iconSheet.TileMatrix(Icon.Tile))
                               .Translate(Rect.X + (Rect.Width / 2) - (iconSheet.TileWidth / 2),
                                          Rect.Y + (Rect.Height / 2) - (iconSheet.TileHeight / 2))
                               .Colorize(Enabled ? Tint : new Vector4(0.15f * Tint.X, 0.15f * Tint.Y, 0.15f * Tint.Z, 1 * Tint.W)));
                }
                else
                {
                    meshes.Add(Gui.Mesh.Quad()
                               .Scale(interior.Width, interior.Height)
                               .Texture(iconSheet.TileMatrix(Icon.Tile))
                               .Translate(interior.X, interior.Y)
                               .Colorize(Enabled ? Tint : new Vector4(0.15f * Tint.X, 0.15f * Tint.Y, 0.15f * Tint.Z, 1 * Tint.W)));
                }
            }

            if (!string.IsNullOrEmpty(Text))
            {
                if (Enabled && ChangeTextColorOnEnable)
                {
                    TextColor = EnabledTextColor;
                }
                else if (!Enabled && ChangeTextColorOnEnable)
                {
                    TextColor = DisabledTextColor;
                }
                base.GetTextMesh(meshes);
            }

            if (DrawIndicator && IndicatorValue != 0)
            {
                var indicatorTile = Root.GetTileSheet("indicator-circle");
                meshes.Add(Gui.Mesh.Quad()
                           .Scale(16, 16)
                           .Texture(indicatorTile.TileMatrix(0))
                           .Translate(Rect.Right - 16,
                                      Rect.Bottom - 16).Colorize(Color.OrangeRed.ToVector4()));
                var numberSize = new Rectangle();
                var font       = Root.GetTileSheet("font8");
                var stringMesh = Gui.Mesh.CreateStringMesh(
                    IndicatorValue.ToString(),
                    font,
                    new Vector2(1, 1),
                    out numberSize)
                                 .Colorize(new Vector4(1, 1, 1, 1));
                meshes.Add(stringMesh.
                           Translate(Rect.Right - 8 - (numberSize.Width / 2),
                                     Rect.Bottom - 8 - (numberSize.Height / 2)));
            }

            if (DrawHotkey)
            {
                var  font       = Root.GetTileSheet("font8");
                var  numberSize = new Rectangle();
                char hotkey     = '?';
                InputManager.TryConvertKeyboardInput(HotkeyValue, false, out hotkey);
                var stringMesh = Gui.Mesh.CreateStringMesh(
                    hotkey.ToString(),
                    font,
                    new Vector2(1, 1),
                    out numberSize)
                                 .Colorize(new Vector4(1, 1, 1, 0.4f));
                meshes.Add(stringMesh.
                           Translate(Rect.Left + 8 - (numberSize.Width / 2),
                                     Rect.Top + 8 - (numberSize.Height / 2)));
            }

            return(Gui.Mesh.Merge(meshes.ToArray()));
        }
        /// <summary>
        /// Adds Oncho information
        /// </summary>
        /// <param name="xlsWorksheet"></param>
        /// <param name="rng"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="demography"></param>
        /// <param name="aggIntvs"></param>
        private void AddOncho(excel.Worksheet xlsWorksheet, excel.Range rng, DateTime start, DateTime end, List<AdminLevel> demography, Dictionary<int, DataRow> aggIntvs)
        {
            List<string> typeNames = new List<string> { "IntvIvmPzqAlb", "IntvIvmPzq", "IntvIvmAlb", "IntvIvm" };
            List<int> typeIds = new List<int> { (int)StaticIntvType.IvmPzqAlb, (int)StaticIntvType.IvmPzq, (int)StaticIntvType.IvmAlb, (int)StaticIntvType.Ivm };
            // Get ONCHO Disease Distributions
            DiseaseDistroPc oncho;
            Dictionary<int, DataRow> onchoDd;
            GetDdForDisease(start, end, demography, out oncho, out onchoDd, DiseaseType.Oncho);

            // Get ONCHO Surveys 
            var surveys = surveyRepo.GetByTypeInDateRange(
                new List<int> { (int)StaticSurveyType.OnchoMapping, (int)StaticSurveyType.OnchoAssessment }, StartDate, EndDate);
            int maxLvl = 0;
            foreach (var s in surveys)
            {
                IndicatorValue posVal = new IndicatorValue { DynamicValue = null };
                if (s.TypeOfSurvey.Id == (int)StaticSurveyType.OnchoMapping)
                    posVal = s.IndicatorValues.FirstOrDefault(v => v.Indicator.DisplayName == "OnchoMapSurNumberOfIndividualsPositive");
                else
                    posVal = s.IndicatorValues.FirstOrDefault(v => v.Indicator.DisplayName == "OnchoSurNumberOfIndividualsPositive");

                if (!string.IsNullOrEmpty(posVal.DynamicValue) && maxLvl < s.AdminLevels.Max(a => a.LevelNumber))
                    maxLvl = s.AdminLevels.Max(a => a.LevelNumber);
            }
            var level = settings.GetAdminLevelTypeByLevel(maxLvl);

            int rowCount = 16;
            foreach (var unit in demography)
            {
                // SURVEYS
                if (level != null && !string.IsNullOrEmpty(level.DisplayName))
                    AddValueToRange(xlsWorksheet, rng, "F" + rowCount, level.DisplayName);
           
                var mostRecentSurvey = surveys.Where(s => s.AdminLevels.Select(a => a.Id).Contains(unit.Id)).OrderByDescending(s => s.DateReported).FirstOrDefault();
                if (mostRecentSurvey != null)
                {
                    string testType = null;
                    string percent = null;
                    int year = 0;
                    if (mostRecentSurvey.TypeOfSurvey.Id == (int)StaticSurveyType.OnchoAssessment)
                    {
                        var ind = mostRecentSurvey.IndicatorValues.FirstOrDefault(v => v.Indicator.DisplayName == "OnchoSurTestType");
                        if (ind != null)
                            testType = ind.DynamicValue;
                        percent = GetPercentPositive(mostRecentSurvey, "OnchoSurNumberOfIndividualsPositive", "OnchoSurNumberOfIndividualsExamined", out year);
                    }
                    else if (mostRecentSurvey.TypeOfSurvey.Id == (int)StaticSurveyType.OnchoMapping)
                    {
                        var ind = mostRecentSurvey.IndicatorValues.FirstOrDefault(v => v.Indicator.DisplayName == "OnchoMapSurTestType");
                        if (ind != null)
                            testType = ind.DynamicValue;
                        percent = GetPercentPositive(mostRecentSurvey, "OnchoMapSurNumberOfIndividualsPositive", "OnchoMapSurNumberOfIndividualsExamined", out year);
                    }
                    AddValueToRange(xlsWorksheet, rng, "H" + rowCount, percent);
                    AddValueToRange(xlsWorksheet, rng, "I" + rowCount, year);
                    AddValueToRange(xlsWorksheet, rng, "J" + rowCount, testType);
                }

                // DISEASE DISTRO
                if (onchoDd.ContainsKey(unit.Id))
                {
                    string endemicity = ParseOnchoDdEndo(onchoDd[unit.Id][TranslationLookup.GetValue("DDOnchoDiseaseDistributionPcInterventio") + " - " + oncho.Disease.DisplayName].ToString());
                    AddValueToRange(xlsWorksheet, rng, "G" + rowCount, endemicity);

                    AddValueToRange(xlsWorksheet, rng, "K" + rowCount,
                        onchoDd[unit.Id][TranslationLookup.GetValue("DDOnchoPopulationAtRisk") + " - " + oncho.Disease.DisplayName]);
                    AddValueToRange(xlsWorksheet, rng, "L" + rowCount,
                        onchoDd[unit.Id][TranslationLookup.GetValue("DDOnchoPopulationRequiringPc") + " - " + oncho.Disease.DisplayName]);
                    AddValueToRange(xlsWorksheet, rng, "M" + rowCount,
                        onchoDd[unit.Id][TranslationLookup.GetValue("DDOnchoPopulationLivingInTheDistrictsTha") + " - " + oncho.Disease.DisplayName]);
                    AddValueToRange(xlsWorksheet, rng, "N" + rowCount,
                        onchoDd[unit.Id][TranslationLookup.GetValue("DDOnchoYearDeterminedThatAchievedCriteri") + " - " + oncho.Disease.DisplayName]);
                    AddValueToRange(xlsWorksheet, rng, "O" + rowCount,
                        onchoDd[unit.Id][TranslationLookup.GetValue("DDOnchoNumPcRoundsYearCurrentlyImplemen") + " - " + oncho.Disease.DisplayName]);
                    AddValueToRange(xlsWorksheet, rng, "Q" + rowCount,
                        onchoDd[unit.Id][TranslationLookup.GetValue("DDOnchoYearPcStarted") + " - " + oncho.Disease.DisplayName]);
                }

                // MDA count
                int mdas = 0, consecutive = 0;
                CountMdas(typeIds, unit.Id, unit.Children.Select(c => c.Id).ToList(), out mdas, out consecutive, "Oncho");
                AddValueToRange(xlsWorksheet, rng, "R" + rowCount, mdas);
                AddValueToRange(xlsWorksheet, rng, "S" + rowCount, consecutive);

                // INTVS
                if (aggIntvs.ContainsKey(unit.Id))
                {
                    // ROUND 1
                    List<string> typesToCalc = new List<string>();
                    DateTime? startMda = GetDateFromRow("PcIntvStartDateOfMda", ref typesToCalc, aggIntvs[unit.Id], false, 1, 1, "Oncho", typeNames);
                    if (startMda.HasValue)
                    {
                        AddValueToRange(xlsWorksheet, rng, "V" + rowCount, startMda.Value.ToString("MMMM"));
                        AddValueToRange(xlsWorksheet, rng, "W" + rowCount, startMda.Value.Year);
                    }
                    DateTime? endMda = GetDateFromRow("PcIntvEndDateOfMda", ref typesToCalc, aggIntvs[unit.Id], true, 1, 1, "Oncho", typeNames);
                    if (endMda.HasValue)
                    {
                        AddValueToRange(xlsWorksheet, rng, "X" + rowCount, endMda.Value.ToString("MMMM"));
                        AddValueToRange(xlsWorksheet, rng, "Y" + rowCount, endMda.Value.Year);
                    }
                    AddValueToRange(xlsWorksheet, rng, "AB" + rowCount, GetIntFromRow("PcIntvNumEligibleIndividualsTargeted", ref typesToCalc, aggIntvs[unit.Id], 1, 1, "Oncho", typeNames, "PcIntvOfTotalTargetedForOncho"));
                    AddValueToRange(xlsWorksheet, rng, "AE" + rowCount, GetIntFromRow("PcIntvNumIndividualsTreated", ref typesToCalc, aggIntvs[unit.Id], 1, 1, "Oncho", typeNames, "PcIntvOfTotalTreatedForOncho"));
                    AddValueToRange(xlsWorksheet, rng, "AG" + rowCount, GetIntFromRow("PcIntvNumFemalesTreated", ref typesToCalc, aggIntvs[unit.Id], 1, 1, "Oncho", typeNames, "PcIntvOfTotalFemalesOncho"));
                    AddValueToRange(xlsWorksheet, rng, "AI" + rowCount, GetIntFromRow("PcIntvNumMalesTreated", ref typesToCalc, aggIntvs[unit.Id], 1, 1, "Oncho", typeNames, "PcIntvOfTotalMalesOncho"));
                    AddValueToRange(xlsWorksheet, rng, "AK" + rowCount, GetDropdownFromRow("PcIntvStockOutDuringMda", ref typesToCalc, aggIntvs[unit.Id], 249, 1, 1, "Oncho", typeNames));
                    AddValueToRange(xlsWorksheet, rng, "AM" + rowCount, GetDropdownFromRow("PcIntvLengthOfStockOut", ref typesToCalc, aggIntvs[unit.Id], 251, 1, 1, "Oncho", typeNames));
                    AddValueToRange(xlsWorksheet, rng, "AL" + rowCount, GetCombineFromRow("PcIntvStockOutDrug", ref typesToCalc, aggIntvs[unit.Id], 1, 1, "Oncho", typeNames));

                    RemoveDataValidation(xlsWorksheet, rng, "U" + rowCount);
                    AddValueToRange(xlsWorksheet, rng, "U" + rowCount, TranslateMdaType(typesToCalc));

                    // ROUND 2
                    typesToCalc = new List<string>();
                    startMda = GetDateFromRow("PcIntvStartDateOfMda", ref typesToCalc, aggIntvs[unit.Id], false, 2, 2, "Oncho", typeNames);
                    if (startMda.HasValue)
                    {
                        AddValueToRange(xlsWorksheet, rng, "AU" + rowCount, startMda.Value.ToString("MMMM"));
                        AddValueToRange(xlsWorksheet, rng, "AV" + rowCount, startMda.Value.Year);
                    }
                    endMda = GetDateFromRow("PcIntvEndDateOfMda", ref typesToCalc, aggIntvs[unit.Id], true, 2, 2, "Oncho", typeNames);
                    if (endMda.HasValue)
                    {
                        AddValueToRange(xlsWorksheet, rng, "AW" + rowCount, endMda.Value.ToString("MMMM"));
                        AddValueToRange(xlsWorksheet, rng, "AX" + rowCount, endMda.Value.Year);
                    }
                    AddValueToRange(xlsWorksheet, rng, "BA" + rowCount, GetIntFromRow("PcIntvNumEligibleIndividualsTargeted", ref typesToCalc, aggIntvs[unit.Id], 2, 2, "Oncho", typeNames, "PcIntvOfTotalTargetedForOncho"));
                    AddValueToRange(xlsWorksheet, rng, "BD" + rowCount, GetIntFromRow("PcIntvNumIndividualsTreated", ref typesToCalc, aggIntvs[unit.Id], 2, 2, "Oncho", typeNames, "PcIntvOfTotalTreatedForOncho"));
                    AddValueToRange(xlsWorksheet, rng, "BF" + rowCount, GetIntFromRow("PcIntvNumFemalesTreated", ref typesToCalc, aggIntvs[unit.Id], 2, 2, "Oncho", typeNames, "PcIntvOfTotalFemalesOncho"));
                    AddValueToRange(xlsWorksheet, rng, "BH" + rowCount, GetIntFromRow("PcIntvNumMalesTreated", ref typesToCalc, aggIntvs[unit.Id], 2, 2, "Oncho", typeNames, "PcIntvOfTotalMalesOncho"));
                    AddValueToRange(xlsWorksheet, rng, "BJ" + rowCount, GetDropdownFromRow("PcIntvStockOutDuringMda", ref typesToCalc, aggIntvs[unit.Id], 249, 2, 2, "Oncho", typeNames));
                    AddValueToRange(xlsWorksheet, rng, "BL" + rowCount, GetDropdownFromRow("PcIntvLengthOfStockOut", ref typesToCalc, aggIntvs[unit.Id], 251, 2, 2, "Oncho", typeNames));
                    AddValueToRange(xlsWorksheet, rng, "BK" + rowCount, GetCombineFromRow("PcIntvStockOutDrug", ref typesToCalc, aggIntvs[unit.Id], 2, 2, "Oncho", typeNames));
                    AddValueToRange(xlsWorksheet, rng, "BS" + rowCount, GetCombineFromRow("Notes", ref typesToCalc, aggIntvs[unit.Id], 1, Util.MaxRounds, "Oncho", typeNames));

                    RemoveDataValidation(xlsWorksheet, rng, "AT" + rowCount);
                    AddValueToRange(xlsWorksheet, rng, "AT" + rowCount, TranslateMdaType(typesToCalc));
                }

                rowCount++;
            }
        }