private void btnProcesar_Click_1(object sender, EventArgs e)
        {
            statusLblProcesando.Text = "Procesando datos...";

            IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass();
            IStepProgressor        pStepPro   = pProDiaFac.Create(null, 0);

            pStepPro.MinRange  = 1;
            pStepPro.MaxRange  = 5;
            pStepPro.StepValue = 1;
            IProgressDialog2 pProDia = (IProgressDialog2)pStepPro;

            pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe;

            pProDia.Title = "Incorporando Lecturas";
            pProDia.ShowDialog();
            pStepPro.Step();
            pStepPro.Message = "Procesando precipitacion...";


            ProcesarLecturas procesarLecturas = new ProcesarLecturas();

            try
            {
                procesarLecturas.CalcularResultadosPrecipitacion(_sigpiDao, "DEFI_PRECI", "LECTUS_PRECI", dtPickerFechaAProcesar.Value, 10);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error procesando las lecturas:\n" + ex.Message);
            }

            pStepPro.Step();
            pStepPro.Message = "Procesando Temperatura...";
            try
            {
                procesarLecturas.CalcularResultadosTemperatura(_sigpiDao, "DEFI_TEMPE", "LECTUS_TEMPE", dtPickerFechaAProcesar.Value, "T5", 10);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error procesando las lecturas:\n" + ex.Message);
            }

            string sSQL = "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + dtPickerFechaAProcesar.Value.ToString("MM/dd/yyyy") + "#";

            try
            {
                _sigpiDao.EjecutarSentenciaSinQuery(sSQL);
            }
            catch (Exception ex)
            {
                MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message);
            }
            _sigpi.FechaProcesamiento  = dtPickerFechaAProcesar.Value;
            txtUltimaFechaProceso.Text = dtPickerFechaAProcesar.Value.ToLongDateString();

            pProDia.HideDialog();
            MessageBox.Show("Datos Procesados");
        }
