public ExceptedHalfhoursCalculator(
            DateTime dTStartServer,
            string timeZoneId,
            Dictionary <int, DBDataSourceToTiTp> dataSourceTiTpByMonthNumber,
            Dictionary <int, EnumDataSourceType> dataSourceIdToTypeDict,
            Dictionary <int, List <DBPriorityList> > totalPriorityByMonthNumber,
            bool isExistsNotWorkedPeriod,
            List <Tuple <int, int?> > notWorkedRange,
            List <int> intervalTimeList,
            EnumUnitDigit unitDigit
            , PeriodCoeffWorker <double> coeffTranformationWorker        = null
            , PeriodCoeffWorker <double> coeffLossesWorker               = null
            , PeriodCoeffWorker <bool> coeffTransformationDisabledWorker = null
            , bool useLossesCoeff = false
            , bool isCoeffTransformationDisabledByDefault = false)
        {
            _dTStartServer = dTStartServer;
            _timeZoneId    = timeZoneId;
            _dataSourceTiTpByMonthNumber = dataSourceTiTpByMonthNumber;
            _dataSourceIdToTypeDict      = dataSourceIdToTypeDict;
            _totalPriorityByMonthNumber  = totalPriorityByMonthNumber;
            _isExistsNotWorkedPeriod     = isExistsNotWorkedPeriod;
            _notWorkedRange   = notWorkedRange;
            _unitDigit        = (double)unitDigit;
            _intervalTimeList = intervalTimeList;

            _coeffTranformationWorker          = coeffTranformationWorker;
            _coeffLossesWorker                 = coeffLossesWorker;
            _coeffTransformationDisabledWorker = coeffTransformationDisabledWorker;
            _useLossesCoeff = useLossesCoeff;
            _isCoeffTransformationDisabledByDefault = isCoeffTransformationDisabledByDefault;

            _calculateCoeffs = _coeffTranformationWorker != null && _coeffLossesWorker != null && _coeffTransformationDisabledWorker != null;
        }
예제 #2
0
 /// <summary>
 /// Конструктор
 /// </summary>
 /// <param name="dtStartClien">Начало по времени клиента</param>
 /// <param name="dtEndClient">Окончание по времени клиента</param>
 /// <param name="clientTimeZoneId">Идентификатор часового пояса клиента</param>
 /// <param name="unitDigit">Запрошенные ед. измерения</param>
 /// <param name="discreteType"></param>
 public RecalculatorResiudes(DateTime dtStartClien, DateTime dtEndClient, string clientTimeZoneId, EnumUnitDigit unitDigit, enumTimeDiscreteType discreteType)
 {
     _tiForRecalculateResiudes = new ConcurrentStack <TArchivesValue>();
     TiForResaveResiudes       = new ConcurrentStack <DBResiduesTable>();
     _dtStartClient            = dtStartClien;
     _dtStartServer            = _dtStartClient.ClientToServer(clientTimeZoneId);
     _unitDigit          = unitDigit;
     _discreteType       = discreteType;
     _resiudes24Hindexes = MyListConverters.GetIntervalTimeList(dtStartClien, dtEndClient, enumTimeDiscreteType.DB24Hour, clientTimeZoneId);
 }
예제 #3
0
 public ArchivesHierObjectProvider(List <IHierarchyChannelID> list, bool v, DateTime dtStart, DateTime dtEnd, EnumDataSourceType?_dataSourceType, enumTimeDiscreteType discreteType, EnumUnitDigit none, bool _isReadCalculatedValues, string _timeZoneId)
 {
     this.list                    = list;
     this.v                       = v;
     this.dtStart                 = dtStart;
     this.dtEnd                   = dtEnd;
     this._dataSourceType         = _dataSourceType;
     this.discreteType            = discreteType;
     this.none                    = none;
     this._isReadCalculatedValues = _isReadCalculatedValues;
     this._timeZoneId             = _timeZoneId;
 }
