class MDFA(QMainWindow): def __init__(self): super().__init__() self.initUI() #%% def cargarSenial(self): self.aux = False self.list3.clear() self.list_MDFA.clear() self.plot1.clear() self.nombreSenial = QFileDialog.getOpenFileNames( None, 'Open file(s)', '/home') self.rutas = self.nombreSenial[0] self.dialog = Dialog( str(len(self.rutas)) + ' Files(s) loaded', 'open.png') self.dialog.show() self.list3.addItem('') for i in range(len(self.rutas)): names = str.split(self.rutas[i], "/") t = len(names) nombre = names[t - 1] self.list3.addItem(nombre) if (len(self.rutas) == 0): self.lbl_num_files.setStyleSheet("color : red; ") self.lbl_num_files.setText("Files loaded: " + str(len(self.rutas))) else: self.lbl_num_files.setStyleSheet("color : blue; ") self.lbl_num_files.setText("Files loaded: " + str(len(self.rutas))) self.aux = True self.btnMDFA.setEnabled(True) #%% def plots(self): if (self.aux == True): self.plot1.clear() i = self.list3.currentIndex() - 1 if (len(self.rutas) != 0): data = pd.read_csv(self.rutas[i], sep='\t', header=None) lineas = data.shape[1] if (lineas == 1): self.y = np.asarray(data[0]) elif (lineas == 2): self.y = np.asarray(data[1]) self.plot1.setLabel('bottom', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('bottom').setPen( pg.mkPen(color='k', width=1)) # Y1 axis self.plot1.setLabel('left', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('left').setPen(pg.mkPen(color='k', width=1)) names = str.split(self.rutas[i], "/") t = len(names) nombre = names[t - 1] self.plot1.setTitle(nombre) self.plot1.plot(self.y, pen='k') #%% def print_val(self): print(str(self.plots.checkedId())) #%% def MDFA(self): self.t_inicial = time() self.plot1.clear() qmax = int(self.txtQmax.text()) qmin = int(self.txtQmin.text()) dq = float(self.txtdQ.text()) q = np.arange(qmin, qmax, dq) m = int(self.txtm.text()) xn = np.arange(0, 135, 1) func = np.vectorize(lambda x: int(10.1 * math.exp(0.0866 * x))) n = func(xn) self.alphas = np.transpose(np.zeros((len(q) - 1, len(self.rutas)))) self.fespectros = np.transpose(np.zeros((len(q) - 1, len(self.rutas)))) self.qs = np.transpose(np.zeros((len(q) - 1, len(self.rutas)))) self.taus = np.transpose(np.zeros((len(q) - 1, len(self.rutas)))) self.hches = np.transpose(np.zeros((len(q) - 1, len(self.rutas)))) for i in range(len(self.rutas)): R = [] self.y = np.asarray( pd.read_csv(self.rutas[i], sep='\t', header=None)) val = len(self.y) / 4 s = n[n < val] if (self.int_state == 0): Y = np.cumsum((self.y - np.mean(self.y))) elif (self.int_state == 1): Y = np.cumsum((self.y - np.mean(self.y))) Y = np.cumsum((Y - np.mean(Y))) YRev = Y N = len(Y) q = np.arange(qmin, qmax, dq) Fq = np.zeros((len(s), len(q))) znumb = np.where((q >= -0.1) & (q <= 0.1))[0][-1] - 1 for ns in range(len(s)): Ns = int(N / s[ns]) Var = np.zeros((Ns, len(q))) Varr = np.zeros((Ns, len(q))) for v in range(Ns): SegNumb = np.arange(((v + 1) - 1) * s[ns], (v + 1) * s[ns]) Seg = Y[SegNumb] SegRev = YRev[SegNumb] poly = np.polyfit(SegNumb, Seg, m) polyr = np.polyfit(SegNumb, SegRev, m) fit = np.polyval(poly, SegNumb) fitr = np.polyval(polyr, SegNumb) myfunc(q, Var, Varr, v, Seg, fit, s, ns, SegRev, fitr) Var = np.transpose(Var) Varr = np.transpose(Varr) for nq in range(len(q)): Fq[ns][nq] = pow( (sum(Var[:][nq]) + sum(Varr[:][nq])) / (2 * Ns), 1 / q[nq]) Fq[ns][znumb] = (Fq[ns][znumb - 1] + Fq[ns][znumb + 1]) / 2 del (Var, Varr) logFq = np.log10(Fq) logFq = np.transpose(logFq) Hq = np.zeros(len(q)) fes = [] eses = [] for nq in range(len(q)): f = np.transpose(logFq[:][nq]) fes.append(f) eses.append(np.log10(s)) P = np.polyfit(np.log10(s), logFq[:][nq], 1) if (self.int_state == 0): Hq[nq] = P[0] elif (self.int_state == 1): Hq[nq] = P[0] - 1 ajuste = [] for w in range(len(s)): ajuste.append((Hq[nq] + 1) * np.log10(s[w]) + P[1]) rcuadrada = round(r2_score(f, ajuste), 4) R.append(rcuadrada) # fes = pd.DataFrame(fes) # fes.to_csv(self.rutas[i]+'F(sq).txt', sep = '\t', index = False, header = None) # eses = pd.DataFrame(eses) # eses.to_csv(self.rutas[i]+'s.txt', sep = '\t', index = False, header = None) # ajustes = pd.DataFrame(R) # ajustes.to_csv(self.rutas[i]+'R_cuadrada.txt', sep = '\t', index = False, header = None) t = q * Hq - 1 α = np.diff(t) / dq Hq = Hq[0:len(Hq) - 1] t = t[0:len(t) - 1] q = q[0:len(q) - 1] ####### α y f(α) ############################################# fα = np.zeros(len(t)) fα = q * α - t self.fα = fα self.α = α self.t = t self.Hq = Hq self.q = q self.btnMDFA.setEnabled(False) self.t_final = time() self.tiempo = round(float(self.t_final - self.t_inicial), 4) self.txttime.setText(str(self.tiempo)) self.alphas[:][i] = self.α self.fespectros[:][i] = self.fα self.taus[:][i] = self.t self.hches[:][i] = self.Hq self.qs[:][i] = self.q self.list_MDFA.addItem('') for i in range(len(self.rutas)): names = str.split(self.rutas[i], "/") t = len(names) nombre = names[t - 1] self.list_MDFA.addItem(nombre) self.alphas = np.transpose(self.alphas) self.fespectros = np.transpose(self.fespectros) self.taus = np.transpose(self.taus) self.hches = np.transpose(self.hches) self.qs = np.transpose(self.qs) self.dialogo_done = Dialog('Done!!', 'Icons\listo.png') self.dialogo_done.show() #%% def plots_MDFA(self): self.alphas2 = np.transpose(self.alphas) self.fespectros2 = np.transpose(self.fespectros) self.taus2 = np.transpose(self.taus) self.hches2 = np.transpose(self.hches) self.qs2 = np.transpose(self.qs) op = self.plots.checkedId() if (op == -2): if (self.aux == True): self.plot1.clear() i = self.list_MDFA.currentIndex() - 1 if (len(self.rutas) != 0): self.plot1.setLabel('bottom', 'α', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('bottom').setPen( pg.mkPen(color='k', width=1)) # Y1 axis self.plot1.setLabel('left', 'f(α)', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('left').setPen( pg.mkPen(color='k', width=1)) names = str.split(self.rutas[i], "/") t = len(names) nombre = names[t - 1] self.plot1.setTitle(nombre) self.plot1.plot(self.alphas2[i], self.fespectros2[i], pen='r', symbol='o', symbolSize=10) elif (op == -3): if (self.aux == True): self.plot1.clear() i = self.list_MDFA.currentIndex() - 1 if (len(self.rutas) != 0): self.plot1.setLabel('bottom', 'q', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('bottom').setPen( pg.mkPen(color='k', width=1)) # Y1 axis self.plot1.setLabel('left', 'τ(q)', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('left').setPen( pg.mkPen(color='k', width=1)) names = str.split(self.rutas[i], "/") t = len(names) nombre = names[t - 1] self.plot1.setTitle(nombre) self.plot1.plot(self.qs2[i], self.taus2[i], pen='r', symbol='o', symbolSize=10) elif (op == -4): if (self.aux == True): self.plot1.clear() i = self.list_MDFA.currentIndex() - 1 if (len(self.rutas) != 0): self.plot1.setLabel('bottom', 'q', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('bottom').setPen( pg.mkPen(color='k', width=1)) self.plot1.setLabel('left', 'h(q)', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('left').setPen( pg.mkPen(color='k', width=1)) names = str.split(self.rutas[i], "/") t = len(names) nombre = names[t - 1] self.plot1.setTitle(nombre) self.plot1.plot(self.qs2[i], self.hches2[i], pen='r', symbol='o', symbolSize=10) #%% def saveFile(self): nom = QFileDialog.getSaveFileName(None, 'Saving Data in Current Plot') writer = pd.ExcelWriter(nom[0] + ".xlsx") a = pd.DataFrame(self.alphas) a.to_excel(writer, 'Atable', index=False, header=None) f = pd.DataFrame(self.fespectros) f.to_excel(writer, 'Ftable', index=False, header=None) t = pd.DataFrame(self.taus) t.to_excel(writer, 'Ttable', index=False, header=None) H = pd.DataFrame(self.hches) H.to_excel(writer, 'Htable', index=False, header=None) q = pd.DataFrame(self.qs) q.to_excel(writer, 'Qtable', index=False, header=None) writer.save() #%% def state_check(self, state): if (state == Qt.Checked): self.int_state = 1 else: self.int_state = 0 #%% def initUI(self): pg.setConfigOption('background', 'w') self.setWindowTitle('Multifractal Detrended Analysis Fluctuation') self.setWindowIcon(QIcon("Icons\multifractal.ico")) ########Variables Globales #################################################### ############################################################################### self.rutas = None self.nombreSenial = '' self.int_state = 0 contain = QSplitter(Qt.Horizontal) botones = QVBoxLayout() graficos = QVBoxLayout() results1 = QFormLayout() results2 = QFormLayout() results3 = QFormLayout() group_box_files = QGroupBox("Load file(s)") group_box_settings = QGroupBox("Settings") group_box_plots = QGroupBox("Plots") ################################################################# ## Elementos del layout botones ################################################################# font_size = 'font-size: 18px' self.btnLoadSig = QPushButton('Load signal') self.btnLoadSig.clicked.connect(self.cargarSenial) self.btnLoadSig.setStyleSheet(font_size) self.btnLoadSig.setEnabled(True) self.btnMDFA = QPushButton('MFDFA') self.btnMDFA.clicked.connect(self.MDFA) self.btnMDFA.setStyleSheet(font_size) self.btnMDFA.setEnabled(False) self.btnSavechar = QPushButton('Save data') self.btnSavechar.clicked.connect(self.saveFile) self.btnSavechar.setStyleSheet(font_size) self.txtQmax = QLineEdit('5') self.txtQmax.setEnabled(True) self.txtQmax.setStyleSheet(font_size) self.txtQmin = QLineEdit('-5') self.txtQmin.setEnabled(True) self.txtQmin.setStyleSheet(font_size) self.txtdQ = QLineEdit('0.1') self.txtdQ.setEnabled(True) self.txtdQ.setStyleSheet(font_size) self.txtm = QLineEdit('1') self.txtm.setEnabled(True) self.txtm.setStyleSheet(font_size) lbl_check1 = QLabel("Nonstationary ts:") lbl_check1.setStyleSheet(font_size) self.check1 = QCheckBox() self.check1.stateChanged.connect(self.state_check) self.lbl_num_files = QLabel("Files loaded: ") self.lbl_num_files.setStyleSheet(font_size) lbl_file = QLabel("File: ") lbl_file.setStyleSheet("font-size: 18px") self.list3 = QComboBox() self.list3.currentIndexChanged.connect(self.plots) self.lbltime = QLabel("Exe. time:") self.lbltime.setStyleSheet(font_size) self.txttime = QLabel("") self.txttime.setStyleSheet(font_size) b1 = QRadioButton("f(α) Vs α") b1.setStyleSheet(font_size) b2 = QRadioButton("τ(q) Vs q") b2.setStyleSheet(font_size) b3 = QRadioButton("h(q) Vs q") b3.setStyleSheet(font_size) self.plots = QButtonGroup() self.plots.addButton(b1) self.plots.addButton(b2) self.plots.addButton(b3) self.plots.exclusive() self.plots.buttonClicked.connect(self.print_val) lbl_MDFA = QLabel("File: ") lbl_MDFA.setStyleSheet(font_size) self.list_MDFA = QComboBox() self.list_MDFA.currentIndexChanged.connect(self.plots_MDFA) ################################################################# ## Elementos del layout graficos ################################################################# self.plot1 = pg.PlotWidget() self.plot1.setLabel('bottom', " ", color='k', **{'font-size': '20pt'}) self.plot1.getAxis('bottom').setPen(pg.mkPen(color='k', width=1)) # Y1 axis self.plot1.setLabel('left', " ", color='k', **{'font-size': '20pt'}) self.plot1.getAxis('left').setPen(pg.mkPen(color='k', width=1)) self.plot1.showGrid(1, 1, 0.2) ################################################################# ## Colocar elementos en layout botones ################################################################# results1.addRow(self.btnLoadSig) results1.addRow(self.lbl_num_files) results1.addRow(lbl_file, self.list3) group_box_files.setLayout(results1) results2.addRow(lbl_check1, self.check1) results2.addRow('Q+:', self.txtQmax) results2.addRow('Q-:', self.txtQmin) results2.addRow('dQ:', self.txtdQ) results2.addRow('m:', self.txtm) results2.addRow(self.lbltime, self.txttime) group_box_settings.setLayout(results2) results3.addRow(lbl_MDFA, self.list_MDFA) results3.addRow(b1) results3.addRow(b2) results3.addRow(b3) group_box_plots.setLayout(results3) botones.addWidget(group_box_files) botones.addWidget(group_box_settings) botones.addWidget(group_box_plots) botones.addWidget(self.btnMDFA) botones.addWidget(self.btnSavechar) ################################################################# ## Colocar elementos en layout graficos ################################################################# graficos.addWidget(self.plot1) bot = QWidget() bot.setLayout(botones) gra = QWidget() gra.setLayout(graficos) contain.addWidget(bot) contain.addWidget(gra) self.setCentralWidget(contain)
class Principal(QMainWindow): def __init__(self): super().__init__() self.initUI() def DFA_boton(self): self.DFAWindow = DFA() self.DFAWindow.show() def MFDFA_boton(self): self.MFDFAWindow = MDFA() self.MFDFAWindow.show() #%% def cargarSenial(self): self.txt_total.setText('') self.lbl_inicio.setText('') self.lbl_final.setText('') self.seg_pos.clear() self.btnIniciar.setEnabled(True) self.plot1.clear() self.nombreSenial = QFileDialog.getOpenFileName( None, 'Open file', '/home') if (len(self.nombreSenial[0]) != 0): print(self.nombreSenial) datos = read_csv(self.nombreSenial[0], sep='\t', header=None) lineas = datos.shape[1] if (lineas == 1): self.y = asarray(datos[0]) self.y_auto = datos[0] elif (lineas == 2): self.y = asarray(datos[1]) self.y_auto = datos[1] self.plot1.setLabel('bottom', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('bottom').setPen(pg.mkPen(color='k', width=1)) # Y1 axis self.plot1.setLabel('left', color='k', **{'font-size': '14pt'}) self.plot1.getAxis('left').setPen(pg.mkPen(color='k', width=1)) names = str.split(self.nombreSenial[0], "/") t = len(names) self.nombre = names[t - 1] self.plot1.setTitle(self.nombre) self.plot1.plot(self.y, pen='k') self.btnauto.setEnabled(True) #%% def localizacion(self): if (self.aux == True): i = self.seg_pos.currentIndex() if (i == 0): self.lbl_inicio.setText('ini') self.lbl_final.setText('end') else: self.lbl_inicio.setText(str(self.inicio[i - 1])) self.lbl_final.setText(str(self.final[i - 1])) #%% def colocar(self): inicio = int(self.lbl_inicio.text()) final = int(self.lbl_final.text()) if (self.aux2 == True): self.lr.setRegion([inicio, final]) #%% def autoseg(self): self.aux == False self.inicio = [] self.final = [] self.seg_pos.clear() self.seg_pos.addItem('') def group_consecutives(vals, step=1): run = [] result = [run] expect = None for v in vals: if (v == expect) or (expect is None): run.append(v) else: run = [v] result.append(run) expect = v + step return result if (len(self.txt_umbral.text()) != 0 and len(self.txt_basal.text()) != 0 and len(self.txt_ancho.text()) != 0 and len(self.txt_separacion.text()) != 0): umbral = float(self.txt_umbral.text()) basal = float(self.txt_basal.text()) ancho = float(self.txt_ancho.text()) separacion = float(self.txt_separacion.text()) y = self.y_auto loc_x = [] for i in range(len(y)): if (y[i] > umbral): loc_x.append(i) pico_range = group_consecutives(loc_x) loc_x1 = [] for i in range(len(pico_range)): aux = pico_range[i] pico = list(y[aux]) pos_aux = pico.index(max(pico)) loc_x1.append(aux[pos_aux]) loc = [] loc.append(loc_x[0]) for i in range(1, len(loc_x1)): if (loc_x1[i] - loc_x1[i - 1] > ancho): loc.append(loc_x1[i]) ini = [] end = [] for i in range(len(loc)): if (loc[0] > 2 * separacion): x_ini = arange(loc[i] - separacion, loc[i]) y_ini = y[x_ini] x_end = arange(loc[i], loc[i] + separacion) y_end = y[x_end] donde_ini = where(y_ini <= min(y_ini) + basal)[0] donde_fin = where(y_end <= min(y_ini) + basal)[0] if (len(donde_fin) != 0 and len(donde_ini) != 0): ini.append(x_ini[max(donde_ini)]) end.append(x_end[min(donde_fin)]) elif (loc[0] < separacion): x_ini = arange(0, loc[i]) y_ini = y[x_ini] x_end = arange(loc[i], loc[i] + separacion) y_end = y[x_end] donde_ini = where(y_ini <= min(y_ini) + basal)[0] donde_fin = where(y_end <= min(y_ini) + basal)[0] if (len(donde_fin) != 0 and len(donde_ini) != 0): ini.append(x_ini[max(donde_ini)]) end.append(x_end[min(donde_fin)]) elif (len(y) - (loc[len(loc) - 1] + separacion) < 0): x_ini = arange(loc[i] - separacion, loc[i]) y_ini = y[x_ini] x_end = arange(loc[i], len(y)) y_end = y[x_end] donde_ini = where(y_ini <= min(y_ini) + basal)[0] donde_fin = where(y_end <= min(y_ini) + basal)[0] if (len(donde_fin) != 0): ini.append(x_ini[max(donde_ini)]) end.append(x_end[min(donde_fin)]) ini = list(set(ini)) end = list(set(end)) ini = list(sorted(ini)) end = list(sorted(end)) names = str.split(self.nombreSenial[0], self.nombre) nam = str.split(self.nombre, '.') for i in range(len(ini)): self.seg_pos.addItem(str(i + 1)) self.inicio.append(int(ini[i])) self.final.append(int(end[i])) data = DataFrame(y[int(ini[i]):int(end[i])]) data.to_csv(names[0] + nam[0] + '_seg_' + str(i + 1) + '.txt', sep='\t', header=None, index=False) self.aux = True self.txt_total.setText(str(len(self.inicio))) self.btn_loc.setEnabled(True) self.btnauto.setEnabled(False) elif (len(self.txt_umbral.text()) != 0 or len(self.txt_basal.text()) != 0 or len(self.txt_ancho.text()) != 0 or len(self.txt_separacion.text()) != 0): self.dialogo_error = Dialog('Error: Missing value ', 'Icons\error.png') self.dialogo_error.show() elif (len(self.txt_umbral.text()) != 0 and len(self.txt_basal.text()) != 0 and len(self.txt_ancho.text()) != 0 and len(self.txt_separacion.text()) != 0): self.dialogo_error = Dialog('Error: Missing value ', 'Icons\error.png') self.dialogo_error.show() #%% def enabledButtons(self): self.btnAdd.setEnabled(True) self.txtns.setEnabled(True) self.plot1.addItem(self.lr) self.btnIniciar.setEnabled(False) self.aux2 = True #%% def addInterval(self): duracion = [] contador = 0 if (len(self.txtns.text()) == 0): self.dialogo_error = Dialog( 'A segment number must be type() = int ', 'Icons\error.png') self.dialogo_error.show() else: contador = int(self.txtns.text()) regionSelected = self.lr.getRegion() ini = int(regionSelected[0]) fin = int(regionSelected[1]) duracion.append(self.y[ini:fin]) duracion = transpose(duracion) df = DataFrame(duracion) names = str.split(self.nombreSenial[0], self.nombre) nam = str.split(self.nombre, '.') df.to_csv(names[0] + nam[0] + '_seg_' + str(contador) + '.txt', index=False, sep='\t', header=None, mode='w') duracion = [] linea1 = pg.InfiniteLine(pos=ini, angle=90, movable=False) linea2 = pg.InfiniteLine(pos=fin, angle=90, movable=False) self.plot1.addItem(linea1) self.plot1.addItem(linea2) self.lr.setRegion([fin, fin + 6000]) #%% def reboot(self): self.contador = 0 self.valorContador.setText("") #%% def initUI(self): pg.setConfigOption('background', 'w') self.setWindowTitle('PyMFDFA') self.setWindowIcon(QIcon("Icons\multifractal.ico")) ################################################################## ### Barra de Herramientas ################################################################## self.barra_estado = QStatusBar() self.setStatusBar(self.barra_estado) barra_herr = QToolBar("Toolbar") self.addToolBar(barra_herr) barra_menu = QMenuBar() self.setMenuBar(barra_menu) abrir_action = QAction(QIcon('Icons/open.png'), 'Load Signal', self) abrir_action.setToolTip('Load Signal') abrir_action.setStatusTip('Load signal to segment') abrir_action.triggered.connect(self.cargarSenial) barra_herr.addAction(abrir_action) barra_herr.addSeparator() DFA_action = QAction(QIcon('Icons/DFA.ico'), 'Detrended Analysis Fluctuation', self) DFA_action.setToolTip('Detrended Analysis Fluctuation') DFA_action.setStatusTip('Detrended Analysis Fluctuation') DFA_action.triggered.connect(self.DFA_boton) barra_herr.addAction(DFA_action) MDFA_action = QAction(QIcon('Icons/multifractal.ico'), 'Multifractal Detrended Analysis Fluctuation', self) MDFA_action.setToolTip('Multifractal Detrended Analysis Fluctuation') MDFA_action.setStatusTip('Multifractal Detrended Analysis Fluctuation') MDFA_action.triggered.connect(self.MFDFA_boton) barra_herr.addAction(MDFA_action) ################################################################# ## Definición de variables globales ################################################################# self.nombreSenial = '' self.y = [] self.aux = 0 self.aux2 = False ################################################################# ## Definición de elementos contenedores ################################################################# contain = QSplitter(Qt.Horizontal) graficos = QVBoxLayout() botones = QVBoxLayout() results2 = QFormLayout() results3 = QFormLayout() results = QFormLayout() ################################################################# ## Elementos del layout botones ################################################################# #Region for segment in signal self.lr = pg.LinearRegionItem([0, 6000]) btnLoadSig = QPushButton('Load signal') btnLoadSig.clicked.connect(self.cargarSenial) btnLoadSig.setStyleSheet("font-size: 18px") self.btnIniciar = QPushButton('Start segmentation') self.btnIniciar.clicked.connect(self.enabledButtons) self.btnIniciar.setEnabled(False) self.btnIniciar.setStyleSheet("font-size: 18px") self.btnAdd = QPushButton('Add segment') self.btnAdd.clicked.connect(self.addInterval) self.btnAdd.setEnabled(False) self.btnAdd.setStyleSheet("font-size: 18px") txtnumseg = QLabel("Segment num:") txtnumseg.setStyleSheet("font-size: 18px") validator = QIntValidator() validator.setRange(100, 999) self.txtns = QLineEdit() self.txtns.setValidator(validator) self.txtns.setEnabled(False) lbl_umbral = QLabel('Upper threshold:') lbl_umbral.setStyleSheet("font-size: 18px") self.txt_umbral = QLineEdit() lbl_basal = QLabel('Lower threshold') lbl_basal.setStyleSheet("font-size: 18px") self.txt_basal = QLineEdit() lbl_ancho = QLabel('Segment width ') lbl_ancho.setStyleSheet("font-size: 18px") self.txt_ancho = QLineEdit() lbl_separacion = QLabel('Distance:') lbl_separacion.setStyleSheet("font-size: 18px") self.txt_separacion = QLineEdit() self.btnauto = QPushButton('Start auto-segmentation') self.btnauto.clicked.connect(self.autoseg) self.btnauto.setStyleSheet("font-size: 18px") self.btnauto.setEnabled(False) lbl_total = QLabel('# of segments:') lbl_total.setStyleSheet('font-size: 18px') self.txt_total = QLabel() self.txt_total.setStyleSheet('font-size: 18px') lbl_file = QLabel('Segment: ') lbl_file.setStyleSheet("font-size: 18px") self.seg_pos = QComboBox() self.seg_pos.currentIndexChanged.connect(self.localizacion) self.lbl_inicio = QLabel() self.lbl_inicio.setStyleSheet("font-size: 18px") self.lbl_final = QLabel() self.lbl_final.setStyleSheet("font-size: 18px") self.btn_loc = QPushButton('Find segment') self.btn_loc.setStyleSheet("font-size: 18px") self.btn_loc.clicked.connect(self.colocar) self.btn_loc.setEnabled(False) lbl_autoseg = QLabel("Auto-Segmentation") lbl_autoseg.setStyleSheet("font-size: 20px") ################################################################# ## Elementos del layout graficos ################################################################# self.plot1 = pg.PlotWidget() self.plot1.setLabel('bottom', color='k', **{'font-size': '16pt'}) self.plot1.getAxis('bottom').setPen(pg.mkPen(color='k', width=1)) self.plot1.setLabel('left', color='k', **{'font-size': '16pt'}) self.plot1.getAxis('left').setPen(pg.mkPen(color='k', width=1)) self.plot1.showGrid(1, 1, 0.2) graficos.addWidget(self.plot1) ################################################################# ## Colocar elementos en layout botones ################################################################# botones.addWidget(btnLoadSig) botones.addWidget(self.btnIniciar) results.addRow(txtnumseg, self.txtns) results.addRow(self.btnAdd) botones.addLayout(results) results2.addRow(lbl_autoseg) results2.addRow(lbl_umbral, self.txt_umbral) results2.addRow(lbl_basal, self.txt_basal) results2.addRow(lbl_ancho, self.txt_ancho) results2.addRow(lbl_separacion, self.txt_separacion) botones.addLayout(results2) botones.addWidget(self.btnauto) results3.addRow(lbl_total, self.txt_total) results3.addRow(lbl_file, self.seg_pos) results3.addRow(self.lbl_inicio, self.lbl_final) results3.addRow(self.btn_loc) botones.addLayout(results3) ################################################################# ## Colocar elementos en la ventana ################################################################# bot = QWidget() bot.setLayout(botones) gra = QWidget() gra.setLayout(graficos) contain.addWidget(gra) contain.addWidget(bot) self.setCentralWidget(contain) self.show()
class DFA(QMainWindow): def __init__(self): super(DFA,self).__init__() self.initUI() #%% def cargarSenial1(self): self.aux = False self.list3.clear() self.plot1.clear() self.list_DFA.clear() self.txth1.clear() self.txtr1.clear() self.nombreSenial= QFileDialog.getOpenFileNames(None, 'Open file(s)', '/home') self.rutas = self.nombreSenial[0] self.dialog = Dialog(str(len(self.rutas))+' Files(s) loaded','open.png') self.dialog.show() self.list3.addItem('') for i in range(len(self.rutas)): names=str.split(self.rutas[i],"/") t=len(names) nombre= names[t-1] self.list3.addItem(nombre) if(len(self.rutas)==0): self.btnDFA1.setEnabled(False) self.lbl_num_files.setStyleSheet("color : red; ") self.lbl_num_files.setText("Files loaded: "+str(len(self.rutas))) else: self.lbl_num_files.setStyleSheet("color : blue; ") self.lbl_num_files.setText("Files loaded: "+str(len(self.rutas))) self.aux = True self.btnDFA1.setEnabled(True) self.txtm1.setEnabled(True) #%% def DFA1(self): self.txth1.setEnabled(True) self.plot1.clear() self.list_DFA.clear() self.h = [] self.fn = [] self.s = [] self.R = [] order = int(self.txtm1.text()) nombres_archivos = [] for i in range(len(self.rutas)): data = read_csv(self.rutas[i], sep='\t', header = None ) lineas= data.shape[1] if(lineas == 1): self.y1 = asarray(data[0]) elif(lineas == 2): self.y1 = asarray(data[1]) names = str.split(self.rutas[i],"/") t = len(names) nombre= names[t-1] names = str.split(self.rutas[i],nombre) nam = str.split(nombre,'.') RUTA = names[0] + '/DFA/' path = Path(RUTA) path.mkdir(parents = True,exist_ok = True) xn = arange(0, 135, 1) func = vectorize(lambda x: int(10.1*exp(0.0866 * x))) n = func(xn) self.s1 = [] for j in range(len(n)): if(n[j]<=int(len(self.y1)/4)): self.s1.append(n[j]) self.fn1 = zeros(len(self.s1)) for l in range(len(self.s1)): n_1= self.s1[l] N = len(self.y1) n = int(N/n_1) N1 = int(n_1*n) y = zeros((N)) Yn = zeros((N)) fitcoef = zeros((n,order+1)) y = cumsum((self.y1-mean(self.y1))) x_aux = zeros(int(n_1)) for i in range(int(n_1)): x_aux[i] = i for j in range(n): y_aux = y[int(j*n_1):int(j*n_1+n_1)] fitcoef[j] = polyfit(x_aux,y_aux,order) for j in range(n): Yn[int(j*n_1):int(j*n_1+n_1)] = polyval(fitcoef[j],x_aux) sum1 = sum(pow(transpose(y)-Yn,2))/N1 self.fn1[l] = sqrt(sum1) self.h1 = round(polyfit(log10(self.s1), log10(self.fn1),1)[0],4) self.fn.append(log10(self.fn1)) self.s.append(log10(self.s1)) self.h.append(self.h1) plt.figure() plt.title(nam[0], fontsize = 15) plt.grid(True) plt.plot(self.y1) plt.savefig(RUTA + nam[0]+' Serie.png', dpi = 300) plt.close() datos = [] datos.append(log10(self.s1)) datos.append(log10(self.fn1)) datos = transpose(asarray(datos)) datos = DataFrame(datos) datos.to_csv(RUTA + nam[0]+' ln(F) vs ln(n).txt',header = None, index = False, sep='\t') rutaSave = RUTA nombres_archivos.append(nam[0]+':') if(len(self.rutas)!=0): ajuste = [] b = polyfit(log10(self.s1), log10(self.fn1),1)[1] for i in range(len(self.s1)): ajuste.append(self.h1*log10(self.s1[i])+b) rcuadrada = round(r2_score(log10(self.fn1), ajuste),4) self.R.append(rcuadrada) plt.figure() plt.grid(True) plt.title(nam[0], fontsize = 15) plt.xlabel('Ln(n)', fontsize = 10) plt.ylabel('Ln(F(n))', fontsize = 10) plt.plot(log10(self.s1), log10(self.fn1), label = 'Original') plt.plot(log10(self.s1), ajuste, label = 'Adjust') plt.legend() plt.savefig(RUTA + nam[0]+' ln(F) vs ln(n).png', dpi = 300) plt.close() self.R = asarray(self.R) self.h = asarray(self.h) self.list_DFA.addItem('') for i in range(len(self.rutas)): names=str.split(self.rutas[i],"/") t=len(names) nombre= names[t-1] self.list_DFA.addItem(nombre) datos_R = [] datos_R.append(nombres_archivos) datos_R.append(self.R) datos_R = transpose(asarray(datos_R)) datos_R = DataFrame(datos_R) datos_R.to_csv(rutaSave+'R^2.txt', header = None, index = False, sep = '\t') datos_h = [] datos_h.append(nombres_archivos) datos_h.append(self.h) datos_h = transpose(asarray(datos_h)) datos_h = DataFrame(datos_h) datos_h.to_csv(rutaSave+'Hurst Exponent.txt', header = None, index = False, sep = '\t') self.dialog = Dialog('Done!!','Icons\listo.png') self.dialog.show() #%% def plots(self): if(self.aux == True): self.plot1.clear() i= self.list3.currentIndex()-1 if(len(self.rutas)!=0): data = read_csv(self.rutas[i],sep='\t', header=None) lineas= data.shape[1] if(lineas == 1): self.y = asarray(data[0]) elif(lineas == 2): self.y = asarray(data[1]) self.plot1.setLabel('bottom',color='k', **{'font-size':'14pt'}) self.plot1.getAxis('bottom').setPen(pg.mkPen(color='k', width=1)) # Y1 axis self.plot1.setLabel('left',color='k', **{'font-size':'14pt'}) self.plot1.getAxis('left').setPen(pg.mkPen(color='k', width=1)) names=str.split(self.rutas[i],"/") t=len(names) nombre= names[t-1] self.plot1.setTitle(nombre) self.plot1.plot(self.y,pen='k') #%% def plots_DFA(self): if(self.aux == True): self.plot1.clear() i= self.list_DFA.currentIndex()-1 if(len(self.rutas)!=0): self.plot1.setLabel('bottom',"ln(n)",color='k', **{'font-size':'14pt'}) self.plot1.getAxis('bottom').setPen(pg.mkPen(color='k', width=1)) # Y1 axis self.plot1.setLabel('left',"ln(F(n))",color='k', **{'font-size':'14pt'}) self.plot1.getAxis('left').setPen(pg.mkPen(color='k', width=1)) names=str.split(self.rutas[i],"/") t=len(names) nombre= names[t-1] self.plot1.setTitle(nombre) self.plot1.plot(self.s[i],self.fn[i], symbol='o') self.txtr1.setText(str(self.R[i])) self.txth1.setText(str(self.h[i])) #%% def initUI(self): pg.setConfigOption('background', 'w') params = { 'figure.figsize': [4, 4], 'figure.dpi': 300, 'savefig.dpi': 300 } plt.rcParams.update(params) ############################################################################### ########Variables Globales #################################################### ############################################################################### self.setWindowTitle('Detrended Analysis Fluctuation') self.setWindowIcon(QIcon("Icons\DFA.ico")) self.resize(1000, 600) self.ruta = None self.nombreSenial1='' self.x=[] self.y1=[] self.h1=[] contain = QSplitter(Qt.Horizontal) botones = QtWidgets.QVBoxLayout() graficos = QVBoxLayout() results1 = QFormLayout() results2 = QFormLayout() results3 = QFormLayout() results4 = QFormLayout() group_box_files = QGroupBox("Load file(s)") group_box_settings = QGroupBox("Settings") group_box_plots = QGroupBox("Plots") group_box_values = QGroupBox("Values") ################################################################# ## Elementos del layout botones ################################################################# self.btnLoadSig1 = QPushButton('Load signal') self.btnLoadSig1.clicked.connect(self.cargarSenial1) self.btnLoadSig1.setStyleSheet("font-size: 18px") lblm1 = QLabel("P adjust degree: ") lblm1.setStyleSheet("font-size: 18px") self.txtm1 = QLineEdit('1') self.txtm1.setEnabled(False) self.txtm1.setStyleSheet("font-size: 18px") lblh1 = QLabel("Hurst exponent h: ") lblh1.setStyleSheet("font-size: 18px") self.txth1 = QLineEdit('') self.txth1.setEnabled(False) lblr1 = QLabel("R^2: ") lblr1.setStyleSheet("font-size: 18px") self.txtr1 = QLabel('') self.lbl_num_files = QLabel("Files loaded: ") self.lbl_num_files.setStyleSheet("font-size: 18px") self.btnDFA1 = QPushButton('DFA') self.btnDFA1.clicked.connect(self.DFA1) self.btnDFA1.setStyleSheet("font-size: 18px") self.btnDFA1.setEnabled(False) lbl_file = QLabel("File: ") lbl_file.setStyleSheet("font-size: 18px") self.list3 = QComboBox() self.list3.currentIndexChanged.connect(self.plots) lbl_DFA = QLabel("DFA: ") lbl_DFA.setStyleSheet("font-size: 18px") self.list_DFA = QComboBox() self.list_DFA.currentIndexChanged.connect(self.plots_DFA) ################################################################# ## Colocar elementos en layout botones ################################################################# results1.addRow(self.btnLoadSig1) results1.addRow(self.lbl_num_files) group_box_files.setLayout(results1) results2.addRow(lblm1, self.txtm1) group_box_settings.setLayout(results2) results3.addRow(lbl_file, self.list3) results3.addRow(lbl_DFA, self.list_DFA) group_box_plots.setLayout(results3) results4.addRow(lblh1, self.txth1) results4.addRow(lblr1, self.txtr1) group_box_values.setLayout(results4) botones.addWidget(group_box_files) botones.addWidget(group_box_settings) botones.addWidget(group_box_plots) botones.addWidget(group_box_values) botones.addWidget(self.btnDFA1) ################################################################# ## Colocar elementos en layout graficos ################################################################# self.plot1=pg.PlotWidget() self.plot1.setLabel('bottom',color='k', **{'font-size':'14pt'}) self.plot1.getAxis('bottom').setPen(pg.mkPen(color='k', width=1)) self.plot1.setLabel('left',color='k', **{'font-size':'14pt'}) self.plot1.getAxis('left').setPen(pg.mkPen(color='k', width=1)) self.plot1.showGrid(1,1,0.2) graficos.addWidget(self.plot1) bot = QWidget() bot.setLayout(botones) gra = QWidget() gra.setLayout(graficos) contain.addWidget(bot) contain.addWidget(gra) self.setCentralWidget(contain)