Exemple #2
0
        /// <summary>
        /// Calcula promedio de temperatura
        /// </summary>
        /// <param name="SigpiDao"></param>
        /// <param name="sTablaConsolidados"></param>
        /// <param name="sTablaLecturas"></param>
        /// <param name="FechaCalculos"></param>
        /// <param name="sCampoPromedioTemp"></param>
        /// <param name="NumDias"></param>
        /// <returns></returns>
        public bool CalcularResultadosTemperatura(SIGPIDao SigpiDao, string sTablaConsolidados,
                                                  string sTablaLecturas, DateTime FechaCalculos,
                                                  string sCampoPromedioTemp, int NumDias)
        {
            string sSQL = "DROP TABLE " + sTablaConsolidados;

            try
            {
                SigpiDao.EjecutarSentenciaSinQuery(sSQL);
            }
            catch (Exception)
            {
                //throw new Exception(e.Message);
            }
            DateTime FechaCalculosInicial = FechaCalculos.AddDays(-1 * (NumDias - 1));

            //sSQL = "SELECT CODIGO, Avg(LECTURA) AS T5, Max(LECTUS_TEMPE.FECHA) AS FECHA INTO " +
            //        sTablaConsolidados + " From " + sTablaLecturas +
            //        " WHERE FECHA <=#" + FechaCalculos.ToString("MM/dd/yyyy") + "#" +
            //        " AND FECHA >=#" + FechaCalculosInicial.ToString("MM/dd/yyyy") + "#" +
            //        " GROUP BY CODIGO";

            sSQL = "SELECT CODIGO, Avg(LECTURA) AS " + sCampoPromedioTemp + ", Max(LECTUS_TEMPE.FECHA) AS FECHA, " + NumDias.ToString() + " AS NO_DIAS INTO " +
                   sTablaConsolidados + " From " + sTablaLecturas +
                   " WHERE FECHA <= ?" +
                   " AND FECHA >= ?" +
                   " GROUP BY CODIGO";


            OleDbCommand command = SigpiDao.LocalDBConnection.CreateCommand();

            command.CommandText = sSQL;
            OleDbParameter paramFechaCalculos        = command.CreateParameter();
            OleDbParameter paramFechaCalculosInicial = command.CreateParameter();

            paramFechaCalculos.Value        = FechaCalculos;
            paramFechaCalculosInicial.Value = FechaCalculosInicial;
            command.Parameters.Add(paramFechaCalculos);
            command.Parameters.Add(paramFechaCalculosInicial);

            try
            {
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return(true);
        }
Exemple #3
0
        /// <summary>
        /// Calcular Resultados Precipitacion
        /// </summary>
        /// <param name="SigpiDao"></param>
        /// <param name="sTablaConsolidados"></param>
        /// <param name="sTablaLecturas"></param>
        /// <param name="FechaCalculos"></param>
        /// <returns></returns>
        public bool CalcularResultadosPrecipitacion(SIGPIDao SigpiDao, string sTablaConsolidados,
                                                    string sTablaLecturas, DateTime FechaCalculos,
                                                    int numDias)
        {
            string sSQL = "DELETE FROM " + sTablaConsolidados;

            try
            {
                SigpiDao.EjecutarSentenciaSinQuery(sSQL);
            }
            catch (Exception e)
            {
                // throw new Exception(e.Message + sSQL);
            }
            DateTime FechaCalculosInicial = FechaCalculos.AddDays(-1 * (numDias - 1));

            //sSQL = "SELECT CODIGO,LECTURA,FECHA From " + sTablaLecturas +
            //        " WHERE FECHA <=#" + FechaCalculos.ToString("MM/dd/yyyy") + "#" +
            //        " AND FECHA >=#" + FechaCalculosInicial.ToString("MM/dd/yyyy") + "#" +
            //        " ORDER BY CODIGO,FECHA";

            sSQL = "SELECT CODIGO,LECTURA,FECHA From " + sTablaLecturas +
                   " WHERE FECHA <= ? AND FECHA >= ? ORDER BY CODIGO,FECHA";

            OleDbCommand command = SigpiDao.LocalDBConnection.CreateCommand();

            command.CommandText = sSQL;
            OleDbParameter paramFechaCalculos        = command.CreateParameter();
            OleDbParameter paramFechaCalculosInicial = command.CreateParameter();

            command.Parameters.Add(paramFechaCalculos);
            command.Parameters.Add(paramFechaCalculosInicial);
            paramFechaCalculos.Value        = FechaCalculos;
            paramFechaCalculosInicial.Value = FechaCalculosInicial;
            OleDbDataReader dataReader = null;

            try
            {
                dataReader = command.ExecuteReader();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + " :: " + sSQL);
            }

            Lectura                lectura;
            List <Lectura>         lecturas = new List <Lectura>();
            int                    dCodigo;
            int                    i = 0;
            PrecipitacionProcesada precipitacionProcesada = new PrecipitacionProcesada();
            double                 dAcumuladoPrecipitacion;
            int                    iNumeroDiasSinLluvia, iNumeroLecturasConsecutivas, iAmenazaXDiaSinLluvia;

            dAcumuladoPrecipitacion = 0;
            iNumeroDiasSinLluvia    = 0;
            dCodigo = -1;

            OleDbCommand command2 = SigpiDao.LocalDBConnection.CreateCommand();

            sSQL = "INSERT INTO " + sTablaConsolidados + " VALUES (?,?,?,?,?,?,?)";
            command2.CommandText = sSQL;
            OleDbParameter paramCodigo      = command2.CreateParameter();
            OleDbParameter paramP5          = command2.CreateParameter();
            OleDbParameter paramDSLL5       = command2.CreateParameter();
            OleDbParameter paramDSLLC5      = command2.CreateParameter();
            OleDbParameter paramFecha       = command2.CreateParameter();
            OleDbParameter paramNoDias      = command2.CreateParameter();
            OleDbParameter paramAmenazaXDSL = command2.CreateParameter();

            command2.Parameters.Add(paramCodigo);
            command2.Parameters.Add(paramP5);
            command2.Parameters.Add(paramDSLL5);
            command2.Parameters.Add(paramDSLLC5);
            command2.Parameters.Add(paramFecha);
            command2.Parameters.Add(paramNoDias);
            command2.Parameters.Add(paramAmenazaXDSL);

            paramFecha.Value = FechaCalculos;


            while (dataReader.Read())
            {
                lectura = new Lectura();
                if (i == 0)
                {
                    dCodigo = dataReader.GetInt32(0);
                }
                else
                {
                    if (dCodigo != dataReader.GetInt32(0))
                    {
                        foreach (Lectura lect in lecturas)
                        {
                            if (lect.Valor <= 0.5)
                            {
                                iNumeroDiasSinLluvia++;
                            }
                            //if (lect.Valor < 2)
                            //{
                            //  iAmenazaXDiaSinLluvia = 5;
                            //}
                        }
                        iNumeroLecturasConsecutivas         = LecturasConsecutivas(lecturas);
                        iAmenazaXDiaSinLluvia               = AmenazasXLluvia(lecturas);
                        precipitacionProcesada.Codigo       = System.Convert.ToInt32(dCodigo);
                        precipitacionProcesada.P5           = dAcumuladoPrecipitacion;
                        precipitacionProcesada.DSLL5        = iNumeroDiasSinLluvia;
                        precipitacionProcesada.DSLLC5       = iNumeroLecturasConsecutivas;
                        precipitacionProcesada.FEC_UL_LECTU = lecturas[0].Fecha;

                        paramCodigo.Value      = precipitacionProcesada.Codigo;
                        paramP5.Value          = dAcumuladoPrecipitacion;
                        paramDSLL5.Value       = precipitacionProcesada.DSLL5;
                        paramDSLLC5.Value      = precipitacionProcesada.DSLLC5;
                        paramNoDias.Value      = numDias;
                        paramAmenazaXDSL.Value = iAmenazaXDiaSinLluvia;
                        try
                        {
                            command2.ExecuteNonQuery();
                        }
                        catch (Exception e)
                        {
                            throw new Exception(e.Message + " :: " + command2.CommandText);
                        }
                        dCodigo = dataReader.GetInt32(0);
                        dAcumuladoPrecipitacion     = 0;
                        iNumeroLecturasConsecutivas = 0;
                        iNumeroDiasSinLluvia        = 0;
                        lecturas = new List <Lectura>();
                        i        = 0;
                    }
                }
                lectura                  = new Lectura();
                lectura.Codigo           = System.Convert.ToInt32(dataReader.GetInt32(0));
                lectura.Valor            = dataReader.GetDouble(1);
                dAcumuladoPrecipitacion += lectura.Valor;
                lectura.Fecha            = dataReader.GetDateTime(2);
                lecturas.Add(lectura);
                i++;
            }
            return(true);
        }
