lunes 26 de diciembre de 2011

Simulación BPSK en python/numpy/matplotlib

Una pequeña prueba



import numpy as np
from scipy.special import erfc
#from scipy import weave
#from scipy.weave import converters
import matplotlib.pyplot as plt
from time import time

N = 5000000
ip = np.random.rand(1,N)>0.5;
s = 2*ip-1
t = time()
n = 1.0/np.sqrt(2.0)*(np.random.randn(1,N)+1j*np.random.randn(1,N))
print(time()-t)
Eb_N0_dB = np.arange(-3.0,11.0,1.0) #-3 a 10 dB
errors = []
terrors = []
for EbN0 in Eb_N0_dB:
t = time()
y = s+10**(-EbN0/20.0)*n
ipHat = y.real>0
err = float((ip != ipHat).sum())/N
errors.append(err)
terrors.append(0.5*erfc(np.sqrt(10**(EbN0/10.0))))
print("time = %s, EbN0 = %s, ber = %s"%(time()-t,EbN0,err))
plt.semilogy(Eb_N0_dB,errors,'-o')
plt.semilogy(Eb_N0_dB,terrors,':v')
plt.legend(('simulation','theory'),'upper right',shadow=True,fancybox=True)
plt.title('Bit Error Rate for BPSK')
plt.xlabel(r'$\frac{Eb}{N0}$, dB')
plt.ylabel('Bit Error Rate')
plt.grid(True)
plt.show()



viernes 29 de julio de 2011

Una prueba de code2html

code2html es una aplicación destinada a convertir tu código en html para poder publicarlo.

$ code2html -h
Code2Html, version 0.9.1, Jan 2002, peter@palfrader.org
Usage: code2html [options] [input_file [output_file]]

Convert a program source to syntax highlighted HTML,
or any other format for wich rules are defined.

-l, --language-mode set language mode
--fallback LANG fallback language mode
-v, --verbose prints progress information to STDER
-n, --linenumbers print out the source code with line numbers
-P, --prefix optional prefix to use for linenumber anchors
-N, --linknumbers linenumbers will link to themselves
-t, --replace-tabs[=TABSTOP-WIDTH]
replace with spaces
-L, --language-file=LANGUAGE-FILE
specify an alternate file for definitions
-m, --modes print all available modes
-h, --help print this message
-V, --version print version
-c, --content-type prints a Content-Type header
-o, --output-format selects the output-format
-H, --no-header don't use the template
--template=FILE override template
-T, --title set title

-w, --linewidth max characters per line
-b, --linebreakprefix prefix of the new lines

see the man-page code2html for further help


$ code2html -m
Defined modes: ada, ada95, awk, c, c++, cc, cpp, cxx, gpasm, groff, html, java, javascript, js, lisp, m4, make, makefile, pas, pascal, patch, perl, plain, pov, povray, python, ruby, sh, shellscript, sql.
Defined outputformats: html, html-dark, html-fntlck, html-light, html-nobg, html-nocolor, html-simple.

ejemplos:

code2html pex.py -H
import xlrd
import
xlwt
from
xlutils.copy import copy

class
xls(xlwt.Workbook):
def __init__(self, encoding='ascii', style_compression=0):
xlwt.Workbook.__init__(self,encoding, style_compression)

def add_sheet2(self,worksheet):
if
isinstance(worksheet,xlwt.Worksheet):
self._Workbook__worksheet_idx_from_name[worksheet.name.lower()] = len(self._Workbook__worksheets)
self._Workbook__worksheets.append(worksheet)
else
:
raise
Exception("invalid worksheet")

file_name = 'tb_wbdh13.xls'
rb = xlrd.open_workbook(file_name,formatting_info=True)

print
rb
print
rb.name_and_scope_map
print
rb.name_map
print
rb.name_obj_list
print
"____________________________________"
for
name in rb.name_obj_list:
print
name
print
name.name
print
name.raw_formula
print
name.result.text
print
name.scope