예제 #4
0
        private string UnitDigitToName(EnumUnitDigit unitDigit)
        {
            switch (unitDigit)
            {
            case EnumUnitDigit.Null:
            case EnumUnitDigit.None:
                return("Вт*ч");

            case EnumUnitDigit.Kilo:
                return("кВт*ч");

            case EnumUnitDigit.Mega:
                return("МВт*ч");
            }

            return(string.Empty);
        }
        public TForecastObjectFactDemand(IEnumerable <string> forecastObjectUns, DateTime dtStart, DateTime dtEnd, string timeZoneId,
                                         EnumUnitDigit unitDigit, enumTimeDiscreteType forecastDiscreteType, bool isReadCalculatedValues)
        {
            if (forecastObjectUns == null)
            {
                Errors.Append("Выберите объекты!");
                return; //Критическая ошибка
            }

            ForecastObjectUns      = new HashSet <string>(forecastObjectUns);
            DtStart                = dtStart;
            DtEnd                  = dtEnd;
            TimeZoneId             = timeZoneId;
            UnitDigit              = unitDigit;
            ForecastDiscreteType   = forecastDiscreteType;
            Archives               = new Dictionary <string, List <ForecastByInputParamArchives> >();
            IsReadCalculatedValues = isReadCalculatedValues;
            Errors                 = new StringBuilder();

            if (dtEnd < dtStart)
            {
                Errors.Append("Начальная дата должна быть больше конечной!");
                return; //Критическая ошибка
            }

            #region Читаем архивы

            //_numberHalfHoursForForecasting = MyListConverters.GetNumbersValuesInPeriod(ForecastDiscreteType, forecastingStart, forecastingEnd, TimeZoneId);

            var objectParams = ForecastObjectFactory.GetForecastObjectParams(ForecastObjectUns, dtStart, dtEnd, null, timeZoneId,
                                                                             Errors, unitDigit, forecastDiscreteType, isReadCalculatedValues);

            foreach (var objectParam in objectParams)
            {
                Archives[objectParam.ForecastObject_UN] = objectParam.ArchivesByInputParam;
            }

            #endregion
        }