Exemple #4
0
        private void GenerarModelo(string sTablaPrecipPromedio, string sConsultaTablaPrecipPromedio, string sPrefijo,
                                   string sTablaTempPromedio, string sConsultaTablaTempPromedio)
        {
            ProcesarLecturas procesarLecturas = new ProcesarLecturas();

            try
            {
                procesarLecturas.CalcularResultadosPrecipitacion(sigpiDao, "DEFI_PRECI", "LECTUS_PRECI", sigpi.FechaProcesamiento, 5);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error procesando las lecturas:\n" + ex.Message);
            }

            //pStepPro.Step();
            //pStepPro.Message = "Procesando Temperatura...";
            try
            {
                procesarLecturas.CalcularResultadosTemperatura(sigpiDao, "DEFI_TEMPE", "LECTUS_TEMPE", sigpi.FechaProcesamiento, "T5", 5);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error procesando las lecturas:\n" + ex.Message);
            }

            string sSQL = "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#";

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery(sSQL);
            }
            catch (Exception ex)
            {
                MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message);
            }

            IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass();
            IStepProgressor        pStepPro   = pProDiaFac.Create(null, 0);

            pStepPro.MinRange  = 1;
            pStepPro.MaxRange  = 5;
            pStepPro.StepValue = 1;
            IProgressDialog2 pProDia = (IProgressDialog2)pStepPro;

            pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe;

            pProDia.Title = "Generar Grids";
            pProDia.ShowDialog();
            pStepPro.Step();
            pStepPro.Message = "Generando Grids Meteorologicos...";

            IFeatureClass     pFeatureClass;
            IWorkspaceFactory pShpWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
            IWorkspace        pWorkspaceTemp       = pShpWorkspaceFactory.OpenFromFile(parametros.RutaSIGPI + parametros.Temporal, 0);

            // Crear FeatureClass a partir de los datos de la tabla de los promedios de la precipitacion
            try
            {
                //pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_PRECI", "estaciones", "CODIGO", "DEFI_PRECI.P5 >= 0", "JP");
                pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, sTablaPrecipPromedio, "estaciones", "CODIGO", sConsultaTablaPrecipPromedio, "JP");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error generando el FeatureClass de Estaciones. Descripcion: \n" + ex.Message);
                return;
            }

            IWorkspaceFactory pWF     = new AccessWorkspaceFactoryClass();
            IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0);
            IGeoDataset       pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara);


            DateTime date   = sigpi.FechaProcesamiento;
            string   sMonth = date.ToString("MM");

            //P5
            pStepPro.Step();
            pStepPro.Message = "Generando Grids Meteorologicos: Precipitacion Total";
            IRaster pRaster1 = procesamiento.ConstruirGrid(pFeatureClass, "P5", parametros, pFCMask, "RP5", "", true);

            //DSLL5
            pStepPro.Step();
            pStepPro.Message = "Generando Grids Meteorologicos: Promedio ultimos 5 dias sin lluvia";
            IRaster pRaster2 = procesamiento.ConstruirGrid(pFeatureClass, "DSLL5", parametros, pFCMask, "DSLL5", "", true);

            //Crear FeatureClass a partir de la tabla de promedios de temperatura
            //pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, "DEFI_TEMPE", "estaciones", "CODIGO", "DEFI_TEMPE.T5 >= 0", "JT");
            pFeatureClass = procesamiento.ConstruirFeatureClass(pWorkspaceTemp, sTablaTempPromedio, "estaciones", "CODIGO", sConsultaTablaTempPromedio, "JT");
            //T5
            pStepPro.Step();
            pStepPro.Message = "Generando Grids Meteorologicos: Temperatura promedio";
            IRaster pRaster3 = procesamiento.ConstruirGrid(pFeatureClass, "T5", parametros, pFCMask, "RT5", "", true);
            //TMMMM
            IRaster pRaster4 = SIGPIUtils.AbrirRasterDesdeArchivo(parametros.RutaSIGPI + "\\" + parametros.TMMMM, "tmmx" + sMonth);
            //Susceptibilidad
            //IRaster pRaster5 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Susceptibilidad);
            IRaster pRaster5 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Susceptibilidad);
            //Asentamientos
            //IRaster pRaster6 = SIGPIUtils.AbrirRaster(parametros.RutaSIGPI + "\\" + parametros.Grids, parametros.Asentamientos);
            IRaster pRaster6 = SIGPIUtils.AbrirRasterDesdeGDB(parametros.RutaGBD, parametros.Asentamientos);

            IRaster[] pRasters = { pRaster1, pRaster2, pRaster3, pRaster4, pRaster5, pRaster6 };
            try
            {
                procesamiento.AlgoritmoCompleto(pRasters, sigpi);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            pProDia.HideDialog();
            MessageBox.Show("Algoritmo completo ejecutado");
        }
