Example #1
0
        ConvertPivotDatatableToList(Dictionary <DataTable, List <DescriptiveStatistics> > dataTableDictionary,
                                    GadgetParameters gadgetParameters)

        {
            Dictionary <List <EwavFrequencyControlDto>, List <DescriptiveStatistics> > DtoDictionary =
                new Dictionary <List <EwavFrequencyControlDto>, List <DescriptiveStatistics> >();

            EwavGadgetParameters g = new EwavGadgetParameters()
            {
                CrosstabVariableName = gadgetParameters.CrosstabVariableName,
                CustomFilter         = gadgetParameters.CustomFilter,
                CustomSortColumnName = gadgetParameters.CustomSortColumnName,
                InputVariableList    = gadgetParameters.InputVariableList,
                MainVariableName     = gadgetParameters.MainVariableName,
                MainVariableNames    = gadgetParameters.MainVariableNames,
                ShouldIncludeFullSummaryStatistics = gadgetParameters.ShouldIncludeFullSummaryStatistics,
                ShouldIncludeMissing         = gadgetParameters.ShouldIncludeMissing,
                ShouldShowCommentLegalLabels = gadgetParameters.ShouldSortHighToLow,
                ShouldUseAllPossibleValues   = gadgetParameters.ShouldUseAllPossibleValues,
                StrataVariableNames          = gadgetParameters.StrataVariableNames,
                WeightVariableName           = gadgetParameters.WeightVariableName,
                NameOfDtoList = gadgetParameters.MainVariableName
            };

            foreach (KeyValuePair <DataTable, List <DescriptiveStatistics> > khp in dataTableDictionary)
            {
                DataTable dt = Ewav.Web.Utilities.Pivot(khp.Key, "Frequency", "MainVarname", "totals");
                List <EwavFrequencyControlDto> ewavFrequencyControlDto = Mapper.FrequencyOutputList(dt, g);
                DtoDictionary.Add(ewavFrequencyControlDto, khp.Value);
            }

            return(DtoDictionary);
        }
        public void getData(string filename, string filterstring = null)
        {
            string configFilePath = "..\\..\\..\\Build\\Debug\\Configuration\\EpiInfo.Config.xml";

            Epi.DataSets.Config configDataSet = new Epi.DataSets.Config();
            configDataSet.ReadXml(configFilePath);
            Epi.Configuration.Load(configFilePath);
            System.Data.Common.DbConnectionStringBuilder dbCnnStringBuilder = new System.Data.Common.DbConnectionStringBuilder();
            string           provider  = "Epi.Data.Office.CsvFileFactory, Epi.Data.Office";
            IDbDriverFactory dbFactory = null;

            dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(provider);
            IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);

            db.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\..\\Data;Extended Properties=\"text;HDR=Yes;FMT=Delimited\"";
            object selectedDataSource = db;

            IDbDriver dbDriver = (IDbDriver)selectedDataSource;

            DashboardHelper = new DashboardHelper(filename + "#csv", dbDriver);
            IGadgetParameters inputs = new GadgetParameters();

            DashboardHelper.UserVarsNeedUpdating = true;
            string fs = null;

            if (!String.IsNullOrEmpty(filterstring))
            {
                fs = "select * from " + filename + "#csv where " + filterstring;
            }
            PopulateDataSet(inputs, fs);
        }
Example #3
0
        public TwoxTwoAndMxNResultsSet SetupGadget(GadgetParameters clientGadgetOptions, List <EwavDataFilterCondition> ewavDataFilters, List <EwavRule_Base> rules)
        {
            TwoxTwoManager          twoxTwoManager    = new TwoxTwoManager();
            TwoxTwoAndMxNResultsSet twoxTwoResultsSet = twoxTwoManager.SetupGadget(clientGadgetOptions, ewavDataFilters, rules);

            return(twoxTwoResultsSet);
        }
Example #4
0
        /// <summary>
        /// Constructs the gadget
        /// </summary>
        protected virtual void Construct()
        {
            strataGridList     = new List <Grid>();
            strataPanelList    = new List <StackPanel>();
            strataExpanderList = new List <Expander>();
            strataCount        = 0;

            GadgetOptions = new GadgetParameters();
            GadgetOptions.InputVariableList = new Dictionary <string, string>();
            GadgetOptions.ShouldIncludeFullSummaryStatistics = false;
            GadgetOptions.ShouldIncludeMissing       = false;
            GadgetOptions.ShouldSortHighToLow        = false;
            GadgetOptions.ShouldUseAllPossibleValues = false;
            GadgetOptions.StrataVariableNames        = new List <string>();
            GadgetOptions.PSUVariableName            = string.Empty;
            GadgetOptions.CustomFilter = string.Empty;

            if (this.DashboardHelper != null)
            {
                this.dataFilters = new Epi.WPF.Dashboard.DataFilters(this.DashboardHelper);
            }

            object el = this.FindName("headerPanel");

            if (el != null)
            {
                Controls.GadgetHeaderPanel headerPanel = el as Controls.GadgetHeaderPanel;
                headerPanel.GadgetCloseButtonClicked          += new GadgetCloseButtonHandler(CloseGadget);
                headerPanel.GadgetOutputCollapseButtonClicked += new GadgetOutputCollapseButtonHandler(CollapseOutput);
                headerPanel.GadgetOutputExpandButtonClicked   += new GadgetOutputExpandButtonHandler(ExpandOutput);
                headerPanel.GadgetConfigButtonClicked         += new GadgetConfigButtonHandler(ShowHideConfigPanel);
                headerPanel.GadgetDescriptionButtonClicked    += new GadgetDescriptionButtonHandler(ShowHideDescriptionPanel);
                headerPanel.GadgetFilterButtonClicked         += new GadgetFilterButtonHandler(ShowCustomFilterDialog);
            }

            el = this.FindName("messagePanel");
            if (el != null)
            {
                Controls.GadgetMessagePanel messagePanel = el as Controls.GadgetMessagePanel;
                messagePanel.MessagePanelType = Controls.MessagePanelType.StatusPanel;
                messagePanel.Text             = string.Empty;
                messagePanel.Visibility       = System.Windows.Visibility.Collapsed;
            }

            el = this.FindName("descriptionPanel");
            if (el != null)
            {
                Controls.GadgetDescriptionPanel descriptionPanel = el as Controls.GadgetDescriptionPanel;
                if (!string.IsNullOrEmpty(CustomOutputDescription) && !CustomOutputHeading.Equals("(none)"))
                {
                    descriptionPanel.Text      = CustomOutputDescription;
                    descriptionPanel.PanelMode = Controls.GadgetDescriptionPanel.DescriptionPanelMode.DisplayMode;
                }
                else
                {
                    descriptionPanel.PanelMode = Controls.GadgetDescriptionPanel.DescriptionPanelMode.Collapsed;
                }
            }
        }
Example #5
0
        public List <CrossTabResponseObjectDto> GenerateCrossTabFrequency(GadgetParameters gadgetParameters)
        {
            //dh = new DashboardHelper();
            Dictionary <DataTable, List <DescriptiveStatistics> > dataTableDictionary;

            dataTableDictionary = dh.GenerateFrequencyTable(gadgetParameters, gadgetParameters.DatasourceName, gadgetParameters.TableName);     //   DatasourceName, TableName);
            return(MeansManager.ConvertCrossTabDictToDto(dataTableDictionary, gadgetParameters));
        }
Example #6
0
        /// <summary>
        /// Gets columns from Domain Service
        /// </summary>
        /// <param name="DataSourceName"></param>
        /// <param name="TableName"></param>
        /// <param name="completed"></param>
        //public void GetColumns(string DataSourceName, string TableName, Action<List<EwavColumn>, Exception> completed)
        //{
        //    _completed = completed;
        //    LinearRegressionDomainContext linrCtx = new LinearRegressionDomainContext();
        //    InvokeOperation<List<EwavColumn>> linrCtxColumnResults = linrCtx.GetColumns(DataSourceName, TableName);
        //    linrCtxColumnResults.Completed += new EventHandler(linrCtxColumnResults_Completed);
        //}

        /// <summary>
        /// Gets the regression table results from Domain service
        /// </summary>
        /// <param name="DatasourceName"></param>
        /// <param name="TableName"></param>
        /// <param name="gadgetOptions"></param>
        /// <param name="columnNames"></param>
        /// <param name="inputDtoList"></param>
        /// <param name="completed"></param>
        public void GetRegressionResults(GadgetParameters gadgetOptions, List <string> columnNames, List <DictionaryDTO> inputDtoList, Action <LinRegressionResults, Exception> completed)
        {
            _rresultsCompleted = completed;
            LinearRegressionDomainContext          linrCtx           = new LinearRegressionDomainContext();
            InvokeOperation <LinRegressionResults> linrCtxRegResults = linrCtx.GetRegressionResult(gadgetOptions, columnNames, inputDtoList, ApplicationViewModel.Instance.EwavDatafilters, ApplicationViewModel.Instance.EwavDefinedVariables, ApplicationViewModel.Instance.AdvancedDataFilterString);

            linrCtxRegResults.Completed += new EventHandler(linrCtxRegResults_Completed);
        }