예제 #6
0
        public static void ConvertClipboardValuesFromVt(bool fromVt, EnumUnitDigit selectedUnitDigits,
                                                        string cultureName, string subformatString, Action <string> onError)
        {
            var result = new StringBuilder();

            try
            {
                var cl   = Clipboard.GetText();
                var ci   = new CultureInfo(cultureName);
                var rows = cl.Split(new[] { "\r\n" }, StringSplitOptions.None);
                foreach (var row in rows.Take(rows.Length - 1))
                {
                    if (row != null)
                    {
                        var cols = row.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
                        if (cols.Length > 0)
                        {
                            foreach (var col in cols)
                            {
                                var    indScope = col.IndexOf('(');
                                string text;

                                if (indScope > 0)
                                {
                                    text = col.Substring(0, indScope);
                                }
                                else
                                {
                                    text = col;
                                }

                                double v;
                                if (double.TryParse(text, NumberStyles.Any, ci, out v) || double.TryParse(text, out v))
                                {
                                    if (fromVt)
                                    {
                                        v = v / (double)selectedUnitDigits;         //Преобразуем из Вт
                                    }
                                    else
                                    {
                                        v = v * (double)selectedUnitDigits;  //Преобразуем в Вт
                                    }
                                    result.Append(v.ToString(subformatString, ci).Trim()).Append("\t");
                                }
                                else
                                {
                                    result.Append(col).Append("\t");
                                }
                            }

                            result.Remove(result.Length - 1, 1);
                        }

                        result.Append(" \r\n");
                    }
                }

                // result.Remove(result.Length - 4, 4);
            }
            catch (Exception ex)
            {
                if (onError != null)
                {
                    onError(ex.Message);
                }
            }

            try
            {
                //Здесь могут быть проблемы в XP, microsoft не пофиксили до сих пор
                Clipboard.SetDataObject(result.ToString());
            }
            catch
            {
            }
        }
        public BalanceFreeHierarchyResults(List <string> balanceFreeHierarchyUNs, DateTime dTStart, DateTime dTEnd,
                                           string timeZoneId, TExportExcelAdapterType adapterType, bool isGenerateDoc, enumTimeDiscreteType discreteType, EnumUnitDigit unitDigit,
                                           EnumUnitDigit unitDigitIntegrals, CancellationToken?cancellationToken = null)
        {
            if (unitDigit == EnumUnitDigit.Null)
            {
                unitDigit = EnumUnitDigit.None;
            }

            BalanceFreeHierarchyUNs = balanceFreeHierarchyUNs.Distinct().ToList();
            DTStart            = dTStart.RoundToHalfHour(true);
            DTEnd              = dTEnd.RoundToHalfHour(true);
            TimeZoneId         = timeZoneId;
            UnitDigit          = unitDigit;
            UnitDigitIntegrals = unitDigitIntegrals;
            AdapterType        = adapterType;
            DiscreteType       = discreteType;
            _cancellationToken = cancellationToken;
            Errors             = new StringBuilder();
            CalculatedValues   = new ConcurrentDictionary <string, BalanceFreeHierarchyCalculatedResult>();

            if (BalanceFreeHierarchyUNs == null || BalanceFreeHierarchyUNs.Count == 0)
            {
                Errors.Append("Неверный идентификатор(ы) баланса!");
                return;
            }

            if ((DTEnd < DTStart))
            {
                Errors.Append("Дата окончания должна быть больше или равна даты начала!");
                return;
            }

            _dtServerStart = DTStart.ClientToServer(TimeZoneId);
            _dtServerEnd   = DTEnd.ClientToServer(TimeZoneId);
            _isGenerateDoc = isGenerateDoc;


            var tiForRequestAdditionalInfo = new ConcurrentDictionary <TI_ChanelType, ConcurrentStack <BalanceFreeHierarchyItemParams> >(new TI_ChanelComparer());

            using (var calculator = new BalanceFreeHierarchyCalculator(BalanceFreeHierarchyUNs, isGenerateDoc, Errors, DiscreteType, DTStart, DTEnd, TimeZoneId, tiForRequestAdditionalInfo,
                                                                       UnitDigit, UnitDigitIntegrals))
            {
                SectionsByType = calculator.SectionsByType;

                var po = new ParallelOptions();
                if (cancellationToken.HasValue)
                {
                    po.CancellationToken = cancellationToken.Value;
                }

                po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
                po.CancellationToken.ThrowIfCancellationRequested();

                //Строим результаты по документам
                Parallel.ForEach(BalanceFreeHierarchyUNs, po, (balanceFreeHierarchyUn, loopState) =>
                {
                    try
                    {
                        if (po.CancellationToken.IsCancellationRequested)
                        {
                            loopState.Break();
                        }

                        var calculatedResult = calculator.Calculate(balanceFreeHierarchyUn);
                        if (calculatedResult == null)
                        {
                            return;
                        }

                        CalculatedValues.TryAdd(balanceFreeHierarchyUn, calculatedResult);
                    }
                    catch (Exception ex)
                    {
                        lock (Errors)
                        {
                            Errors.Append(ex.Message);
                        }
                    }
                });

                SubsectionNames = calculator.SubsectionNames;
            }

            if (_cancellationToken.HasValue && _cancellationToken.Value.IsCancellationRequested)
            {
                return;
            }

            #region Собираем доп. информацию


            if (!tiForRequestAdditionalInfo.IsEmpty)
            {
                SortedList <TI_ChanelType, List <TTransformators_Information> > transormatorsInformation = null;
                ConcurrentDictionary <TI_ChanelType, List <ArchCalc_Replace_ActUndercount> > replaceActUndercountList = null;

                Parallel.Invoke(() =>
                {
                    //Информация о смене трансформаторов
                    transormatorsInformation = SectionIntegralActsResultsList.GetTransformationInformationList(DTStart, DTEnd, tiForRequestAdditionalInfo.Keys, UnitDigit,
                                                                                                               enumOVMode.NormalMode, true,
                                                                                                               TimeZoneId);
                },
                                () =>
                {
                    ConcurrentDictionary <TI_ChanelType, List <ArchCalc_Replace_ActUndercount> > resultOvs;
                    //Информация об акте недоучета
                    replaceActUndercountList = SectionIntegralActsResultsList.GetReplaceActUndercount(_dtServerStart, _dtServerEnd, tiForRequestAdditionalInfo.Keys, Errors, out resultOvs);
                }
                                );

                foreach (var pair in tiForRequestAdditionalInfo)
                {
                    if (transormatorsInformation != null)
                    {
                        List <TTransformators_Information> informations;
                        if (transormatorsInformation.TryGetValue(pair.Key, out informations))
                        {
                            foreach (var itemParam in pair.Value)
                            {
                                itemParam.Transformatos_Information = informations;
                            }
                        }
                    }

                    if (replaceActUndercountList != null && replaceActUndercountList.Count > 0)
                    {
                        List <ArchCalc_Replace_ActUndercount> replaceInformation;
                        if (replaceActUndercountList.TryGetValue(pair.Key, out replaceInformation) && replaceInformation != null)
                        {
                            foreach (var itemParam in pair.Value)
                            {
                                itemParam.ReplaceActUndercountList = replaceInformation;
                            }
                        }
                    }
                }
            }

            #endregion
        }
        public ExcelReportFreeHierarchyAdapter(BalanceFreeHierarchyResults balanceCalculated,
                                               Dictionary <string, List <IFreeHierarchyBalanceSignature> > signaturesByBalance,
                                               TExportExcelAdapterType adapterType, StringBuilder errors,
                                               bool isFormingSeparateList,
                                               bool isUseThousandKVt, bool printLandscape, string branchName, byte doublePrecisionProfile,
                                               byte doublePrecisionIntegral, bool need0, bool isAnalisIntegral, string timeZoneId, bool setPercisionAsDisplayed)
        {
            _branchName          = branchName;
            _printLandscape      = printLandscape;
            _balanceCalculated   = balanceCalculated;
            _signaturesByBalance = signaturesByBalance;
            AdapterType          = adapterType;
            _discreteType        = balanceCalculated.DiscreteType;
            _errors  = errors;
            _dtStart = balanceCalculated.DTStart;
            _dtEnd   = balanceCalculated.DTEnd;
            _dts     = MyListConverters.GetDateTimeListForPeriod(balanceCalculated.DTStart, balanceCalculated.DTEnd, balanceCalculated.DiscreteType, balanceCalculated.TimeZoneId.GeTimeZoneInfoById());
            _isFormingSeparateList   = isFormingSeparateList && (AdapterType == TExportExcelAdapterType.toXLS || AdapterType == TExportExcelAdapterType.toXLSx);
            _unitDigitIntegrals      = balanceCalculated.UnitDigitIntegrals;
            _unitDigit               = balanceCalculated.UnitDigit;
            _doublePrecisionIntegral = doublePrecisionIntegral;
            _doublePrecisionProfile  = doublePrecisionProfile;
            _need0                   = need0;
            IsAnalisIntegral         = isAnalisIntegral;
            _setPercisionAsDisplayed = setPercisionAsDisplayed;

            _intervalTimeList = MyListConverters.GetIntervalTimeList(_dtStart, _dtEnd, _discreteType, timeZoneId);

            switch (_unitDigit)
            {
            case EnumUnitDigit.Null:
            case EnumUnitDigit.None:
                _unitDigitName = "";
                break;

            case EnumUnitDigit.Kilo:
                _unitDigitName = "к";
                break;

            case EnumUnitDigit.Mega:
                _unitDigitName = isUseThousandKVt ? "тыс.к" : "М";
                break;
            }

            switch (_unitDigitIntegrals)
            {
            case EnumUnitDigit.Null:
            case EnumUnitDigit.None:
                _unitDigitIntegralName = "";
                break;

            case EnumUnitDigit.Kilo:
                _unitDigitIntegralName = "к";
                break;

            case EnumUnitDigit.Mega:
                _unitDigitIntegralName = isUseThousandKVt ? "тыс.к" : "М";
                break;
            }

            _unitDigitHeatName      = "Гкал"; //решили что отпуск тепла будет хранится/отображаться как есть (например в ЛЭРС) в Гкал
            _unitDigitName         += "Вт*ч";
            _unitDigitIntegralName += "Вт*ч";
        }