Exemple #5
0
        /// <summary>
        /// Ejecuta el modelo de amenazas de incendios
        /// </summary>
        /// <param name="sTablaPrecipPromedio">Tabla Precipitacion Promedio</param>
        /// <param name="sConsultaTablaPrecipPromedio">SQL para la table precipitacion promedio</param>
        /// <param name="sPrefijo">Prefijo para los nombres de las capas</param>
        /// <param name="sTablaTempPromedio">Nombre de la tabla temporal de promedios</param>
        /// <param name="sConsultaTablaTempPromedio">SQL para la tabla temporal de promedios</param>
        /// <param name="bUsarSatelite">Indica si se han de utilizar las imagenes de satelita</param>
        /// <param name="bMostrarIntermedios">Indica si se mostraran los resultados intermedios en el mapa activo</param>
        private void GenerarModelo(string sTablaPrecipPromedio, string sConsultaTablaPrecipPromedio, string sPrefijo,
                                   string sTablaTempPromedio, string sConsultaTablaTempPromedio, bool bUsarSatelite,
                                   bool bMostrarIntermedios, String[] sRastersPrecipitacion)
        {
            String sPath   = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            String tempDir = "";

            sPath = sPath.Replace("file:\\", "");
            SIGPIParametros parametros = new SIGPIParametros();

            try
            {
                XmlSerializer          serializer = new XmlSerializer(typeof(SIGPIParametros));
                System.IO.StreamReader r          = new System.IO.StreamReader(sPath + "\\parameters\\parametros.xml");
                parametros = (SIGPIParametros)serializer.Deserialize(r);
                r.Close();
                serializer = null;
                r          = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SIGPI 2013");
                return;
            }

            SIGPIProcesamiento procesamiento = new SIGPIProcesamiento(parametros);
            SIGPICls           sigpi         = new SIGPICls();
            SIGPIDao           sigpiDao      = new SIGPIDao();

            sigpiDao.ConnectLocalDB(parametros.RutaBD);
            sigpiDao.UltimaFechaIncorporacion(sigpi);
            sigpi.Parametros = parametros;

            OleDbCommand   command = sigpiDao.LocalDBConnection.CreateCommand();
            OleDbParameter param   = command.CreateParameter();
            OleDbParameter param1  = command.CreateParameter();

            param.ParameterName = "fecProce";
            param.Value         = sigpi.FechaProcesamiento;

            command.CommandText = "UPDATE FECHAS_PROCESO SET FEC_PROCE = @fecProce";
            command.Parameters.Add(param);

            string sSQL = ""; // "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#";

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery(command);
            }
            catch (Exception ex)
            {
                MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message);
            }

            IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass();
            IStepProgressor        pStepPro   = pProDiaFac.Create(null, 0);

            pStepPro.MinRange  = 1;
            pStepPro.MaxRange  = 5;
            pStepPro.StepValue = 1;
            IProgressDialog2 pProDia = (IProgressDialog2)pStepPro;

            pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe;

            pProDia.Title = "Generar Modelo Amenazas";
            pProDia.ShowDialog();
            pStepPro.Step();
            pStepPro.Message = "Generando Grids Meteorologicos...";

            IFeatureClass     pFeatureClass;
            IWorkspaceFactory pShpWorkspaceFactory     = new ShapefileWorkspaceFactoryClass();
            IWorkspaceFactory pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass();

            string sFormatTmp = "gdb_" + sigpi.FechaProcesamiento.ToString("yyyyMMdd") + "_" +
                                DateTime.Now.ToString("HHmmss");

            tempDir = sigpi.Parametros.TempDir;

            if (tempDir == null || tempDir.Trim().Equals(""))
            {
                tempDir = System.IO.Path.GetTempPath();
            }
            string sRutaFileGDB = System.IO.Path.GetTempPath() + sFormatTmp + ".gdb";

            if (System.IO.Directory.Exists(sRutaFileGDB))
            {
                try
                {
                    System.IO.Directory.Delete(sRutaFileGDB);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("No se pudo borrar la File Geodatabase Temporal: " +
                                    sRutaFileGDB +
                                    " Intente Borrarla Manualmente. " + ex.Message);
                    return;
                }
            }

            Geoprocessor   gp = new Geoprocessor();
            IWorkspaceName pWSName;
            string         sCapaResultado = "Amenaza_" + sigpi.FechaProcesamiento.ToString("yyyy_MM_dd");

            string sRutaGdbResultados = parametros.RutaSIGPI + parametros.Resultado + "\\" +
                                        sigpi.FechaProcesamiento.Year.ToString() + "-" +
                                        sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb";

            if (System.IO.Directory.Exists(sRutaGdbResultados))
            {
                GPUtilitiesClass gpUtilClass = new GPUtilitiesClass();
                try
                {
                    Delete del = new Delete();
                    del.in_data = sRutaGdbResultados + "\\" + sCapaResultado;
                    gp.Execute(del, null);
                }
                catch (Exception)
                {
                }
            }
            else
            {
                try
                {
                    pWSName = pFileGDBWorkspaceFactory.Create(parametros.RutaSIGPI + parametros.Resultado + "\\",
                                                              sigpi.FechaProcesamiento.Year.ToString() + "-" +
                                                              sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb", null, 0);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("No se pudo crear la Geodatabase de resultados: \n" + sRutaGdbResultados);
                    pStepPro.Hide();
                }
            }

            pWSName = pFileGDBWorkspaceFactory.Create(System.IO.Path.GetTempPath(), sFormatTmp, null, 0);
            ESRI.ArcGIS.esriSystem.IName name = (ESRI.ArcGIS.esriSystem.IName)pWSName;

            IFeatureWorkspace pWorkspaceTemp;

            try
            {
                pWorkspaceTemp = (IFeatureWorkspace)name.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            IWorkspaceFactory pWF     = new AccessWorkspaceFactoryClass();
            IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0);
            IGeoDataset       pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara);
            ISpatialReference pSpaRef = pFCMask.SpatialReference;
            IEnvelope         pEnv    = pFCMask.Extent;

            string sNombreTabla = "TMPPR_";

            DateTime fechaProcesamiento = sigpi.FechaProcesamiento;

            fechaProcesamiento = fechaProcesamiento.Date;


            for (int i = 0; i < 10; i++)
            {
                try
                {
                    sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE " + sNombreTabla + i.ToString());
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                }
                // "IIf([LECTUS_PRECI]![LECTURA]<=2,5,IIf([LECTUS_PRECI]![LECTURA]<=8 And [LECTUS_PRECI]![LECTURA]>2,4,IIf([LECTUS_PRECI]![LECTURA]<=14 And [LECTUS_PRECI]![LECTURA]>8,3,IIf([LECTUS_PRECI]![LECTURA]<=24 And [LECTUS_PRECI]![LECTURA]>14,2,IIf([LECTUS_PRECI]![LECTURA]>24,1,0))))) AS LECTURAS " +
                //sSQL = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " +
                //              "INTO " + sNombreTabla + i.ToString() + " " +
                //              "FROM LECTUS_PRECI " +
                //              "WHERE (((FECHA)=#" + sigpi.FechaProcesamiento.AddDays(-i).ToString("MM/dd/yyyy") + "#))";
                command             = sigpiDao.LocalDBConnection.CreateCommand();
                command.CommandText = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " +
                                      "INTO " + sNombreTabla + i.ToString() + " " +
                                      "FROM LECTUS_PRECI " +
                                      "WHERE (((FECHA) >=@fecha) and ((FECHA) <@fecha1))";
                param = command.CreateParameter();
                param.ParameterName = "fecha";
                param.Value         = sigpi.FechaProcesamiento.AddDays(-i);
                command.Parameters.Add(param);
                param1 = command.CreateParameter();
                param1.ParameterName = "fecha1";
                param1.Value         = sigpi.FechaProcesamiento.AddDays(-i + 1);
                command.Parameters.Add(param1);

                try
                {
                    sigpiDao.EjecutarSentenciaSinQuery(command);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error generando las tablas temporales de precipitaciones. Descripcion: \n" + ex.Message);
                    //pProDia.HideDialog();
                    return;
                }
            }

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE TEMPERATURA_PROMEDIO");
            }
            catch (Exception ex)
            {
            }

            //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=6,1,IIf(Avg(LECTUS_TEMPE.LECTURA) <=12 And Avg(LECTUS_TEMPE.LECTURA)>6,2," +
            //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=18 And Avg(LECTUS_TEMPE.LECTURA)>12,3,IIf(Avg(LECTUS_TEMPE.LECTURA)<=24 And " +
            //"Avg(LECTUS_TEMPE.LECTURA)>12,4,IIf(Avg(LECTUS_TEMPE.LECTURA)>24,5,0))))) AS LECTURAS, " +

            //sSQL = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " +
            //        "INTO TEMPERATURA_PROMEDIO " +
            //        "FROM LECTUS_TEMPE " +
            //        "WHERE (((FECHA)>=#" + sigpi.FechaProcesamiento.AddDays(-10).ToString("MM/dd/yyyy") + "# " +
            //        "And (FECHA)<=#" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#)) " +
            //        "GROUP BY CODIGO, X, Y";
            command             = sigpiDao.LocalDBConnection.CreateCommand();
            command.CommandText = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " +
                                  "INTO TEMPERATURA_PROMEDIO " +
                                  "FROM LECTUS_TEMPE " +
                                  "WHERE (((FECHA)>= @fecha1 " +
                                  "And (FECHA)<= @fecha)) " +
                                  "GROUP BY CODIGO, X, Y";
            param = command.CreateParameter();
            param.ParameterName = "fecha";
            param.Value         = sigpi.FechaProcesamiento;
            param1 = command.CreateParameter();
            param1.ParameterName = "fecha1";
            param1.Value         = sigpi.FechaProcesamiento.AddDays(-10);
            command.Parameters.Add(param1);
            command.Parameters.Add(param);

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery(command);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Generando Tabla: TEMPERATURA_PROMEDIO " + ex.Message);
                pProDia.HideDialog();
                return;
            }

            string sExpression = "";
            string sOutGrid;
            double dPeso = 0;
            string sAmenazaXPrecipitacion    = sRutaFileGDB + "\\amenaza_x_precipitacion";
            string sTablaTemperaturaPromedio = "TEMPERATURA_PROMEDIO";
            string sFCTempPromedio           = "TEMP_PROMEDIO";
            string sPrefijoIDW                     = "idw";
            string sAmenazaXTemperatura            = sRutaFileGDB + "\\" + "amenaza_x_temperatura";
            string sAmenazasParciales              = parametros.RutaGBD + "\\" + "amenazas_parciales_2";
            string sAmenazaBruta                   = sRutaFileGDB + "\\amenaza_incendio_bruta";
            string sAmenazaFinal                   = sRutaFileGDB + "\\amenaza_incendio_final";
            string sTablaReclassIncendios          = parametros.TablaReclasificacionIncendios;     //"tbl_reclass_amenaza_incendios";
            string sTablaReclassTemp               = parametros.TablaReclasificacionTemperatura;   //"tbl_reclass_temperatura";
            string sTablaReclassPrecip             = parametros.TablaReclasificacionPrecipitacion; //"tbl_reclass_precipitacion";
            string sAmenazaXTemperaturaCombinada   = sRutaFileGDB + "\\" + "amenaza_x_temperatura_combinada";
            string sEstVirtualesPrecipitacion      = sRutaFileGDB + "\\" + "estaciones_virtuales_precipitacion";
            string sAmenazaXPrecipitacionCombinada = sRutaFileGDB + "\\" + "amenaza_x_precipitacion_combinada";
            string sAmenazaFinalBrutaNVI           = sRutaFileGDB + "\\" + "amenaza_incend_raw_nvi";
            string sNVITempReclass                 = sRutaFileGDB + "\\" + "nvi_reclass_temp";
            string sFromField             = "FROM_";
            string sToField               = "TO_";
            string sOutField              = "OUT";
            string sNoData                = "NODATA";
            string sFieldLecturas         = "RASTERVALU";               //LECTURAS";
            string sTipoEstadistico       = parametros.TipoEstadistico; //"MAXIMUM";
            string sAmenazaXPrecipReclass = sAmenazaXPrecipitacion + "_reclass";
            string sAmenazaXTempReclass   = sAmenazaXTemperatura + "_reclass";
            string nvi = parametros.RutaSIGPI + "NVI" + "\\" + "tmpMosaic.500m_16_days_NDVI_GEO.tif";

            double dPesoPrecipitacion     = parametros.PesoPrecipitacion;     //0.29;
            double dPesoTemperatura       = parametros.PesoTemperatura;       //0.24;
            double dPesoAmenazasParciales = parametros.PesoAmenazasParciales; //0.47;

            IDataset         pDS;
            IDatasetName     pDSName;
            IDatasetName     pDSName2  = new FeatureClassNameClass();
            IExportOperation pExportOp = new ExportOperationClass();

            string sEstacionesVirtuales           = sRutaFileGDB + "\\" + "EstacionesVirtuales.shp";
            ExtractValuesToPoints extractValPoint = new ExtractValuesToPoints();

            extractValPoint.in_point_features  = sEstacionesVirtuales;
            extractValPoint.interpolate_values = "NONE";
            extractValPoint.add_attributes     = "VALUE_ONLY";


            //'0.037037037;
            // 1" = 1/3600
            double dCellSize = parametros.TamanoCelda / (3600 * 30);

            double[] iPesos      = parametros.Pesos; //{ 30, 20, 10, 9, 8, 7, 6, 5, 4, 3 };
            double   iTotalPesos = 0;                //102;

            foreach (double dP in iPesos)
            {
                iTotalPesos += dP;
            }

            gp.AddOutputsToMap = bMostrarIntermedios;
            gp.SetEnvironmentValue("Mask", parametros.RutaGBD + "\\" + parametros.Mascara);
            gp.SetEnvironmentValue("Extent", pEnv.XMin.ToString() + " " + pEnv.YMin.ToString() + " " +
                                   pEnv.XMax.ToString() + " " + pEnv.YMax.ToString());

            ESRI.ArcGIS.SpatialAnalystTools.Idw idw = new Idw();
            idw.z_field   = sFieldLecturas;
            idw.cell_size = dCellSize;

            for (int i = 0; i < 10; i++)
            {
                pFeatureClass          = procesamiento.FCPrecipitacion(sNombreTabla + i.ToString(), pSpaRef);
                pDS                    = (IDataset)pFeatureClass;
                pDSName                = (IDatasetName)pDS.FullName;
                pDSName2.Name          = sNombreTabla + i.ToString();
                pDSName2.WorkspaceName = pWSName;
                try
                {
                    pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    pProDia.HideDialog();
                    return;
                }

                if (bUsarSatelite)
                {
                    //Geoprocessor gp1 = new Geoprocessor();
                    //extractValPoint.in_raster = sRastersPrecipitacion[i];  // txtRutaPrecipitacion.Text;
                    //extractValPoint.out_point_features = sEstVirtualesPrecipitacion + i.ToString();

                    //try
                    //{
                    //  gp1.Execute(extractValPoint, null);
                    //}
                    //catch (Exception ex)
                    //{
                    //  MessageBox.Show(ex.Message);
                    //}

                    //Merge merge = new Merge();
                    //string sInputMerge = sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString();
                    //merge.inputs = sInputMerge;
                    ////"[" + sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString() + "]" ;
                    //merge.output = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString();
                    //try
                    //{
                    //  gp.Execute(merge, null);
                    //}
                    //catch (Exception ex)
                    //{
                    //  MessageBox.Show(ex.Message);
                    //}

                    //idw.in_point_features = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString();

                    idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString();
                }
                else
                {
                    idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString();
                }

                sOutGrid       = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString();
                idw.out_raster = sOutGrid;
                try
                {
                    gp.Execute(idw, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                dPeso        = iPesos[i] / iTotalPesos;
                sExpression += "( Raster(r'" + sOutGrid + "') * " + dPeso.ToString().Replace(",", ".") + ")";
                if (i < 9)
                {
                    sExpression += " + ";
                }
            }


            pStepPro.Step();

            ////for (int i = 0; i < 10; i++)
            ////{
            ////  //pStepPro.Message = "Generando Modelo Precipitacion: " + i.ToString();
            ////  sOutGrid = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString();
            ////  idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString();
            ////  idw.out_raster = sOutGrid;
            ////  gp.Execute(idw, null);
            ////  dPeso = iPesos[i] / iTotalPesos;
            ////  sExpression += "(" + sOutGrid + " * " + dPeso.ToString() + ")";
            ////  if (i < 9)
            ////    sExpression += " + ";
            ////}
            //gp.AddMessage("Expresion: " + sExpression);
            //SingleOutputMapAlgebra mapAlgebra = new SingleOutputMapAlgebra();

            ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator mapAlgebra = new RasterCalculator();
            //mapAlgebra.expression_string = sExpression;
            // mapAlgebra.out_raster = sAmenazaXPrecipitacion;

            mapAlgebra.expression = sExpression;

            mapAlgebra.output_raster = sAmenazaXPrecipitacion;
            pStepPro.Message         = "Generando Amenaza Precipitacion...";
            try
            {
                gp.Execute(mapAlgebra, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Generando Amenaza x Precipitacion. " + ex.Message);
                pProDia.HideDialog();
                return;
            }

            //if (bUsarSatelite)  // Para la combinacion de la precipitacion x estaciones y satelite
            //{

            //  //CellStatistics cellStatisticsP = new CellStatistics();
            //  //cellStatisticsP.in_rasters_or_constants = sAmenazaXPrecipitacion + ";" + txtRutaPrecipitacion.Text;
            //  //cellStatisticsP.out_raster = sAmenazaXPrecipitacionCombinada;
            //  //cellStatisticsP.statistics_type = sTipoEstadistico;
            //  try
            //  {
            //    gp.Execute(extractValPoint, null);
            //    //sAmenazaXPrecipitacion = sAmenazaXPrecipitacionCombinada;
            //  }
            //  catch (Exception ex)
            //  {
            //    MessageBox.Show("Error generando estaciones virtuales con precipitacion." + ex.Message);
            //    return;
            //  }

            //  Merge merge = new Merge();
            //  merge.inputs =

            //}

            DateTime date   = sigpi.FechaProcesamiento;
            string   sMonth = date.ToString("MM");

            pStepPro.Step();
            pStepPro.Message = "Generando Amenaza x Temperatura";
            pFeatureClass    = procesamiento.FCPrecipitacion(sTablaTemperaturaPromedio, pSpaRef);
            pDS                    = (IDataset)pFeatureClass;
            pDSName                = (IDatasetName)pDS.FullName;
            pDSName2.Name          = sFCTempPromedio;
            pDSName2.WorkspaceName = pWSName;
            try
            {
                pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            idw.in_point_features = sRutaFileGDB + "\\" + sFCTempPromedio;
            idw.out_raster        = sAmenazaXTemperatura;
            try
            {
                gp.Execute(idw, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            //if (bUsarSatelite)
            //{
            //  Geoprocessor gp1 = new Geoprocessor();
            //  Con pContmp = new Con();
            //  pContmp.in_conditional_raster = txtRutaTemperatura.Text;
            //  pContmp.in_true_raster_or_constant = txtRutaTemperatura.Text;
            //  pContmp.in_false_raster_or_constant = -99;
            //  string sRasterTTemp = sAmenazaXTemperaturaCombinada + "_ajs";
            //  pContmp.out_raster = sRasterTTemp;
            //  pContmp.where_clause = "VALUE < 55";

            //  try
            //  {
            //    gp1.Execute(pContmp, null);
            //  }
            //  catch (Exception)
            //  {
            //    sRasterTTemp = txtRutaTemperatura.Text; ;
            //  }
            //  gp1 = null;

            //  CellStatistics cellStatistics = new CellStatistics();
            //  cellStatistics.in_rasters_or_constants = sAmenazaXTemperatura + ";" + sRasterTTemp;
            //  cellStatistics.out_raster = sAmenazaXTemperaturaCombinada;
            //  cellStatistics.statistics_type = sTipoEstadistico;
            //  try
            //  {
            //    gp.Execute(cellStatistics, null);
            //    sAmenazaXTemperatura = sAmenazaXTemperaturaCombinada;
            //  }
            //  catch (Exception)
            //  {
            //  }
            //}

            ReclassByTable rbt = new ReclassByTable();

            rbt.in_raster          = sAmenazaXPrecipitacion;
            rbt.in_remap_table     = sTablaReclassPrecip; // parametros.RutaGBD + "\\" + sTablaReclassPrecip;
            rbt.from_value_field   = sFromField;
            rbt.to_value_field     = sToField;
            rbt.output_value_field = sOutField;
            rbt.missing_values     = sNoData;
            rbt.out_raster         = sAmenazaXPrecipReclass;
            //pStepPro.Message = "Generando Amenaza X Precipitacion Reclasificada";
            try
            {
                gp.Execute(rbt, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                pProDia.HideDialog();
                return;
            }

            rbt.in_raster      = sAmenazaXTemperatura;
            rbt.in_remap_table = sTablaReclassTemp; // parametros.RutaGBD + "\\" + sTablaReclassTemp;
            rbt.out_raster     = sAmenazaXTempReclass;
            //pStepPro.Message = "Generando Amenaza X Temperatura Reclasificada";
            try
            {
                gp.Execute(rbt, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                pProDia.HideDialog();
                return;
            }

            sExpression = "( Raster(r'" + sAmenazaXPrecipReclass + "') * " + dPesoPrecipitacion.ToString().Replace(",", ".") + ") + " +
                          "( Raster(r'" + sAmenazaXTempReclass + "') * " + dPesoTemperatura.ToString().Replace(",", ".") + ") + " +
                          "( Raster(r'" + sAmenazasParciales + "') * " + dPesoAmenazasParciales.ToString().Replace(",", ".") + ")";

            //mapAlgebra.expression_string = sExpression;
            //mapAlgebra.out_raster = sAmenazaBruta;

            sExpression              = sExpression.Replace("\\\\", "/").Replace("\\", "/");
            mapAlgebra.expression    = sExpression;
            mapAlgebra.output_raster = sAmenazaBruta;

            pStepPro.Message = "Generando Amenaza Final Bruta";
            try
            {
                gp.Execute(mapAlgebra, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //if (txtRutaNVI.Text.Trim() != "")
            //{
            Geoprocessor gp2 = new Geoprocessor();

            mapAlgebra               = new RasterCalculator();
            sExpression              = "Con (Raster(r'" + nvi + "') < 0.75, Raster(r'" + sAmenazaBruta + "'), Raster(r'" + sAmenazaBruta + "') -1)";
            sExpression              = sExpression.Replace("\\\\", "/").Replace("\\", "/");
            mapAlgebra.expression    = sExpression;
            mapAlgebra.output_raster = sAmenazaFinalBrutaNVI;

            try
            {
                gp2.Execute(mapAlgebra, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //}


            rbt.in_raster          = sAmenazaFinalBrutaNVI;  // sAmenazaBruta;
            rbt.in_remap_table     = sTablaReclassIncendios; // parametros.RutaGBD + "\\" + sTablaReclassIncendios;
            rbt.from_value_field   = sFromField;
            rbt.to_value_field     = sToField;
            rbt.output_value_field = sOutField;
            rbt.missing_values     = sNoData;
            rbt.out_raster         = sAmenazaFinal;
            pStepPro.Message       = "Generando Amenaza Final Reclasificada";
            gp.AddOutputsToMap     = true;
            try
            {
                gp.Execute(rbt, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            Copy copy = new Copy();

            copy.in_data = sAmenazaFinal;

            copy.out_data = sRutaGdbResultados + "\\" + sCapaResultado;
            try
            {
                gp.Execute(copy, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Copiando el resultado. \n " + ex.Message);
            }



            MessageBox.Show("Algoritmo completo ejecutado: " + sRutaGdbResultados + "\\" + sCapaResultado);

            if (m_pApp != null)
            {
                IRasterLayer pRLayer = new RasterLayerClass();
                try
                {
                    IWorkspaceFactory  pWF2      = new FileGDBWorkspaceFactoryClass();
                    IRasterWorkspaceEx pRW       = (IRasterWorkspaceEx)pWF2.OpenFromFile(sRutaGdbResultados, 0);
                    IRasterDataset     pRDataset = pRW.OpenRasterDataset(sCapaResultado);
                    pRLayer.CreateFromDataset(pRDataset);
                    pRLayer.Name = sCapaResultado;
                    IMxDocument pMxDoc = m_pApp.Document as IMxDocument;
                    IMap        pMap   = pMxDoc.FocusMap;
                    AsignarSimbologiaProbabilidad(pRLayer);
                    pMap.AddLayer(pRLayer);
                    if (pMap.LayerCount > 0)
                    {
                        pMap.MoveLayer(pRLayer, pMap.LayerCount - 1);
                    }

                    pMxDoc.UpdateContents();
                    pMxDoc.ActiveView.Refresh();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error cargando Capa!!!");
                }
            }

            pProDia.HideDialog();
        }