Example #7
0
        public void GetCrossTabResults(GadgetParameters gadgetParameters, Action <List <CrossTabResponseObjectDto>, Exception> completed)
        {
            _meansCompleted = completed;
            meansCtx        = new MeansDomainContext();
            InvokeOperation <List <CrossTabResponseObjectDto> > meanResults = meansCtx.GenerateCrossTabFrequency(gadgetParameters);

            meanResults.Completed += new EventHandler(meanResults_Completed);
        }
Example #8
0
 public void SetupGadget(GadgetParameters gadgetParameters)
 {
     this.ObservableResultSets.Clear();
     foreach (string mainVariableName in gadgetParameters.MainVariableNames)
     {
         this.ServiceAgent.SetupGadget(gadgetParameters, SetupGadgetCompleted);
     }
 }
Example #9
0
        //void ILogisticRegressionServiceAgent.GetColumns(string DataSourceName, string TableName, Action<List<EwavColumn>, Exception> completed)
        //{
        //    throw new NotImplementedException();
        //}

        //void ILogisticRegressionServiceAgent.GenerateTable(string DataSourceName, string TableName, List<string> columnNames, string customFilter, Action<List<ListOfStringClass>, Exception> completed)
        //{
        //    throw new NotImplementedException();
        //}



        void ILogisticRegressionServiceAgent.GetRegressionResults(GadgetParameters gadgetOptions, List <string> columnNames, string customFilter, List <DictionaryDTO> inputDtoList, Action <LogRegressionResults, Exception> completed)
        {
            _rresultsCompleted = completed;
            LogisticRegressionDomainContext        logrCtx           = new LogisticRegressionDomainContext();
            InvokeOperation <LogRegressionResults> logrCtxRegResults = logrCtx.GetRegressionResult(gadgetOptions, columnNames, inputDtoList, ApplicationViewModel.Instance.EwavDatafilters, ApplicationViewModel.Instance.EwavDefinedVariables, ApplicationViewModel.Instance.AdvancedDataFilterString, customFilter);

            logrCtxRegResults.Completed += new EventHandler(logrCtxRegResults_Completed);
        }
Example #10
0
        /// <summary>
        /// Gets the regression table results from Domain service
        /// </summary>
        /// <param name="DatasourceName"></param>
        /// <param name="TableName"></param>
        /// <param name="gadgetOptions"></param>
        /// <param name="columnNames"></param>
        /// <param name="inputDtoList"></param>
        /// <param name="completed"></param>
        //public void GetRegressionResults(string DatasourceName, string TableName, GadgetParameters gadgetOptions, List<string> columnNames, List<DictionaryDTO> inputDtoList, Action<LinRegressionResults, Exception> completed)
        //{
        //    _rresultsCompleted = completed;
        //    ScatterDomainContext sctrCtx = new ScatterDomainContext();
        //    InvokeOperation<LinRegressionResults> sctrCtxRegResults = sctrCtx.GetRegressionResult(DatasourceName, TableName, gadgetOptions, columnNames, inputDtoList);
        //    sctrCtxRegResults.Completed += new EventHandler(sctrCtxRegResults_Completed);
        //}


        #endregion


        public void GenerateTable(GadgetParameters gadgetOptions, IEnumerable <EwavDataFilterCondition> ewavDataFilters,
                                  string filterString, Action <ScatterDataDTO, Exception> completed)
        {
            _tableCompleted = completed;
            ScatterDomainContext             sctrCtx             = new ScatterDomainContext();
            InvokeOperation <ScatterDataDTO> sctrCtxtableResults = sctrCtx.GenerateTable(gadgetOptions, ewavDataFilters, ApplicationViewModel.Instance.EwavDefinedVariables, ApplicationViewModel.Instance.AdvancedDataFilterString);

            sctrCtxtableResults.Completed += new EventHandler(sctrCtxtableResults_Completed);
        }
Example #11
0
        public List <DatatableBag> GetLineList(GadgetParameters gadgetParameters,
                                               IEnumerable <EwavDataFilterCondition> ewavDataFilters, List <EwavRule_Base> rules, string filterString = "")
        {
            LineListManager llm = new LineListManager();

            List <DatatableBag> datatableBagList = llm.GetLineList(gadgetParameters, ewavDataFilters, rules, filterString);


            return(datatableBagList);
        }
Example #12
0
        public FrequencyAndCrossTable GenerateCrossTableWithFrequencyTable(GadgetParameters gadgetParameters,
                                                                           IEnumerable <EwavDataFilterCondition> ewavDataFilters, List <EwavRule_Base> rules, string filterString = "")
        {
            FrequencyAndCrossTable fct = new FrequencyAndCrossTable();
            GadgetParameters       gp  = gadgetParameters;                                                       //Storing it in saperate variable for some reason gadgetparameters got updated after first call.

            fct.FrequencyTable = GenerateFrequencyTable(gadgetParameters, ewavDataFilters, rules, filterString); //     DatasourceName, TableName);
            fct.CrossTable     = GenerateCrossTabFrequency(gadgetParameters);                                    //      DatasourceName, TableName);
            return(fct);
        }
Example #13
0
        // POST api/<controller>
        public HttpResponseMessage Post([FromBody]      JObject value)
        {
            CombinedFrequencyDomainService CFDS        = new CombinedFrequencyDomainService();
            HttpResponseMessage            ReturnedObj = null;
            GadgetParameters     GadgetParameters      = null;
            ControllerCommon     CommonClass           = new ControllerCommon();
            List <EwavRule_Base> Rules = new List <EwavRule_Base>();

            JObject gadgetJSON = (JObject)value["gadget"];


            CFDS = new CombinedFrequencyDomainService();
            EwavCombinedFrequencyGadgetParameters CombinedParameters = new EwavCombinedFrequencyGadgetParameters();

            CombinedParameters.CombineMode     = (CombineModeTypes)Enum.Parse(typeof(CombineModeTypes), gadgetJSON["combinedmode"].ToString());
            CombinedParameters.ShowDenominator = Convert.ToBoolean(gadgetJSON["showdenominator"].ToString());
            CombinedParameters.SortHighToLow   = Convert.ToBoolean(gadgetJSON["sort"].ToString());
            CombinedParameters.TrueValue       = (gadgetJSON["truevalue"].ToString().Trim().Length == 0 ? null : value["truevalue"].ToString());


            GadgetParameters = new GadgetParameters();

            GadgetParameters.DatasourceName    = gadgetJSON["@DatasourceName"].ToString();
            GadgetParameters.MainVariableName  = gadgetJSON["mainVariable"].ToString();
            GadgetParameters.InputVariableList = new Dictionary <string, string>();
            GadgetParameters.InputVariableList.Add("tableName", gadgetJSON["@DatasourceName"].ToString());

            GadgetParameters.TableName = CommonClass.GetDatabaseObject(GadgetParameters.DatasourceName);

            string groupVar = gadgetJSON["mainVariable"].ToString();

            List <EwavDataFilterCondition> dashboardFilters = new List <EwavDataFilterCondition>();


            Rules = CommonClass.ReadRules(value);

            dashboardFilters = CommonClass.GetFilters(value);


            GadgetParameters.GadgetFilters = CommonClass.GetFilters(gadgetJSON, true);



            DatatableBag dtBag = CFDS.GenerateCombinedFrequency(CombinedParameters, groupVar, GadgetParameters, dashboardFilters, Rules);

            ReturnedObj = new HttpResponseMessage()
            {
                Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(dtBag))
            };

            ReturnedObj.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");


            return(ReturnedObj);
        }