예제 #9
0
        public static BalanceFreeHierarchyResults BL_GetFreeHierarchyBalanceResult(List <string> balanceFreeHierarchyUNs, DateTime dTStart, DateTime dTEnd, string timeZoneId,
                                                                                   TExportExcelAdapterType adapterType, bool isGenerateDoc, enumTimeDiscreteType discreteType,
                                                                                   EnumUnitDigit unitDigit, bool isFormingSeparateList, EnumUnitDigit unitDigitIntegrals, bool isUseThousandKVt, bool printLandscape, byte doublePrecisionProfile, byte doublePrecisionIntegral,
                                                                                   bool need0, bool isAnalisIntegral, bool setPercisionAsDisplayed, CancellationToken?cancellationToken = null)
        {
            var balance = new BalanceFreeHierarchyResults(balanceFreeHierarchyUNs, dTStart, dTEnd, timeZoneId, adapterType, isGenerateDoc,
                                                          discreteType, unitDigit, unitDigitIntegrals, cancellationToken);

            if (cancellationToken.HasValue && cancellationToken.Value.IsCancellationRequested)
            {
                return(balance);
            }

            if (isGenerateDoc)
            {
                string branchName;
                //Читаем подписантов
                var signaturesByBalance = GetBalanceSignatures(balanceFreeHierarchyUNs, out branchName);

                var po = new ParallelOptions();
                if (cancellationToken.HasValue)
                {
                    po.CancellationToken = cancellationToken.Value;
                }

                po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
                po.CancellationToken.ThrowIfCancellationRequested();

                using (var adapter = new ExcelReportFreeHierarchyAdapter(balance, signaturesByBalance, adapterType, balance.Errors,
                                                                         isFormingSeparateList, isUseThousandKVt, printLandscape, branchName,
                                                                         doublePrecisionProfile, doublePrecisionIntegral, need0, isAnalisIntegral, timeZoneId, setPercisionAsDisplayed))
                {
                    Parallel.ForEach(balanceFreeHierarchyUNs, po, (balanceUn, loopState) =>
                    {
                        BalanceFreeHierarchyCalculatedResult calculatedValue;
                        if (!balance.CalculatedValues.TryGetValue(balanceUn, out calculatedValue))
                        {
                            return;
                        }

                        //Формирование документов по каждому балансу
                        try
                        {
                            if (po.CancellationToken.IsCancellationRequested)
                            {
                                loopState.Break();
                            }

                            calculatedValue.CompressedDoc = CompressUtility.CompressGZip(adapter.BuildBalanceFreeHier(calculatedValue));
                        }
                        catch (Exception ex)
                        {
                            lock (balance.Errors)
                            {
                                balance.Errors.Append("Ошибка генерации документа - " + ex.Message);
                            }
                        }
                    });
                }
            }

            return(balance);
        }
