NMF_method1_test_version<-function(tg_list, data_ng, data_normalized, max_ES_cut=0.3,tProp,NMF_RR=10)
{
	tg_selected_R4_RR<-tg_list
	data.matrix0_s<-data_ng
	data_23_s<-data_normalized
	Rbase_selected_R4_RR<-Compute_Rbase_SVD(data.matrix0_s,tg_selected_R4_RR)
	stat_selected_R4_RR<-compute_IM_stat(tg_list_c=tg_selected_R4_RR)
	stat_selected_R4_RR_max<-apply(stat_selected_R4_RR,1,max)
	tg_I_id<-which(stat_selected_R4_RR_max==max(stat_selected_R4_RR_max))[1]
	tg_selected_id<-tg_I_id
	X_I<-data.matrix0_s[tg_selected_R4_RR[[tg_I_id]],]
	N<-0
	NMF_list_c<-list()
	N<-N+1
	NMF_list_c[[N]]<-tg_selected_R4_RR[[tg_I_id]]
	names(NMF_list_c)<- names(tg_I_id)
	NMF_self_c1<-Building_NMF_input_no_cancer(tg_data=X_I,tg_list=NMF_list_c,tg_list_add=list())
	V_I<-t(as.matrix(Rbase_selected_R4_RR[tg_I_id,]))
	V_I_n<-normalize_data2(V_I)
	V_c<-V_I_n
	ccc<-compute_CompRowspace_NN(data_23_s,module_RB=V_c,ROUNDS=min(nrow(V_I),3))
	ES_I<-RMSE_row(ccc)/RMSE_row(data_23_s)
	ES_base_c<-Compute_base_ES_score(ES_I,tg_selected_R4_RR)
	ES_max<-max(ES_base_c)
	tg_id_del<-c()
	track_N_cor<-list()
	track_N_cor[[1]]<-apply(cor(t(tProp),t(V_c)),1,max)
	tg_id<-setdiff(1:length(tg_selected_R4_RR),tg_I_id)
	while((ES_max>max_ES_cut)&(length(tg_id)>0))
	{
		N<-N+1
		tg_id<-which(abs(ES_base_c-max(ES_base_c))<0.01)
		tg_id<-setdiff(tg_id,tg_selected_id)
		if(length(tg_id)==0)
		{
			break
		}
		tg_id_add<-tg_id[which(stat_selected_R4_RR_max[tg_id]==max(stat_selected_R4_RR_max[tg_id]))[1]]
		tg_selected_id<-c(tg_selected_id,tg_id_add)
		NMF_list_c<-select_R_base(tg_selected_R4_RR,tg_selected_id)
		names(NMF_list_c)<-names(tg_selected_R4_RR)[tg_selected_id]	#?????
		NMF_self_c1<-Building_NMF_input_no_cancer(tg_data=data.matrix0_s,tg_list=NMF_list_c,tg_list_add=list())
		qnmf_result_c_temp <- run_NMF(NMF_self_c1,RR0=NMF_RR,maxIter=20000, tProp)
		U_temp = qnmf_result_c_temp[["U"]]
		V_temp = qnmf_result_c_temp[["V"]]
		########check correlation between: V and true Proportion
		V_c<-normalize_data2(t(V_temp))
		ccc<-compute_CompRowspace_NN(data_23_s,module_RB=V_c,ROUNDS=min(nrow(V_I),3))
		ES_I<-RMSE_row(ccc)/RMSE_row(data_23_s)
		ES_base_c_temp<-Compute_base_ES_score(ES_I,tg_selected_R4_RR)
		if(ES_base_c_temp[tg_id_add]>max_ES_cut)
		{
			tg_selected_id<-setdiff(tg_selected_id,tg_id_add)
			tg_id_del<-c(tg_id_del,tg_id_add)
			if(length(tg_id_del)>0)
			{
				ES_base_c[tg_id_del]<-0
			}
			N<-N-1
		}
		else
		{
			qnmf_result_c<-qnmf_result_c_temp
			track_N_cor[[N]]<-qnmf_result_c[[4]]
			V<- qnmf_result_c[["V"]]
			ES_base_c<-ES_base_c_temp
			if(length(tg_id_del)>0)
			{
				ES_base_c[tg_id_del]<-0
			}
			ES_max<-max(ES_base_c)
			ictd.ccc= t(cor(t(tProp),V) )
			o6_predict_ture = apply(ictd.ccc, 1, max)
			o6_predict_ture2 = apply(ictd.ccc, 2, max)
			print(N)
			print(o6_predict_ture2)
			print(apply(cor(t(tProp),t(Rbase_selected_R4_RR[tg_selected_id,])),1,max))
		}
	}
	return(list(qnmf_result_c,track_N_cor))
}


code 'Cur'
name '币种折算演示'
dimensions {
	accbook {
		appendBetweenParam 'yes'
	}
	currency loadErate: true
}
layout {
	rows 'accbook'
	columns 'currency'
}
dataRequest {
	table 'mcf',allDimensions: ['accbook','currency','cfDate']
	fields 'accbook,currency,sum(endingBalance) value'
	groupFields 'accbook,currency'
	params {
		date 'CONTEXT[]'
		cfDate 'CONTEXT[]'
		staticModel 'CONTEXT[]'
	}
}
heads {
	accbook {
		params {
			id (['between',[10021,10030]])
		}
	}
}
derivedHeads {
	currency {
		head {
			name '美元折人民币'
			formula {
				v([currency:'14'])*100/(rc.erateMap['14'])
			}
		}
		head {
			name '外币折人民币'
			aggregator {curvs->
				currencyExchange(curvs,'01')
			}
		}
		head {
			name '外币折美元'
			aggregator {curvs->
				currencyExchange(curvs,'14')
			}
		}
		head {
			name '本外币合计'
			aggregator {curvs->
				currencyExchange(curvs,'01',true)
			}
		}
	}
}


##Raster=raster
##Poligono=vector polygon
##Output=output vector
##Carpeta=folder
##Nombre=string Lote prueba 1
##Unidad_de_medicion=string kg/ha
##Comentarios=string Poner alguna informacion importante...
#Version_simplificada=string no
##Escala=selection quantiles(7);quantiles(4);15cm(15-120);500-4000(kg);1000-8000(kg);0.5-4(Tn);1-8(Tn);

##output_plots_to_html
##showplots

nombre<-Nombre
detalleslote <-Comentarios
unidad_de_cosecha<-Unidad_de_medicion
#version_simplificada<-Escala

if(Escala == 0){version_simplificada = "no"}
if(Escala == 1){version_simplificada = "si"}
if(Escala == 2){version_simplificada = "ni"}
if(Escala == 3){version_simplificada = "na"}
if(Escala == 4){version_simplificada = "nu"}
if(Escala == 5){version_simplificada = "n1"}
if(Escala == 6){version_simplificada = "n2"}

poligono <- as_Spatial(Poligono)

if("sp" %in% rownames(installed.packages()) == FALSE) {install.packages("sp")} else {print("sp ya esta..")}
if("gstat" %in% rownames(installed.packages()) == FALSE) {install.packages("gstat")} else {print("gstat ya esta..")}
if("maptools" %in% rownames(installed.packages()) == FALSE) {install.packages("maptools")} else {print("maptools ya esta..")}
if("rgeos" %in% rownames(installed.packages()) == FALSE) {install.packages("rgeos")} else {print("rgeos ya esta..")}
if("raster" %in% rownames(installed.packages()) == FALSE) {install.packages("raster")} else {print("raster ya esta..")}
if("automap" %in% rownames(installed.packages()) == FALSE) {install.packages("automap")} else {print("automap ya esta..")}
if("spdep" %in% rownames(installed.packages()) == FALSE) {install.packages("spdep")} else {print("spdep ya esta..")}
if("grid" %in% rownames(installed.packages()) == FALSE) {install.packages("grid")} else {print("grid ya esta..")}
if("ggplotify" %in% rownames(installed.packages()) == FALSE) {install.packages("ggplotify")} else {print("ggplotify ya esta..")}
if("gridExtra" %in% rownames(installed.packages()) == FALSE) {install.packages("gridExtra")} else {print("gridExtra ya esta..")}
if("ggplot2" %in% rownames(installed.packages()) == FALSE) {install.packages("ggplot2")} else {print("ggplot2 ya esta..")}
if("ggspatial" %in% rownames(installed.packages()) == FALSE) {install.packages("ggspatial")} else {print("ggspatial ya esta..")}

library(sp)
library(spdep)
library(gstat)
library(raster)
library(rgdal)
library(rgeos)
library(grid)
library(ggplotify)
library(gridExtra)
library(ggplot2)
library(ggspatial)

print(Carpeta)
setwd(Carpeta)
Kg_wls<-as(Raster, "SpatialPixelsDataFrame")
valores<-na.omit(Kg_wls@data[,1])

print(str(Kg_wls))
print(paste("Los archivos seran guardados en:", getwd()))
print(paste("Metodo de salida grafica:",Escala))
print(paste("Metodo de salida grafica:",version_simplificada))