Example #14
0
        public LogRegressionResults GetRegressionResult(GadgetParameters gadgetOptions, List <string> columnNames, List <DictionaryDTO> inputDtoList, IEnumerable <EwavDataFilterCondition> ewavDataFilters, List <EwavRule_Base> rules, string filterString = "", string customFilter = "")
        {
            if (gadgetOptions.UseAdvancedDataFilter)
            {
                dh = new DashboardHelper(gadgetOptions, filterString, rules);
                gadgetOptions.UseAdvancedDataFilter  = true;
                gadgetOptions.AdvancedDataFilterText = filterString;
            }
            else
            {
                dh = new DashboardHelper(gadgetOptions, ewavDataFilters, rules);
            }
            DataTable dt;
            Dictionary <string, string> inputVariableList = RegressionManager.ConvertDtoToDic(inputDtoList);

            //LogRegressionResults results = new LogRegressionResults();
            StatisticsRepository.LogisticRegression logisticRegression = new StatisticsRepository.LogisticRegression();
            try
            {
                dt = dh.GenerateTable(columnNames, gadgetOptions, customFilter);
            }
            catch (System.Exception e)
            {
                throw new Exception("Error retrieving data from Dashboard Helper");
                //results.ErrorMessage = e.Message;
                //return results;
            }



            StatisticsRepository.LogisticRegression.LogisticRegressionResults regressionResults = logisticRegression.LogisticRegression(inputVariableList, dt);

            LogRegressionResults results = RegressionManager.ConvertToLogRegResults(regressionResults);

            //results.CasesIncluded = results.RegressionResults1.CasesIncluded;
            //results.Convergence = results.RegressionResults1.Convergence;
            //results.FinalLikelihood = results.RegressionResults1.FinalLikelihood;
            //results.Iterations = results.RegressionResults1.Iterations;
            //results.LRDF = results.RegressionResults1.LRDF;
            //results.LRP = results.RegressionResults1.LRP;
            //results.LRStatistic = results.RegressionResults1.LRStatistic;
            //results.ScoreDF = results.RegressionResults1.ScoreDF;
            //results.ScoreP = results.RegressionResults1.ScoreP;
            //results.ScoreStatistic = results.RegressionResults1.ScoreStatistic;
            //if (results.RegressionResults1.ErrorMessage != null)
            //{
            //    results.ErrorMessage = results.RegressionResults1.ErrorMessage.Replace("<tlt>", string.Empty).Replace("</tlt>", string.Empty);
            //}

            //results.Variables = results.RegressionResults1.Variables;


            return(results);
        }
Example #15
0
        public void SetupGadget(GadgetParameters gadgetParameters, Action <TwoxTwoAndMxNResultsSet, Exception> completed)
        {
            _setupCompleted = completed;
            TwoByTwoDomainContext twoxTwoCtx = new TwoByTwoDomainContext();
            InvokeOperation <TwoxTwoAndMxNResultsSet> resultSet = twoxTwoCtx.SetupGadget(gadgetParameters,
                                                                                         ViewModels.ApplicationViewModel.Instance.EwavDatafilters,
                                                                                         ViewModels.ApplicationViewModel.Instance.EwavDefinedVariables);

            resultSet.Completed += new EventHandler(resultSet_Completed);
            //  AAAA
        }
Example #16
0
        public void GetCrossTableAndFreq(GadgetParameters gadgetParameters, Action <FrequencyAndCrossTable, Exception> completed)
        {
            _crossandfreqCompleted = completed;
            meansCtx = new MeansDomainContext();
            InvokeOperation <FrequencyAndCrossTable> crossFreqResults =
                meansCtx.GenerateCrossTableWithFrequencyTable(gadgetParameters,
                                                              ApplicationViewModel.Instance.EwavDatafilters,
                                                              ApplicationViewModel.Instance.EwavDefinedVariables,
                                                              ApplicationViewModel.Instance.AdvancedDataFilterString);

            crossFreqResults.Completed += new EventHandler(crossFreqResults_Completed);
        }
Example #17
0
 /// <summary>
 /// Loads the map data.
 /// </summary>
 public void LoadMapData(GadgetParameters gp)
 {
     try
     {
         //       MapControlServiceAgent mcsa = new MapControlServiceAgent();
         serviceAgent.LoadMapData(gp, LoadMapDataCompleted);
     }
     catch (Exception ex)
     {
         throw new Exception();
     }
 }
Example #18
0
        public void GetFrequencyResults(GadgetParameters gadgetParameters, IEnumerable <EwavDataFilterCondition> ewavDataFilters,
                                        string filterString, Action <List <FrequencyResultData>, Exception> completed)
        {
            _freqCompleted = completed;
            freqCtx        = new FrequencyDomainContext();
            InvokeOperation <List <FrequencyResultData> > freqResults =
                freqCtx.GenerateFrequencyTable(gadgetParameters, ewavDataFilters,
                                               ApplicationViewModel.Instance.EwavDefinedVariables, filterString);

            // Not used a
            //    Dictionary<List<DTO.EwavFrequencyControlDto>, List<DescriptiveStatistics>> freqTableResults = new Dictionary<List<DTO.EwavFrequencyControlDto>, List<DescriptiveStatistics>>();
            freqResults.Completed += new EventHandler(freqTableResults_Completed);
        }
Example #19
0
        /// <summary>
        /// GetColumns Method that calls the method in Domain Service
        /// </summary>
        /// <param name="DataSourceName"></param>
        /// <param name="TableName"></param>
        /// <param name="completed"></param>
        //public void GetColumns(string DataSourceName, string TableName, Action<List<EwavColumn>, Exception> completed)
        //{
        //    _completed = completed;
        //    AberrationDomainContext abrCtx = new AberrationDomainContext();
        //    InvokeOperation<List<EwavColumn>> freqColumnResults = abrCtx.GetColumns(DataSourceName, TableName);
        //    freqColumnResults.Completed += new EventHandler(freqColumnResults_Completed);
        //}

        /// <summary>
        /// GetFrequencyResults method that calls Domain Service Method.
        /// </summary>
        /// <param name="DataSourceName"></param>
        /// <param name="TableName"></param>
        /// <param name="gadgetParameters"></param>
        /// <param name="completed"></param>
        void IAberrationControlServiceAgent.GetFrequencyResults(GadgetParameters gadgetParameters, Action <List <FrequencyResultData>, Exception> completed)
        {
            _freqCompleted = completed;
            freqCtx        = new AberrationDomainContext();
            InvokeOperation <List <FrequencyResultData> > freqResults =
                freqCtx.GenerateFrequencyTable(gadgetParameters, Ewav.ViewModels.ApplicationViewModel.Instance.EwavDatafilters,
                                               Ewav.ViewModels.ApplicationViewModel.Instance.EwavDefinedVariables,
                                               Ewav.ViewModels.ApplicationViewModel.Instance.AdvancedDataFilterString);

            Dictionary <List <DTO.EwavFrequencyControlDto>, List <DescriptiveStatistics> > freqTableResults = new Dictionary <List <DTO.EwavFrequencyControlDto>, List <DescriptiveStatistics> >();

            freqResults.Completed += new EventHandler(freqTableResults_Completed);
        }
Example #20
0
        public LinRegressionResults GetRegressionResult(GadgetParameters gadgetOptions, List <string> columnNames, List <DictionaryDTO> inputDtoList, IEnumerable <EwavDataFilterCondition> ewavDataFilters, List <EwavRule_Base> rules, string filterString = "")
        {
            if (gadgetOptions.UseAdvancedDataFilter)
            {
                dh = new DashboardHelper(gadgetOptions, filterString, rules);
                gadgetOptions.UseAdvancedDataFilter  = true;
                gadgetOptions.AdvancedDataFilterText = filterString;
            }
            else
            {
                dh = new DashboardHelper(gadgetOptions, ewavDataFilters, rules);
            }
            DataTable            dt;
            LinRegressionResults results = new LinRegressionResults();

            try
            {
                dt = dh.GenerateTable(columnNames, gadgetOptions);
            }
            catch (Exception e)
            {
                results.ErrorMessage = e.Message;
                return(results);
            }
            Dictionary <string, string> inputVariableList = RegressionManager.ConvertDtoToDic(inputDtoList);


            StatisticsRepository.LinearRegression linearRegression = new StatisticsRepository.LinearRegression();

            StatisticsRepository.LinearRegression.LinearRegressionResults regressionResults = linearRegression.LinearRegression(inputVariableList, dt);

            results.RegressionResults = RegressionManager.ConvertToLinRegResults(regressionResults);

            results.CorrelationCoefficient = results.RegressionResults.CorrelationCoefficient;
            results.RegressionDf           = results.RegressionResults.RegressionDf;
            results.RegressionF            = results.RegressionResults.RegressionF;
            results.RegressionMeanSquare   = results.RegressionResults.RegressionMeanSquare;
            results.RegressionSumOfSquares = results.RegressionResults.RegressionSumOfSquares;
            results.ResidualsDf            = results.RegressionResults.ResidualsDf;
            results.ResidualsMeanSquare    = results.RegressionResults.ResidualsMeanSquare;
            results.ResidualsSumOfSquares  = results.RegressionResults.ResidualsSumOfSquares;
            results.TotalDf           = results.RegressionResults.TotalDf;
            results.TotalSumOfSquares = results.RegressionResults.TotalSumOfSquares;
            results.Variables         = results.RegressionResults.Variables;
            if (results.RegressionResults.ErrorMessage != null)
            {
                results.ErrorMessage = results.RegressionResults.ErrorMessage.Replace("<tlt>", string.Empty).Replace("</tlt>", string.Empty);
            }

            return(results);
        }
