#!/bin/env python
# -*- coding: utf-8 -*-
#Author: Pierre Ratinaud
#Copyright (c) 2008 Pierre Ratinaud
#License: GNU/GPL
#from __future__ import division
import os
import wx
from chemins import ffr, FFF
import tempfile
from time import sleep
from analysematrix import AnalyseMatrix
from functions import exec_rcode, check_Rresult
from dialog import FreqDialog
from PrintRScript import PrintRScript
class Frequences(AnalyseMatrix) :
def doparametres(self, dlg=None) :
if dlg is None :
return
else :
dial = FreqDialog(self.parent, self.tableau.get_colnames(), u"Fréquences")
dial.CenterOnParent()
val = dial.ShowModal()
if val == wx.ID_OK :
self.parametres['colsel'] = dial.m_listBox1.GetSelections()
self.parametres['header'] = dial.header
self.parametres['NA'] = dial.includeNA.GetValue()
else :
self.parametres = None
dial.Destroy()
def doanalyse(self):
self.pathout.createdir(self.parametres['pathout'])
header = self.tableau.get_colnames()
select = self.parametres['colsel']
self.listtitre = [header[i] for i in select]
b, self.outframe = tempfile.mkstemp()
self.fileforR = [ffr(os.path.join(self.pathout.dirout, 'freq_%i.png' % i)) for i in range(len(select))]
self.Rscript = PrintRScript(self)
sel = 'c(' + ','.join([str(val + 1) for val in select]) + ')'
listfiles = 'c("' + '","'.join(self.fileforR) + '")'
titles = 'c("' + '","'.join(self.listtitre) + '")'
txt = """
filein <- "%s"
encoding <- '%s'
dm <- read.csv2(filein, encoding = encoding, header = TRUE, row.names = 1, sep='\\t', quote = '"', na.string = '')
""" %(ffr(self.tableau.parametres['csvfile']), self.tableau.parametres['syscoding'])
txt += """
outframe <- data.frame(cbind('***','****','****'))
colnames(outframe)<-c('effectif','pourcentage', 'labels')
select <- %s
listfiles <- %s
titles <- %s
compteur <- 1
""" % (sel, listfiles, titles)
if self.parametres['NA'] :
txt += """
countNA <- TRUE
"""
else :
txt += """
countNA <- FALSE
"""
txt += """
for (i in select) {
if (countNA) {
freq <- table(dm[,i], useNA = 'ifany')
} else {
freq <- table(dm[,i])
}
sumfreq <- sum(freq)
pour <- prop.table(as.matrix(freq), 2) * 100
sumpour <- sum(pour)
pour <- round(pour, 2)
ntable <- cbind(as.matrix(freq), pour)
graphout <- listfiles[compteur]
if (Sys.info()["sysname"]=='Darwin') {
quartz(file=graphout,type='png')
par(cex=1)
} else {
png(graphout)
par(cex=0.3)
}
if (max(nchar(rownames(ntable))) > 15) {
lab.bar <- 1:nrow(ntable)
} else {
lab.bar <- rownames(ntable)
}
barplot(ntable[,2],border=NA,beside=TRUE,names.arg=lab.bar)
ntable <- cbind(ntable, rownames(as.matrix(freq)))
colnames(ntable) <- c('effectif','pourcentage', 'labels')
title(main=titles[compteur])
dev.off()
ntable<-rbind(ntable,total=c(sumfreq,sumpour,''))
outframe<-rbind(outframe,c('***','****','****'))
#datasum[,1]<-as.character(datasum[,1])
#datasum[,2]<-as.character(datasum[,2])
outframe<-rbind(outframe,ntable)
compteur <- compteur + 1
}
outframe<-rbind(outframe,c('***','****','****'))
write.table(outframe, file="%s", sep="\\t")
""" % ffr(self.outframe)
self.Rscript.add(txt)
self.Rscript.write()
self.doR(self.Rscript.scriptout)
self.dolayout()
def dolayout(self):
listtab = []
tab = []
with open(self.outframe) as f :
content = f.read().splitlines()
content.pop(0)
content.pop(0)
content = ['\t'.join(line.split('\t')[1:]).replace('"','') for line in content]
content = '\n'.join(content)
content = content.split(u'***\t****\t****')
content = [[line.split('\t') for line in tab.splitlines() if line.split('\t') != ['']] for tab in content]
listtab = [tab for tab in content if tab != []]
texte = ''
#for ligne in content:
# ligne = ligne.replace('"', '')
# ligne = ligne.split('\t')
# if ligne[1] == u'***' :
# if tab != []:
# listtab.append(tab)
# tab = []
# else :
# tab.append(ligne)
pretexte = u'''
\nFréquences
''' % self.parent.SysEncoding
for i in range(0, len(listtab)):
pretexte += '%s
' % (str(i), self.listtitre[i])
texte += '
\n'
texte += 'Retour
\n'
texte += '%s
\n' % (str(i), self.listtitre[i])
texte += '\n\n'
texte += ' | Effectifs | pourcentage | '
for line in listtab[i] :
texte += ''
texte += """
%s | %s | %s %% |
""" % (line[2], line[0], line[1])
texte += ' '
texte += '
| '
texte += """
|
\n
""" % os.path.basename(self.fileforR[i])
texte += '\n'
fileout = os.path.join(self.pathout.dirout, 'resultats.html')
with open(fileout, 'w') as f :
f.write(pretexte + texte)
#return fileout