예제 #10
0
        /// <summary>
        /// Берем первую попавшуюся модель прогнозирования для объекта
        /// </summary>
        /// <param name="forecastObjectUn"></param>
        /// <returns></returns>
        public static List <TForecastCalculateParams> GetForecastObjectParams(HashSet <string> forecastObjectUns, DateTime dtStart, DateTime dtEnd,
                                                                              int?forecastModelUserSelected, string timeZoneId, StringBuilder errors, EnumUnitDigit unitDigit, enumTimeDiscreteType forecastDiscreteType, bool isReadCalculatedValues)
        {
            var tis      = new List <TI_ChanelType>();
            var formulas = new List <TFormulaParam>();
            var tps      = new List <TP_ChanelType>();
            var nodes    = new List <long>();

            var result = new Dictionary <string, TForecastCalculateParams>();

            var periodsPriorityByForecastObject = new Dictionary <string, Dictionary <string, Queue <PeriodHierarchy> > >();

            if (forecastObjectUns == null)
            {
                return(result.Values.ToList());
            }

            #region Читаем параметры объектов прогнозирования из базы

            var forecastObjectUnsString = string.Join(",", forecastObjectUns);

            try
            {
                using (var db = new LightDBDataContext(Settings.DbConnectionString)
                {
                    ObjectTrackingEnabled = false, //Указываем что это у нас ReadOnly
                    DeferredLoadingEnabled = false,
                    CommandTimeout = 180,
                })
                {
                    var multiResult = db.usp2_ForecastObjectParams(forecastObjectUnsString, dtStart.ClientToServer(timeZoneId), dtEnd.ClientToServer(timeZoneId));

                    //Читаем доступные модели, которым будем считать
                    foreach (var modelsGroupByObject in multiResult.GetResult <usp2_ForecastObjectParamsResult1>().ToList().GroupBy(g => g.ForecastObject_UN))
                    {
                        result[modelsGroupByObject.Key] = new TForecastCalculateParams(modelsGroupByObject.Key, forecastModelUserSelected,
                                                                                       new HashSet <int>(modelsGroupByObject.Where(m => m.ForecastCalculateModel_ID.HasValue).OrderBy(m => m.Priority ?? 1000).Select(m => (int)(m.ForecastCalculateModel_ID ?? 0))));
                    }

                    #region Читаем ТИ, ТП формулы и т.д. для обсчета

                    foreach (var inputParamByObject in multiResult.GetResult <usp2_ForecastObjectParamsResult2>().ToList().GroupBy(g => g.ForecastObject_UN))
                    {
                        TForecastCalculateParams calculateParams;
                        if (!result.TryGetValue(inputParamByObject.Key, out calculateParams) || calculateParams == null)
                        {
                            continue;
                        }

                        calculateParams.DtStart      = dtStart;
                        calculateParams.DtEnd        = dtEnd;
                        calculateParams.DiscreteType = forecastDiscreteType;

                        var periodsByInputParam = new Dictionary <string, Queue <PeriodHierarchy> >();
                        periodsPriorityByForecastObject[inputParamByObject.Key] = periodsByInputParam;

                        foreach (var inputParam in inputParamByObject.GroupBy(g => g.ForecastInputParam_UN))
                        {
                            var periods = new Queue <PeriodHierarchy>();
                            periodsByInputParam[inputParam.Key] = periods;

                            var archiveByInputParam = new ForecastByInputParamArchives(inputParam.Key);
                            calculateParams.ArchivesByInputParam.Add(archiveByInputParam);
                            var isFirst = true;
                            foreach (var physicalParam in inputParam)
                            {
                                bool isFullPeriod;
                                var  period = BuildHalfHoursPeriods(physicalParam, dtStart, dtEnd, timeZoneId, out isFullPeriod);

                                if (isFirst)
                                {
                                    archiveByInputParam.MeasureQuantityType_UN = physicalParam.MeasureQuantityType_UN;
                                    isFirst = false;
                                }

                                //Формула
                                if (!string.IsNullOrEmpty(physicalParam.Formula_UN))
                                {
                                    var formulaParam = new TFormulaParam
                                    {
                                        FormulaID     = physicalParam.Formula_UN,
                                        FormulasTable = enumFormulasTable.Info_Formula_Description,
                                        IsFormulaHasCorrectDescription = true,
                                    };
                                    formulas.Add(formulaParam);
                                    //archiveByInputParam.Formulas.Add(formulaParam);
                                    periods.Enqueue(new PeriodHierarchy
                                    {
                                        Id           = new ID_Hierarchy_Channel(enumTypeHierarchy.Formula, physicalParam.Formula_UN, 0),
                                        IsFullPeriod = isFullPeriod,
                                        IndxStart    = period.Item1,
                                        IndxFinish   = period.Item2,
                                    });

                                    if (isFullPeriod)
                                    {
                                        continue;               //Объект действует на весь период, остальные объекты пропускаем
                                    }
                                }

                                //OPC пока не используется, т.к. не понятно как приводить к получасовкам
                                if (physicalParam.UANode_ID.HasValue)
                                {
                                    //archiveByInputParam.Nodes.Add(physicalParam.UANode_ID.Value);
                                    nodes.Add(physicalParam.UANode_ID.Value);

                                    periods.Enqueue(new PeriodHierarchy
                                    {
                                        Id           = new ID_Hierarchy_Channel(enumTypeHierarchy.UANode, physicalParam.UANode_ID.Value.ToString(), 0),
                                        IsFullPeriod = isFullPeriod,
                                        IndxStart    = period.Item1,
                                        IndxFinish   = period.Item2,
                                    });

                                    if (isFullPeriod)
                                    {
                                        continue;               //Объект действует на весь период, остальные объекты пропускаем
                                    }
                                }

                                //Для остальных нужен канал, если не указан пропускаем
                                //if (!inputParam.ChannelType.HasValue) continue;

                                //ТИ
                                if (physicalParam.TI_ID.HasValue)
                                {
                                    if (!physicalParam.ChannelType.HasValue)
                                    {
                                        errors.Append("Для ТИ {").Append(physicalParam.TI_ID).Append("} нужно указать канал");
                                        continue;
                                    }

                                    var tiId = new TI_ChanelType
                                    {
                                        ChannelType = physicalParam.ChannelType.Value,
                                        TI_ID       = physicalParam.TI_ID.Value,
                                        MsTimeZone  = timeZoneId, //Это возможно не нужно
                                    };
                                    //archiveByInputParam.TiIds.Add(tiId);
                                    tis.Add(tiId);
                                    periods.Enqueue(new PeriodHierarchy
                                    {
                                        Id           = new ID_Hierarchy_Channel(enumTypeHierarchy.Info_TI, physicalParam.TI_ID.Value.ToString(), physicalParam.ChannelType.Value),
                                        IsFullPeriod = isFullPeriod,
                                        IndxStart    = period.Item1,
                                        IndxFinish   = period.Item2,
                                    });

                                    if (isFullPeriod)
                                    {
                                        continue;               //Объект действует на весь период, остальные объекты пропускаем
                                    }
                                }

                                //ТП
                                if (physicalParam.TP_ID.HasValue)
                                {
                                    if (!physicalParam.ChannelType.HasValue)
                                    {
                                        errors.Append("Для ТП {").Append(physicalParam.TP_ID).Append("} нужно указать канал");
                                        continue;
                                    }

                                    var tpId = new TP_ChanelType
                                    {
                                        ChannelType = physicalParam.ChannelType.Value,
                                        TP_ID       = physicalParam.TP_ID.Value,
                                    };
                                    //archiveByInputParam.TpIds.Add(tpId);
                                    tps.Add(tpId);
                                    periods.Enqueue(new PeriodHierarchy
                                    {
                                        Id           = new ID_Hierarchy_Channel(enumTypeHierarchy.Info_TP, physicalParam.TP_ID.Value.ToString(), physicalParam.ChannelType.Value),
                                        IsFullPeriod = isFullPeriod,
                                        IndxStart    = period.Item1,
                                        IndxFinish   = period.Item2,
                                    });
                                }
                            }
                        }
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                errors.Append(ex.Message);
            }

            #endregion

            #region Читаем архивы

            //Пока запрашиваем только получасовки
            var resultCommonTi = new ArchivesValues_List2(tis, dtStart, dtEnd,
                                                          true, false, enumTimeDiscreteType.DBHalfHours, enumTypeInformation.Energy, false,
                                                          unitDigit, enumOVMode.NormalMode, timeZoneId, isReadCalculatedValues: isReadCalculatedValues);

            if (resultCommonTi.Errors != null)
            {
                errors.Append(resultCommonTi.Errors);
            }

            //Запрос значений всех ТП
            var resultCommonTp = new ArchivesTPValues(tps, dtStart, dtEnd, enumBusRelation.PPI_OurSide, enumTimeDiscreteType.DBHalfHours, null, enumTypeInformation.Energy, unitDigit,
                                                      timeZoneId, false, isSupressTpNotFound: true, isReadCalculatedValues: isReadCalculatedValues);
            if (resultCommonTp.Errors != null)
            {
                errors.Append(resultCommonTp.Errors);
            }

            //Все формулы
            var resultCommonFormula = new FormulasResult(formulas, dtStart, dtEnd, enumTimeDiscreteType.DBHalfHours, null, 0, enumTypeInformation.Energy, unitDigit, timeZoneId, //Для описанных здесь формул ед. изм. не учитываем
                                                         true, false, false, false, isReadCalculatedValues: isReadCalculatedValues, ovMode: enumOVMode.NormalMode);              //Для формулы сумму с ОВ считаем всегда!!!
            if (resultCommonFormula.Errors != null)
            {
                errors.Append(resultCommonFormula.Errors);
            }

            //Чтение архивов OPC
            UADataReader resultCommonUAData = null;
            try
            {
                resultCommonUAData = new UADataReader(nodes, dtStart, dtEnd, false, false, false, timeZoneId);
            }
            catch
            { }

            #endregion

            #region Подготовка архивов

            var numberHalfHoursForForecasting = MyListConverters.GetNumbersValuesInPeriod(enumTimeDiscreteType.DBHalfHours, dtStart, dtEnd, timeZoneId);

            result.Values.AsParallel().ForAll(calculateParam => //AsParallel().ForAll()
            {
                //new TVALUES_DB[numberHalfHoursForForecasting].Select(v => new TVALUES_DB(VALUES_FLAG_DB.IsNull, 0)).ToList();

                Dictionary <string, Queue <PeriodHierarchy> > periodsByInputParam;
                if (!periodsPriorityByForecastObject.TryGetValue(calculateParam.ForecastObject_UN, out periodsByInputParam) || periodsByInputParam.Count == 0)
                {
                    return;                                                                                                                                            //Нет параметров для обсчета
                }
                foreach (var paramArchives in calculateParam.ArchivesByInputParam)
                {
                    Queue <PeriodHierarchy> periods;
                    if (!periodsByInputParam.TryGetValue(paramArchives.ForecastInputParamUn, out periods) || periods.Count == 0)
                    {
                        continue;                                                                                                          //Нет параметров для обсчета
                    }
                    //var period = periods.Dequeue(); //Первый объект в интервале
                    PeriodHierarchy period = null;
                    var halfHours          = new List <TVALUES_DB>();
                    for (var hh = 0; hh < numberHalfHoursForForecasting; hh++)
                    {
                        if (!PeriodInHalfHour(ref period, periods, hh, resultCommonTi, resultCommonFormula,
                                              resultCommonTp, resultCommonUAData) || period.Archives == null)
                        {
                            halfHours.Add(new Servers.Calculation.DBAccess.Interface.Data.TVALUES_DB(VALUES_FLAG_DB.IsNull, 0)); //Получасовка не входит в наш диапазон, или нет архива
                            continue;
                        }

                        var aVal = period.Archives.ElementAtOrDefault(hh);
                        if (aVal == null)
                        {
                            aVal = new Servers.Calculation.DBAccess.Interface.Data.TVALUES_DB(VALUES_FLAG_DB.IsNull, 0); //Непонятная ситуация, помечаем как отсутствующие
                        }

                        var cVal = halfHours.ElementAtOrDefault(hh);
                        if (cVal == null)
                        {
                            cVal = new Servers.Calculation.DBAccess.Interface.Data.TVALUES_DB(aVal.F_FLAG, aVal.F_VALUE);
                            halfHours.Add(cVal);
                        }
                        else
                        {
                            cVal.F_VALUE = aVal.F_VALUE;
                            cVal.F_FLAG  = aVal.F_FLAG;
                        }
                    }


                    paramArchives.Archives.AddRange(MyListConverters.ConvertHalfHoursToOtherList(forecastDiscreteType, halfHours,
                                                                                                 dtStart, dtEnd, timeZoneId).Select(v => new Servers.Calculation.DBAccess.Interface.Data.TVALUES_DB(v.F_FLAG, v.F_VALUE)));
                }
            });

            #endregion

            return(result.Values.ToList());
        }
예제 #11
0
        public BalanceFreeHierarchyCalculator(List <string> balanceFreeHierarchyUN, bool isGenerateDoc, StringBuilder errors, enumTimeDiscreteType discreteType, DateTime dtStart, DateTime dtEnd, string timeZoneId,
                                              ConcurrentDictionary <TI_ChanelType, ConcurrentStack <BalanceFreeHierarchyItemParams> > tiForRequestAdditionalInfo,
                                              EnumUnitDigit unitDigit, EnumUnitDigit unitDigitIntegrals)
        {
            _errors       = errors ?? new StringBuilder();
            _discreteType = discreteType;
            _dtStart      = dtStart;
            _dtEnd        = dtEnd;
            _timeZoneId   = timeZoneId;

            _tiForRequestAdditionalInfo = tiForRequestAdditionalInfo;
            _unitDigit          = unitDigit;
            _unitDigitIntegrals = unitDigitIntegrals;
            _intervalTimeList   = MyListConverters.GetIntervalTimeList(_dtStart, _dtEnd, _discreteType, timeZoneId);

            _dtServerStart    = dtStart.ClientToServer(timeZoneId);
            _dtServerEnd      = dtEnd.ClientToServer(timeZoneId);
            _isGenerateDoc    = isGenerateDoc;
            _numbersHalfHours = MyListConverters.GetNumbersValuesInPeriod(enumTimeDiscreteType.DBHalfHours, dtStart, dtEnd, timeZoneId);

            var transIds    = new ConcurrentDictionary <int, string>();
            var reactorsIds = new ConcurrentStack <int>();
            var tiForTransformatorsAndReactors = new ConcurrentStack <TI_ChanelType>();

            var tis                = new ConcurrentStack <TI_ChanelType>();
            var integralTis        = new ConcurrentStack <TI_ChanelType>();
            var tps                = new ConcurrentStack <TP_ChanelType>();
            var formulas           = new ConcurrentStack <TFormulaParam>();
            var sections           = new ConcurrentStack <TSectionChannel>();
            var formulaConstantIds = new ConcurrentStack <string>();

            try
            {
                _itemsResultByBalance = ReadBalanceParams(balanceFreeHierarchyUN, transIds, reactorsIds, tis, integralTis, tps, formulas,
                                                          sections, formulaConstantIds);
            }
            catch (AggregateException aex)
            {
                //критическая ошибка
                throw aex.ToException();
            }

            #region Параметры трансформаторов и реакторов

            try
            {
                ReadTransformatorsParams(transIds, tiForTransformatorsAndReactors, _itemsResultByBalance);
            }
            catch (AggregateException aex)
            {
                //не критическая ошибка
                _errors.Append(aex.ToException());
            }

            #endregion

            _archiveHalfhours = new TArchiveHalfhours(isGenerateDoc, dtStart, dtEnd,
                                                      unitDigit, timeZoneId, unitDigitIntegrals, tiForTransformatorsAndReactors,
                                                      tis, integralTis, tps, formulas, sections, formulaConstantIds, _intervalTimeList);

            _numbersByDiscreteType = MyListConverters.GetNumbersValuesInPeriod(_discreteType, _dtStart, _dtEnd, timeZoneId);

            SectionsByType = new ConcurrentDictionary <EnumBalanceFreeHierarchyType, List <Dict_Balance_FreeHierarchy_Section> >(GetFreeHierarchyBalanceSections(_itemsResultByBalance.Values.Select(v => (byte)v.BalanceFreeHierarchyType).Distinct())
                                                                                                                                 .GroupBy(g => (EnumBalanceFreeHierarchyType)g.BalanceFreeHierarchyType_ID)
                                                                                                                                 .ToDictionary(k => k.Key, v => v.ToList()));
        }