Example #21
0
        public List <FrequencyResultData> GenerateFrequencyTable(GadgetParameters gadgetParameters,
                                                                 IEnumerable <EwavDataFilterCondition> ewavDataFilters, List <EwavRule_Base> rules, string filterString = "")
        {
            if (gadgetParameters.UseAdvancedDataFilter)
            {
                dh = new DashboardHelper(gadgetParameters, filterString, rules);
                gadgetParameters.UseAdvancedDataFilter  = true;
                gadgetParameters.AdvancedDataFilterText = filterString;
            }
            else
            {
                dh = new DashboardHelper(gadgetParameters, ewavDataFilters, rules);
            }


            Dictionary <DataTable, List <DescriptiveStatistics> > dataTableDictionary;

            dataTableDictionary = dh.GenerateFrequencyTable(gadgetParameters, gadgetParameters.DatasourceName, gadgetParameters.TableName);


            Dictionary <List <EwavFrequencyControlDto>, List <DescriptiveStatistics> > dtoDictionary;

            dtoDictionary = FrequencyManager.ConvertDatatableToList(dataTableDictionary, gadgetParameters);

            List <FrequencyResultData> outputList = new List <FrequencyResultData>();

            foreach (KeyValuePair <List <EwavFrequencyControlDto>, List <DescriptiveStatistics> > khp in dtoDictionary)
            {
                List <EwavFrequencyControlDto> outFreqList = new List <EwavFrequencyControlDto>();
                List <DescriptiveStatistics>   outDscStat  = new List <DescriptiveStatistics>();

                foreach (EwavFrequencyControlDto freqDto in khp.Key)
                {
                    outFreqList.Add(freqDto);
                }
                foreach (DescriptiveStatistics descStat in khp.Value)
                {
                    outDscStat.Add(descStat);
                }

                var frequencyResultData = new FrequencyResultData()
                {
                    FrequencyControlDtoList   = outFreqList,
                    DescriptiveStatisticsList = outDscStat
                };
                outputList.Add(frequencyResultData);
            }

            return(outputList);
        }
Example #22
0
        public DataTable GetLoadedData(DashboardHelper dashboardHelper, string dataKey, ref string valueField)
        {
            if (dashboardHelper == null)
            {
                return(null);
            }

            List <string> columnNames = new List <string>();

            if (dashboardHelper.IsUsingEpiProject)
            {
                columnNames.Add("UniqueKey");
            }
            columnNames.Add(valueField);
            columnNames.Add(dataKey);

            DataTable loadedData;

            if (valueField.Equals("{Record Count}"))
            {
                GadgetParameters gadgetOptions = new GadgetParameters();
                gadgetOptions.MainVariableName = dataKey;

                Dictionary <string, string> inputVariableList = new Dictionary <string, string>();
                inputVariableList.Add("freqvar", dataKey);
                inputVariableList.Add("allvalues", "false");
                inputVariableList.Add("showconflimits", "false");
                inputVariableList.Add("showcumulativepercent", "false");
                inputVariableList.Add("includemissing", "false");
                inputVariableList.Add("maxrows", "500");

                gadgetOptions.InputVariableList     = inputVariableList;
                gadgetOptions.ShouldIgnoreRowLimits = true;
                loadedData = dashboardHelper.GenerateFrequencyTableforMap(gadgetOptions).First().Key;

                foreach (DataRow dr in loadedData.Rows)
                {
                    dr[0] = dr[0].ToString().Trim();
                }

                _valueField = "freq";
            }
            else
            {
                loadedData = dashboardHelper.GenerateTable(columnNames);
            }

            return(loadedData);
        }
Example #23
0
        public List <PointDTOCollection> GetMapValues(GadgetParameters gadgetParameters,
                                                      IEnumerable <EwavDataFilterCondition> ewavDataFilters, List <EwavRule_Base> rules, string filterString = "")
        {
            try
            {
                MapManager mmanager = new MapManager();

                List <PointDTOCollection> MapList = mmanager.GetMapValues(gadgetParameters, ewavDataFilters, rules, filterString);

                return(MapList);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message + "\n" + e.StackTrace);
            }
        }
Example #24
0
        private TwoxTwoTableDTO CreateDTO(GadgetParameters gp, DashboardHelper dh, DataTable table)
        {
            int YesRowIndexExp = 1;
            int NoRowIndexExp  = 0;
            int YesRowIndexOut = 1;
            int NoRowIndexOut  = 2;

            if (dh.GetColumnType(gp.MainVariableName.ToString()).ToLower() != "system.string")
            {
                YesRowIndexExp = FindYesRowIndex(table);

                NoRowIndexExp = FindNoRowIndex(table);
            }


            if (dh.GetColumnType(gp.CrosstabVariableName.ToString()).ToLower() != "system.string")
            {
                YesRowIndexOut = FindYesColIndex(table);

                NoRowIndexOut = FindNoColIndex(table);
            }

            TwoxTwoTableDTO ttDTO = new TwoxTwoTableDTO
            {
                Yy = int.Parse(table.Rows[YesRowIndexExp][YesRowIndexOut].ToString()),
                Yn = int.Parse(table.Rows[YesRowIndexExp][NoRowIndexOut].ToString()),
                Ny = int.Parse(table.Rows[NoRowIndexExp][YesRowIndexOut].ToString()),
                Nn = int.Parse(table.Rows[NoRowIndexExp][NoRowIndexOut].ToString())
            };

            //Yy = int.Parse(table.Rows[1][1].ToString()),
            //               Yn = int.Parse(table.Rows[1][2].ToString()),
            //               Ny = int.Parse(table.Rows[0][1].ToString()),
            //               Nn = int.Parse(table.Rows[0][2].ToString())
            //ttDTO.Rows[0, 1] = int.Parse(table.Rows[0][1].ToString());
            //ttDTO.Rows[0, 2] = int.Parse(table.Rows[0][2].ToString());
            //ttDTO.Rows[1, 1] = int.Parse(table.Rows[1][1].ToString());
            //ttDTO.Rows[1, 2] = int.Parse(table.Rows[1][2].ToString());



            ttDTO.ColumnName1 = table.Columns[1].ColumnName;
            ttDTO.ColumnName2 = table.Columns[2].ColumnName;

            return(ttDTO);
        }
Example #25
0
        public TwoxTwoAndMxNResultsSet SetupGadget(GadgetParameters clientGadgetOptions, List <EwavDataFilterCondition> ewavDataFilters, List <EwavRule_Base> rules)
        {
            TwoxTwoAndMxNResultsSet resultSet = this.EvaluateData(clientGadgetOptions, ewavDataFilters, rules);

            if (resultSet.Errors.Count > 0 || resultSet.FreqResultsDataTable == null)
            {
                return(resultSet);
            }

            if (resultSet.FreqResultsDataTable.Rows.Count == 2 && resultSet.FreqResultsDataTable.Columns.Count == 3)
            {
                return(resultSet);
            }
            else
            {
                resultSet = this.SetupMxN(clientGadgetOptions, resultSet);
                return(resultSet);
            }
        }
Example #26
0
        /// <summary>
        /// Gets the line list.
        /// </summary>
        /// <param name="filterList">The filter list.</param>
        /// <param name="gp">The gp.</param>
        /// <returns></returns>
        public List <DatatableBag> GetLineList(GadgetParameters gadgetParameters,
                                               IEnumerable <EwavDataFilterCondition> ewavDataFilters, List <EwavRule_Base> rules, string filterString = "")
        {
            DashboardHelper dh;

            if (gadgetParameters.UseAdvancedDataFilter)
            {
                dh = new DashboardHelper(gadgetParameters, filterString, rules);
                gadgetParameters.UseAdvancedDataFilter  = true;
                gadgetParameters.AdvancedDataFilterText = filterString;
            }
            else
            {
                dh = new DashboardHelper(gadgetParameters, ewavDataFilters, rules);
            }

            List <DatatableBag> datatableBagList = new List <DatatableBag>();

            List <DataTable> dtList = dh.GenerateLineList(gadgetParameters, rules);

            foreach (DataTable dt in dtList)
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    int       numberOfRows = Convert.ToInt32(gadgetParameters.InputVariableList["maxrows"].ToString());
                    DataTable newDt        = dt.AsEnumerable().Take(numberOfRows).ToList().CopyToDataTable();

                    newDt.TableName = dt.TableName;
                    DatatableBag d = new DatatableBag(newDt, "");


                    datatableBagList.Add(d);
                }
            }


            return(datatableBagList);
        }