sheet = rb.sheet_by_index(0)
print
sheet.colinfo_map
print
sheet.rowinfo_map
print
sheet.col_label_ranges
print
sheet.row_label_ranges
print
sheet.cell(1,3).xf_index
print
sheet.colinfo_map[0].xf_index
print
dir(sheet)
#print xlrd.dump(file_name)
wb = copy(rb)
ws = wb.get_sheet(0)
doc = xls()
doc.add_sheet("CLK_PROCESS_0")
doc.add_sheet("CLK_PROCESS_1")
doc.add_sheet("CLK_PROCESS_bak")

doc.add_sheet2(ws)
doc.save('out.xls')


code2html -n pex.py -H
 1 import xlrd
2 import
xlwt
3 from
xlutils.copy import copy
4
5 class
xls(xlwt.Workbook):
6 def __init__(self, encoding='ascii', style_compression=0):
7
xlwt.Workbook.__init__(self,encoding, style_compression)
8
9 def add_sheet2(self,worksheet):
10
if
isinstance(worksheet,xlwt.Worksheet):
11
self._Workbook__worksheet_idx_from_name[worksheet.name.lower()] = len(self._Workbook__worksheets)
12
self._Workbook__worksheets.append(worksheet)
13 else
:
14 raise
Exception("invalid worksheet")
15
16
file_name = 'tb_wbdh13.xls'
17
rb = xlrd.open_workbook(file_name,formatting_info=True)
18
19 print
rb
20 print
rb.name_and_scope_map
21 print
rb.name_map
22 print
rb.name_obj_list
23 print
"____________________________________"
24 for
name in rb.name_obj_list:
25 print
name
26 print
name.name
27 print
name.raw_formula
28 print
name.result.text
29 print
name.scope
30
31
sheet = rb.sheet_by_index(0)
32 print
sheet.colinfo_map
33 print
sheet.rowinfo_map
34 print
sheet.col_label_ranges
35 print
sheet.row_label_ranges
36 print
sheet.cell(1,3).xf_index
37 print
sheet.colinfo_map[0].xf_index
38 print
dir(sheet)
39
#print xlrd.dump(file_name)
40
wb = copy(rb)
41
ws = wb.get_sheet(0)
42
doc = xls()
43
doc.add_sheet("CLK_PROCESS_0")
44
doc.add_sheet("CLK_PROCESS_1")
45
doc.add_sheet("CLK_PROCESS_bak")
46
47
doc.add_sheet2(ws)
48
doc.save('out.xls')


code2html -o html-nocolors -H prex.py
import xlrd
import xlwt
from xlutils.copy import copy

class xls(xlwt.Workbook):
def __init__(self, encoding='ascii', style_compression=0):
xlwt.Workbook.__init__(self,encoding, style_compression)

def add_sheet2(self,worksheet):
if isinstance(worksheet,xlwt.Worksheet):
self._Workbook__worksheet_idx_from_name[worksheet.name.lower()] = len(self._Workbook__worksheets)
self._Workbook__worksheets.append(worksheet)
else:
raise Exception("invalid worksheet")

file_name = 'tb_wbdh13.xls'
rb = xlrd.open_workbook(file_name,formatting_info=True)

print rb
print rb.name_and_scope_map
print rb.name_map
print rb.name_obj_list
print "____________________________________"
for name in rb.name_obj_list:
print name
print name.name
print name.raw_formula
print name.result.text
print name.scope

sheet = rb.sheet_by_index(0)
print sheet.colinfo_map
print sheet.rowinfo_map
print sheet.col_label_ranges
print sheet.row_label_ranges
print sheet.cell(1,3).xf_index
print sheet.colinfo_map[0].xf_index
print dir(sheet)
#print xlrd.dump(file_name)
wb = copy(rb)
ws = wb.get_sheet(0)
doc = xls()
doc.add_sheet("CLK_PROCESS_0")
doc.add_sheet("CLK_PROCESS_1")
doc.add_sheet("CLK_PROCESS_bak")

doc.add_sheet2(ws)
doc.save('out.xls')

domingo 24 de julio de 2011

[Python] Descargando desde rapidshare usando la api

Sólo por probar como funciona la api de rapidshare que se encuentra documentada en http://images.rapidshare.com/apidoc.txt
#!/usr/bin/env python