if (version_simplificada == "no"){
                cols <- c("#AA0014","#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850")
                cortes<-quantile(valores, probs = c(0.10,0.20,0.40,0.50,0.60,0.80,1))
                #reclasifico los valores continuos de raster por la calsificación de tomas.
                values_tg<-unname(cortes)

                lamatrix<-matrix(nrow=8,ncol=3)
                lamatrix[1,1]<--Inf
                lamatrix[1,2]<-values_tg[1]
                lamatrix[1,3]<-values_tg[1]
                lamatrix[8,1]<-values_tg[7]
                lamatrix[8,2]<-Inf
                lamatrix[8,3]<-values_tg[7]

                for (i in 2:7){
                a<-i-1
                lamatrix[i,1]<-values_tg[a]
                b<-i
                lamatrix[i,2]<-values_tg[b]
                a<-i
                lamatrix[i,3]<-values_tg[a]
            }
        }

 if (version_simplificada == "si"){
             cols <- c("#d73027","#fee08b","#d9ef8b","#1a9850")
             cortes<-quantile(valores, probs =c(0.2,0.5,0.8,1))
             #son 5
              #reclasifico los valores continuos de raster por la calsificación de tomas.
              values_tg<-unname(cortes)

              lamatrix<-matrix(nrow=4,ncol=3)
              lamatrix[1,1]<--Inf
              lamatrix[1,2]<-values_tg[1]
              lamatrix[1,3]<-values_tg[1]
              lamatrix[4,1]<-values_tg[3]
              lamatrix[4,2]<-Inf
              lamatrix[4,3]<-values_tg[4]

              for (i in 2:4){
              a<-i-1
              lamatrix[i,1]<-values_tg[a]
              b<-i
              lamatrix[i,2]<-values_tg[b]
              a<-i
              lamatrix[i,3]<-values_tg[a]
              }

        }