Example #27
0
 public void GetFrequencyData(string DataSourceName, string TableName, GadgetParameters gadgetParameters)
 {
     this.ServiceAgent.GetFrequencyResults(DataSourceName, TableName, gadgetParameters,
                                           applicationViewModel.EwavDatafilters,
                                           GetFrequencyTableCompleted);
 }
        public void SetShapeRangeValues(DashboardHelper dashboardHelper, string shapeKey, string dataKey, string valueField, Color dotColor, int dotValue)
        {
            try
            {
                this.dotValue = dotValue;
                this.dashboardHelper = dashboardHelper;
                this.shapeKey = shapeKey;
                this.dataKey = dataKey;
                this.valueField = valueField;
                this.dotColor = dotColor;

                List<string> columnNames = new List<string>();
                if (dashboardHelper.IsUsingEpiProject)
                {
                    columnNames.Add("UniqueKey");
                }
                columnNames.Add(valueField);
                columnNames.Add(dataKey);

                DataTable loadedData;

                if (valueField.Equals("{Record Count}"))
                {
                    GadgetParameters gadgetOptions = new GadgetParameters();
                    gadgetOptions.MainVariableName = dataKey;

                    Dictionary<string, string> inputVariableList = new Dictionary<string, string>();
                    inputVariableList.Add("freqvar", dataKey);
                    inputVariableList.Add("allvalues", "false");
                    inputVariableList.Add("showconflimits", "false");
                    inputVariableList.Add("showcumulativepercent", "false");
                    inputVariableList.Add("includemissing", "false");
                    inputVariableList.Add("maxrows", "500");

                    gadgetOptions.InputVariableList = inputVariableList;
                    loadedData = dashboardHelper.GenerateFrequencyTable(gadgetOptions).First().Key;
                    foreach (DataRow dr in loadedData.Rows)
                    {
                        dr[0] = dr[0].ToString().Trim();
                    }
                    valueField = "freq";
                }
                else
                {
                    loadedData = dashboardHelper.GenerateTable(columnNames);
                }

                GraphicsLayer graphicsLayer = myMap.Layers[layerId.ToString()] as GraphicsLayer;

                List<double> valueList = new List<double>();
                List<Graphic> graphicsToBeAdded = new List<Graphic>();
                SpatialReference geoReference = new SpatialReference(4326);
                for (int i = 0; i < graphicsLayer.Graphics.Count; i++)
                {
                    Graphic graphicFeature = graphicsLayer.Graphics[i];

                    double xmin = graphicFeature.Geometry.Extent.XMin;
                    double xmax = graphicFeature.Geometry.Extent.XMax;
                    double ymin = graphicFeature.Geometry.Extent.YMin;
                    double ymax = graphicFeature.Geometry.Extent.YMax;

                    Random rnd = new Random();

                    string shapeValue = graphicFeature.Attributes[shapeKey].ToString().Replace("'", "''").Trim();

                    string filterExpression = "";
                    if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                        filterExpression += "[";
                    filterExpression += dataKey;
                    if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                        filterExpression += "]";
                    filterExpression += " = '" + shapeValue + "'";

                    double graphicValue = Double.PositiveInfinity;
                    try
                    {
                        graphicValue = Convert.ToDouble(loadedData.Select(filterExpression)[0][valueField]);

                        for (int counter = 0; counter < graphicValue; counter += dotValue)
                        {
                            bool pointInGraphic = false;

                            ExtendedGraphic graphic = new ExtendedGraphic();
                            while (!pointInGraphic)
                            {
                                double rndX = xmin + (rnd.NextDouble() * (xmax - xmin));
                                double rndY = ymin + (rnd.NextDouble() * (ymax - ymin));
                                graphic.Geometry = new MapPoint(rndX, rndY, geoReference);
                                graphic.Symbol = MarkerSymbol;

                                bool foundBottomLeft = false;
                                bool foundBottomRight = false;
                                bool foundTopLeft = false;
                                bool foundTopRight = false;
                                foreach (ESRI.ArcGIS.Client.Geometry.PointCollection pc in ((ESRI.ArcGIS.Client.Geometry.Polygon)graphicFeature.Geometry).Rings)
                                {
                                    foundBottomLeft = pc.Any((point) => point.Y <= ((MapPoint)graphic.Geometry).Y && point.X <= ((MapPoint)graphic.Geometry).X);
                                    foundBottomRight = pc.Any((point) => point.Y <= ((MapPoint)graphic.Geometry).Y && point.X >= ((MapPoint)graphic.Geometry).X);
                                    foundTopLeft = pc.Any((point) => point.Y >= ((MapPoint)graphic.Geometry).Y && point.X <= ((MapPoint)graphic.Geometry).X);
                                    foundTopRight = pc.Any((point) => point.Y >= ((MapPoint)graphic.Geometry).Y && point.X >= ((MapPoint)graphic.Geometry).X);

                                    if (foundBottomLeft && foundBottomRight && foundTopLeft && foundTopRight)
                                    {
                                        try
                                        {
                                            MapPoint firstBottomLeft = pc.First((point) => point.Y <= ((MapPoint)graphic.Geometry).Y && point.X <= ((MapPoint)graphic.Geometry).X);
                                            MapPoint firstBottomRight = pc.First((point) => point.Y <= ((MapPoint)graphic.Geometry).Y && point.X >= ((MapPoint)graphic.Geometry).X);
                                            MapPoint firstTopLeft = pc.First((point) => point.Y >= ((MapPoint)graphic.Geometry).Y && point.X <= ((MapPoint)graphic.Geometry).X);
                                            MapPoint firstTopRight = pc.First((point) => point.Y >= ((MapPoint)graphic.Geometry).Y && point.X >= ((MapPoint)graphic.Geometry).X);

                                            int indexBL = pc.IndexOf(firstBottomLeft);
                                            int indexBR = pc.IndexOf(firstBottomRight);
                                            int indexTL = pc.IndexOf(firstTopLeft);
                                            int indexTR = pc.IndexOf(firstTopRight);

                                            MapPoint lastBottomLeft = pc.Last((point) => point.Y <= ((MapPoint)graphic.Geometry).Y && point.X <= ((MapPoint)graphic.Geometry).X);
                                            MapPoint lastBottomRight = pc.Last((point) => point.Y <= ((MapPoint)graphic.Geometry).Y && point.X >= ((MapPoint)graphic.Geometry).X);
                                            MapPoint lastTopLeft = pc.Last((point) => point.Y >= ((MapPoint)graphic.Geometry).Y && point.X <= ((MapPoint)graphic.Geometry).X);
                                            MapPoint lastTopRight = pc.Last((point) => point.Y >= ((MapPoint)graphic.Geometry).Y && point.X >= ((MapPoint)graphic.Geometry).X);

                                            int indexBL2 = pc.IndexOf(lastBottomLeft);
                                            int indexBR2 = pc.IndexOf(lastBottomRight);
                                            int indexTL2 = pc.IndexOf(lastTopLeft);
                                            int indexTR2 = pc.IndexOf(lastTopRight);

                                            if ((Math.Abs(indexTL - indexTR2) == 1 && Math.Abs(indexTR - indexBR2) == 1) || (Math.Abs(indexBL - indexTL2) == 1 && Math.Abs(indexTL - indexTR2) == 1) || (Math.Abs(indexBR - indexBL2) == 1 && Math.Abs(indexTR - indexBR2) == 1))
                                            {
                                                pointInGraphic = true;
                                                break;
                                            }
                                            else if ((Math.Abs(indexBL - indexBR2) == 1 && Math.Abs(indexTL - indexBL2) == 1) || (Math.Abs(indexTL - indexBL2) == 1 && Math.Abs(indexTR - indexTL2) == 1) || (Math.Abs(indexBR - indexTR2) == 1 && Math.Abs(indexTR - indexTL2) == 1))
                                            {
                                                pointInGraphic = true;
                                                break;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            pointInGraphic = false;
                                        }
                                    }
                                }
                            }
                            graphicsToBeAdded.Add(graphic);
                        }

                    }
                    catch (Exception ex)
                    {
                        graphicValue = Double.PositiveInfinity;
                    }
                }

                foreach (Graphic g in graphicsLayer.Graphics)
                {
                    SimpleFillSymbol symbol = new SimpleFillSymbol()
                    {
                        Fill = new SolidColorBrush(Colors.Transparent),
                        BorderBrush = new SolidColorBrush(Colors.Black),
                        BorderThickness = 1
                    };

                    g.Symbol = symbol;
                }

                GraphicsLayer dotLayer = myMap.Layers[layerId.ToString() + "_dotLayer"] as GraphicsLayer;
                int currentDotIndex = myMap.Layers.Count;
                if (dotLayer != null)
                {
                    currentDotIndex = myMap.Layers.IndexOf(dotLayer);
                    myMap.Layers.Remove(dotLayer);
                }
                dotLayer = new GraphicsLayer();
                dotLayer.ID = layerId.ToString() + "_dotLayer";
                myMap.Layers.Insert(currentDotIndex, dotLayer);
                foreach (Graphic g in graphicsToBeAdded)
                {
                    dotLayer.Graphics.Add(g);
                }

            }
            catch (Exception ex)
            {
            }
        }
Example #29
0
 public void GetCrossTabResults(string DataSourceName, string TableName, GadgetParameters gadgetParameters)
 {
     this.ServiceAgent.GetCrossTabResults(DataSourceName, TableName, gadgetParameters, MeansCrossTabDataCompleted);
 }
Example #30
0
 public void SetupGadget(GadgetParameters gadgetParameters)
 {
     this.ServiceAgent.SetupGadget(gadgetParameters, SetupGadgetCompleted);
 }
        protected override void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            lock (syncLock)
            {
                Dictionary<string, string> inputVariableList = ((GadgetParameters)e.Argument).InputVariableList;

                //Stopwatch stopwatch = new Stopwatch();
                //stopwatch.Start();

                this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToProcessingState));
                this.Dispatcher.BeginInvoke(new SimpleCallback(ClearResults));

                AddFreqGridDelegate addGrid = new AddFreqGridDelegate(AddFreqGrid);
                SetGridTextDelegate setText = new SetGridTextDelegate(SetGridText);
                AddGridRowDelegate addRow = new AddGridRowDelegate(AddGridRow);
                RenderFrequencyHeaderDelegate renderHeader = new RenderFrequencyHeaderDelegate(RenderFrequencyHeader);
                DrawFrequencyBordersDelegate drawBorders = new DrawFrequencyBordersDelegate(DrawOutputGridBorders);

                string freqVar = string.Empty;
                string weightVar = string.Empty;
                string strataVar = string.Empty;
                string crosstabVar = string.Empty;
                bool includeMissing = false;
                bool outcomeContinuous = false;
                bool showStrataSummaryOnly = false;

                if (inputVariableList.ContainsKey("freqvar"))
                {
                    freqVar = inputVariableList["freqvar"];
                }

                if (inputVariableList.ContainsKey("crosstabvar"))
                {
                    crosstabVar = inputVariableList["crosstabvar"];
                }

                if (inputVariableList.ContainsKey("weightvar"))
                {
                    weightVar = inputVariableList["weightvar"];
                }

                if (inputVariableList.ContainsKey("stratavar"))
                {
                    strataVar = inputVariableList["stratavar"];
                }

                if (inputVariableList.ContainsKey("includemissing"))
                {
                    if (inputVariableList["includemissing"].Equals("true"))
                    {
                        includeMissing = true;
                    }
                }

                if (inputVariableList.ContainsKey("stratasummaryonly"))
                {
                    if (inputVariableList["stratasummaryonly"].Equals("true"))
                    {
                        showStrataSummaryOnly = true;
                    }
                }

                if (inputVariableList.ContainsKey("treatoutcomeascontinuous"))
                {
                    if (inputVariableList["treatoutcomeascontinuous"].Equals("true"))
                    {
                        outcomeContinuous = true;
                    }
                }

                List<string> stratas = new List<string>();
                if (!string.IsNullOrEmpty(strataVar))
                {
                    stratas.Add(strataVar);
                }

                try
                {
                    GadgetOptions.GadgetStatusUpdate += new GadgetStatusUpdateHandler(requestUpdateStatus);
                    GadgetOptions.GadgetCheckForCancellation += new GadgetCheckForCancellationHandler(checkForCancellation);

                    if (this.DataFilters != null && this.DataFilters.Count > 0)
                    {
                        GadgetOptions.CustomFilter = this.DataFilters.GenerateDataFilterString(false);
                    }
                    else
                    {
                        GadgetOptions.CustomFilter = string.Empty;
                    }

                    bool runGroup = false;

                    Dictionary<DataTable, List<DescriptiveStatistics>> stratifiedFrequencyTables = new Dictionary<DataTable, List<DescriptiveStatistics>>();

                    List<string> allGroupFields = dashboardHelper.GetAllGroupsAsList();

                    if (GadgetOptions.MainVariableNames != null && GadgetOptions.MainVariableNames.Count > 0)
                    {
                        Dictionary<DataTable, List<DescriptiveStatistics>> grpTables = new Dictionary<DataTable, List<DescriptiveStatistics>>();

                        foreach (string mainVariableName in GadgetOptions.MainVariableNames)
                        {
                            GadgetParameters newOptions = new GadgetParameters(GadgetOptions);
                            newOptions.MainVariableNames = null;
                            newOptions.MainVariableName = mainVariableName;

                            grpTables = dashboardHelper.GenerateFrequencyTable(newOptions);

                            foreach (KeyValuePair<DataTable, List<DescriptiveStatistics>> kvp in grpTables)
                            {
                                stratifiedFrequencyTables.Add(kvp.Key, kvp.Value);
                            }
                        }
                        runGroup = true;
                    }
                    else if (allGroupFields.Contains(GadgetOptions.MainVariableName))
                    {
                        Dictionary<DataTable, List<DescriptiveStatistics>> grpTables = new Dictionary<DataTable, List<DescriptiveStatistics>>();

                        foreach (string variableName in dashboardHelper.GetVariablesInGroup(GadgetOptions.MainVariableName))
                        {
                            if (!allGroupFields.Contains(variableName) && dashboardHelper.TableColumnNames.ContainsKey(variableName))
                            {
                                GadgetParameters newOptions = new GadgetParameters(GadgetOptions);
                                newOptions.MainVariableNames = null;
                                newOptions.MainVariableName = variableName;

                                grpTables = dashboardHelper.GenerateFrequencyTable(newOptions);

                                foreach (KeyValuePair<DataTable, List<DescriptiveStatistics>> kvp in grpTables)
                                {
                                    stratifiedFrequencyTables.Add(kvp.Key, kvp.Value);
                                }
                            }
                        }
                        runGroup = true;
                    }
                    else
                    {
                        stratifiedFrequencyTables = dashboardHelper.GenerateFrequencyTable(GadgetOptions/*, freqVar, weightVar, stratas, crosstabVar, useAllPossibleValues, sortHighLow, includeMissing, false*/);
                        runGroup = false;
                    }

                    if (runGroup) showStrataSummaryOnly = false;

                    if (stratifiedFrequencyTables == null || stratifiedFrequencyTables.Count == 0)
                    {
                        this.Dispatcher.BeginInvoke(new RenderFinishWithErrorDelegate(RenderFinishWithError), DashboardSharedStrings.GADGET_MSG_NO_DATA);
                        this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToFinishedState));
                        return;
                    }
                    else if (worker.CancellationPending)
                    {
                        this.Dispatcher.BeginInvoke(new RenderFinishWithErrorDelegate(RenderFinishWithError), SharedStrings.DASHBOARD_GADGET_STATUS_OPERATION_CANCELLED);
                        this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToFinishedState));
                        //Debug.Print("Thread cancelled");
                        return;
                    }
                    else
                    {
                        string formatString = string.Empty;

                        foreach (KeyValuePair<DataTable, List<DescriptiveStatistics>> tableKvp in stratifiedFrequencyTables)
                        {
                            SmartTable(tableKvp.Key);

                            string strataValue = tableKvp.Key.TableName;

                            double count = 0;
                            foreach (DescriptiveStatistics ds in tableKvp.Value)
                            {
                                count = count + ds.observations;
                            }

                            if (count == 0 && stratifiedFrequencyTables.Count == 1)
                            {
                                // this is the only table and there are no records, so let the user know
                                this.Dispatcher.BeginInvoke(new RenderFinishWithErrorDelegate(RenderFinishWithError), SharedStrings.NO_RECORDS_SELECTED);
                                this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToFinishedState));
                                return;
                            }
                            else if (count == 0)
                            {
                                continue;
                            }
                            DataTable frequencies = tableKvp.Key;

                            if (frequencies.Rows.Count == 0)
                            {
                                continue;
                            }

                            if (outcomeContinuous)
                            {
                                if (frequencies.Columns.Count <= 128)
                                {
                                    int min;
                                    int max;

                                    if (int.TryParse(frequencies.Columns[1].ColumnName, out min) && int.TryParse(frequencies.Columns[frequencies.Columns.Count - 1].ColumnName, out max))
                                    {
                                        bool addedColumns = false;

                                        for (int i = min; i <= max; i++)
                                        {
                                            if (!frequencies.Columns.Contains(i.ToString()))
                                            {
                                                DataColumn newColumn = new DataColumn(i.ToString(), typeof(double));
                                                newColumn.DefaultValue = 0;
                                                frequencies.Columns.Add(newColumn);
                                                addedColumns = true;
                                            }
                                        }

                                        if (addedColumns)
                                        {
                                            int ordinal = 1;
                                            for (int i = min; i <= max; i++)
                                            {
                                                if (frequencies.Columns.Contains(i.ToString()))
                                                {
                                                    frequencies.Columns[i.ToString()].SetOrdinal(ordinal);
                                                    ordinal++;
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            this.Dispatcher.BeginInvoke(addGrid, strataVar, frequencies.TableName, crosstabVar, frequencies.Columns[0].ToString(), frequencies);
                        }

                        foreach (KeyValuePair<DataTable, List<DescriptiveStatistics>> tableKvp in stratifiedFrequencyTables)
                        {
                            if (runGroup)
                            {
                                freqVar = tableKvp.Key.Columns[0].ColumnName;
                            }

                            string strataValue = tableKvp.Key.TableName;

                            double count = 0;
                            foreach (DescriptiveStatistics ds in tableKvp.Value)
                            {
                                count = count + ds.observations;
                            }

                            if (count == 0)
                            {
                                continue;
                            }
                            DataTable frequencies = tableKvp.Key;

                            if (frequencies.Rows.Count == 0)
                            {
                                continue;
                            }

                            string tableHeading = tableKvp.Key.TableName;

                            if (stratifiedFrequencyTables.Count > 1)
                            {
                                tableHeading = freqVar;
                            }

                            this.Dispatcher.BeginInvoke(renderHeader, strataValue, tableHeading, frequencies.Columns);

                            rowCount = 1;

                            int[] totals = new int[frequencies.Columns.Count - 1];
                            columnCount = 1;

                            DataRow[] SortedRows = new DataRow[frequencies.Rows.Count];
                            int rowcounter = 0;
                            foreach (System.Data.DataRow row in frequencies.Rows)
                            {
                                SortedRows[rowcounter++] = row;
                                if (!row[freqVar].Equals(DBNull.Value) || (row[freqVar].Equals(DBNull.Value) && includeMissing == true))
                                {
                                    this.Dispatcher.Invoke(addRow, strataValue, -1);
                                    string displayValue = row[freqVar].ToString();

                                    if (dashboardHelper.IsUserDefinedColumn(freqVar))
                                    {
                                        displayValue = dashboardHelper.GetFormattedOutput(freqVar, row[freqVar]);
                                    }
                                    else
                                    {
                                        if (dashboardHelper.IsUsingEpiProject && View.Fields[freqVar] is YesNoField)
                                        {
                                            if (row[freqVar].ToString().Equals("1"))
                                                displayValue = "Yes";
                                            else if (row[freqVar].ToString().Equals("0"))
                                                displayValue = "No";
                                        }
                                        else if (dashboardHelper.IsUsingEpiProject && View.Fields[freqVar] is DateField)
                                        {
                                            displayValue = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:d}", row[freqVar]);
                                        }
                                        else if (dashboardHelper.IsUsingEpiProject && View.Fields[freqVar] is TimeField)
                                        {
                                            displayValue = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:T}", row[freqVar]);
                                        }
                                        else
                                        {
                                            displayValue = dashboardHelper.GetFormattedOutput(freqVar, row[freqVar]);
                                        }
                                    }

                                    if (string.IsNullOrEmpty(displayValue))
                                    {
                                        Configuration config = dashboardHelper.Config;
                                        displayValue = config.Settings.RepresentationOfMissing;
                                    }

                                    this.Dispatcher.BeginInvoke(setText, strataValue, new TextBlockConfig(displayValue, new Thickness(4, 0, 4, 0), VerticalAlignment.Center, HorizontalAlignment.Left, TextAlignment.Left, rowCount, 0, System.Windows.Visibility.Visible), FontWeights.Normal);

                                    int rowTotal = 0;
                                    columnCount = 1;

                                    foreach (DataColumn column in frequencies.Columns)
                                    {
                                        if (column.ColumnName.Equals(freqVar))
                                        {
                                            continue;
                                        }

                                        this.Dispatcher.BeginInvoke(setText, strataValue, new TextBlockConfig(row[column.ColumnName].ToString(), new Thickness(4, 0, 4, 0), VerticalAlignment.Center, HorizontalAlignment.Right, TextAlignment.Right, rowCount, columnCount, System.Windows.Visibility.Visible), FontWeights.Normal);
                                        columnCount++;

                                        int rowValue = 0;
                                        bool success = int.TryParse(row[column.ColumnName].ToString(), out rowValue);
                                        if (success)
                                        {
                                            totals[columnCount - 2] = totals[columnCount - 2] + rowValue;
                                            rowTotal = rowTotal + rowValue;
                                        }
                                    }
                                    this.Dispatcher.BeginInvoke(setText, strataValue, new TextBlockConfig(rowTotal.ToString(), new Thickness(4, 0, 4, 0), VerticalAlignment.Center, HorizontalAlignment.Right, TextAlignment.Right, rowCount, columnCount, System.Windows.Visibility.Visible), FontWeights.Bold);
                                    rowCount++;
                                }
                            }

                            double[] tableChiSq = Epi.Statistics.SingleMxN.CalcChiSq(SortedRows, false);
                            double tableChiSqDF = (double)(SortedRows.Length - 1) * (SortedRows[0].ItemArray.Length - 2);
                            double tableChiSqP = Epi.Statistics.SharedResources.PValFromChiSq(tableChiSq[0], tableChiSqDF);
                            String disclaimer = "";
                            if (tableChiSq[1] == 1.0)
                                disclaimer = SharedStrings.TABLES_CHI_SQUARE_NOT_VALID;

                            this.Dispatcher.BeginInvoke(new AddChiSquareDelegate(RenderChiSquare), tableChiSq[0], tableChiSqDF, tableChiSqP, disclaimer, strataValue);
                            this.Dispatcher.BeginInvoke(new AddGridFooterDelegate(RenderFrequencyFooter), strataValue, rowCount, totals);
                            this.Dispatcher.BeginInvoke(drawBorders, strataValue);
                        }
                    }

                    this.Dispatcher.BeginInvoke(new SimpleCallback(RenderFinish));
                    this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToFinishedState));

                    // check for existence of 2x2 table...
                    if (rowCount == 3 && columnCount == 3)
                    {
                    }

                    stratifiedFrequencyTables.Clear();
                }
                catch (Exception ex)
                {
                    this.Dispatcher.BeginInvoke(new RenderFinishWithErrorDelegate(RenderFinishWithError), ex.Message);
                    this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToFinishedState));
                }
                finally
                {
                    //stopwatch.Stop();
                    //Debug.Print("Crosstab gadget took " + stopwatch.Elapsed.ToString() + " seconds to complete with " + dashboardHelper.RecordCount.ToString() + " records and the following filters:");
                    //Debug.Print(dashboardHelper.DataFilters.GenerateDataFilterString());
                }
            }
        }