import sys
import urllib2
import urllib
import time
url =  "http://rapidshare.com/#!download|958tl|40"
url += "20022538|NarutoKizunaDriveSaveData.rar|222|"
url += "R~3187F38923AB1D7B76BF6D2C55ADDCEE"
print url #link de prueba
url_api = "http://api.rapidshare.com/cgi-bin/rsapi.cgi"

status_file = {0:'File not found',
1:'File OK',
3:'Server down',
4:'File marked as illegal',
5:'Direct download'
}

headers = {'User-Agent':'Firefox Mozilla 7.0'}

class opener(urllib.FancyURLopener):
version = headers['User-Agent']

def check_files(link):
#Aquí vamos a verficar que el link sea válido
#?sub=checkfiles_v1&filenames=?&files=?
try:
file_id, file_name = link.rsplit('/')[3].split('|')[2:4]
except:
print("No rapidshare link")
sys.exit(1)

params = {'filenames':file_name,
'files':file_id,
}
params_string = urllib.urlencode(params)
check_link = "%s?sub=checkfiles_v1&%s"%(url_api,params_string)
request = urllib2.Request(url=check_link, headers=headers)
conn = urllib2.urlopen(request)
file_id, file_name,size,serverid,status,short_host,fmd5 = conn.read().split(',')
print("check_files -----------------|\n")
print(status_file[int(status)])
if status == '1':
print("File ID: %s\nFile Name: %s\nsize: %s bytes"%(file_id,file_name,size))
print("Server ID: %s\nShort host: %s\nmd5_hex: %s"%(serverid,short_host,fmd5))
return file_id,file_name,size,serverid,fmd5
else:
print('Aborting download')
sys.exit(1)


def get_download_auth(file_id,file_name):
#Para usuarios con cuentas gratuitas obtenemos primero el la autorización de descarga
# y el tiempo de espera para descargar
#?sub=download_v1&filname=?&fileid=?
params = {'filename':file_name,
'fileid':file_id
}
params_string = urllib.urlencode(params)
link = "%s?sub=download_v1&%s"%(url_api,params_string)
request = urllib2.Request(url=link, headers=headers)
conn = urllib2.urlopen(request)
key, value = conn.read().split(':')
if key == "ERROR":
print("Error:%s"%value)
sys.exit(1)
host, dlauth, countdown, fmd5 = value.split(',')
print("get_download_auth ---------------|\n")
print(link)
print("\nHost: %s\ndlauth: %s\ncountdown: %s seconds"%(host,dlauth,countdown))
return host, dlauth, countdown, fmd5

def download_file(file_id,file_name,host,dlauth, countdown, fmd5):
#Descargamos el archivo
params = {'fileid':file_id,
'filename':file_name,
'dlauth':dlauth
}
params_string = urllib.urlencode(params)
download_link = "http://%s/cgi-bin/rsapi.cgi?sub=download_v1&%s"%(host,
params_string)
time.spleep(int(countdown))
print("download_file --------------|\n")
print(download_link)
download_opener = opener()
filename, headers = download_opener.retrieve(download_link, file_name)
print('Download Completed')
print("File Name: %s"%filename)
print("Headers: %s"%headers)

if __name__== '__main__':
file_id,file_name,size,serverid,fmd5 = check_files(url)
host,dlauth,countdown,fmd5 = get_download_auth(file_id,file_name)
download_file(file_id,file_name,host,dlauth,countdown, fmd5)

Salida

http://rapidshare.com/#!download|958tl|4020022538|NarutoKizunaDriveSaveData.rar|222|R~3187F38923AB1D7B76BF6D2C55ADDCEE
check_files -----------------|

File OK
File ID: 4020022538
File Name: NarutoKizunaDriveSaveData.rar
size: 222575 bytes
Server ID: 958
Short host: tg
md5_hex: 41C7C90CDA303BDBBF90A053130255F6

get_download_auth ---------------|

http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=download_v1&fileid=4020022538&filename=NarutoKizunaDriveSaveData.rar

Host: rs958tl2.rapidshare.com
dlauth: 189BDE52B120B121E40E4B492293947FFB6A0EDB426797339B9045C39527BC28EFEAE1F4FAE96472AFC73963140F1485706FC8FCE1E931D4ADB4A3B0AD3F5A4E505C6225F0C4F70DB7CA37B9D9E35886189BDE52B120B121E40E4B492293947FFB6A0EDB426797339B9045C39527BC283F2A732A85F08C6E98E793B05368EB42
countdown: 0 seconds
download_file --------------|