if (version_simplificada == "ni"){
            cols <- c("#AA0014","#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850","#0b5229")
     		values_tg<-c(15,30,45,60,75,90,105,120)
            cortes<-values_tg
            lamatrix<-matrix(nrow=9,ncol=3)

			lamatrix[1,1]<--Inf
			lamatrix[1,2]<-values_tg[1]
			lamatrix[1,3]<-values_tg[1]
			lamatrix[9,1]<-values_tg[8]
			lamatrix[9,2]<-Inf
			lamatrix[9,3]<-values_tg[8]

			for (i in 2:8){
			a<-i-1
			lamatrix[i,1]<-values_tg[a]
			b<-i
			lamatrix[i,2]<-values_tg[b]
			a<-i
			lamatrix[i,3]<-values_tg[a]
			}

        }

    if (version_simplificada == "na"){
                    cols <- c("#AA0014","#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850","#0b5229")
             		values_tg<-c(500,1000,1500,2000,2500,3000,3500,4000)
                    cortes<-values_tg
                    lamatrix<-matrix(nrow=9,ncol=3)

        			lamatrix[1,1]<--Inf
        			lamatrix[1,2]<-values_tg[1]
        			lamatrix[1,3]<-values_tg[1]
        			lamatrix[9,1]<-values_tg[8]
        			lamatrix[9,2]<-Inf
        			lamatrix[9,3]<-values_tg[8]

        			for (i in 2:8){
        			a<-i-1
        			lamatrix[i,1]<-values_tg[a]
        			b<-i
        			lamatrix[i,2]<-values_tg[b]
        			a<-i
        			lamatrix[i,3]<-values_tg[a]
        			}

          }
    if (version_simplificada == "nu"){
                          cols <- c("#AA0014","#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850","#0b5229")
                   		values_tg<-c(1000,2000,3000,4000,5000,6000,7000,8000)
                          cortes<-values_tg
                          lamatrix<-matrix(nrow=9,ncol=3)

              			lamatrix[1,1]<--Inf
              			lamatrix[1,2]<-values_tg[1]
              			lamatrix[1,3]<-values_tg[1]
              			lamatrix[9,1]<-values_tg[8]
              			lamatrix[9,2]<-Inf
              			lamatrix[9,3]<-values_tg[8]

              			for (i in 2:8){
              			a<-i-1
              			lamatrix[i,1]<-values_tg[a]
              			b<-i
              			lamatrix[i,2]<-values_tg[b]
              			a<-i
              			lamatrix[i,3]<-values_tg[a]
          			}

            }
    if (version_simplificada == "n1"){
                                  cols <- c("#AA0014","#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850","#0b5229")
                           		values_tg<-c(0.5,1,1.5,2,2.5,3,3.5,4)
                                  cortes<-values_tg
                                  lamatrix<-matrix(nrow=9,ncol=3)

                      			lamatrix[1,1]<--Inf
                      			lamatrix[1,2]<-values_tg[1]
                      			lamatrix[1,3]<-values_tg[1]
                      			lamatrix[9,1]<-values_tg[8]
                      			lamatrix[9,2]<-Inf
                      			lamatrix[9,3]<-values_tg[8]

                      			for (i in 2:8){
                      			a<-i-1
                      			lamatrix[i,1]<-values_tg[a]
                      			b<-i
                      			lamatrix[i,2]<-values_tg[b]
                      			a<-i
                      			lamatrix[i,3]<-values_tg[a]
              			}
          }
  if (version_simplificada == "n2"){
                                cols <- c("#AA0014","#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850","#0b5229")
                            values_tg<-c(1,2,3,4,5,6,7,8)
                                cortes<-values_tg
                                lamatrix<-matrix(nrow=9,ncol=3)

                          lamatrix[1,1]<--Inf
                          lamatrix[1,2]<-values_tg[1]
                          lamatrix[1,3]<-values_tg[1]
                          lamatrix[9,1]<-values_tg[8]
                          lamatrix[9,2]<-Inf
                          lamatrix[9,3]<-values_tg[8]

                          for (i in 2:8){
                          a<-i-1
                          lamatrix[i,1]<-values_tg[a]
                          b<-i
                          lamatrix[i,2]<-values_tg[b]
                          a<-i
                          lamatrix[i,3]<-values_tg[a]
                }

      }

	  #Recorto al area del lote....
	  r <- mask(Raster, poligono)

    rc <- reclassify(r, lamatrix,include.lowest=TRUE)
    print("ACA ESTA LA VECTORIZACION")
    vectorizado<-rasterToPolygons(rc,na.rm=TRUE,dissolve=TRUE)
	  #Este error me lo marco el Juani Orcellet.
	  colnames(vectorizado@data)<-c("output")

      #vectorizado@data$colores<-as.factor(unname(cortes))
      #Reordeno los valores para hacer coincidir la escala de colores con la del dataframe. Error marcado por Wilson y Zilio
      vectorizado<-vectorizado[order(vectorizado$output),]
      plot(vectorizado["output"],col=cols,border="NA")

    proj4string(vectorizado) <- CRS(proj4string(poligono))

	  gIsValid(vectorizado, reason = T)
    vectorizado <- gBuffer(vectorizado, width=0, byid = T)
    print("generando buffer para solucionar problemas de geometria")
    gIsValid(vectorizado, reason = T)

	  #Calculo del area del lote por rendimiento
	  #25/02/2021, corregido algun lio con las librerias y actualizaciones de proj4
    #vectorizado <- spTransform(vectorizado,CRS("+init=epsg:4326"))

	  vectorizado <- sf::st_as_sf(vectorizado)
	  vectorizado<-st_transform(vectorizado,4326)
	  vectorizado <- as_Spatial(vectorizado)

    #calculo de area para cada zona para pasar al informe.
	  raster::area(vectorizado,na.rm=TRUE)/10000
	  areas_lote<-raster::area(vectorizado)
	  datos_pdf<-data.frame(round(vectorizado@data$output,2),round(areas_lote/10000,2))
	  arealote<-sum(round(areas_lote/10000,2))
	  valores[valores == 0] <- NA
	  valores<-na.omit(valores)
	  media_lote<-round(mean(valores),2)
	  colnames(datos_pdf)<-c("Rendimiento","Area (ha)")
	  total<-data.frame(media_lote,arealote)
	  colnames(total)<-c("Rendimiento","Area (ha)")
	  datos_pdf <- rbind(datos_pdf, total)

         writeOGR(vectorizado, layer = paste(nombre," vectorizado",sep=""), dsn="vectorizado R", driver="ESRI Shapefile",overwrite_layer=TRUE)
         print("ACA ARMO EL PDF")

      factores<-c("")
	  for (i in 1:nrow(datos_pdf)){
		  rinde<-round(datos_pdf[i,1],2)
		  area<-round(datos_pdf[i,2],2)
		  valor<-paste(as.character(rinde)," ","(",as.character(area)," ha)",sep="")
		  factores<-c(factores,valor)
		  }

	 vectorizado1<-st_as_sf(vectorizado)
		if (version_simplificada == "no"){
		  rindemedio<-factores[9]
		  factores<-factores[2:8]
		  sizes <- factor(factores, levels = c(factores[1],factores[2],factores[3],factores[4],factores[5],factores[6],factores[7]))
		}
		if (version_simplificada == "si"){
		  rindemedio<-factores[6]
		  factores<-factores[2:5]
		  sizes <- factor(factores, levels = c(factores[1],factores[2],factores[3],factores[4],factores[5]))
		}
		if (version_simplificada == "ni"){
			rindemedio<-factores[length(factores)]
			factores<-factores[2:(length(factores)-1)]
			sizes <- factor(factores, levels = c(factores[1:(length(factores))]))
		}
		if (version_simplificada == "nu"){
			rindemedio<-factores[length(factores)]
			factores<-factores[2:(length(factores)-1)]
			sizes <- factor(factores, levels = c(factores[1:(length(factores))]))
		}
		if (version_simplificada == "n1"){
			rindemedio<-factores[length(factores)]
			factores<-factores[2:(length(factores)-1)]
			sizes <- factor(factores, levels = c(factores[1:(length(factores))]))
		}
		if (version_simplificada == "n2"){
			rindemedio<-factores[length(factores)]
			factores<-factores[2:(length(factores)-1)]
			sizes <- factor(factores, levels = c(factores[1:(length(factores))]))
		}
		if (version_simplificada == "na"){
			rindemedio<-factores[length(factores)]
			factores<-factores[2:(length(factores)-1)]
			sizes <- factor(factores, levels = c(factores[1:(length(factores))]))
		}

	 >print(sizes)

	 mapa<-ggplot(data = vectorizado1["output"]) +
  	 xlab("Longitud") + ylab("Latitud") +
 	 ggtitle(paste0(nombre), subtitle = paste0(detalleslote,"\n","Media(",unidad_de_cosecha,"): ",rindemedio))+
  	 geom_sf(color = "black", aes(fill = sizes))+
  	 scale_fill_manual(values = cols, name= unidad_de_cosecha)+
    	 theme(axis.text.x = element_text(size = 6),axis.text.y = element_text(size = 6),legend.position = "right", panel.grid.major = element_line(color = gray(.5), linetype = "dashed", size = 0.5), panel.background = element_rect(fill = "aliceblue"))

         title <- textGrob(paste("Realizado usando https://github.com/francofrolla/mapaderindes/ - INTA Bordenave"),gp=gpar(fontsize=7),just = "center")

	 arreglo<-grid.arrange(
    		mapa,
    		title,
    		nrow = 2,
    		ncol=1,
    		heights = c(1,0.1))

         ruta<-getwd()
         nombre1<-paste("Mapa-",nombre,".pdf",sep= "")
         ggsave(file=paste(ruta,"/",nombre1,sep=""), arreglo)

          print("ACA ARMO EL KML")
          hacerkml<-function(){
            #obj <- spTransform(vectorizado, CRS("+init=epsg:4326"))
            obj<-vectorizado
			inners<-c("")
            outers<-c("")
            union<-c("")
            superkml<-c("")
            stack<-c("")
	    print(str(obj))
            if (version_simplificada == "no"){
            cabezera<-c('<?xml version="1.0"?>
                        <kml xmlns:xsd="http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd" version="1.0">
                        <Document><Style id="1"><LineStyle><width>2.0</width><color>ff1400aa</color></LineStyle><PolyStyle><color>ff1400aa</color></PolyStyle></Style><Style id="2"><LineStyle><width>2.0</width><color>ff2730d7</color></LineStyle><PolyStyle><color>ff2730d7</color></PolyStyle></Style><Style id="3"><LineStyle><width>2.0</width><color>ff598dfc</color></LineStyle><PolyStyle><color>ff598dfc</color></PolyStyle></Style><Style id="4"><LineStyle><width>2.0</width><color>ff8be0fe</color></LineStyle><PolyStyle><color>ff8be0fe</color></PolyStyle></Style><Style id="5"><LineStyle><width>2.0</width><color>ff8befd9</color></LineStyle><PolyStyle><color>ff8befd9</color></PolyStyle></Style><Style id="6"><LineStyle><width>2.0</width><color>ff60cf91</color></LineStyle><PolyStyle><color>ff60cf91</color></PolyStyle></Style><Style id="7"><LineStyle><width>2.0</width><color>ff50981a</color></LineStyle><PolyStyle><color>ff50981a</color></PolyStyle></Style><Style id="8"><LineStyle><width>2.0</width><color>ff882754</color></LineStyle><PolyStyle><color>ff882754</color></PolyStyle></Style>
                        <ScreenOverlay><name>Legend: Logo</name><Icon> <href>http://lmingenieria.com.ar/images/logo.png</href> </Icon> <overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>
                         <screenXY x="25" y="40" xunits="pixels" yunits="pixels"/>
                        <rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
                        <size x="0" y="0" xunits="pixels" yunits="pixels"/>
                          </ScreenOverlay>')}
             if (version_simplificada == "si"){
            cabezera<-c('<?xml version="1.0"?>
                        <kml xmlns:xsd="http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd" version="1.0">
                        <Document><Style id="1"><LineStyle><width>0</width><color>ff2730d7</color></LineStyle><PolyStyle><color>ff2730d7</color></PolyStyle></Style><Style id="2"><LineStyle><width>0</width><color>ff8be0fe</color></LineStyle><PolyStyle><color>ff8be0fe</color></PolyStyle></Style><Style id="3"><LineStyle><width>0</width><color>ff8befd9</color></LineStyle><PolyStyle><color>ff8befd9</color></PolyStyle></Style><Style id="4"><LineStyle><width>0</width><color>ff50981a</color></LineStyle><PolyStyle><color>ff50981a</color></PolyStyle></Style><Style id="5"><LineStyle><width>2.0</width><color>ff8befd9</color></LineStyle><PolyStyle><color>ff8befd9</color></PolyStyle></Style><Style id="6"><LineStyle><width>2.0</width><color>ff60cf91</color></LineStyle><PolyStyle><color>ff60cf91</color></PolyStyle></Style><Style id="7"><LineStyle><width>2.0</width><color>ff50981a</color></LineStyle><PolyStyle><color>ff50981a</color></PolyStyle></Style><Style id="8"><LineStyle><width>2.0</width><color>ff882754</color></LineStyle><PolyStyle><color>ff882754</color></PolyStyle></Style>
                        <ScreenOverlay><name>Legend: Logo</name><Icon> <href>http://lmingenieria.com.ar/images/logo.png</href> </Icon> <overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>
                         <screenXY x="25" y="40" xunits="pixels" yunits="pixels"/>
                        <rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
                        <size x="0" y="0" xunits="pixels" yunits="pixels"/>
                          </ScreenOverlay>')}
		    if (version_simplificada == "ni"){
            cabezera<-c('<?xml version="1.0"?>
                        <kml xmlns:xsd="http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd" version="1.0">
                        <Document><Style id="1"><LineStyle><width>2.0</width><color>ff1400aa</color></LineStyle><PolyStyle><color>ff1400aa</color></PolyStyle></Style><Style id="2"><LineStyle><width>2.0</width><color>ff2730d7</color></LineStyle><PolyStyle><color>ff2730d7</color></PolyStyle></Style><Style id="3"><LineStyle><width>2.0</width><color>ff598dfc</color></LineStyle><PolyStyle><color>ff598dfc</color></PolyStyle></Style><Style id="4"><LineStyle><width>2.0</width><color>ff8be0fe</color></LineStyle><PolyStyle><color>ff8be0fe</color></PolyStyle></Style><Style id="5"><LineStyle><width>2.0</width><color>ff8befd9</color></LineStyle><PolyStyle><color>ff8befd9</color></PolyStyle></Style><Style id="6"><LineStyle><width>2.0</width><color>ff60cf91</color></LineStyle><PolyStyle><color>ff60cf91</color></PolyStyle></Style><Style id="7"><LineStyle><width>2.0</width><color>ff50981a</color></LineStyle><PolyStyle><color>ff50981a</color></PolyStyle></Style><Style id="8"><LineStyle><width>2.0</width><color>ff882754</color></LineStyle><PolyStyle><color>ff882754</color></PolyStyle></Style>
						<ScreenOverlay><name>Legend: Logo</name><Icon> <href>http://lmingenieria.com.ar/images/logo.png</href> </Icon> <overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>
                         <screenXY x="25" y="40" xunits="pixels" yunits="pixels"/>
                        <rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
                        <size x="0" y="0" xunits="pixels" yunits="pixels"/>
                          </ScreenOverlay>')}
			if (version_simplificada == "na"){
            cabezera<-c('<?xml version="1.0"?>
                        <kml xmlns:xsd="http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd" version="1.0">
                        <Document><Style id="1"><LineStyle><width>2.0</width><color>ff1400aa</color></LineStyle><PolyStyle><color>ff1400aa</color></PolyStyle></Style><Style id="2"><LineStyle><width>2.0</width><color>ff2730d7</color></LineStyle><PolyStyle><color>ff2730d7</color></PolyStyle></Style><Style id="3"><LineStyle><width>2.0</width><color>ff598dfc</color></LineStyle><PolyStyle><color>ff598dfc</color></PolyStyle></Style><Style id="4"><LineStyle><width>2.0</width><color>ff8be0fe</color></LineStyle><PolyStyle><color>ff8be0fe</color></PolyStyle></Style><Style id="5"><LineStyle><width>2.0</width><color>ff8befd9</color></LineStyle><PolyStyle><color>ff8befd9</color></PolyStyle></Style><Style id="6"><LineStyle><width>2.0</width><color>ff60cf91</color></LineStyle><PolyStyle><color>ff60cf91</color></PolyStyle></Style><Style id="7"><LineStyle><width>2.0</width><color>ff50981a</color></LineStyle><PolyStyle><color>ff50981a</color></PolyStyle></Style><Style id="8"><LineStyle><width>2.0</width><color>ff882754</color></LineStyle><PolyStyle><color>ff882754</color></PolyStyle></Style>
						<ScreenOverlay><name>Legend: Logo</name><Icon> <href>http://lmingenieria.com.ar/images/logo.png</href> </Icon> <overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>
                         <screenXY x="25" y="40" xunits="pixels" yunits="pixels"/>
                        <rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
                        <size x="0" y="0" xunits="pixels" yunits="pixels"/>
                          </ScreenOverlay>')}
            if (version_simplificada == "nu"){
            cabezera<-c('<?xml version="1.0"?>
                        <kml xmlns:xsd="http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd" version="1.0">
                        <Document><Style id="1"><LineStyle><width>2.0</width><color>ff1400aa</color></LineStyle><PolyStyle><color>ff1400aa</color></PolyStyle></Style><Style id="2"><LineStyle><width>2.0</width><color>ff2730d7</color></LineStyle><PolyStyle><color>ff2730d7</color></PolyStyle></Style><Style id="3"><LineStyle><width>2.0</width><color>ff598dfc</color></LineStyle><PolyStyle><color>ff598dfc</color></PolyStyle></Style><Style id="4"><LineStyle><width>2.0</width><color>ff8be0fe</color></LineStyle><PolyStyle><color>ff8be0fe</color></PolyStyle></Style><Style id="5"><LineStyle><width>2.0</width><color>ff8befd9</color></LineStyle><PolyStyle><color>ff8befd9</color></PolyStyle></Style><Style id="6"><LineStyle><width>2.0</width><color>ff60cf91</color></LineStyle><PolyStyle><color>ff60cf91</color></PolyStyle></Style><Style id="7"><LineStyle><width>2.0</width><color>ff50981a</color></LineStyle><PolyStyle><color>ff50981a</color></PolyStyle></Style><Style id="8"><LineStyle><width>2.0</width><color>ff882754</color></LineStyle><PolyStyle><color>ff882754</color></PolyStyle></Style>
						<ScreenOverlay><name>Legend: Logo</name><Icon> <href>http://lmingenieria.com.ar/images/logo.png</href> </Icon> <overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>
                         <screenXY x="25" y="40" xunits="pixels" yunits="pixels"/>
                        <rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
                        <size x="0" y="0" xunits="pixels" yunits="pixels"/>
                          </ScreenOverlay>')}
            if (version_simplificada == "n1"){
            cabezera<-c('<?xml version="1.0"?>
                        <kml xmlns:xsd="http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd" version="1.0">
                        <Document><Style id="1"><LineStyle><width>2.0</width><color>ff1400aa</color></LineStyle><PolyStyle><color>ff1400aa</color></PolyStyle></Style><Style id="2"><LineStyle><width>2.0</width><color>ff2730d7</color></LineStyle><PolyStyle><color>ff2730d7</color></PolyStyle></Style><Style id="3"><LineStyle><width>2.0</width><color>ff598dfc</color></LineStyle><PolyStyle><color>ff598dfc</color></PolyStyle></Style><Style id="4"><LineStyle><width>2.0</width><color>ff8be0fe</color></LineStyle><PolyStyle><color>ff8be0fe</color></PolyStyle></Style><Style id="5"><LineStyle><width>2.0</width><color>ff8befd9</color></LineStyle><PolyStyle><color>ff8befd9</color></PolyStyle></Style><Style id="6"><LineStyle><width>2.0</width><color>ff60cf91</color></LineStyle><PolyStyle><color>ff60cf91</color></PolyStyle></Style><Style id="7"><LineStyle><width>2.0</width><color>ff50981a</color></LineStyle><PolyStyle><color>ff50981a</color></PolyStyle></Style><Style id="8"><LineStyle><width>2.0</width><color>ff882754</color></LineStyle><PolyStyle><color>ff882754</color></PolyStyle></Style>
						<ScreenOverlay><name>Legend: Logo</name><Icon> <href>http://lmingenieria.com.ar/images/logo.png</href> </Icon> <overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>
                         <screenXY x="25" y="40" xunits="pixels" yunits="pixels"/>
                        <rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
                        <size x="0" y="0" xunits="pixels" yunits="pixels"/>
                          </ScreenOverlay>')}
            if (version_simplificada == "n2"){
            cabezera<-c('<?xml version="1.0"?>
                        <kml xmlns:xsd="http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd" version="1.0">
                        <Document><Style id="1"><LineStyle><width>2.0</width><color>ff1400aa</color></LineStyle><PolyStyle><color>ff1400aa</color></PolyStyle></Style><Style id="2"><LineStyle><width>2.0</width><color>ff2730d7</color></LineStyle><PolyStyle><color>ff2730d7</color></PolyStyle></Style><Style id="3"><LineStyle><width>2.0</width><color>ff598dfc</color></LineStyle><PolyStyle><color>ff598dfc</color></PolyStyle></Style><Style id="4"><LineStyle><width>2.0</width><color>ff8be0fe</color></LineStyle><PolyStyle><color>ff8be0fe</color></PolyStyle></Style><Style id="5"><LineStyle><width>2.0</width><color>ff8befd9</color></LineStyle><PolyStyle><color>ff8befd9</color></PolyStyle></Style><Style id="6"><LineStyle><width>2.0</width><color>ff60cf91</color></LineStyle><PolyStyle><color>ff60cf91</color></PolyStyle></Style><Style id="7"><LineStyle><width>2.0</width><color>ff50981a</color></LineStyle><PolyStyle><color>ff50981a</color></PolyStyle></Style><Style id="8"><LineStyle><width>2.0</width><color>ff882754</color></LineStyle><PolyStyle><color>ff882754</color></PolyStyle></Style>
						<ScreenOverlay><name>Legend: Logo</name><Icon> <href>http://lmingenieria.com.ar/images/logo.png</href> </Icon> <overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>
                         <screenXY x="25" y="40" xunits="pixels" yunits="pixels"/>
                        <rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
                        <size x="0" y="0" xunits="pixels" yunits="pixels"/>
                          </ScreenOverlay>')}
            #ACTIVAR PARA SACAR LOS MULTYPOLYGON Y SILENCIAR LOS DE ABAJO
            #prefijo<-c('<Placemark><name>30</name><styleUrl>#1</styleUrl><Polygon>')
            #sufijo<-c('</Polygon></Placemark>')
            fin<-c('</Document></kml>')

            #prefijo<-c('<Placemark><name>1</name><styleUrl>#1</styleUrl><MultiGeometry>')
            sufijo<-c('</MultiGeometry></Placemark>')
            prefijo.poligono<-c('<Polygon>')
            sufijo.poligono<-c('</Polygon>')

            for (a in 1:length(obj@polygons)){

			  if (version_simplificada == "ni"){

			  #cols[1:nrow(vectorizado1@data["output"])]
			  minimo_datos<- min(vectorizado@data["output"])
  			  maximo_datos<- max(vectorizado@data["output"])

              indice_min<-which(cortes == minimo_datos)[[1]]
              indice_max<-which(cortes == maximo_datos)[[1]]

  				  if (obj$output[a] == minimo_datos){estilo.id = 1}
				  if(is.na(match(cortes[indice_min+1],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+1]){estilo.id = 2}}
   				  if(is.na(match(cortes[indice_min+2],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}}
				  if(is.na(match(cortes[indice_min+3],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}}
				  if(is.na(match(cortes[indice_min+4],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}}
				  if(is.na(match(cortes[indice_min+5],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}}
				  if(is.na(match(cortes[indice_min+6],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}}
				  if(is.na(match(cortes[indice_min+7],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}}
				  if(is.na(match(cortes[indice_min+8],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+8]){estilo.id = 8}}
				  >print(paste(obj$output[a],estilo.id))

                  #if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}
                  #if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}
         		  #if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}
    			  #if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}
                  #if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}
         		  #if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}

              }

			  if (version_simplificada == "na"){

			  #cols[1:nrow(vectorizado1@data["output"])]
			  minimo_datos<- min(vectorizado@data["output"])
  			  maximo_datos<- max(vectorizado@data["output"])

              indice_min<-which(cortes == minimo_datos)[[1]]
              indice_max<-which(cortes == maximo_datos)[[1]]

  				  if (obj$output[a] == minimo_datos){estilo.id = 1}
				  if(is.na(match(cortes[indice_min+1],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+1]){estilo.id = 2}}
   				  if(is.na(match(cortes[indice_min+2],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}}
				  if(is.na(match(cortes[indice_min+3],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}}
				  if(is.na(match(cortes[indice_min+4],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}}
				  if(is.na(match(cortes[indice_min+5],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}}
				  if(is.na(match(cortes[indice_min+6],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}}
				  if(is.na(match(cortes[indice_min+7],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}}
				  if(is.na(match(cortes[indice_min+8],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+8]){estilo.id = 8}}
				  >print(paste(obj$output[a],estilo.id))

                  #if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}
                  #if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}
         		  #if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}
    			  #if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}
                  #if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}
         		  #if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}

              }

			  if (version_simplificada == "nu"){

			  #cols[1:nrow(vectorizado1@data["output"])]
			  minimo_datos<- min(vectorizado@data["output"])
  			  maximo_datos<- max(vectorizado@data["output"])

              indice_min<-which(cortes == minimo_datos)[[1]]
              indice_max<-which(cortes == maximo_datos)[[1]]

  				  if (obj$output[a] == minimo_datos){estilo.id = 1}
				  if(is.na(match(cortes[indice_min+1],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+1]){estilo.id = 2}}
   				  if(is.na(match(cortes[indice_min+2],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}}
				  if(is.na(match(cortes[indice_min+3],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}}
				  if(is.na(match(cortes[indice_min+4],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}}
				  if(is.na(match(cortes[indice_min+5],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}}
				  if(is.na(match(cortes[indice_min+6],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}}
				  if(is.na(match(cortes[indice_min+7],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}}
				  if(is.na(match(cortes[indice_min+8],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+8]){estilo.id = 8}}
				  >print(paste(obj$output[a],estilo.id))

                  #if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}
                  #if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}
         		  #if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}
    			  #if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}
                  #if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}
         		  #if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}

              }

			  if (version_simplificada == "n1"){

			  #cols[1:nrow(vectorizado1@data["output"])]
			  minimo_datos<- min(vectorizado@data["output"])
  			  maximo_datos<- max(vectorizado@data["output"])

              indice_min<-which(cortes == minimo_datos)[[1]]
              indice_max<-which(cortes == maximo_datos)[[1]]

  				  if (obj$output[a] == minimo_datos){estilo.id = 1}
				  if(is.na(match(cortes[indice_min+1],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+1]){estilo.id = 2}}
   				  if(is.na(match(cortes[indice_min+2],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}}
				  if(is.na(match(cortes[indice_min+3],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}}
				  if(is.na(match(cortes[indice_min+4],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}}
				  if(is.na(match(cortes[indice_min+5],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}}
				  if(is.na(match(cortes[indice_min+6],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}}
				  if(is.na(match(cortes[indice_min+7],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}}
				  if(is.na(match(cortes[indice_min+8],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+8]){estilo.id = 8}}
				  >print(paste(obj$output[a],estilo.id))

                  #if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}
                  #if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}
         		  #if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}
    			  #if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}
                  #if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}
         		  #if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}

              }

			  if (version_simplificada == "n2"){

			  #cols[1:nrow(vectorizado1@data["output"])]
			  minimo_datos<- min(vectorizado@data["output"])
  			  maximo_datos<- max(vectorizado@data["output"])

              indice_min<-which(cortes == minimo_datos)[[1]]
              indice_max<-which(cortes == maximo_datos)[[1]]

  				  if (obj$output[a] == minimo_datos){estilo.id = 1}
				  if(is.na(match(cortes[indice_min+1],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+1]){estilo.id = 2}}
   				  if(is.na(match(cortes[indice_min+2],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}}
				  if(is.na(match(cortes[indice_min+3],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}}
				  if(is.na(match(cortes[indice_min+4],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}}
				  if(is.na(match(cortes[indice_min+5],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}}
				  if(is.na(match(cortes[indice_min+6],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}}
				  if(is.na(match(cortes[indice_min+7],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}}
				  if(is.na(match(cortes[indice_min+8],cortes)) == FALSE){if (obj$output[a] == cortes[indice_min+8]){estilo.id = 8}}
				  >print(paste(obj$output[a],estilo.id))

                  #if (obj$output[a] == cortes[indice_min+7]){estilo.id = 8}
                  #if (obj$output[a] == cortes[indice_min+6]){estilo.id = 7}
         		  #if (obj$output[a] == cortes[indice_min+5]){estilo.id = 6}
    			  #if (obj$output[a] == cortes[indice_min+4]){estilo.id = 5}
                  #if (obj$output[a] == cortes[indice_min+3]){estilo.id = 4}
         		  #if (obj$output[a] == cortes[indice_min+2]){estilo.id = 3}

              }

              if (version_simplificada == "no"){

              if (obj$output[a] == unname(cortes[7])){estilo.id = 7}
              if (obj$output[a] == unname(cortes[6])){estilo.id = 6}
              if (obj$output[a] == unname(cortes[5])){estilo.id = 5}
              if (obj$output[a] == unname(cortes[4])){estilo.id = 4}
              if (obj$output[a] == unname(cortes[3])){estilo.id = 3}
              if (obj$output[a] == unname(cortes[2])){estilo.id = 2}
              if (obj$output[a] == unname(cortes[1])){estilo.id = 1}
              }

              if (version_simplificada == "si"){

              if (obj$output[a] == unname(cortes[4])){estilo.id = 4}
              if (obj$output[a] == unname(cortes[3])){estilo.id = 3}
              if (obj$output[a] == unname(cortes[2])){estilo.id = 2}
              if (obj$output[a] == unname(cortes[1])){estilo.id = 1}
              }

              prefijo<-sprintf('<Placemark><name>%s</name><styleUrl>#%s</styleUrl><MultiGeometry>',obj$output[a],estilo.id)

              #print(paste("corrida numero",a))
              agujeros<-c()
              superkml<-c("")
              for (i in 1:length(obj@polygons[[a]]@Polygons)){
                agujero<-obj@polygons[[a]]@Polygons[[i]]@hole
                agujeros<-c(agujeros,agujero)
              }
              #print(agujeros)

              for (i in 1:length(agujeros)){
                if(agujeros[i] == FALSE){
                  #obtengo el outboundary
                  xyz<-obj@polygons[[a]]@Polygons[[i]]@coords
                  coords.out <- paste(xyz[,1], ',', xyz[,2], ',', 0, collapse='\n ', sep = "")
                  outers<-sprintf('<outerBoundaryIs><LinearRing><coordinates>%s</coordinates></LinearRing></outerBoundaryIs>', coords.out)
                  if(is.na(agujeros[i+1])){
                    union<-paste(prefijo.poligono,outers,sufijo.poligono)
                    #union<-paste(prefijo,outers,sufijo)
                    superkml<-paste(superkml,union)
                    #stop("Se termino la ejecución porque no habia mas poligonos")
                  } else {
                    repeat {
                      if(agujeros[i+1] == TRUE){
                        xyz<-obj@polygons[[a]]@Polygons[[i+1]]@coords
                        coords.int <- paste(xyz[,1], ',', xyz[,2], ',', 0, collapse='\n ', sep = "")
                        xt<-sprintf('<innerBoundaryIs><LinearRing><coordinates>%s</coordinates></LinearRing></innerBoundaryIs>',coords.int)
                        inners<-paste(inners,xt)
                        i<-i+1
                      }
                      if (agujeros[i+1] == FALSE  | is.na(agujeros[i+1])){
                        union<-paste(prefijo.poligono,outers,inners,sufijo.poligono)
                        #activar para sacar los multypolygons
                        #union<-paste(prefijo,outers,inners,sufijo)
                        inners<-c("")
                        outers<-c("")
                        #print("era false")
                        #print(i+1)
                        break
                      }
                    }
                  }
                  superkml<-paste(superkml,union)
                  #superkml<-paste(prefijo.poligono,superkml,union,sufijo.poligono)
                  #stack<-paste(stack,superkml)
                } else {#print("era verdadero")
                }
              }
              stack<-paste(stack,prefijo,superkml,sufijo)

            }

            write(paste(cabezera,stack,fin), paste(nombre,".kml",sep=""))

          }
   hacerkml()

Output <- sf::st_as_sf(vectorizado)


pdf_file<-"pdf/maps_world_great_circles.pdf"
cairo_pdf(bg="grey98", pdf_file,width=13.75,height=8)

par(omi=c(0.5,0.5,1.25,0.5),mai=c(0,0,0,0),lend=1,bg="antiquewhite",family="Lato Light")
library(mapdata)
library(geosphere)
library(gdata)
# library(mapproj)

# Import data and prepare chart

myProj.type<-"mercator"
myProj.orient<-c(90,0,30)
x<-map(proj=myProj.type,orient=myProj.orient,wrap=T)

# Create chart and other elements

plot(x,xlim=c(-3,3),ylim=c(-1,2),type="n",axes=F,xaxs="i",yaxs="i")
rect(-3,-1,3,3,col="aliceblue",border=NA)
map("worldHires","Germany",fill=T,add=T,col="antiquewhite",proj=myProj.type,orient=myProj.orient)
lines(x,col="darkgrey")
data(world.cities)
myData<-read.xls("myData/orthodat.xlsx", encoding="latin1")
attach(myData)

myTColour<-rgb(128,128,128,100,maxColorValue=255)
for (i in 1:nrow(myData))
{
myStart<-world.cities[11769,] # Frankfurt
myDestination<-subset(world.cities,name==stadt[i] & country.etc==land[i])
myGC1<-gcIntermediate(c(myStart$long,myStart$lat),c(myDestination$long,myDestination$lat),addStartEnd=T, n=50)
merc<-mapproject(myGC1[,1],myGC1[,2],projection=myProj.type,orientation=myProj.orient)
lines(merc$x,merc$y,lwd=10,col=myTColour)

myDestP<-mapproject(myDestination$long,myDestination$lat,proj=myProj.type,orient=myProj.orient)
points(myDestP,col="darkred",pch=19,cex=2)
}
myStartP<-mapproject(myStart$long,myStart$lat,proj=myProj.type,orient=myProj.orient)
points(myStartP,col="darkblue",pch=19,cex=2)

# Titling

mtext("Destination Airports of Airbus A380 (Lufthansa)",3,line=3,adj=0,cex=3,family="Lato Black",outer=T)
mtext("As of: August 2013",3,line=1,adj=0,cex=1.75,font=3,outer=T)
mtext("Source: de.wikipedia.org/wiki/Lufthansa",1,line=0.8,adj=1.0,cex=1.25,font=3)
dev.off()


devtools::load_all()
## make a species pool
mc = metacommunity(nsp = 2, nr = 1, niche_args = list(r_use = c(0.3, 0.1)))
saveRDS(mc, "inst/testdata/metacom.rds")

## make a river network
##
Q = c(13,12,8,7,1,4,1,1,2,1)
nsites = length(Q)
adj = matrix(0, nrow=nsites, ncol=nsites)
adj[2,1] = adj[3,2] = adj[9,2] = adj[4,3] = adj[5,4] = adj[6,4] = adj[7,6] = adj[8,6] =
	adj[10,9] = 1

layout = matrix(c(0,0,0,1,-0.5,2,-0.5,3,-1,4,0,4,-0.5,5,0.5,5,0.5,2,1,3),
	byrow=TRUE, nrow=nsites)
R = matrix(seq(0, 1, length.out = nsites), ncol=1, dimnames = list(NULL, 'R'))
network = river_network(adjacency = adj, discharge = Q, layout = layout)
state(network, "resources") = R
boundary(network, "resources") = R
state(network, "species") = community_equilibrium(network, mc)
saveRDS(network, "inst/testdata/river_network.rds")

sim = flume(mc, network)
set.seed(45580085)
sim = run_simulation(sim, 50)
saveRDS(sim, "inst/testdata/sim.rds")


# -*- coding: utf-8 -*-
"""ar_hw6.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/18rtZgaq0UI96qYguCIX8fQ6apMYKxQ8W

# Práctico 6 - Modelos de grafos

# 1). Ambientes de trabajo

## 1.a) Ambiente COLAB remoto

1.   Abrir en navegador: https://colab.research.google.com/
2.   Abrir el notebook de la tarea:
     File-> Open Notebook -> Github -> https://github.com/prbocca/na101_master -> homework_6_models
3.   Guardar el notebook en su Google Drive:
     File -> Save a Copy in Drive...
4.   Renombrar el archivo `"cedula ID"_ar_hw6.ipynb`, por ejemplo *33484022_ar_hw6.ipynb*
5.   Al final usted deberá descargar el notebook. Asegurarse que se están guardando las salidas de ejecución en el notebook: File -> Download .ipynb
6.   Luego estos archivos deberán ser enviados a prbocca@fing.edu.uy

##1.b) Ambiente RSTUDIO local (opcional)

Abrir el .r de la tarea en: https://github.com/prbocca/na101_master/tree/master/homework_6_models

## 1.c) Cargar Librerias

Todas las librerías deben instalarse correctamente, si el proceso se interrumpe o alguna librería da error en la instalación, entonces habrá problemas en el código más adelante. Si tiene este tipo de problemas pruebe hacer `Runtime -> Factory reset runtime`, y volver a intentar.
"""

# cargar librerias
load_libs <- function(libraries = libs, install=TRUE){
  if (install){ # instalar librerias no instaladas
    new.packages <- libs[!(libs %in% installed.packages()[,"Package"])]
    if(length(new.packages)) install.packages(new.packages)
  }
  #cargo librerias
  for (lib in libraries){
    require(lib, character.only=TRUE, quietly = FALSE)
  }
}

libs = c("sand","igraph")

load_libs(libs)

"""## 1.d) Descargar funciones auxiliares"""

#directorio donde se va a trabajar
data_path = "/content/ar/hw6/"

dir.create(data_path, showWarnings = FALSE, recursive = TRUE)
setwd(data_path)
getwd()
list.files()

# cargo funciones auxiliares
source("https://raw.githubusercontent.com/prbocca/na101_master/master/homeworks_common.r")

"""# 2). Modelos clásicos de grafos en `R`

Seguir las Secciones 5.1 y 5.2 del libro [SANDR], ejecutando el código fuente incluido.
"""

#5.1 Introduction
#5.2 Classical Random Graph Models

#The function erdos.renyi.game in igraph can be used to simulate classical
#random graphs of either type. Figure 5.1 shows a realization of a classical random
#graph, based on the choice of N v = 100 vertices and a probability of p = 0.02 of an
#edge between any pair of vertices. Using a circular layout, we can see that the edges
#appear to be scattered between vertex pairs in a fairly uniform manner, as expected.
set.seed(42)
g.er <- erdos.renyi.game(100, 0.02)
plot(g.er, layout=layout.circle, vertex.label=NA)

# Note that random graphs generated in the manner described above need not be connected.
is.connected(g.er)
#2 [1] FALSE

#Although this particular realization is not connected, it does nevertheless have a
# giant component, containing 71 of the 100 vertices. All other components contain
#between one and four vertices only.
table(sapply(decompose.graph(g.er), vcount))
# 3 1 2 3 4 71
#4 15 2 2 1 1
#In general, a classical random graph G will with high probability have a giant com-
#ponent if p = c/N v for some c > 1.

# Under this same parameterization for p, for c > 0, the degree distribution will
# be well-approximated by a Poisson distribution, with mean c, for large N v .
# Indeed, in our simulated random graph, the mean degree is quite close to the
# expected value of (100 − 1) × 0.02 = 1.98.
mean(degree(g.er))

# Furthermore, we see that the degree distribution is quite homogeneous.
hist(degree(g.er), col="lightblue", xlab="Degree", ylab="Frequency", main="")

#Other properties of classical random graphs include that there are relatively few
#vertices on shortest paths between vertex pairs72
average.path.length(g.er)
#[1] 5.276511
diameter(g.er)
#[1] 14
#and that there is low clustering.
transitivity(g.er)
#[1] 0.01639344
# More specifically, under the conditions above, it can be shown that the diameter
# varies like O(log N v ), and the clustering coefficient, like N v −1.

"""# 3). Distribución de grado de Erdös-Renyi, $G(n, p)$ , en `R`.

Utilizando la función `erdos.renyi.game()` generar grafos aleatorios de distinto orden.

## 3.a) Crecer la cantidad de vértices

Si fijamos $p = 0.02$, al crecer la cantidad de vértices:
¿qué sucede con el grado promedio?, y
¿la distribución de grado se acerca a una Normal o a una Poisson?

Verificar comparando el histograma con la distribución teórica para $n \in \{10, 100, 1000, 10000\}$.
"""

# Gnp: efecto de crecer la red, se aproxima a una normal
par(mfrow=c(3,2))
p=0.02
for (i in 1:5){
  n = 10^i
  g.er <- erdos.renyi.game(n, p.or.m=p, type="gnp")
  #hist(degree(g.er), probability = T, col="lightblue", xlab="Degree", ylab="Probabilities", main="")
  g.er.dd = degree_distribution(g.er)
  plot(g.er.dd, xlab="Degree", ylab="Probabilities", main=paste("n=",n))
  x = seq(from=1,to=length(g.er.dd), by=1)
  lines(x, dnorm(x, mean = n*p, sd = sqrt(n*p*(1-p))), type="l",col="red")
  print(paste("n =",n,", grado promedio =", mean(degree(g.er))))
}

par(mfrow=c(1,1))

"""## 3.b) Crecer la cantidad de vértices y obtener una distribución de Poisson

¿Cómo debemos cambiar el parámetro $p$ del modelo al crecer $n$ para que la  distribución tienda a una Poisson?

Verificar comparando el histograma con la distribución de Poisson para $n \in \{10, 100, 1000, 10000\}$ y un grado promedio de $1.8$.

Nota: Los parámtros de la distribución teórica fueron vistos en las clases teóricas.
"""

##################################################################
#                       TU CÓDIGO ACÁ
# Tip: similar a 3.a), los parámtros de la distribución teórica fueron vistos en las clases teóricas.
#
#
#
##################################################################

"""# 4). Otros modelos de grafos en `R`.

Seguir las Secciones 5.3 y 5.4 del libro [SANDR], ejecutando el código fuente incluido. En ellas se explican los modelos de configuración, acoplamiento preferencial, Barabási-Albert, y mundo pequeño.
"""

# 5.3 Generalized Random Graph Models

set.seed(42)

# The igraph function degree.sequence.game can be used to uniformly
# sample random graphs with fixed degree sequence. Suppose, for example, that we
# are interested in graphs of N v = 8 vertices, half of which have degree d = 2, and the
# other half, degree d = 3. Two examples of such graphs, drawn uniformly from the
# collection of all such graphs, are shown in Fig. 5.2.
degs <- c(2,2,2,2,3,3,3,3)
g1 <- degree.sequence.game(degs, method="vl")
g2 <- degree.sequence.game(degs, method="vl")
plot(g1, vertex.label=NA)
plot(g2, vertex.label=NA)

#Note that these two graphs do indeed differ, in that they are not isomorphic.
graph.isomorphic(g1, g2)
#[1] FALSE

# For a fixed number of vertices N v , the collection of random graphs with fixed
# degree sequence all have the same number of edges N e , due to the relation d  ̄ =
# 2N e /N v , where d  ̄ is the mean degree of the sequence (d (1) , . . . , d (N v ) ).
c(ecount(g1), ecount(g2))
#[1] 10 10

# On the other hand, it is important to keep in mind that all other characteristics
# are free to vary to the extent allowed by the chosen degree sequence. For example,
# we can generate a graph with the same degree sequence as our network of protein–
# protein interactions in yeast.
data(yeast)
degs <- degree(yeast)
fake.yeast <- degree.sequence.game(degs, method=c("vl"))
all(degree(yeast) == degree(fake.yeast))
# [1] TRUE

#But the original network has twice the diameter of the simulated version
diameter(yeast)
# [1] 15
diameter(fake.yeast)
# [1] 8

# and virtually all of the substantial amount of clustering originally present is now gone.
transitivity(yeast)
#[1] 0.4686178
transitivity(fake.yeast)
#[1] 0.0396504

# 5.4 Network Graph Models Based on Mechanisms

set.seed(42)

# 5.4.1 Small-World Models
# Work on modeling of this type received a good deal of its impetus from the seminal
# paper of Watts and Strogatz [146] and the ‘small-world’ network model introduced
# therein. These authors were intrigued by the fact that many networks in the real
# world display high levels of clustering, but small distances between most nodes.
#
# In order to create a network graph with both of these properties, Watts and Strogatz
# suggested instead beginning with a graph with lattice structure, and then randomly
# ‘rewiring’ a small percentage of the edges. More specifically, in this model
# we begin with a set of N v vertices, arranged in a periodic fashion, and join each
# vertex to r of its neighbors to each side. Then, for each edge, independently and
# with probability p, one end of that edge will be moved to be incident to another
# vertex, where that new vertex is chosen uniformly, but with attention to avoid the
# construction of loops and multi-edges.
# An example of a small-world network graph of this sort can be generated in
# igraph using the function watts.strogatz.game.

g.ws <- watts.strogatz.game(1, 25, 5, 0.05)
plot(g.ws, layout=layout.circle, vertex.label=NA)

# For the lattice alone, which we generate by setting p = 0, there is a substantial amount of clustering.
g.lat100 <- watts.strogatz.game(1, 100, 5, 0)
plot(g.lat100, layout=layout.circle, vertex.label=NA)
transitivity(g.lat100)
#[1] 0.6666667
#But the distance between vertices is non-trivial.
diameter(g.lat100)
#[1] 10
average.path.length(g.lat100)
#[1] 5.454545

#The effect of rewiring a relatively small number of edges in a random fashion is to
# noticeably reduce the distance between vertices, while still maintaining a similarly
# high level of clustering.
g.ws100 <- watts.strogatz.game(1, 100, 5, 0.05)
plot(g.ws100, layout=layout.circle, vertex.label=NA)
diameter(g.ws100)
#[1] 5
average.path.length(g.ws100)
#[1] 2.793939393
transitivity(g.ws100)
#[1] 0.5121305

# This effect may be achieved even with very small p. To illustrate, we simulate ac-
# cording to a particular Watts-Strogatz small-world network model, with N v = 1, 000
#and r = 10, and re-wiring probability p, as p varies over a broad range.
steps <- seq(-4, -0.5, 0.1)
len <- length(steps)
cl <- numeric(len)
apl <- numeric(len)
ntrials <- 100
for (i in (1:len)) {
  cltemp <- numeric(ntrials)
  apltemp <- numeric(ntrials)
  for (j in (1:ntrials)) {
    g <- watts.strogatz.game(1, 1000, 10, 1^steps[i])
    cltemp[j] <- transitivity(g)
    apltemp[j] <- average.path.length(g)
  }
  cl[i] <- mean(cltemp)
  apl[i] <- mean(apltemp)
}
# The results shown in Fig. 5.4, where approximate expected values for normalized
# versions of average path length and clustering coefficient are plotted, indicate that
# over a substantial range of p the network exhibits small average distance while main-
# taining a high level of clustering.
plot(steps, cl/max(cl), ylim=c(0, 1), lwd=3, type="l", col="blue", xlab=expression(log[10](p)),
  ylab="Clustering and Average Path Length")
lines(steps, apl/max(apl), lwd=3, col="red")

# 5.4.2 Preferential Attachment Models

# Many networks grow or otherwise evolve in time. The World Wide Web and
# scientific citation networks are two obvious examples. Similarly, many biological
# networks may be viewed as evolving as well, over appropriately defined time scales.
# Much energy has been invested in the development of models that mimic network growth.
# In this arena, typically a simple mechanism(s) is specified for how the network
# changes at any given point in time, based on concepts like vertex preference, fitness,
# copying, age, and the like. A celebrated example of such a mechanism is that of
# preferential attachment, designed to embody the principle that ‘the rich get richer.’
# ...

# Using the igraph function barabasi.game, we can simulate a BA random
# graph of, for example, N v = 100 vertices, with m = 1 new edges added for each new vertex.
set.seed(42)
g.ba <- barabasi.game(100, directed=FALSE)
# A visualization of this graph is shown in Fig. 5.5.
plot(g.ba, layout=layout.circle, vertex.label=NA)

# Note that the edges are spread among vertex pairs in a decidedly less uniform man-
# ner than in the classical random graph we saw in Fig. 5.1. And, in fact, there appear
# to be vertices of especially high degree—so-called ‘hub’ vertices.
# Examination of the degree distribution (also shown in Fig. 5.5)
hist(degree(g.ba), col="lightblue", xlab="Degree", ylab="Frequency", main="")
# confirms this suspicion, and indicates, moreover, that the overall distribution is quite
# heterogeneous. Actually, the vast majority of vertices have degree no more than two
# in this graph, while, on the other hand, one vertex has a degree of 11.
summary(degree(g.ba))
#Min. 1st Qu. Median Mean 3rd Qu. Max.
#1.00 1.00 1.00 1.98 2.00 11.00

# On the other hand, network graphs generated according to the BA model will
# share with their classical counterparts the tendency towards relatively few vertices
# on shortest paths between vertex pairs
average.path.length(g.ba)
# [1] 5.81555555555556
diameter(g.ba)
# [1] 12
#and low clustering.
transitivity(g.ba)
# [1] 0

"""# 5). Distribución de grado de Barabási-Albert en `R`.

Verificar que el modelo de Barabasi-Albert tiende a una distribución power-law de parámetro $\alpha = 3$ al crecer $n$.
Para esto graficar la función de distribución acumulada complementaria (CCDF) en conjunto con la recta teórica de la power-law. Usar los $n \in \{10, 100, 1000, 10000, 100000, 1000000\}$.
Para cada caso, encontrar el $\hat{\alpha}$ usando la función de ajuste de igraph, llamada `power.law.fit()`.
Además entender el test de hipótesis que se realiza en el ajuste, e interpretar el p-value del resultado.
"""

# BA: efecto de crecer la red
set.seed(42)
par(mfrow=c(3,2))

for (i in 1:6){
  n = 10^i
  g.ba = barabasi.game(n)

  # Degree distribution is the cumulative frequency of nodes with a given degree
  # this, like degree() can be specified as "in", "out", or "all"
  g.ba.dd = degree.distribution(g.ba, cumulative=T,mode="all")
  g.ba.d = degree(g.ba,v=V(g.ba),mode="all")

  # Using the power.law.fit() function I can fit a power law to the degree distribution
  # Plot degree distribution histogram, and theoretical line
  g.ba.power = NA
  ##################################################################
  #                       TU CÓDIGO ACÁ
  #
  #
  #
  ##################################################################
  print(paste("n =",n,", alpha =", g.ba.power$alpha, ", xmin =", g.ba.power$xmin))
}

"""# 6) Distribución de grado de una red real.

Mark Newman en 2006 creó un grafo de routers en Internet, con 22963 vértices y 48436 aristas.
Descargar el grafo en formato GML desde:
https://github.com/prbocca/na101_master/raw/master/homework_6_models/internet_routers-22july06.gml.zip

## 6.a) Descargar los datos

Descargar los datos en formato `GML` en el siguiente link:
https://github.com/prbocca/na101_master/raw/master/homework_6_models/internet_routers-22july06.gml.zip.

Cargar los datos en `R`.
"""

# download data
download.file(url="https://github.com/prbocca/na101_master/raw/master/homework_6_models/internet_routers-22july06.gml.zip", destfile="internet_routers-22july06.gml.zip", mode="wb")
unzip(zipfile="internet_routers-22july06.gml.zip")
list.files()

# cargar datos
g.real = NA
##################################################################
#                       TU CÓDIGO ACÁ
# Tip: usar funciones de igraph
#
#
#
##################################################################
summary(g.real)

"""## 6.b) (Opcional) Visualizar el grafo en Gephi

Visualizar los vértices de mayor grado con mayor tamaño,
y los vértices con mayor PageRank más oscuros.

El resultado debe ser similar al de la siguiente Figura: ![alt text](https://github.com/prbocca/na101_master/raw/master/homework_6_models/routers_gephi.png)

## 6.c) En `R`, graficar la distribución de grado.

También graficar con ejes log-log para una mejor visualización.
"""

# graficar distribución de grado de g.real
##################################################################
#                       TU CÓDIGO ACÁ
# Tip: usar funciones de igraph
#
#
#
##################################################################

"""## 6.d) Graficar la función de distribución acumulada complementaria (CCDF)."""

# graficar CCDF de g.real
##################################################################
#                       TU CÓDIGO ACÁ
# Tip: usar funciones de igraph
#
#
#
##################################################################

"""## 6.e) Austar una distribución Power-law

Ajustar la distribución a una power-law.

¿Cuál es el $\hat{\alpha}$ y el $d_{min}$ del ajuste?

¿Cómo interpretar el $p-value$ del test de hipotesis del resultado del ajuste?

Verificar las conclusiones comparando la CCDF con la recta ajustada. La gráfica debería ser similar a la siguiente: ![alt text](https://github.com/prbocca/na101_master/raw/master/homework_6_models/routers_powerlaw.png)
"""

# graficar la CCDF de g.real, y la distribución power-low ajustada
g.real.power = NA
##################################################################
#                       TU CÓDIGO ACÁ
# Tip: usar funciones de igraph
#
#
#
##################################################################
print(paste("El alpha estimado es =",g.real.power$alpha))


# Day 25: Sea Cucumber

get_day25_input_path <- function() {
    paste(getwd(), "/2021/Day 25/Day25_input.txt", sep = "")
}

part1 <- function() {
    readings <- readLines(get_day25_input_path())

    max_col <- nchar(readings[1])
    max_row <- length(readings)

    floor <- matrix(ncol = max_col)[-1, ]
    for (i in seq_len(max_row)) {
        floor <- rbind(floor, unlist(strsplit(readings[i], "")))
    }

    has_moved <- TRUE
    num_steps <- 1

    while (has_moved) {
        moves_this_step <- 0

        # Get indexes for right moving cucumbers with empty spaces to the right
        eastward <- which(floor == ">", arr.ind = TRUE)
        east_over <- get_adj_east_spaces(eastward, max_col)
        east_moveable <- matrix(which(floor[east_over] == "."), ncol = 2)

        moves_this_step <- length(east_moveable)

        # Swap values of the above indexes with the indexes to the right of them
        floor[east_over[east_moveable, ]] <- ">"
        floor[eastward[east_moveable, ]] <- "."

        # Get indexes for down moving cucumbers with empty spaces below
        southward <- which(floor == "v", arr.ind = TRUE)
        south_below <- get_adj_south_spaces(southward, max_row)
        south_moveable <- matrix(which(floor[south_below] == "."), ncol = 2)

        moves_this_step <- moves_this_step + length(south_moveable)

        # Swap values of the above indexes with the indexes below them
        floor[south_below[south_moveable, ]] <- "v"
        floor[southward[south_moveable, ]] <- "."

        if (moves_this_step == 0) {
            has_moved <- FALSE
        } else {
            num_steps <- num_steps + 1
        }
    }

    print(num_steps)
}

part2 <- function() {
    print("TODO")
}

get_adj_east_spaces <- function(eastward, max_col) {
    east_over <- eastward
    east_over[, 2] <- east_over[, 2] + 1
    east_over[, 2][east_over[, 2] > max_col] <- 1

    east_over
}

get_adj_south_spaces <- function(southward, max_row) {
    south_below <- southward
    south_below[, 1] <- south_below[, 1] + 1
    south_below[, 1][south_below[, 1] > max_row] <- 1

    south_below
}

part1()
part2()


#!/usr/bin/env Rscript --vanilla
# build video steam train plot from gapminder and berkeley earth data
# james goldie ('rensa'), august 2017

library(tidyverse)
library(magrittr)
library(stringr)
library(plotly)
library(ggflags)
library(gganimate)
filter = dplyr::filter # this is going to kill me one day
source('util.r')

# create data directory if it's missing
if(!dir.exists('data') | !file.exists('data/gapminder-berkeley-tidy.csv'))
{
  stop(paste('Error: can\'t find the tidied data! If it\'s been deleted from',
    'the repo, you can run tidy.r to recalculate it (or just clone the repo',
    'again)'))
}

# constants
# on_url = 'https://raw.githubusercontent.com/open-numbers/'
# berk_url = 'http://berkeleyearth.lbl.gov/'
year_start = 1900
year_end = 2012
frames_per_year = 30
plot_font_1 = 'Helvetica Neue Light'
plot_font_2 = 'Helvetica Neue'

all_data =
  read_csv('data/gapminder-berkeley-tidy.csv') %>%
  replace_na(list(flag_emoji = '274e'))

message(run.time(), ' trimming excess data for bubble geom')

message(run.time(), ' building emissions plot')
steamtrain = ggplot(all_data) +
  geom_pointrange(
    aes(
      x = gdppc,
      ymin = temp_min,
      y = temp,
      ymax = temp_max,
      colour = world_6region,
      frame = year)) +
  geom_flag(
    aes(
      x = gdppc,
      y = 3,
      country = str_to_lower(iso3166_1_alpha2),
      group = world_6region,
      size = co2_cum / 1000,
      frame = year),
    colour = 'black', stroke = 2,
    position = position_jitter(width = 0, height = 0.25)) +
  scale_x_log10(name = 'GDP (2010 US Dollars)') +
  scale_y_continuous(name = 'Temperature anomaly (°C)', limits = c(-1.5, 3.5)) +
  scale_size(name = 'Cumulative CO2 (Gt)', range = c(0, 25)) +
  scale_colour_discrete(name = 'Region') +
  ggtitle('Cumulative CO2 emissions, GDP per capita and temperature anomaly',
    subtitle = paste('Who contributed to the greenhouse effect,',
      'and who suffers for it?')) +
  theme_classic(base_size = 10, base_family = plot_font_1) +
  theme(plot.title = element_text(family = plot_font_2, face = 'bold'))
gganimate(steamtrain, 'steamtrain.mp4', title_frame = TRUE, interval = 0.5)

# static version (just 2012)
all_data_2012 = all_data %>% filter(year == 2012)
st2012 = ggplot(all_data_2012) +
  geom_pointrange(
    aes(
      x = gdppc,
      ymin = temp_min,
      y = temp,
      ymax = temp_max,
      colour = world_6region)) +
  geom_flag(
    aes(
      x = gdppc,
      y = 3,
      country = str_to_lower(iso3166_1_alpha2),
      group = world_6region,
      size = co2_cum / 1000),
    colour = 'black', stroke = 2,
    position = position_jitter(width = 0, height = 0.25)) +
    # position = position_jitter(width = 0, height = 0.25)) +
  scale_x_log10(name = 'GDP (2010 US Dollars)') +
  scale_y_continuous(name = 'Temperature anomaly (°C)', limits = c(-0.5, 3.5)) +
  scale_size(name = 'Cumulative CO2 (Gt as of 2012)', range = c(0, 25)) +
  scale_colour_discrete(name = 'Region') +
  labs(
    title = paste(
      'Cumulative CO2 emissions (1900–2012), GDP per capita and',
      'temperature anomaly'),
    subtitle = paste('Who contributed to the greenhouse effect,',
      'and who suffers for it?',
    caption = paste('Data from Open Numbers and Berkeley Earth; Flags from EmojiOne'))) +
  theme_classic(base_size = 10, base_family = plot_font_1) +
  theme(plot.title = element_text(family = plot_font_2, face = 'bold'))
ggsave('st2012.png', st2012,
  width = 192, height = 108, units = 'mm', scale = 1.5)

message(run.time(), ' done! Static (2012) frame saved as st2012.png; ',
  'animated version saved as steamtrain.mp4')


segmentation_Length_Distribution_of_RPM_of_segmented_loci<- function(fprefix='input',wdir=".") {
start_time <- proc.time()
cat("Length distribution of loci RPM across lengths (M3.01) start", date(), "\n")

# Plots for Module 3 Analysis and visualization of SPAR output
# Session: Segmentation characteristics

# Module_3_Figure_1(Figure 3.01)
# Description: Distribution of loci RPM across different lengths after segmentation
# input: input_annot.with_conservation.xls, input.unannot.final.with_conservation.xls
# output: Length_Distribution_of_RPM_of_segmented_loci.png / Length_Distribution_of_RPM_of_segmented_loci.pdf

# parameters for the plot
datafile1=paste(wdir, "/", fprefix, "_annot.with_conservation.xls", sep="")
datafile2=paste(wdir, "/", fprefix, "_unannot.with_conservation.xls", sep="")
BASENAME="Length_Distribution_of_RPM_of_segmented_loci"
PLOTTITLE="Distribution of loci RPM\n at different lengths after segmentation"
XTITLE="Peak_length(nt)"
YTITLE="Percentage"

# libraries needed
suppressPackageStartupMessages(library(reshape2))
suppressPackageStartupMessages(library(ggplot2))
suppressPackageStartupMessages(library(plyr))

#args<-commandArgs(TRUE)
#datafile1=args[1] # input file 1
#datafile2=args[2] # input file 2
#wdir=args[3] # output / working directory
#if (length(args)<1) { stop("ERROR: No input! USAGE: script inputfile <output-dir>")}
#if (length(args)<2) { stop("ERROR: No input! USAGE: script inputfile <output-dir>")}
#if (length(args)<3) { wdir="." }
#use current dir if no
#working dir has been specified

# output image file
pngfile = paste(wdir, "/../figures/", paste(BASENAME,".png",sep=""), sep="")
#pdffile= paste(wdir, "/", paste(BASENAME,".pdf",sep=""), sep="")

# Read in data
D = read.table(datafile1,sep='\t',header=T,comment.ch="")
E = read.table(datafile2,sep='\t',header=T,comment.ch="")
E$annotRNAclass = "unannot"
#DE = rbind(D[,c(1:20,25,29:31)],E)
DE = rbind(D,E)

DE$Peak_length = DE$peakChrEnd-DE$peakChrStart
DX = DE[DE$Peak_length<=44,]
DXT = dcast(DX, DX$annotRNAclass ~ DX$Peak_length,sum)
DXT = colSums(DXT[,-1])
DXT = data.frame(DXT)
DXT$norm = DXT$DXT/sum(DXT$DXT)*100
DXT$Var1 = rownames(DXT)

# make plot
png(pngfile,width = 7, height = 7, units = 'in', res = 300, type="cairo")
options(scipen=10000)
print(	ggplot(data = DXT, aes(x = Var1, y= norm)) +
		geom_bar(stat="identity") + theme_classic()+
		ggtitle(PLOTTITLE) + xlab(XTITLE)+ylab(YTITLE)+
		ylim(0,30)+
		theme(text = element_text(size=16),axis.text.x = element_text(angle=90, vjust = 0.5, hjust=1)))
dev.off()

cat("Total time for length distribution of loci RPM across lengths (M3.01) analysis:", (proc.time() - start_time)[['elapsed']], "seconds (", date(), ")\n")
}

# segmentation_Length_Distribution_of_RPM_of_segmented_loci(fprefix=fprefix,wdir=wdir)