Example #32
0
        // TODO: Add methods that will be called by the view

        public void GetLineList(GadgetParameters gp)
        {
            this.serviceAgent.GenerateLineList(gp, GetLineListCompleted);
        }
        public void SetShapeRangeValues(DashboardHelper dashboardHelper, string shapeKey, string dataKey, string valueField, List<SolidColorBrush> colors, int classCount)
        {
            try
            {
                this.classCount = classCount;
                this.dashboardHelper = dashboardHelper;
                this.shapeKey = shapeKey;
                this.dataKey = dataKey;
                this.valueField = valueField;
                this.colors = colors;

                List<string> columnNames = new List<string>();
                if (dashboardHelper.IsUsingEpiProject)
                {
                    columnNames.Add("UniqueKey");
                }
                columnNames.Add(valueField);
                columnNames.Add(dataKey);

                DataTable loadedData;

                if (valueField.Equals("{Record Count}"))
                {
                    GadgetParameters gadgetOptions = new GadgetParameters();
                    gadgetOptions.MainVariableName = dataKey;

                    Dictionary<string, string> inputVariableList = new Dictionary<string, string>();
                    inputVariableList.Add("freqvar", dataKey);
                    inputVariableList.Add("allvalues", "false");
                    inputVariableList.Add("showconflimits", "false");
                    inputVariableList.Add("showcumulativepercent", "false");
                    inputVariableList.Add("includemissing", "false");
                    inputVariableList.Add("maxrows", "500");

                    gadgetOptions.InputVariableList = inputVariableList;
                    loadedData = dashboardHelper.GenerateFrequencyTable(gadgetOptions).First().Key;
                    foreach (DataRow dr in loadedData.Rows)
                    {
                        dr[0] = dr[0].ToString().Trim();
                    }
                    valueField = "freq";
                }
                else
                {
                    loadedData = dashboardHelper.GenerateTable(columnNames);
                }

                GraphicsLayer graphicsLayer = myMap.Layers[layerId.ToString()] as GraphicsLayer;
                ThematicItem thematicItem = new ThematicItem() { Name = dataKey, Description = dataKey, CalcField = "" };
                List<double> valueList = new List<double>();
                for (int i = 0; i < graphicsLayer.Graphics.Count; i++)
                {
                    Graphic graphicFeature = graphicsLayer.Graphics[i];
                    //string filterExpression = dataKey + " = '" + graphicFeature.Attributes[shapeKey].ToString().Trim() + "'";
                    string filterExpression = "";
                    if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                        filterExpression += "[";
                    filterExpression += dataKey;
                    if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                        filterExpression += "]";
                    filterExpression += " = '" + graphicFeature.Attributes[shapeKey].ToString().Replace("'", "''").Trim() + "'";

                    double graphicValue = Double.PositiveInfinity;
                    try
                    {
                        graphicValue = Convert.ToDouble(loadedData.Select(filterExpression)[0][valueField]);
                    }
                    catch (Exception ex)
                    {
                        graphicValue = Double.PositiveInfinity;
                    }

                    string graphicName = graphicFeature.Attributes[shapeKey].ToString();

                    if (i == 0)
                    {
                        thematicItem.Min = Double.PositiveInfinity;
                        thematicItem.Max = Double.NegativeInfinity;
                        thematicItem.MinName = string.Empty;
                        thematicItem.MaxName = string.Empty;
                    }
                    else
                    {
                        if (graphicValue < thematicItem.Min) { thematicItem.Min = graphicValue; thematicItem.MinName = graphicName; }
                        if (graphicValue > thematicItem.Max && graphicValue != Double.PositiveInfinity) { thematicItem.Max = graphicValue; thematicItem.MaxName = graphicName; }
                    }

                    if (graphicValue < Double.PositiveInfinity)
                    {
                        valueList.Add(graphicValue);
                    }
                }
                thematicItem.RangeStarts = new List<double>();

                double totalRange = thematicItem.Max - thematicItem.Min;
                double portion = totalRange / classCount;

                thematicItem.RangeStarts.Add(thematicItem.Min);
                double startRangeValue = thematicItem.Min;
                IEnumerable<double> valueEnumerator =
                from aValue in valueList
                orderby aValue
                select aValue;

                int increment = Convert.ToInt32(Math.Round((double)valueList.Count / (double)classCount));
                for (int i = increment; i < valueList.Count; i += increment)
                {
                    double value = valueEnumerator.ElementAt(i);
                    if (value < thematicItem.Min)
                        value = thematicItem.Min;
                    thematicItem.RangeStarts.Add(value);
                }

                if (graphicsLayer.Graphics != null && graphicsLayer.Graphics.Count > 0)
                {

                    for (int i = 0; i < graphicsLayer.Graphics.Count; i++)
                    {
                        Graphic graphicFeature = graphicsLayer.Graphics[i];

                        //string filterExpression = dataKey + " = '" + graphicFeature.Attributes[shapeKey].ToString().Trim() + "'";
                        string filterExpression = "";
                        if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                            filterExpression += "[";
                        filterExpression += dataKey;
                        if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                            filterExpression += "]";
                        filterExpression += " = '" + graphicFeature.Attributes[shapeKey].ToString().Replace("'", "''").Trim() + "'";

                        double graphicValue = Double.PositiveInfinity;
                        try
                        {
                            graphicValue = Convert.ToDouble(loadedData.Select(filterExpression)[0][valueField]);
                        }
                        catch (Exception)
                        {
                            graphicValue = Double.PositiveInfinity;
                        }

                        int brushIndex = GetRangeIndex(graphicValue, thematicItem.RangeStarts);

                        SimpleFillSymbol symbol = new SimpleFillSymbol()
                        {
                            Fill = graphicValue == Double.PositiveInfinity ? new SolidColorBrush(Colors.Transparent) : colors[brushIndex],
                            BorderBrush = new SolidColorBrush(Colors.Black),
                            BorderThickness = 1
                        };

                        graphicFeature.Symbol = symbol;

                        TextBlock t = new TextBlock();
                        t.Background = Brushes.White;
                        if (graphicValue == Double.PositiveInfinity)
                        {
                            t.Text = graphicFeature.Attributes[shapeKey].ToString().Trim() + " : No Data";
                        }
                        else
                        {
                            t.Text = graphicFeature.Attributes[shapeKey].ToString().Trim() + " : " + graphicValue.ToString();
                        }
                        t.FontSize = 14;
                        Border border = new Border();
                        border.BorderThickness = new Thickness(1);
                        Panel panel = new StackPanel();
                        panel.Children.Add(t);
                        border.Child = panel;

                        graphicFeature.MapTip = border;
                    }

                }

                if (LegendStackPanel == null)
                {
                    LegendStackPanel = new StackPanel();
                }
                LegendStackPanel.Children.Clear();

                System.Windows.Controls.ListBox legendList = new System.Windows.Controls.ListBox();
                legendList.Margin = new Thickness(5);
                legendList.Background = Brushes.White;// new LinearGradientBrush(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF), Color.FromArgb(0x7F, 0xFF, 0xFF, 0xFF), 45);
                legendList.BorderBrush = Brushes.Black;
                legendList.BorderThickness = new Thickness(3);
                //LegendTitle.Text = thematicItem.Description;

                for (int c = 0; c < classCount; c++)
                {
                    try
                    {
                        Rectangle swatchRect = new Rectangle()
                        {
                            Width = 20,
                            Height = 20,
                            Stroke = new SolidColorBrush(Colors.Black),
                            Fill = colors[c]
                        };

                        TextBlock classTextBlock = new TextBlock();

                        if (c == 0)
                        {
                            if (thematicItem.RangeStarts[1] == thematicItem.Min)
                                classTextBlock.Text = String.Format("  Exactly {0}", Math.Round(thematicItem.RangeStarts[1], 2));
                            else
                                classTextBlock.Text = String.Format("  Less than {0}", Math.Round(thematicItem.RangeStarts[1], 2));
                        }
                        else if (c == classCount - 1)
                            classTextBlock.Text = String.Format("  {0} and above", Math.Round(thematicItem.RangeStarts[c], 2));
                        else if (thematicItem.RangeStarts.Count <= c + 1)
                        {
                            classTextBlock.Text = String.Format("  {0} and above", Math.Round(thematicItem.RangeStarts[c], 2));
                        }
                        // Middle classifications
                        else
                        {
                            if (thematicItem.RangeStarts[c] == thematicItem.RangeStarts[c + 1])
                                classTextBlock.Text = String.Format("  Exactly {0}", Math.Round(thematicItem.RangeStarts[c], 2));
                            else
                                classTextBlock.Text = String.Format("  {0} to {1}", Math.Round(thematicItem.RangeStarts[c], 2), Math.Round(thematicItem.RangeStarts[c + 1], 2));
                        }

                        StackPanel classStackPanel = new StackPanel();
                        classStackPanel.Orientation = System.Windows.Controls.Orientation.Horizontal;
                        classStackPanel.Children.Add(swatchRect);
                        classStackPanel.Children.Add(classTextBlock);

                        legendList.Items.Add(classStackPanel);
                        if (thematicItem.RangeStarts.Count <= c + 1)
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }

                TextBlock minTextBlock = new TextBlock();
                StackPanel minStackPanel = new StackPanel();
                minStackPanel.Orientation = System.Windows.Controls.Orientation.Horizontal;
                minTextBlock.Text = thematicItem.MinName != null ? String.Format("Min: {0} ({1})", thematicItem.Min, thematicItem.MinName.Trim()) : String.Format("Min: {0} ({1})", thematicItem.Min, string.Empty);
                minStackPanel.Children.Add(minTextBlock);
                legendList.Items.Add(minStackPanel);

                TextBlock maxTextBlock = new TextBlock();
                StackPanel maxStackPanel = new StackPanel();
                maxStackPanel.Orientation = System.Windows.Controls.Orientation.Horizontal;
                maxTextBlock.Text = thematicItem.MaxName != null ? String.Format("Max: {0} ({1})", thematicItem.Max, thematicItem.MaxName.Trim()) : String.Format("Max: {0} ({1})", thematicItem.Max, string.Empty);
                maxStackPanel.Children.Add(maxTextBlock);
                legendList.Items.Add(maxStackPanel);

                LegendStackPanel.Children.Add(legendList);

            }
            catch (Exception ex)
            {
            }
        }
        protected override void Construct()
        {
            if (!string.IsNullOrEmpty(CustomOutputHeading) && !CustomOutputHeading.Equals("(none)"))
            {
                headerPanel.Text = CustomOutputHeading;
            }

            this.IsProcessing = false;

            this.GadgetStatusUpdate += new GadgetStatusUpdateHandler(RequestUpdateStatusMessage);
            this.GadgetCheckForCancellation += new GadgetCheckForCancellationHandler(IsCancelled);

            cbxFields.SelectionChanged += new SelectionChangedEventHandler(cbxFields_SelectionChanged);

            mnuSendToBack.Click += new RoutedEventHandler(mnuSendToBack_Click);
            mnuClose.Click += new RoutedEventHandler(mnuClose_Click);

            // Init gadget parameters with default values
            GadgetOptions = new GadgetParameters();
            GadgetOptions.ShouldIncludeFullSummaryStatistics = true;
            GadgetOptions.ShouldIncludeMissing = false;
            GadgetOptions.ShouldSortHighToLow = false;
            GadgetOptions.ShouldUseAllPossibleValues = false;
            GadgetOptions.StrataVariableNames = new List<string>();

            base.Construct();
        }