http://rs958tl2.rapidshare.com/cgi-bin/rsapi.cgi?sub=download_v1&filename=NarutoKizunaDriveSaveData.rar&dlauth=189BDE52B120B121E40E4B492293947FFB6A0EDB426797339B9045C39527BC28EFEAE1F4FAE96472AFC73963140F1485706FC8FCE1E931D4ADB4A3B0AD3F5A4E505C6225F0C4F70DB7CA37B9D9E35886189BDE52B120B121E40E4B492293947FFB6A0EDB426797339B9045C39527BC283F2A732A85F08C6E98E793B05368EB42&fileid=4020022538
Download Completed
File Name: NarutoKizunaDriveSaveData.rar
Headers: Date: Sun, 24 Jul 2011 19:50:00 GMT
Connection: close
Content-Type: application/octet-stream
Accept-Ranges: bytes
Content-Disposition: Attachment; filename=NarutoKizunaDriveSaveData.rar
Content-Length: 222575


Es un ejemplo sencillo y nada elaborado, que no pretende ser de uso diario, para eso tenemos plowshare (http://code.google.com/p/plowshare/).

jueves 14 de julio de 2011

[Python] manejando parámetros con optparser

import sys
from optparse import make_option,OptionParser


def opciones(argv):
usage = "usage: %prog [options] Archivo"
usage +="\nManejo de parametros desde la linea de comandos"

option_list = (
make_option("-o","--opcion_1",action='store', dest='opcion_1', default ="", help="Opcion 1"),
make_option("-p","--pi",action='store', type="float", dest='pi', default = 3.1416, help="Constante Pi"),
make_option("-v",action='store_true', dest='verbose', default = True),
make_option("-q",action='store_false', dest='verbose'),
)

parser = OptionParser(prog = argv[0],
usage=usage,
option_list = option_list
)

options, args = parser.parse_args(argv[1:])

if argv[1:] == []:
parser.print_help()
elif argv[1] in ('-h','--help'):
parser.print_help()
elif args == []:
parser.print_help()
else:
print(options.opcion_1)
print(options.pi)
print(options.verbose)
print(args[0])
if __name__ == "__main__":
opciones(sys.argv[:])



ej.


$ python options.py
Usage: options.py [options] Archivo
Manejo de parametros desde la linea de comandos

Options:
-o OPCION_1, --opcion_1=OPCION_1
Opcion 1
-p PI, --pi=PI Constante Pi
-v
-q
-h, --help show this help message and exit

martes 20 de abril de 2010

nvidiactl

Después de actualizar a kubuntu 10.04 Beta 2 y reinstalar los drivers de la tarjeta nvidia como usuario normal perdí la aceleración 3D.

cuando le daba

glxinfo | grep render

me salia una línea que rezaba así

NVIDIA: could not open the device file /dev/nvidiactl (Permission denied).


solución:

Agregamos a nuestro usuario al grupo de video:

¿Porque?

si hacemos un ls -l al dispositivo veremos

ls -l /dev/nvidiactl
crw-rw---- 1 root video 195, 255 2010-04-20 08:02 /dev/nvidiactl


El dispositivo pertenece a root y al grupo de video

Si vemos el contenido de /etc/group veremos que nuestor usuario no pertenece a ese grupo

cat /etc/group | grep video
video:x:44:


Editamos el archivo para agregarnos y que quede algo como

cat /etc/group | grep video
video:x:44:usuario


Cerramos la sesión actual, nos logeamos de nuevo y ya tendremos la aceleración perdida:

glxinfo | grep render
direct rendering: Yes
OpenGL renderer string: GeForce Go 6150/PCI/SSE2
GL_NVX_conditional_render, GL_SGIS_generate_mipmap, GL_SGIS_texture_lod,


glxgears
Running synchronized to the vertical refresh. The framerate should be
approximately the same as the monitor refresh rate.
7866 frames in 5.0 seconds
9066 frames in 5.0 seconds
9059 frames in 5.0 seconds

martes 23 de febrero de 2010

webcam como camara IP en Linux (debian, ubutu)

Primero tenemos que tener instalado los siguientes paquetes, y tener configurado un servidor web (puede ser apache o cualquier otro)

sudo apt-get install webcam lib4l-0

No se crea ningún archivo de configuración por lo cual no creamos en nuestro home, o si vamos a usar la ruta principal del servidor web (/var/www) creamos el archivo webcam.conf dentro de /etc

vim .webcamrc (o con el editor de texto que uses)
vim /etc/webcam.conf (como root o anteponiendo sudo, en caso de pertenecer a los sudoers)

El archivo va contener algo como lo que se muestra enseguida

[ftp]
host = localhost
user = nobody
pass = xxxxxx
dir = /home/usuario/public_html
file = webcam.jpg
tmp = imageup.jpg
local = 1

[grab]
device = /dev/video0
width = 320
height = 240
text = "Webcam %Y-%m-%d %H:%M:%S"
delay = 0
input =sonixj
quality = 75
trigger = 180
fg_red = 255
fg_green = 255
fg_blue = 255
rotate = 2

Como mi webcam pone de cabeza las capturas, con rotate = 2 lo arreglo (1=90 grados 2= 180, etc.)

¿Como saber cual es el nombre de la webcam(input = nombrewebcam)? con v4l-info (dese la terminal)

$ v4l-info

Las partes que nos interesan es la que nos dice el nombre de la camara (sonixj) y la altura y el ancho máximo

inputs
VIDIOC_ENUMINPUT(0)
index : 0
name : "sonixj" <---Este es el valor de input =sonixj type : CAMERA audioset : 0 tuner : 0 std : 0x0 [] status : 0x0 []

y
### video4linux device info [/dev/video0] ###
general info
VIDIOCGCAP
name : "USB camera"
type : 0x1 [CAPTURE]
channels : 1
audios : 0
maxwidth : 640
maxheight : 480
minwidth : 48
minheight : 32


Ahora si lo probamos con

@anaconda-server:~$ webcam
reading config file: /home/usuario/.webcamrc
can't get rgb24 data

Ops! ¿Qué hace ese rgb24 data? si nunca lo mandé llamar.

Solución:

Se me ocurrió que se podría asociar con el LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so webcam, por lo que es la misma solución que para algunas webcam es necesaria para poderlas usar con skype

https://wiki.ubuntu.com/SkypeWebCams

$ LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so webcam
reading config file: /home/usuario/.webcamrc
video4linux webcam v1.5 - (c) 1998-2002 Gerd Knorr
grabber config:
size 320x240 [none]
input sonixj, norm (null), jpeg quality 75
rotate=2, top=0, left=0, bottom=240, right=320
write config [ftp]:
local transfer /home/usuario/public_html/imageup.jpg => /home/usuario/public_html/webcam.jpg
compare: max=50,avg=4
compare: max=255,avg=78
compare: max=8,avg=0
compare: max=24,avg=0
compare: max=17,avg=0
compare: max=33,avg=0
compare: max=29,avg=0
compare: max=35,avg=0
compare: max=34,avg=0
compare: max=42,avg=0
compare: max=39,avg=0
compare: max=46,avg=0
compare: max=52,avg=0

Ya sólo queda ver el resultado en la web, mover la camara y recargar el navedador para ver los resultados. Para probar su funcionamiento utilicé la siguiente página web.

<html>
<head>
<title>WebCam</title>
<meta http-equiv="REFRESH" content="1"></meta>
</head>
<body>
<img src="webcam.jpg"></img>
</body>
</html>


Recargo la página cada segundo.


video
webcam a 320x240


video
webcam a 640x480

miércoles 30 de diciembre de 2009

PCTel Winmodem Debian Testing

Linux anaconda-server 2.6.30-2-686 #1 SMP Fri Dec 4 00:53:20 UTC 2009 i686 GNU/Linux

1.- Creamos un directorio temporal

mkdir tmp
cd tmp

2.- Descargamos el driver de http://linmodems.technion.ac.il/pctel-linux/pctel-0.9.7-9-rht-10.tar.gz
wget http://linmodems.technion.ac.il/pctel-linux/pctel-0.9.7-9-rht-10.tar.gz

3.- Descomprimimos

tar -xvzf pctel-0.9.7-9-rht-10.tar.gz
cd pctel-0.9.7-9-rht-10


tratamos de instalar logueandonos como root (o en su defecto con sudo si es que lo tenemos habilitado para el usuario)

sudo ./setup
checking for running kernel version...2.6.30
checking for ptserial...ptserial-2.6.c
checking for gcc...4.3.4
checking for kernel gcc version...4.3.4
searching for kernel includes...found at /lib/modules/2.6.30-2-686/build/include
checking for autoconf.h.../lib/modules/2.6.30-2-686/build/include/linux/autoconf.h
checking for asm/mach-default...** error <


Después de andar busque y busque por internet no encontré nada, así que me dí a la tarea de ver el directorio de los source y headers del kernel. Para mi sorpresa el mach-default no existe, así que procedí a modificar el archivo configure dentro del src

vim src/configure

Ubicamos la línea siguente (línea 424)
echo -n "checking for asm/mach-default..."
kernel_inc2=${kernel_inc}
if [ ! -d ${kernel_inc}/asm/mach-default ]
then
# SuSE 9.3 doesn't have 'asm' under the build directory, so revert to
# /usr/src/linux
if [ -d /usr/src/linux/include/asm/mach-default ]
then
kernel_inc2=/usr/src/linux/include
else
echo "** error"
echo include/asm/mach-default directory could not be found
echo you probably need to configure your kernel, please read the FAQ
echo about no include/asm/mach-default directory.
exit 1
fi
fi
echo "yes"
extra_includes=-I${kernel_inc2}/asm/mach-default



y las modificamos para que quede


echo -n "checking for asm..."
kernel_inc2=${kernel_inc}
if [ ! -d ${kernel_inc}/asm ]
then
# SuSE 9.3 doesn't have 'asm' under the build directory, so revert to
# /usr/src/linux
if [ -d /usr/src/linux/include/asm/mach-default ]
then
kernel_inc2=/usr/src/linux/include
else
echo "** error"
echo include/asm directory could not be found
echo you probably need to configure your kernel, please read the FAQ
echo about no include/asm/mach-default directory.
exit 1
fi
fi
echo "yes"
extra_includes=-I${kernel_inc2}/asm


Quitamos todo lo referente a /mach-default (líneas 424,426 y 442)


~/tmp/pctel-0.9.7-9-rht-10$ sudo ./setup
checking for running kernel version...2.6.30
checking for ptserial...ptserial-2.6.c
checking for gcc...4.3.4
checking for kernel gcc version...4.3.4
searching for kernel includes...found at /lib/modules/2.6.30-2-686/build/include
checking for autoconf.h.../lib/modules/2.6.30-2-686/build/include/linux/autoconf.h
checking for asm/mach-default...yes
checking for kernel version in utsrelease.h...UTS_RELEASE is 2.6.30-2-686
checking type of tty_struct.count...int
checking for presence of udev...present (kernel version 2.6.13 or later)
detecting your modem...found. Your modem is a cm8738 type modem.

compilation done

installation done

modem activated

~/tmp/pctel-0.9.7-9-rht-10$ ls -l /dev/modem
lrwxrwxrwx 1 root root 11 dic 30 21:49 /dev/modem -> ttyS_PCTEL0

Por lo que se ve ya esta funcionando, para probarlo

sudo minicom -s

con las flechas nos movemos hasta configuración de la puerta serial y le damos enter

Presionamos A para modificar la ruta del dispositivo colocando /dev/modem

Le damos un segundo enter para regresar al menu anterior y con la flechas buscamos Salir y le damos enter, despues de esto vamos a ver que el minicom consulta al modem.

Welcome to minicom 2.4-rc1

OPCIONES: I18n
Compilado en Nov 23 2009, 17:11:14.
Port /dev/modem

Presione CTRL-A Z para obtener ayuda sobre teclas especiales

AT S7=45 S0=0 L1 V1 X4 &c1 E1 Q0
OK


Si aparece algo como lo de arriba, quiere decir que si esta trabajando el modem.