import sys
sys.version
sys.version_info

"""
Explanation: Cargue de datos SciDB
1) Verificar Prerequisitos
Python
SciDB-Py requires Python 2.6-2.7 or 3.3
End of explanation
"""


import numpy as np
np.__version__

"""
Explanation: NumPy
tested with version 1.9 (1.13.1)
End of explanation
"""


import requests
requests.__version__

"""
Explanation: Requests
tested with version 2.7 (2.18.1) Required for using the Shim interface to SciDB.
End of explanation
"""


import pandas as pd
pd.__version__

"""
Explanation: Pandas (optional)
tested with version 0.15. (0.20.3) Required only for importing/exporting SciDB arrays as Pandas Dataframe objects.
End of explanation
"""


import scipy
scipy.__version__

"""
Explanation: SciPy (optional)
tested with versions 0.10-0.12. (0.19.0) Required only for importing/exporting SciDB arrays as SciPy sparse matrices.
End of explanation
"""


import scidbpy
scidbpy.__version__

from scidbpy import connect

"""
Explanation: 2) Importar scidbpy
pip install git+http://github.com/paradigm4/scidb-py.git@devel
End of explanation
"""


sdb = connect('http://localhost:8080')

"""
Explanation: conectarse al servidor de Base de datos
End of explanation
"""


import urllib.request  # urllib2 in python2 the lib that handles the url stuff
target_url = "https://www.physionet.org/physiobank/database/mimic2wdb/matched/RECORDS-waveforms"
data = urllib.request.urlopen(target_url) # it's a file like object and works just like a file

lines = data.readlines();
line = str(lines[0])

"""
Explanation: 3) Leer archivo con cada una de las ondas
End of explanation
"""


carpeta,onda = line.replace('b\'','').replace('\'','').replace('\\n','').split("/")
onda

"""
Explanation: Quitarle caracteres especiales
End of explanation
"""


import wfdb

sig, fields = wfdb.srdsamp(onda,pbdir='mimic3wdb/matched/'+carpeta) #, sampfrom=11000

print(sig)
print("signame: " + str(fields['signame']))
print("units: " + str(fields['units']))
print("fs: " + str(fields['fs']))
print("comments: " + str(fields['comments']))
print("fields: " + str(fields))

"""
Explanation: 4) Importar WFDB para conectarse a physionet
End of explanation
"""


signalII = None
try:
    signalII = fields['signame'].index("II")
except ValueError:
    print("List does not contain value")
if(signalII!=None):
    print("List contain value")

"""
Explanation: Busca la ubicacion de la señal tipo II
End of explanation
"""


array = wfdb.processing.normalize(x=sig[:, signalII], lb=-2, ub=2)
arrayNun = array[~numpy.isnan(array)]
arrayNun = numpy.trim_zeros(arrayNun)
arrayNun

"""
Explanation: Normaliza la señal y le quita los valores en null
End of explanation
"""


ondaName = onda.replace("-", "_")
if arrayNun.size>0 :
    sdb.input(upload_data=array).store(ondaName,gc=False)
#    sdb.iquery("store(input(<x:int64>[i], '{fn}', 0, '{fmt}'), "+ondaName+")", upload_data=array)

"""
Explanation: Cambiar los guiones "-" por raya al piso "_" porque por algun motivo SciDB tiene problemas con estos caracteres
Si el arreglo sin valores nulos no queda vacio lo sube al SciDB
End of explanation
"""


dir(sdb.arrays)

"""
Explanation: lista de los arreglos que actualmente se encuentran en SciDB
End of explanation
"""


myArray = sdb.iquery('scan(s00600_3152_10_19_18_13)', fetch=True, as_dataframe=True)

"""
Explanation: Obtiene el arreglo s00515_3148_06_10_10_44 de SciDB
End of explanation
"""


import matplotlib.pyplot as plt
simpleArray = myArray["x"];
simpleArray.plot()
plt.show()

simpleArray

"""
Explanation: Imprime el contenido del arreglo
End of explanation
"""


file = open("readedWaves.txt","r")    
arrays = dir(sdb.arrays)
filelines = file.readlines()
arrays.extend([w.replace('\n','') for w in filelines])
#type(arrays)
arrays

"""
Explanation: Lee el contenido del archivo donde se encuentran las ondas ya leidas
End of explanation
"""


