From d8e3f57bf8f7b45cee8ebc821b60e47634ec367f Mon Sep 17 00:00:00 2001 From: Jose Manuel Requena Plens Date: Sun, 3 Jun 2018 02:58:35 +0200 Subject: [PATCH] Add files via upload --- include/EASEPost2Distan.m | 58 +++ include/EASEPost2Info.m | 55 +++ include/EASEPost2Matrix.m | 77 +++ include/EASEPost2Otros.m | 54 ++ include/EASEPost2Param.m | 76 +++ include/EASEPost2Param2.m | 76 +++ include/EASEPost2Sala.m | 54 ++ include/guardarErrores.m | 26 + include/importarPostFiles.m | 208 ++++++++ include/multiWaitbar.m | 824 +++++++++++++++++++++++++++++++ include/representaAbsorcion.m | 21 + include/representaDirectividad.m | 21 + include/representaRT.m | 21 + include/representaRespuesta.m | 21 + include/representarCt.m | 331 +++++++++++++ include/representarDt.m | 330 +++++++++++++ include/representarEcograma.m | 30 ++ include/representarG.m | 367 ++++++++++++++ include/representarSPLvsDist2.m | 436 ++++++++++++++++ include/representarSPLvsDist3.m | 421 ++++++++++++++++ 20 files changed, 3507 insertions(+) create mode 100644 include/EASEPost2Distan.m create mode 100644 include/EASEPost2Info.m create mode 100644 include/EASEPost2Matrix.m create mode 100644 include/EASEPost2Otros.m create mode 100644 include/EASEPost2Param.m create mode 100644 include/EASEPost2Param2.m create mode 100644 include/EASEPost2Sala.m create mode 100644 include/guardarErrores.m create mode 100644 include/importarPostFiles.m create mode 100644 include/multiWaitbar.m create mode 100644 include/representaAbsorcion.m create mode 100644 include/representaDirectividad.m create mode 100644 include/representaRT.m create mode 100644 include/representaRespuesta.m create mode 100644 include/representarCt.m create mode 100644 include/representarDt.m create mode 100644 include/representarEcograma.m create mode 100644 include/representarG.m create mode 100644 include/representarSPLvsDist2.m create mode 100644 include/representarSPLvsDist3.m diff --git a/include/EASEPost2Distan.m b/include/EASEPost2Distan.m new file mode 100644 index 0000000..d2e064b --- /dev/null +++ b/include/EASEPost2Distan.m @@ -0,0 +1,58 @@ +function Centro01 = EASEPost2Distan(filename, startRow, endRow) +%IMPORTFILE Import numeric data from a text file as a matrix. +% CENTRO01 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for +% the default selection. +% +% CENTRO01 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows +% STARTROW through ENDROW of text file FILENAME. +% +% Example: +% Centro01 = importfile('Centro_01.txt', [16,22], [16,22]); +% +% See also TEXTSCAN. + +% Auto-generated by MATLAB on 2018/02/28 00:31:51 + +%% Initialize variables. +delimiter = ' '; +if nargin<=2 + startRow = [16,22]; + endRow = [16,22]; +end + +%% Format for each line of text: +% column3: double (%f) +% column4: double (%f) +% column5: double (%f) +% For more information, see the TEXTSCAN documentation. +formatSpec = '%*s%*s%f%f%f%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%[^\n\r]'; + +%% Open the text file. +fileID = fopen(filename,'r'); + +%% Read columns of data according to the format. +% This call is based on the structure of the file used to generate this +% code. If an error occurs for a different file, try regenerating the code +% from the Import Tool. +textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false); +dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); +for block=2:length(startRow) + frewind(fileID); + textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false); + dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); + for col=1:length(dataArray) + dataArray{col} = [dataArray{col};dataArrayBlock{col}]; + end +end + +%% Close the text file. +fclose(fileID); + +%% Post processing for unimportable data. +% No unimportable data rules were applied during the import, so no post +% processing code is included. To generate code which works for +% unimportable data, select unimportable cells in a file and regenerate the +% script. + +%% Create output variable +Centro01 = [dataArray{1:end-1}]; diff --git a/include/EASEPost2Info.m b/include/EASEPost2Info.m new file mode 100644 index 0000000..743cbea --- /dev/null +++ b/include/EASEPost2Info.m @@ -0,0 +1,55 @@ +function Centro01 = EASEPost2Info(filename, startRow, endRow) +%IMPORTFILE Import numeric data from a text file as a matrix. +% CENTRO01 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for +% the default selection. +% +% CENTRO01 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows +% STARTROW through ENDROW of text file FILENAME. +% +% Example: +% Centro01 = importfile('Centro_01.txt', [15,21], [15,21]); +% +% See also TEXTSCAN. + +% Auto-generated by MATLAB on 2018/02/28 00:51:16 + +%% Initialize variables. +delimiter = ' '; +if nargin<=2 + startRow = [15,21]; + endRow = [15,21]; +end + +%% Format for each line of text: +% column2: text (%s) +% For more information, see the TEXTSCAN documentation. +formatSpec = '%*s%s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%[^\n\r]'; + +%% Open the text file. +fileID = fopen(filename,'r'); + +%% Read columns of data according to the format. +% This call is based on the structure of the file used to generate this +% code. If an error occurs for a different file, try regenerating the code +% from the Import Tool. +textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false); +dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); +for block=2:length(startRow) + frewind(fileID); + textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false); + dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); + dataArray{1} = [dataArray{1};dataArrayBlock{1}]; +end + +%% Close the text file. +fclose(fileID); + +%% Post processing for unimportable data. +% No unimportable data rules were applied during the import, so no post +% processing code is included. To generate code which works for +% unimportable data, select unimportable cells in a file and regenerate the +% script. + +%% Create output variable +Centro01 = [dataArray{1:end-1}]; + diff --git a/include/EASEPost2Matrix.m b/include/EASEPost2Matrix.m new file mode 100644 index 0000000..d6b38b0 --- /dev/null +++ b/include/EASEPost2Matrix.m @@ -0,0 +1,77 @@ +function Centro1 = EASEPost2Matrix(filename, startRow, endRow) +%IMPORTFILE Import numeric data from a text file as a matrix. +% CENTRO1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for +% the default selection. +% +% CENTRO1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows +% STARTROW through ENDROW of text file FILENAME. +% +% Example: +% Centro1 = importfile('Centro_1.txt', 31, 61966); +% +% See also TEXTSCAN. + +% Auto-generated by MATLAB on 2018/02/27 22:06:29 + +%% Initialize variables. +delimiter = ' '; +if nargin<=2 + startRow = 31; + endRow = inf; +end + +%% Format for each line of text: +% column2: double (%f) +% column3: double (%f) +% column4: double (%f) +% column5: double (%f) +% column6: double (%f) +% column7: double (%f) +% column8: double (%f) +% column9: double (%f) +% column10: double (%f) +% column11: double (%f) +% column12: double (%f) +% column13: double (%f) +% column14: double (%f) +% column15: double (%f) +% column16: double (%f) +% column17: double (%f) +% column18: double (%f) +% column19: double (%f) +% column20: double (%f) +% column21: double (%f) +% column22: double (%f) +% column23: double (%f) +% For more information, see the TEXTSCAN documentation. +formatSpec = '%*s%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%*s%*s%*s%[^\n\r]'; + +%% Open the text file. +fileID = fopen(filename,'r'); + +%% Read columns of data according to the format. +% This call is based on the structure of the file used to generate this +% code. If an error occurs for a different file, try regenerating the code +% from the Import Tool. +textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false); +dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'EmptyValue', NaN, 'ReturnOnError', false, 'EndOfLine', '\r\n'); +for block=2:length(startRow) + frewind(fileID); + textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false); + dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'EmptyValue', NaN, 'ReturnOnError', false, 'EndOfLine', '\r\n'); + for col=1:length(dataArray) + dataArray{col} = [dataArray{col};dataArrayBlock{col}]; + end +end + +%% Close the text file. +fclose(fileID); + +%% Post processing for unimportable data. +% No unimportable data rules were applied during the import, so no post +% processing code is included. To generate code which works for +% unimportable data, select unimportable cells in a file and regenerate the +% script. + +%% Create output variable +Centro1 = [dataArray{1:end-1}]; diff --git a/include/EASEPost2Otros.m b/include/EASEPost2Otros.m new file mode 100644 index 0000000..1183f34 --- /dev/null +++ b/include/EASEPost2Otros.m @@ -0,0 +1,54 @@ +function Esquina1 = EASEPost2Otros(filename, startRow, endRow) +%IMPORTFILE Import numeric data from a text file as a matrix. +% ESQUINA1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for +% the default selection. +% +% ESQUINA1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows +% STARTROW through ENDROW of text file FILENAME. +% +% Example: +% Esquina1 = importfile('Esquina_1.txt', [18,24,29], [18,24,29]); +% +% See also TEXTSCAN. + +% Auto-generated by MATLAB on 2018/03/02 01:50:48 + +%% Initialize variables. +delimiter = ' '; +if nargin<=2 + startRow = [18,24,29]; + endRow = [18,24,29]; +end + +%% Format for each line of text: +% column4: double (%f) +% For more information, see the TEXTSCAN documentation. +formatSpec = '%*s%*s%*s%f%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%[^\n\r]'; + +%% Open the text file. +fileID = fopen(filename,'r'); + +%% Read columns of data according to the format. +% This call is based on the structure of the file used to generate this +% code. If an error occurs for a different file, try regenerating the code +% from the Import Tool. +textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false); +dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); +for block=2:length(startRow) + frewind(fileID); + textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false); + dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); + dataArray{1} = [dataArray{1};dataArrayBlock{1}]; +end + +%% Close the text file. +fclose(fileID); + +%% Post processing for unimportable data. +% No unimportable data rules were applied during the import, so no post +% processing code is included. To generate code which works for +% unimportable data, select unimportable cells in a file and regenerate the +% script. + +%% Create output variable +Esquina1 = [dataArray{1:end-1}]; diff --git a/include/EASEPost2Param.m b/include/EASEPost2Param.m new file mode 100644 index 0000000..7605e65 --- /dev/null +++ b/include/EASEPost2Param.m @@ -0,0 +1,76 @@ +function Esquina1 = EASEPost2Param(filename, startRow, endRow) +%IMPORTFILE Import numeric data from a text file as a matrix. +% ESQUINA1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for +% the default selection. +% +% ESQUINA1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows +% STARTROW through ENDROW of text file FILENAME. +% +% Example: +% Esquina1 = importfile('Esquina_1.txt', [11,28], [12,28]); +% +% See also TEXTSCAN. + +% Auto-generated by MATLAB on 2018/03/02 02:08:49 + +%% Initialize variables. +delimiter = ' '; +if nargin<=2 + startRow = [11,28]; + endRow = [12,28]; +end + +%% Format for each line of text: +% column3: double (%f) +% column4: double (%f) +% column5: double (%f) +% column6: double (%f) +% column7: double (%f) +% column8: double (%f) +% column9: double (%f) +% column10: double (%f) +% column11: double (%f) +% column12: double (%f) +% column13: double (%f) +% column14: double (%f) +% column15: double (%f) +% column16: double (%f) +% column17: double (%f) +% column18: double (%f) +% column19: double (%f) +% column20: double (%f) +% column21: double (%f) +% column22: double (%f) +% column23: double (%f) +% For more information, see the TEXTSCAN documentation. +formatSpec = '%*s%*s%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%*s%*s%*s%[^\n\r]'; + +%% Open the text file. +fileID = fopen(filename,'r'); + +%% Read columns of data according to the format. +% This call is based on the structure of the file used to generate this +% code. If an error occurs for a different file, try regenerating the code +% from the Import Tool. +textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false); +dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); +for block=2:length(startRow) + frewind(fileID); + textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false); + dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); + for col=1:length(dataArray) + dataArray{col} = [dataArray{col};dataArrayBlock{col}]; + end +end + +%% Close the text file. +fclose(fileID); + +%% Post processing for unimportable data. +% No unimportable data rules were applied during the import, so no post +% processing code is included. To generate code which works for +% unimportable data, select unimportable cells in a file and regenerate the +% script. + +%% Create output variable +Esquina1 = [dataArray{1:end-1}]; diff --git a/include/EASEPost2Param2.m b/include/EASEPost2Param2.m new file mode 100644 index 0000000..6e01796 --- /dev/null +++ b/include/EASEPost2Param2.m @@ -0,0 +1,76 @@ +function Esquina1 = EASEPost2Param2(filename, startRow, endRow) +%IMPORTFILE Import numeric data from a text file as a matrix. +% ESQUINA1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for +% the default selection. +% +% ESQUINA1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows +% STARTROW through ENDROW of text file FILENAME. +% +% Example: +% Esquina1 = importfile('Esquina_1.txt', [13,27], [13,27]); +% +% See also TEXTSCAN. + +% Auto-generated by MATLAB on 2018/03/02 02:11:55 + +%% Initialize variables. +delimiter = ' '; +if nargin<=2 + startRow = [13,27]; + endRow = [13,27]; +end + +%% Format for each line of text: +% column4: double (%f) +% column5: double (%f) +% column6: double (%f) +% column7: double (%f) +% column8: double (%f) +% column9: double (%f) +% column10: double (%f) +% column11: double (%f) +% column12: double (%f) +% column13: double (%f) +% column14: double (%f) +% column15: double (%f) +% column16: double (%f) +% column17: double (%f) +% column18: double (%f) +% column19: double (%f) +% column20: double (%f) +% column21: double (%f) +% column22: double (%f) +% column23: double (%f) +% column24: double (%f) +% For more information, see the TEXTSCAN documentation. +formatSpec = '%*s%*s%*s%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%*s%*s%[^\n\r]'; + +%% Open the text file. +fileID = fopen(filename,'r'); + +%% Read columns of data according to the format. +% This call is based on the structure of the file used to generate this +% code. If an error occurs for a different file, try regenerating the code +% from the Import Tool. +textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false); +dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); +for block=2:length(startRow) + frewind(fileID); + textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false); + dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); + for col=1:length(dataArray) + dataArray{col} = [dataArray{col};dataArrayBlock{col}]; + end +end + +%% Close the text file. +fclose(fileID); + +%% Post processing for unimportable data. +% No unimportable data rules were applied during the import, so no post +% processing code is included. To generate code which works for +% unimportable data, select unimportable cells in a file and regenerate the +% script. + +%% Create output variable +Esquina1 = [dataArray{1:end-1}]; diff --git a/include/EASEPost2Sala.m b/include/EASEPost2Sala.m new file mode 100644 index 0000000..4b22352 --- /dev/null +++ b/include/EASEPost2Sala.m @@ -0,0 +1,54 @@ +function Esquina1 = EASEPost2Sala(filename, startRow, endRow) +%IMPORTFILE Import numeric data from a text file as a matrix. +% ESQUINA1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for +% the default selection. +% +% ESQUINA1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows +% STARTROW through ENDROW of text file FILENAME. +% +% Example: +% Esquina1 = importfile('Esquina_1.txt', 4, 7); +% +% See also TEXTSCAN. + +% Auto-generated by MATLAB on 2018/03/02 01:05:38 + +%% Initialize variables. +delimiter = ' '; +if nargin<=2 + startRow = 4; + endRow = 7; +end + +%% Format for each line of text: +% column2: double (%f) +% For more information, see the TEXTSCAN documentation. +formatSpec = '%*s%f%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%[^\n\r]'; + +%% Open the text file. +fileID = fopen(filename,'r'); + +%% Read columns of data according to the format. +% This call is based on the structure of the file used to generate this +% code. If an error occurs for a different file, try regenerating the code +% from the Import Tool. +textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false); +dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); +for block=2:length(startRow) + frewind(fileID); + textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false); + dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n'); + dataArray{1} = [dataArray{1};dataArrayBlock{1}]; +end + +%% Close the text file. +fclose(fileID); + +%% Post processing for unimportable data. +% No unimportable data rules were applied during the import, so no post +% processing code is included. To generate code which works for +% unimportable data, select unimportable cells in a file and regenerate the +% script. + +%% Create output variable +Esquina1 = [dataArray{1:end-1}]; diff --git a/include/guardarErrores.m b/include/guardarErrores.m new file mode 100644 index 0000000..777ee51 --- /dev/null +++ b/include/guardarErrores.m @@ -0,0 +1,26 @@ + +function guardarErrores(Ucoef,Pcoef,Distancia,Dist_P,Dist_U) + +a = confint(Ucoef); +b = confint(Pcoef); + +% Resolucion de errores +x = linspace(min(Distancia),max(Distancia),8); + +% Puntos de error del campo util +U = Ucoef.a*x.^(Ucoef.b); +Utop = a(2)*x.^(a(4))-U; +Udow = U-a(1)*x.^(a(3)); +TUerrores = table(x',U',Utop',Udow','VariableNames',{'x','y','ymas','ymenos'}); + +writetable(TUerrores,'UtilErrores.dat','Delimiter','\t') + +% Puntos campo perjudicial +% Puntos de error del campo util +P = Pcoef.p1*x+Pcoef.p2; +Ptop = (b(2)*x+(b(4)))-P; +Pdow = P-(b(1)*x+(b(3))); +TPerrores = table(x',P',Ptop',Pdow','VariableNames',{'x','y','ymas','ymenos'}); + +writetable(TPerrores,'PerjudicialErrores.dat','Delimiter','\t') +end \ No newline at end of file diff --git a/include/importarPostFiles.m b/include/importarPostFiles.m new file mode 100644 index 0000000..9e5d4cf --- /dev/null +++ b/include/importarPostFiles.m @@ -0,0 +1,208 @@ +function importarPostFiles(hObject,handles) +% Almacena en la aplicacion (handles.SPLm) la variables +% Es una variable tipo cell que en cada fila almacena los datos extraidos +% de cada fila. Si hay 20 archivos, el cell 'SPLm' tendr� 20 filas. +% En las ultimas lineas se puede observar que contiene cada columna. +% +% Distancia -> Vector de distancias entre cada receptor y la fuente +% PosReceptor -> Vector con la posicion del receptor (X,Y,Z) +% PosFuente -> Vector con la posicion de la fuente (X,Y,Z) +% Fuente -> Vector con la ID de fuente recibida cada receptor +% Receptor -> Vector con las ID de cada receptor +% Volumen -> Variable que contiene el valor del volumen de la sala +% Superficie -> Variable que contiene el valor de la superficie +% Temperatura -> Variable que contiene el valor de la temperatura +% Humedad -> Variable que contiene el valor de la humedad +% SPLm -> Cell que almacena la historia temporal de cada receptor +% RayoDirecto -> Tiempo de llegada del primer rayo a cada receptor +% RetFuente -> Retardo de la fuente +% NumRayos -> Numero de rayos recibidos por cada receptor +% Reverberacion -> Tiempo de reverberacion de cada archivo +% Absorcion -> Coeficiente de absorcion de cada archivo +% Directividad -> Directividad de las fuentes +% RuidoFondo -> Ruido de fondo de cada archivo +% SPLFuente -> Nivel SPL de las fuentes + +%% Importacion de datos +ListaArchivos = handles.ListaArchivos; + +%multiWaitbar(handles,'Importando archivos',N/size(PARAMtxt,1),'color','b'); +% Inicializacion de variables +Distancia = zeros(size(ListaArchivos,2),1); +PosReceptor = zeros(size(ListaArchivos,2),3); +PosFuente = zeros(size(ListaArchivos,2),3); +RayoDirecto = zeros(size(ListaArchivos,2),1); +RetFuente = zeros(size(ListaArchivos,2),1); +NumRayos = zeros(size(ListaArchivos,2),1); +Reverberacion = zeros(size(ListaArchivos,2),21); +Absorcion = zeros(size(ListaArchivos,2),21); +Directividad = zeros(size(ListaArchivos,2),21); +RuidoFondo = zeros(size(ListaArchivos,2),21); +SPLFuente = zeros(size(ListaArchivos,2),21); +handles.SPLm = cell(size(ListaArchivos,2),21); +for i=1:size(ListaArchivos,2) + + % Distancia entre receptores y fuente + A = EASEPost2Distan(ListaArchivos{i}); + Distancia(i) = sqrt(... + (A(1,1)-A(2,1))^2 + (A(1,2)-A(2,2))^2 + (A(1,3)-A(2,3))^2); + PosReceptor(i,:) = A(1,:); + PosFuente(i,:) = A(2,:); + + % Nombre de la fuente y de los receptores + A = EASEPost2Info(ListaArchivos{i}); + Fuente{i} = char(A(2)); + Receptor{i} = char(A(1)); + + % Parametros de la sala + % ToDo: Almacenar la primera vez y el resto comprobar que son iguales, si + % no son iguales mostrar error y detener la importaci�n + A = EASEPost2Sala(ListaArchivos{i}); + Volumen = A(1); + Superficie = A(2); + Temperatura = A(3); + Humedad = A(4); + + % Datos varios + A = EASEPost2Otros(ListaArchivos{i}); + RayoDirecto(i) = A(1); + RetFuente(i) = A(2); + NumRayos(i) = A(3); + + % RT, Absorcion de la sala, Directividad fuente + A = EASEPost2Param(ListaArchivos{i}); + Reverberacion(i,:) = A(1,:); + Absorcion(i,:) = A(2,:); + Directividad(i,:) = A(3,:); + + % Ruido de fondo, SPL fuente + A = EASEPost2Param2(ListaArchivos{i}); + RuidoFondo(i,:) = A(1,:); + SPLFuente(i,:) = A(2,:); + + % Obtener historia temporal para cada receptor + % Obtiene una matriz con la columna de delay y los niveles en tercios de + % octava + A = EASEPost2Matrix(ListaArchivos{i}); + % Eliminar el delay de llegada, restando el valor minimo de llegada a todo + % el vector de tiempos. Asi aseguramos que la integracion por rangos + % temporales sea correcta. + Tnew = A(:,1) - RayoDirecto(i); + % Almacenar en el cell 'SPLm' la informacion del archivo actual 'i' + handles.SPLm{i,1} = []; % Aqui ira el SPL por milisegundo + handles.SPLm{i,2} = Fuente{i}; + handles.SPLm{i,3} = Receptor{i}; + handles.SPLm{i,4} = PosFuente(i,:); + handles.SPLm{i,5} = PosReceptor(i,:); + handles.SPLm{i,6} = Distancia(i); + handles.SPLm{i,7} = RetFuente(i); + handles.SPLm{i,8} = NumRayos(i); + handles.SPLm{i,9} = RayoDirecto(i); + handles.SPLm{i,10} = Reverberacion(i,:); + handles.SPLm{i,11} = Absorcion(i,:); + handles.SPLm{i,12} = RuidoFondo(i,:); + handles.SPLm{i,13} = SPLFuente(i,:); + handles.SPLm{i,14} = Directividad(i,:); + handles.SPLm{i,15} = Volumen; + handles.SPLm{i,16} = Superficie; + handles.SPLm{i,17} = Temperatura; + handles.SPLm{i,18} = Humedad; + % Historia temporal completa + handles.SPLm{i,19} = [Tnew,A(:,2:end)]; + % Historia temporal procesada por milisegundo en bandas de octava + handles.SPLm{i,20} = []; + % Historia temporal procesada por milisegundo en tercios de octava + handles.SPLm{i,21} = []; + +end + +% En primer lugar agrupa los niveles en bloques de 1 milisegundo, ya que hay +% varios niveles por milisegundo, y promedia los valores de cada bloque +for i=1:numel(handles.SPLm(:,1)) + + + for j=1:max(ceil(handles.SPLm{i,19}(:,1))) + Ini = find(handles.SPLm{i,19}(:,1)>=j-1,1); % Inicio del bloque de 'j' milisegundos + Fin = find(handles.SPLm{i,19}(:,1)>j,1)-1; % Fin del bloque de 'j' milisegundos + % Si ha llegado al final del vector, fin estara vacio y inicio y fin + % seran iguales para obtener el valor ultimo del vector + if isempty(find(handles.SPLm{i,19}(:,1)>j,1)); Fin=Ini; end + % Si el bloque del milisegundo 'j' existe, ini sera menor o igual a fin, + % si no existe ini sera mayor a fin y no habra valor en ese milisegundo. + if Ini<=Fin + Valores = handles.SPLm{i,19}(Ini:Fin,2:end); + + if max(Valores(:)) > 0 + % Suma el bloque por octavas y vuelve a sumar para obtener un valor + ValMS(j) = 10*log10(sum(sum(10.^(Valores/10),1))); + % Suma los rayos recibidos en el milisegundo 'j', y lo pasa de + % tercios de octava a bandas de octava + ValMSthirdoct(j,:) = sum(10.^(Valores/10),1); + ValMSoct(j,:) = 10*log10([sum(ValMSthirdoct(j,1:3)),... % 125 Hz + sum(ValMSthirdoct(j,4:6)),... % 250 Hz + sum(ValMSthirdoct(j,7:9)),... % 500 Hz + sum(ValMSthirdoct(j,10:12)),...% 1 kHz + sum(ValMSthirdoct(j,13:15)),...% 2 kHz + sum(ValMSthirdoct(j,16:18)),...% 4 kHz + sum(ValMSthirdoct(j,19:21))]); % 8 kHz + ValMSthirdoct(j,:) = 10*log10(ValMSthirdoct(j,:)); + else + ValMS(j) = 0; + ValMSoct(j,:) = 0; + ValMSthirdoct(j,:) = 0; + end + else + ValMS(j)=NaN; + ValMSoct(j,:) = NaN; + ValMSthirdoct(j,:) = NaN; + end + + end + % Todos los valores 0 y menores a 0 se dejan vacios + %ValMS(ValMS==0) = NaN; + %ValMSoct(ValMSoct==0) = NaN; + % Si se utiliza matlab 2014b o anterior realiza la interpolacion + % manualmente, sino utiliza la funcion fillmising + if verLessThan('matlab','8.7') + % Interpolacion manual global + bd=isnan(ValMS); + gd=find(~bd); + bd([1:(min(gd)-1) (max(gd)+1):end])=0; + ValMS(bd)=interp1(gd,ValMS(gd),find(bd)); + % Interpolacion manual por bandas + for jj=1:7 + bd=isnan(ValMSoct(:,jj)); + gd=find(~bd); + bd([1:(min(gd)-1) (max(gd)+1):end])=0; + ValMSoct(bd,jj)=interp1(gd,ValMSoct(gd,jj),find(bd)); + end + for jj=1:21 + bd=isnan(ValMSthirdoct(:,jj)); + gd=find(~bd); + bd([1:(min(gd)-1) (max(gd)+1):end])=0; + ValMSthirdoct(bd,jj)=interp1(gd,ValMSthirdoct(gd,jj),find(bd)); + end + else + % Interpolar valores en los milisegundos que haya valor 0, desde el inicio + % al final del vector + ValMS = fillmissing(ValMS,'linear','EndValues','extrap'); + ValMSoct = fillmissing(ValMSoct,'linear','EndValues','extrap'); + ValMSthirdoct = fillmissing(ValMSthirdoct,'linear','EndValues','extrap'); + end + handles.SPLm{i,1} = ValMS'; + handles.SPLm{i,20} = ValMSoct; + handles.SPLm{i,21} = ValMSthirdoct; +end +% Obtener el tiempo maximo valor elegible para representacion. Obtiene el +% maximo de cada receptor y despues busca el minimo entre estos. +handles.MaxElegible = min(cell2mat(cellfun( @(val) numel(val), handles.SPLm(:,1),'UniformOutput',0)))-1; + +% Ordenar los datos segun la ID de fuente y despues por receptor. Asi se +% tiene agrupados los datos segun la fuente, necesario para elegir una +% fuente u otra en el programa. +handles.SPLm = sortrows(handles.SPLm,[2,3]); +% Actualizar variable en la aplicacion +guidata(hObject, handles); + +end + diff --git a/include/multiWaitbar.m b/include/multiWaitbar.m new file mode 100644 index 0000000..01e0a00 --- /dev/null +++ b/include/multiWaitbar.m @@ -0,0 +1,824 @@ +function cancel = multiWaitbar( handles,label, varargin ) +%multiWaitbar: add, remove or update an entry on the multi waitbar +% +% multiWaitbar(LABEL,VALUE) adds a waitbar for the specified label, or +% if it already exists updates the value. LABEL must be a string and +% VALUE a number between zero and one or the string 'Close' to remove the +% entry Setting value equal to 0 or 'Reset' will cause the progress bar +% to reset and the time estimate to be re-initialized. +% +% multiWaitbar(LABEL,COMMAND,VALUE,...) or +% multiWaitbar(LABEL,VALUE,COMMAND,VALUE,...) +% passes one or more command/value pairs for changing the named waitbar +% entry. Possible commands include: +% 'Value' Set the value of the named waitbar entry. The +% corresponding value must be a number between 0 and 1. +% 'Increment' Increment the value of the named waitbar entry. The +% corresponding value must be a number between 0 and 1. +% 'Color' Change the color of the named waitbar entry. The +% value must be an RGB triple, e.g. [0.1 0.2 0.3], or a +% single-character color name, e.g. 'r', 'b', 'm'. +% 'Relabel' Change the label of the named waitbar entry. The +% value must be the new name. +% 'Reset' Set the named waitbar entry back to zero and reset its +% timer. No value need be specified. +% 'CanCancel' [on|off] should a "cancel" button be shown for this bar +% (default 'off'). +% 'CancelFcn' Function to call in the event that the user cancels. +% 'ResetCancel' Reset the "cancelled" flag for an entry (ie. if you +% decide not to cancel). +% 'Close' Remove the named waitbar entry. +% 'Busy' Puts this waitbar in "busy mode" where a small bar +% bounces back and forth. Return to normal progress display +% using the 'Reset' command. +% +% cancel = multiWaitbar(LABEL,VALUE) also returns whether the user has +% clicked the "cancel" button for this entry (true or false). Two +% mechanisms are provided for cancelling an entry if the 'CanCancel' +% setting is 'on'. The first is just to check the return argument and if +% it is true abort the task. The second is to set a 'CancelFcn' that is +% called when the user clicks the cancel button, much as is done for +% MATLAB's built-in WAITBAR. In either case, you can use the +% 'ResetCancel' command if you don't want to cancel after all. +% +% multiWaitbar('CLOSEALL') closes the waitbar window. +% +% Example: +% multiWaitbar( 'CloseAll' ); +% multiWaitbar( 'Task 1', 0 ); +% multiWaitbar( 'Task 2', 0.5, 'Color', 'b' ); +% multiWaitbar( 'Task 3', 'Busy'); +% multiWaitbar( 'Task 1', 'Value', 0.1 ); +% multiWaitbar( 'Task 2', 'Increment', 0.2 ); +% multiWaitbar( 'Task 3', 'Reset' ); % Disables "busy" mode +% multiWaitbar( 'Task 3', 'Value', 0.3 ); +% multiWaitbar( 'Task 2', 'Close' ); +% multiWaitbar( 'Task 3', 'Close' ); +% multiWaitbar( 'Task 1', 'Close' ); +% +% Example: +% multiWaitbar( 'Task 1', 0, 'CancelFcn', @(a,b) disp( ['Cancel ',a] ) ); +% for ii=1:100 +% abort = multiWaitbar( 'Task 1', ii/100 ); +% if abort +% % Here we would normally ask the user if they're sure +% break +% else +% pause( 1 ) +% end +% end +% multiWaitbar( 'Task 1', 'Close' ) +% +% Example: +% multiWaitbar( 'CloseAll' ); +% multiWaitbar( 'Red...', 7/7, 'Color', [0.8 0.0 0.1] ); +% multiWaitbar( 'Orange...', 6/7, 'Color', [1.0 0.4 0.0] ); +% multiWaitbar( 'Yellow...', 5/7, 'Color', [0.9 0.8 0.2] ); +% multiWaitbar( 'Green...', 4/7, 'Color', [0.2 0.9 0.3] ); +% multiWaitbar( 'Blue...', 3/7, 'Color', [0.1 0.5 0.8] ); +% multiWaitbar( 'Indigo...', 2/7, 'Color', [0.4 0.1 0.5] ); +% multiWaitbar( 'Violet...', 1/7, 'Color', [0.8 0.4 0.9] ); +% +% Thanks to Jesse Hopkins for suggesting the "busy" mode. + +% Author: Ben Tordoff +% Copyright 2007-2014 The MathWorks, Inc. + +% Modificaciones para CATT2Matlab +global titleprogress +global timedays +global timehours +global timemins +global timesecs +global timesec +titleprogress = handles.LPROGRESSTITLE; +timedays = handles.LTIMEDAYS; +timehours = handles.LTIMEHOURS; +timemins = handles.LTIMEMINS; +timesecs = handles.LTIMESECS; +timesec = handles.LTIMESEC; + + +persistent FIGH; +cancel = false; + +% Check basic inputs +narginchk( 1, inf); % - kept for backwards compatibility +if ~ischar( label ) + error( 'multiWaitbar:BadArg', 'LABEL must be the name of the progress entry (i.e. a string)' ); +end + +% Try to get hold of the figure +if isempty( FIGH ) || ~ishandle( FIGH ) + FIGH = findall( 0, 'Type', 'figure', 'Tag', 'multiWaitbar:Figure' ); + if isempty(FIGH) + FIGH = iCreateFig(); + else + FIGH = handle( FIGH(1) ); + end +end + +% Check for close all and stop early +if any( strcmpi( label, {'CLOSEALL','CLOSE ALL'} ) ) + iDeleteFigure(FIGH); + return; +end + +% Make sure we're on-screen +if ~strcmpi( FIGH.Visible, 'on' ) + FIGH.Visible = 'on'; +end + +% Get the list of entries and see if this one already exists +entries = getappdata( FIGH, 'ProgressEntries' ); +if isempty(entries) + idx = []; +else + idx = find( strcmp( label, {entries.Label} ), 1, 'first' ); +end +bgcol = getappdata( FIGH, 'DefaultProgressBarBackgroundColor' ); + +% If it doesn't exist, create it +needs_redraw = false; +entry_added = isempty(idx); +if entry_added + % Create a new entry + defbarcolor = getappdata( FIGH, 'DefaultProgressBarColor' ); + entries = iAddEntry( FIGH, entries, label, 0, defbarcolor, bgcol ); + idx = numel( entries ); +end + +% Check if the user requested a cancel +if nargout + cancel = entries(idx).Cancel; +end + +% Parse the inputs. We shortcut the most common case as an efficiency +force_update = false; +if nargin==2 && isnumeric( varargin{1} ) + entries(idx).LastValue = entries(idx).Value; + entries(idx).Value = max( 0, min( 1, varargin{1} ) ); + entries(idx).Busy = false; + needs_update = true; +else + [params,values] = iParseInputs( varargin{:} ); + + needs_update = false; + for ii=1:numel( params ) + switch upper( params{ii} ) + case 'BUSY' + entries(idx).Busy = true; + needs_update = true; + + case 'VALUE' + entries(idx).LastValue = entries(idx).Value; + entries(idx).Value = max( 0, min( 1, values{ii} ) ); + entries(idx).Busy = false; + needs_update = true; + + case {'INC','INCREMENT'} + entries(idx).LastValue = entries(idx).Value; + entries(idx).Value = max( 0, min( 1, entries(idx).Value + values{ii} ) ); + entries(idx).Busy = false; + needs_update = true; + + case {'COLOR','COLOUR'} + entries(idx).CData = iMakeColors( values{ii}, 16 ); + needs_update = true; + force_update = true; + + case {'RELABEL', 'UPDATELABEL'} + % Make sure we have a string as the value and that it + % doesn't already appear + if ~ischar( values{ii} ) + error( 'multiWaitbar:BadString', 'Value for ''Relabel'' must be a string.' ); + end + if ismember( values{ii}, {entries.Label} ) + error( 'multiWaitbar:NameAlreadyExists', 'Cannot relabel an entry to a label that already exists.' ); + end + entries(idx).Label = values{ii}; + needs_update = true; + force_update = true; + + case {'CANCANCEL'} + if ~ischar( values{ii} ) || ~any( strcmpi( values{ii}, {'on','off'} ) ) + error( 'multiWaitbar:BadString', 'Parameter ''CanCancel'' must be a ''on'' or ''off''.' ); + end + entries(idx).CanCancel = strcmpi( values{ii}, 'on' ); + entries(idx).Cancel = false; + needs_redraw = true; + + case {'RESETCANCEL'} + entries(idx).Cancel = false; + needs_redraw = true; + + case {'CANCELFCN'} + if ~isa( values{ii}, 'function_handle' ) + error( 'multiWaitbar:BadFunction', 'Parameter ''CancelFcn'' must be a valid function handle.' ); + end + entries(idx).CancelFcn = values{ii}; + if ~entries(idx).CanCancel + entries(idx).CanCancel = true; + end + needs_redraw = true; + + case {'CLOSE','DONE'} + if ~isempty(idx) + % Remove the selected entry + entries = iDeleteEntry( entries, idx ); + end + if isempty( entries ) + iDeleteFigure( FIGH ); + % With the window closed, there's nothing else to do + return; + else + needs_redraw = true; + end + % We can't continue after clearing the entry, so jump out + break; + + otherwise + error( 'multiWaitbar:BadArg', 'Unrecognized command: ''%s''', params{ii} ); + + end + end +end + +% Now work out what to update/redraw +if needs_redraw + setappdata( FIGH, 'ProgressEntries', entries ); + iRedraw( FIGH ); + % NB: Redraw includes updating all bars, so never need to do both +elseif needs_update + [entries(idx),needs_redraw] = iUpdateEntry( entries(idx), force_update ); + setappdata( FIGH, 'ProgressEntries', entries ); + % NB: if anything was updated onscreen, "needs_redraw" is now true. +end +if entry_added || needs_redraw + % If the shape or size has changed, do a full redraw, including events + drawnow(); +end + +% If we have any "busy" entries, start the timer, otherwise stop it. +myTimer = getappdata( FIGH, 'BusyTimer' ); +if any([entries.Busy]) + if strcmpi(myTimer.Running,'off') + start(myTimer); + end +else + if strcmpi(myTimer.Running,'on') + stop(myTimer); + end +end + +clearvars -global titleprogress timedays timehours timemins timesecs timesec +end % multiWaitbar + + +%-------------------------------------------------------------------------% +function [params, values] = iParseInputs( varargin ) +% Parse the input arguments, extracting a list of commands and values +idx = 1; +params = {}; +values = {}; +if nargin==0 + return; +end +if isnumeric( varargin{1} ) + params{idx} = 'Value'; + values{idx} = varargin{1}; + idx = idx + 1; +end + +while idx <= nargin + param = varargin{idx}; + if ~ischar( param ) + error( 'multiWaitbar:BadSyntax', 'Additional properties must be supplied as property-value pairs' ); + end + params{end+1,1} = param; %#ok + values{end+1,1} = []; %#ok + switch upper( param ) + case {'DONE','CLOSE','RESETCANCEL'} + % No value needed, and stop + break; + case {'BUSY'} + % No value needed but parsing should continue + idx = idx + 1; + case {'RESET','ZERO','SHOW'} + % All equivalent to saying ('Value', 0) + params{end} = 'Value'; + values{end} = 0; + idx = idx + 1; + otherwise + if idx==nargin + error( 'multiWaitbar:BadSyntax', 'Additional properties must be supplied as property-value pairs' ); + end + values{end,1} = varargin{idx+1}; + idx = idx + 2; + end +end +if isempty( params ) + error( 'multiWaitbar:BadSyntax', 'Must specify a value or a command' ); +end +end % iParseInputs + +%-------------------------------------------------------------------------% +function fobj = iCreateFig() +global titleprogress +% Create the progress bar group window +bgcol = get(0,'DefaultUIControlBackgroundColor'); +f = figure( ... + 'Name', titleprogress, ... + 'Tag', 'multiWaitbar:Figure', ... + 'Color', bgcol, ... + 'MenuBar', 'none', ... + 'ToolBar', 'none', ... + 'WindowStyle', 'normal', ... % We don't want to be docked! + 'HandleVisibility', 'off', ... + 'IntegerHandle', 'off', ... + 'Visible', 'off', ... + 'NumberTitle', 'off' ); +% Resize and centre on the first screen +screenSize = get(0,'ScreenSize'); +figSz = [360 42]; +figPos = ceil((screenSize(1,3:4)-figSz)/2); +fobj = handle( f ); +fobj.Position = [figPos, figSz]; +setappdata( fobj, 'ProgressEntries', [] ); +% Make sure we have the image +defbarcolor = [0.8 0.0 0.1]; +barbgcol = uint8( 255*0.75*bgcol ); +setappdata( fobj, 'DefaultProgressBarBackgroundColor', barbgcol ); +setappdata( fobj, 'DefaultProgressBarColor', defbarcolor ); +setappdata( fobj, 'DefaultProgressBarSize', [350 16] ); +% Create the timer to use for "Busy" mode, being sure to delete any +% existing ones +delete( timerfind('Tag', 'MultiWaitbarTimer') ); +myTimer = timer( ... + 'TimerFcn', @(src,evt) iTimerFcn(f), ... + 'Period', 0.02, ... + 'ExecutionMode', 'FixedRate', ... + 'Tag', 'MultiWaitbarTimer' ); +setappdata( fobj, 'BusyTimer', myTimer ); + +% Setup the resize function after we've finished setting up the figure to +% avoid excessive redraws +fobj.ResizeFcn = @iRedraw; +fobj.CloseRequestFcn = @iCloseFigure; +end % iCreateFig + +%-------------------------------------------------------------------------% +function cdata = iMakeColors( baseColor, height ) +% Creates a shiny bar from a single base color +lightColor = [1 1 1]; +badColorErrorID = 'multiWaitbar:BadColor'; +badColorErrorMsg = 'Colors must be a three element vector [R G B] or a single character (''r'', ''g'' etc.)'; + +if ischar(baseColor) + switch upper(baseColor) + case 'K' + baseColor = [0.1 0.1 0.1]; + case 'R' + baseColor = [0.8 0 0]; + case 'G' + baseColor = [0 0.6 0]; + case 'B' + baseColor = [0 0 0.8]; + case 'C' + baseColor = [0.2 0.8 0.9]; + case 'M' + baseColor = [0.6 0 0.6]; + case 'Y' + baseColor = [0.9 0.8 0.2]; + case 'W' + baseColor = [0.9 0.9 0.9]; + otherwise + error( badColorErrorID, badColorErrorMsg ); + end +else + if numel(baseColor) ~= 3 + error( badColorErrorID, badColorErrorMsg ); + end + if isa( baseColor, 'uint8' ) + baseColor = double( baseColor ) / 255; + elseif isa( baseColor, 'double' ) + if any(baseColor>1) || any(baseColor<0) + error( 'multiWaitbar:BadColorValue', 'Color values must be in the range 0 to 1 inclusive.' ); + end + else + error( badColorErrorID, badColorErrorMsg ); + end +end + +% By this point we should have a double precision 3-element vector. +cols = repmat( baseColor, [height, 1] ); + +breaks = max( 1, round( height * [1 25 50 75 88 100] / 100 ) ); +cols(breaks(1),:) = 0.6*baseColor; +cols(breaks(2),:) = lightColor - 0.4*(lightColor-baseColor); +cols(breaks(3),:) = baseColor; +cols(breaks(4),:) = min( baseColor*1.2, 1.0 ); +cols(breaks(5),:) = min( baseColor*1.4, 0.95 ) + 0.05; +cols(breaks(6),:) = min( baseColor*1.6, 0.9 ) + 0.1; + +y = 1:height; +cols(:,1) = max( 0, min( 1, interp1( breaks, cols(breaks,1), y, 'pchip' ) ) ); +cols(:,2) = max( 0, min( 1, interp1( breaks, cols(breaks,2), y, 'pchip' ) ) ); +cols(:,3) = max( 0, min( 1, interp1( breaks, cols(breaks,3), y, 'pchip' ) ) ); +cdata = uint8( 255 * cat( 3, cols(:,1), cols(:,2), cols(:,3) ) ); +end % iMakeColors + + +%-------------------------------------------------------------------------% +function cdata = iMakeBackground( baseColor, height ) +% Creates a shaded background +if isa( baseColor, 'uint8' ) + baseColor = double( baseColor ) / 255; +end + +ratio = 1 - exp( -0.5-2*(1:height)/height )'; +cdata = uint8( 255 * cat( 3, baseColor(1)*ratio, baseColor(2)*ratio, baseColor(3)*ratio ) ); +end % iMakeBackground + +%-------------------------------------------------------------------------% +function entries = iAddEntry( parent, entries, label, value, color, bgcolor ) +% Add a new entry to the progress bar + +% Create bar coloring +psize = getappdata( parent, 'DefaultProgressBarSize' ); +cdata = iMakeColors( color, 16 ); +% Create background image +barcdata = iMakeBackground( bgcolor, psize(2) ); + +% Work out the size in advance +labeltext = uicontrol( 'Style', 'Text', ... + 'String', label, ... + 'Parent', parent, ... + 'HorizontalAlignment', 'Left' ); +etatext = uicontrol( 'Style', 'Text', ... + 'String', '', ... + 'Parent', parent, ... + 'HorizontalAlignment', 'Right' ); +progresswidget = uicontrol( 'Style', 'Checkbox', ... + 'String', '', ... + 'Parent', parent, ... + 'Position', [5 5 psize], ... + 'CData', barcdata ); +cancelwidget = uicontrol( 'Style', 'PushButton', ... + 'String', '', ... + 'FontWeight', 'Bold', ... + 'Parent', parent, ... + 'Position', [5 5 16 16], ... + 'CData', iMakeCross( 8 ), ... + 'Callback', @(src,evt) iCancelEntry( src, label ), ... + 'Visible', 'off' ); +mypanel = uipanel( 'Parent', parent, 'Units', 'Pixels' ); + +newentry = struct( ... + 'Label', label, ... + 'Value', value, ... + 'LastValue', inf, ... + 'Created', tic(), ... + 'LabelText', labeltext, ... + 'ETAText', etatext, ... + 'ETAString', '', ... + 'Progress', progresswidget, ... + 'ProgressSize', psize, ... + 'Panel', mypanel, ... + 'BarCData', barcdata, ... + 'CData', cdata, ... + 'BackgroundCData', barcdata, ... + 'CanCancel', false, ... + 'CancelFcn', [], ... + 'CancelButton', cancelwidget, ... + 'Cancel', false, ... + 'Busy', false ); +if isempty( entries ) + entries = newentry; +else + entries = [entries;newentry]; +end +% Store in figure before the redraw +setappdata( parent, 'ProgressEntries', entries ); +if strcmpi( get( parent, 'Visible' ), 'on' ) + iRedraw( parent, [] ); +else + set( parent, 'Visible', 'on' ); +end +end % iAddEntry + +%-------------------------------------------------------------------------% +function entries = iDeleteEntry( entries, idx ) +delete( entries(idx).LabelText ); +delete( entries(idx).ETAText ); +delete( entries(idx).CancelButton ); +delete( entries(idx).Progress ); +delete( entries(idx).Panel ); +entries(idx,:) = []; +end % iDeleteEntry + +%-------------------------------------------------------------------------% +function entries = iCancelEntry( src, name ) +figh = ancestor( src, 'figure' ); +entries = getappdata( figh, 'ProgressEntries' ); +if isempty(entries) + % The entries have been lost - nothing can be done. + return +end +idx = find( strcmp( name, {entries.Label} ), 1, 'first' ); + +% Set the cancel flag so that the user is told on next update +entries(idx).Cancel = true; +setappdata( figh, 'ProgressEntries', entries ); + +% If a user function is supplied, call it +if ~isempty( entries(idx).CancelFcn ) + feval( entries(idx).CancelFcn, name, 'Cancelled' ); +end + +end % iCancelEntry + + +%-------------------------------------------------------------------------% +function [entry,updated] = iUpdateEntry( entry, force ) +% Update one progress bar + +% Deal with busy entries separately +if entry.Busy + entry = iUpdateBusyEntry(entry); + updated = true; + return; +end + +% Some constants +marker_weight = 0.8; + +% Check if the label needs updating +updated = force; +val = entry.Value; +lastval = entry.LastValue; + +% Now update the bar +psize = entry.ProgressSize; +filled = max( 1, round( val*psize(1) ) ); +lastfilled = max( 1, round( lastval*psize(1) ) ); + +% We do some careful checking so that we only redraw what we have to. This +% makes a small speed difference, but every little helps! +if force || (filled(filled-2)) = []; + highlight = [marker_weight*entry.CData, 255 - marker_weight*(255-entry.CData)]; + for ii=1:numel( markers ) + progresscdata(:,markers(ii)+[-1,0],:) = highlight; + end + + % Set the image into the checkbox + entry.BarCData = progresscdata; + set( entry.Progress, 'cdata', progresscdata ); + updated = true; + +elseif filled > lastfilled + % Just need to update the existing data + progresscdata = entry.BarCData; + startIdx = max(1,lastfilled-1); + % Repmat is the obvious way to fill the bar, but BSXFUN is often + % faster. Indexing is obscure but faster still. + progresscdata(:,startIdx:filled,:) = iMakeBarImage(entry.CData, startIdx, filled); + + % Add light/shadow around the markers + markers = round( (0.1:0.1:val)*psize(1) ); + markers(markers(filled-2)) = []; + highlight = [marker_weight*entry.CData, 255 - marker_weight*(255-entry.CData)]; + for ii=1:numel( markers ) + progresscdata(:,markers(ii)+[-1,0],:) = highlight; + end + + entry.BarCData = progresscdata; + set( entry.Progress, 'CData', progresscdata ); + updated = true; +end + +% As an optimization, don't update any text if the bar didn't move and the +% percentage hasn't changed +decval = round( val*100 ); +lastdecval = round( lastval*100 ); + +if ~updated && (decval == lastdecval) + return +end + +% Now work out the remaining time +minTime = 3; % secs +if val <= 0 + % Zero value, so clear the eta + entry.Created = tic(); + elapsedtime = 0; + etaString = ''; +else + elapsedtime = round(toc( entry.Created )); % in seconds + + % Only show the remaining time if we've had time to estimate + if elapsedtime < minTime + % Not enough time has passed since starting, so leave blank + etaString = ''; + else + % Calculate a rough ETA + eta = elapsedtime * (1-val) / val; + etaString = iGetTimeString( eta ); + end +end + +if ~isequal( etaString, entry.ETAString ) + set( entry.ETAText, 'String', etaString ); + entry.ETAString = etaString; + updated = true; +end + +% Update the label too +if force || elapsedtime > minTime + if force || (decval ~= lastdecval) + labelstr = [entry.Label, sprintf( ' (%d%%)', decval )]; + set( entry.LabelText, 'String', labelstr ); + updated = true; + end +end + +end % iUpdateEntry + +function eta = iGetTimeString( remainingtime ) +global timedays +global timehours +global timemins +global timesecs +global timesec +if remainingtime > 172800 % 2 days + eta = [sprintf( '%d ', round(remainingtime/86400) ),timedays]; +else + if remainingtime > 7200 % 2 hours + eta = [sprintf( '%d ', round(remainingtime/3600) ),timehours]; + else + if remainingtime > 120 % 2 mins + eta = [sprintf( '%d ', round(remainingtime/60) ),timemins]; + else + % Seconds + remainingtime = round( remainingtime ); + if remainingtime > 1 + eta = [sprintf( '%d ', remainingtime ),timesecs]; + elseif remainingtime == 1 + eta = ['1 ',timesec]; + else + eta = ''; % Nearly done (<1sec) + end + end + end +end +end % iGetTimeString + + +%-------------------------------------------------------------------------% +function entry = iUpdateBusyEntry( entry ) +% Update a "busy" progress bar +% Make sure the widget is still OK +if ~ishandle(entry.Progress) + return +end +% Work out the new position. Since the bar is 0.1 long and needs to bounce, +% the position varies from 0 up to 0.9 then back down again. We achieve +% this with judicious use of "mod" with 1.8. +entry.Value = mod(entry.Value+0.01,1.8); +val = entry.Value; +if val>0.9 + % Moving backwards + val = 1.8-val; +end +psize = entry.ProgressSize; +startIdx = max( 1, round( val*psize(1) ) ); +endIdx = max( 1, round( (val+0.1)*psize(1) ) ); +barLength = endIdx - startIdx + 1; + +% Create the image +bgim = entry.BackgroundCData(:,ones( 1, psize(1) ),:); +barim = iMakeBarImage(entry.CData, 1, barLength); +bgim(:,startIdx:endIdx,:) = barim; + +% Put it into the widget +entry.BarCData = bgim; +set( entry.Progress, 'CData', bgim ); +end % iUpdateBusyEntry + + +%-------------------------------------------------------------------------% +function barim = iMakeBarImage(strip, startIdx, endIdx) +shadow1_weight = 0.4; +shadow2_weight = 0.7; +barLength = endIdx - startIdx + 1; +% Repmat is the obvious way to fill the bar, but BSXFUN is often +% faster. Indexing is obscure but faster still. +barim = strip(:,ones(1, barLength),:); +% Add highlight to the start of the bar +if startIdx <= 2 && barLength>=2 + barim(:,1,:) = 255 - shadow1_weight*(255-strip); + barim(:,2,:) = 255 - shadow2_weight*(255-strip); +end +% Add shadow to the end of the bar +if endIdx>=4 && barLength>=2 + barim(:,end,:) = shadow1_weight*strip; + barim(:,end-1,:) = shadow2_weight*strip; +end +end % iMakeBarImage + +%-------------------------------------------------------------------------% +function iCloseFigure( fig, evt ) %#ok +% Closing the figure just makes it invisible +set( fig, 'Visible', 'off' ); +end % iCloseFigure + +%-------------------------------------------------------------------------% +function iDeleteFigure( fig ) +% Actually destroy the figure +busyTimer = getappdata( fig, 'BusyTimer' ); +stop( busyTimer ); +delete( busyTimer ); +delete( fig ); +end % iDeleteFigure + +%-------------------------------------------------------------------------% +function iRedraw( fig, evt ) %#ok +entries = getappdata( fig, 'ProgressEntries' ); +fobj = handle( fig ); +p = fobj.Position; +% p = get( fig, 'Position' ); +border = 5; +textheight = 16; +barheight = 16; +panelheight = 10; +N = max( 1, numel( entries ) ); + +% Check the height is correct +heightperentry = textheight+barheight+panelheight; +requiredheight = 2*border + N*heightperentry - panelheight; +if ~isequal( p(4), requiredheight ) + p(2) = p(2) + p(4) - requiredheight; + p(4) = requiredheight; + % In theory setting the position should re-trigger this callback, but + % in practice it doesn't, probably because we aren't calling "drawnow". + set( fig, 'Position', p ) +end +ypos = p(4) - border; +width = p(3) - 2*border; +setappdata( fig, 'DefaultProgressBarSize', [width barheight] ); + +for ii=1:numel( entries ) + set( entries(ii).LabelText, 'Position', [border ypos-textheight width*0.75 textheight] ); + set( entries(ii).ETAText, 'Position', [border+width*0.75 ypos-textheight width*0.25 textheight] ); + ypos = ypos - textheight; + if entries(ii).CanCancel + set( entries(ii).Progress, 'Position', [border ypos-barheight width-barheight+1 barheight] ); + entries(ii).ProgressSize = [width-barheight barheight]; + set( entries(ii).CancelButton, 'Visible', 'on', 'Position', [p(3)-border-barheight ypos-barheight barheight barheight] ); + else + set( entries(ii).Progress, 'Position', [border ypos-barheight width+1 barheight] ); + entries(ii).ProgressSize = [width barheight]; + set( entries(ii).CancelButton, 'Visible', 'off' ); + end + ypos = ypos - barheight; + set( entries(ii).Panel, 'Position', [-500 ypos-500-panelheight/2 p(3)+1000 500] ); + ypos = ypos - panelheight; + entries(ii) = iUpdateEntry( entries(ii), true ); +end +setappdata( fig, 'ProgressEntries', entries ); +end % iRedraw + +function cdata = iMakeCross( sz ) +% Create a cross-shape icon of size sz*sz*3 + +cdata = diag(ones(sz,1),0) + diag(ones(sz-1,1),1) + diag(ones(sz-1,1),-1); +cdata = cdata + flip(cdata,2); + +% Convert zeros to nans (transparent) and non-zeros to zero (black) +cdata(cdata == 0) = nan; +cdata(~isnan(cdata)) = 0; + +% Convert to RGB +cdata = cat( 3, cdata, cdata, cdata ); +end % iMakeCross + + +function iTimerFcn(fig) +% Timer callback for updating stuff every so often +entries = getappdata( fig, 'ProgressEntries' ); +for ii=1:numel(entries) + if entries(ii).Busy + entries(ii) = iUpdateBusyEntry(entries(ii)); + end +end +setappdata( fig, 'ProgressEntries', entries ); +end % iTimerFcn diff --git a/include/representaAbsorcion.m b/include/representaAbsorcion.m new file mode 100644 index 0000000..bdbef2a --- /dev/null +++ b/include/representaAbsorcion.m @@ -0,0 +1,21 @@ +function representaAbsorcion(handles) + +axes(handles.plotfig) +Absor = handles.SPLm{handles.Index,11}; +Frecuencia = [125,250,500,1000,2000,4000,8000]; +Fuente = string(handles.SPLm(handles.Index,2)); +% Pasar de tercios de octava a octavas +Octavas = zeros(1,7); +a = 0; +for i=2:3:21 + a = a+1; + Octavas(a) = (Absor(i-1)+Absor(i)+Absor(i+1))/3; +end + +bar(Octavas*100) +set(gca,'XTickLabel', Frecuencia); + +title('Coeficientes de absorci�n medio') +xlabel('Frecuencia (Hz)') +ylabel('\alpha (%)') +end \ No newline at end of file diff --git a/include/representaDirectividad.m b/include/representaDirectividad.m new file mode 100644 index 0000000..44f83d9 --- /dev/null +++ b/include/representaDirectividad.m @@ -0,0 +1,21 @@ +function representaDirectividad(handles) + +axes(handles.plotfig) +Resp = handles.SPLm{handles.Index,14}; +Frecuencia = [125,250,500,1000,2000,4000,8000]; +Fuente = string(handles.SPLm(handles.Index,2)); +% Obtener solo el valor de las octavas +Octavas = zeros(1,7); +a = 0; +for i=2:3:21 + a = a+1; + Octavas(a) = Resp(i); +end + +bar(Octavas) +set(gca,'XTickLabel', Frecuencia); + +title(sprintf('Respuesta en frecuencia de la fuente %s',Fuente)) +xlabel('Frecuencia (Hz)') +ylabel('DI (dB)') +end \ No newline at end of file diff --git a/include/representaRT.m b/include/representaRT.m new file mode 100644 index 0000000..18d0229 --- /dev/null +++ b/include/representaRT.m @@ -0,0 +1,21 @@ +function representaRT(handles) + +axes(handles.plotfig) +RT = handles.SPLm{handles.Index,10}; +Frecuencia = [125,250,500,1000,2000,4000,8000]; +Fuente = string(handles.SPLm(handles.Index,2)); +% Pasar de tercios de octava a octavas +Octavas = zeros(1,7); +a = 0; +for i=2:3:21 + a = a+1; + Octavas(a) = (RT(i-1)+RT(i)+RT(i+1))/3; +end + +bar(Octavas) +set(gca,'XTickLabel', Frecuencia); + +title(sprintf('Tiempo de reverberaci�n con la fuente %s',Fuente)) +xlabel('Frecuencia (Hz)') +ylabel('Tiempo de reverberaci�n (s)') +end \ No newline at end of file diff --git a/include/representaRespuesta.m b/include/representaRespuesta.m new file mode 100644 index 0000000..299bc75 --- /dev/null +++ b/include/representaRespuesta.m @@ -0,0 +1,21 @@ +function representaRespuesta(handles) + +axes(handles.plotfig) +Resp = handles.SPLm{handles.Index,13}; +Frecuencia = [125,250,500,1000,2000,4000,8000]; +Fuente = string(handles.SPLm(handles.Index,2)); +% Pasar de tercios de octava a octavas +Octavas = zeros(1,7); +a = 0; +for i=2:3:21 + a = a+1; + Octavas(a) = 10*log10(sum(10.^(Resp(i-1)/10)+10.^(Resp(i)/10)+10.^(Resp(i+1)/10))); +end + +bar(Octavas) +set(gca,'XTickLabel', Frecuencia); + +title(sprintf('Respuesta en frecuencia de la fuente %s',Fuente)) +xlabel('Frecuencia (Hz)') +ylabel('Nivel SPL (dB)') +end \ No newline at end of file diff --git a/include/representarCt.m b/include/representarCt.m new file mode 100644 index 0000000..27498d7 --- /dev/null +++ b/include/representarCt.m @@ -0,0 +1,331 @@ +function representarCt(hObject,handles) +% Reprsentacion del parametro claridad +axes(handles.plotfig) + +Rango = handles.Rango; +SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar +SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas +Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor +Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas +Fuente = string(handles.SPLm(:,2)'); +Receptor = string(handles.SPLm(:,3)'); + + +% Comprobar que bandas de frecuencias se han elegido +Bandas = []; +fsel = []; +if handles.frec125.Value==1 + Bandas = [Bandas,1]; + fsel = [fsel,125]; +end +if handles.frec250.Value==1 + Bandas = [Bandas,2]; + fsel = [fsel,250]; +end +if handles.frec500.Value==1 + Bandas = [Bandas,3]; + fsel = [fsel,500]; +end +if handles.frec1000.Value==1 + Bandas = [Bandas,4]; + fsel = [fsel,1000]; +end +if handles.frec2000.Value==1 + Bandas = [Bandas,5]; + fsel = [fsel,2000]; +end +if handles.frec4000.Value==1 + Bandas = [Bandas,6]; + fsel = [fsel,4000]; +end +if handles.frec8000.Value==1 + Bandas = [Bandas,7]; + fsel = [fsel,8000]; +end +if isempty(Bandas); Bandas = 1:7; end +if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end + +%% Procesado de datos +% Separacion e integracion de los niveles antes y despues del rango +Dneto = zeros(1,numel(SPLm)); +Eneto = zeros(1,numel(SPLm)); +Lneto = zeros(1,numel(SPLm)); +for i=1:numel(SPLm) + % Direct - Early - Late EXTRACTION + Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 1 ms + Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 1 ms a tiempo de integracion + Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito + + % Ponderacion A + % f = fsel; % Frecuencias seleccionadas + % ponderacionA = 20*log10(... + % 12194^2*f.^4 ./... + % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2; + % Dbruto = Dbruto + ponderacionA; + % Ebruto = Ebruto + ponderacionA; + % Lbruto = Lbruto + ponderacionA; + + % Suma de niveles para los dos rangos + Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10))); + Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10))); + Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10))); +end + +% Campo util es la suma del campo directo y el early +Uneto = 10*log10(10.^(Dneto/10)+10.^(Eneto/10)); + +%% Representacion grafica del campo Util y el Perjudicial + +%% Puntos y curva de 0ms a Valor +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_U = sortrows([Distancia',Uneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_U(:,1),'stable'); +val = accumarray(idx,Dist_U(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_U = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); +%Dist_U = [[0;V0_0toVal]';Dist_U]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_U(:,1); +Urec = Dist_U(:,2); +% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste +% (Ures) +[Ucoef,Ures,Uoutput]=fit(Dist,Urec,'power1'); +Uplot=Ucoef.a*Distplot.^Ucoef.b; + + + +%% Puntos y curva de valor a infinito ms +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_P = sortrows([Distancia',Lneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_P(:,1),'stable'); +val = accumarray(idx,Dist_P(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_P = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap'); +%Dist_P = [[0;V0_0toVal]';Dist_P]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_P(:,1); +Prec = Dist_P(:,2); +% Obtener coeificentes curva polinomica de grado 1 +[Pcoef,Pres,Poutput] = fit(Dist,Prec,'poly1'); +% Crea la curva +Pplot = Pcoef.p1*Distplot+Pcoef.p2; + + +% Claridad EASE +% Muestra los puntos +plot(Dist,Urec-Prec,'^b','MarkerFaceColor','b'),hold on +% Muestra la curva +Curv(1)=plot(Distplot,Uplot-Pplot,'b','LineWidth',1.2); + +% A�ade las rejillas de las graficas +grid on +grid minor + +% Leyenda +leyenda{1} = sprintf('C_{%s} - EASE',num2str(Rango)); + +%% Teoria corregida +% Si se ha marcado el calculo de la teoria revisada corregida se calcula y +% se a�ade a la grafica +if get(handles.teoriacorregida,'value')==1 + %%% PARAMETROS + % Nivel de presion total de la fuente a 1 metro + SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10))); + % Volumen (m3) + V = handles.SPLm{handles.Index,15}; + % Superficie (m2) + S = handles.SPLm{handles.Index,16}; + % Mean Free Path + mfp = 4*V/S; + % Absorcion media + alpha = mean(handles.SPLm{handles.Index,11}); + % Absorci�n equivalente de Eyring + A = -S*log(1-alpha); + % Temperatura de la sala + temp = handles.SPLm{handles.Index,17}; + % Velocidad del sonido + c = 331.4 + 0.6*temp; + % Densidad del aire. Presion Atm / (constante gas*Temp + % absoluta) + rho = 101325 / (287.058*(273.15+temp)); + % Impedancia acustica del aire + Z = rho*c; + % Presion de referencia + pref = 2*10^(-5); + % Factor de conversion + Fac = Z/(pref^2); + % Directividad de la fuente + Q = str2double(get(handles.Qdir,'string')); + % Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1 + SWL = SPL - 10*log10(1/(4*pi*1)); + % Potencia de la fuente en vatios + W = 10.^(SWL/10)*10^-12; + % Tiempo de reverberacion de Eyring + T = 6*log(10)/c * mfp * 1/(-log(1-alpha)); + % Rango de integracion temporal (s) + t = handles.Rango * 10^(-3); + + %% Obtencion de la curvas directo y early + %% Curva del campo directo + % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl + % asociado + Dist_D = sortrows([Distancia',Dneto']); + % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos + % distancias iguales y elimina el duplicado + [C,~,idx] = unique(Dist_D(:,1),'stable'); + val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); + Dist_D = [C,val]; + % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del + % receptor mas cercano + %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); + %Dist_U = [[0;V0_0toVal]';Dist_U]; + % Separar los valores para graficar y convertirlo en vector fila + Dist = Dist_D(:,1); + Drec = Dist_D(:,2); + % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste + % (Ures) + [Dcoef,Dres]=fit(Dist,Drec,'power1'); + Dplot=Dcoef.a*Distplot.^Dcoef.b; + + %% Curva del campo early + % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl + % asociado + Dist_E = sortrows([Distancia',Eneto']); + % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos + % distancias iguales y elimina el duplicado + [C,~,idx] = unique(Dist_E(:,1),'stable'); + val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); + Dist_E = [C,val]; + % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del + % receptor mas cercano + %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); + %Dist_U = [[0;V0_0toVal]';Dist_U]; + % Separar los valores para graficar y convertirlo en vector fila + Dist = Dist_E(:,1); + Erec = Dist_E(:,2); + % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste + % (Ures) + [Ecoef,Eres]=fit(Dist,Erec,'power1'); + Eplot=Ecoef.a*Distplot.^Ecoef.b; + + % Para no mostrar errores cuando se repite el calculo de coeficientes + warning ('off','all'); + + %% Calculo de coeficiente para el campo directo + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opD = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'Lower',[0,0],... % Minimo valor de los coeficientes + 'Upper',[20,20],... % Maximo valor de los coeficientes + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'Q','W','Fac'},... + 'coefficients',{'Cd'},... + 'options',opD); + [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + + %% Calculo de coeficientes epsilon y Cl para campo late + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','t','T','c','Fac'},... + 'coefficients',{'el','Cl'}); + [fitiL,gofL,outputL] = fit(Distplot',10.^(Pplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + %% Calculo de coeficientes epsilon y Ce para campo early + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opE = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},... + 'coefficients',{'ee','Ce'},... + 'options',opE); + [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + warning ('on','all'); + + PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd)); + Peplot = 10*log10(Fac *(... + (4*W)./(S*(-log(1-alpha))*Distplot) .* ... + (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl))); + Pdeplot = 10*log10(10.^(PDplot/10)+10.^(Peplot/10)); + Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl); + + Curv(2) = plot(Distplot,Pdeplot - Plateplot,'-.r','LineWidth',1); + + % Leyendas + leyenda{2} = sprintf('C_{%s} - Te�rico',num2str(Rango)); + +end + +lgdw=legend(Curv,leyenda); +lgdw.FontSize = 11; +%lgdw.Location = 'northeastoutside'; +% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya +% que no es compatible +if ~verLessThan('matlab','8.7') + title(lgdw,'Curvas') +end +ylabel(sprintf('C_{%s} (dB)',num2str(Rango))) +xlabel('Distancia (m)') +title({sprintf('C_{%s}',num2str(Rango));... + ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]}); + +hold off + diff --git a/include/representarDt.m b/include/representarDt.m new file mode 100644 index 0000000..c593362 --- /dev/null +++ b/include/representarDt.m @@ -0,0 +1,330 @@ +function representarDt(hObject,handles) +% Reprsentacion del parametro definicion +axes(handles.plotfig) +Rango = handles.Rango; +SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar +SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas +Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor +Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas +Fuente = string(handles.SPLm(:,2)'); +Receptor = string(handles.SPLm(:,3)'); + + +% Comprobar que bandas de frecuencias se han elegido +Bandas = []; +fsel = []; +if handles.frec125.Value==1 + Bandas = [Bandas,1]; + fsel = [fsel,125]; +end +if handles.frec250.Value==1 + Bandas = [Bandas,2]; + fsel = [fsel,250]; +end +if handles.frec500.Value==1 + Bandas = [Bandas,3]; + fsel = [fsel,500]; +end +if handles.frec1000.Value==1 + Bandas = [Bandas,4]; + fsel = [fsel,1000]; +end +if handles.frec2000.Value==1 + Bandas = [Bandas,5]; + fsel = [fsel,2000]; +end +if handles.frec4000.Value==1 + Bandas = [Bandas,6]; + fsel = [fsel,4000]; +end +if handles.frec8000.Value==1 + Bandas = [Bandas,7]; + fsel = [fsel,8000]; +end +if isempty(Bandas); Bandas = 1:7; end +if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end + +%% Procesado de datos +% Separacion e integracion de los niveles antes y despues del rango +Dneto = zeros(1,numel(SPLm)); +Eneto = zeros(1,numel(SPLm)); +Lneto = zeros(1,numel(SPLm)); +for i=1:numel(SPLm) + % Direct - Early - Late EXTRACTION + Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 1 ms + Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 1 ms a tiempo de integracion + Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito + + % Ponderacion A + % f = fsel; % Frecuencias seleccionadas + % ponderacionA = 20*log10(... + % 12194^2*f.^4 ./... + % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2; + % Dbruto = Dbruto + ponderacionA; + % Ebruto = Ebruto + ponderacionA; + % Lbruto = Lbruto + ponderacionA; + + % Suma de niveles para los dos rangos + Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10))); + Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10))); + Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10))); +end + +% Campo util es la suma del campo directo y el early +Uneto = 10*log10(10.^(Dneto/10)+10.^(Eneto/10)); + +%% Representacion grafica del campo Util y el Perjudicial + +%% Puntos y curva de 0ms a Valor +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_U = sortrows([Distancia',Uneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_U(:,1),'stable'); +val = accumarray(idx,Dist_U(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_U = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); +%Dist_U = [[0;V0_0toVal]';Dist_U]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_U(:,1); +Urec = Dist_U(:,2); +% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste +% (Ures) +[Ucoef,Ures,Uoutput]=fit(Dist,Urec,'power1'); +Uplot=Ucoef.a*Distplot.^Ucoef.b; + + + +%% Puntos y curva de valor a infinito ms +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_P = sortrows([Distancia',Lneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_P(:,1),'stable'); +val = accumarray(idx,Dist_P(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_P = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap'); +%Dist_P = [[0;V0_0toVal]';Dist_P]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_P(:,1); +Prec = Dist_P(:,2); +% Obtener coeificentes curva polinomica de grado 1 +[Pcoef,Pres,Poutput] = fit(Dist,Prec,'poly1'); +% Crea la curva +Pplot = Pcoef.p1*Distplot+Pcoef.p2; + + +% Claridad EASE +% Muestra los puntos +plot(Dist,10.^(Urec/10)./( 10.^(Urec/10) + 10.^(Prec/10) ),'^b','MarkerFaceColor','b'),hold on +% Muestra la curva +Curv(1)=plot(Distplot,10.^(Uplot/10)./( 10.^(Uplot/10) + 10.^(Pplot/10) ),'b','LineWidth',1.2); + +% A�ade las rejillas de las graficas +grid on +grid minor + +% Leyenda +leyenda{1} = sprintf('D_{%s} - EASE',num2str(Rango)); + +%% Teoria corregida +% Si se ha marcado el calculo de la teoria revisada corregida se calcula y +% se a�ade a la grafica +if get(handles.teoriacorregida,'value')==1 + %%% PARAMETROS + % Nivel de presion total de la fuente a 1 metro + SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10))); + % Volumen (m3) + V = handles.SPLm{handles.Index,15}; + % Superficie (m2) + S = handles.SPLm{handles.Index,16}; + % Mean Free Path + mfp = 4*V/S; + % Absorcion media + alpha = mean(handles.SPLm{handles.Index,11}); + % Absorci�n equivalente de Eyring + A = -S*log(1-alpha); + % Temperatura de la sala + temp = handles.SPLm{handles.Index,17}; + % Velocidad del sonido + c = 331.4 + 0.6*temp; + % Densidad del aire. Presion Atm / (constante gas*Temp + % absoluta) + rho = 101325 / (287.058*(273.15+temp)); + % Impedancia acustica del aire + Z = rho*c; + % Presion de referencia + pref = 2*10^(-5); + % Factor de conversion + Fac = Z/(pref^2); + % Directividad de la fuente + Q = str2double(get(handles.Qdir,'string')); + % Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1 + SWL = SPL - 10*log10(1/(4*pi*1)); + % Potencia de la fuente en vatios + W = 10.^(SWL/10)*10^-12; + % Tiempo de reverberacion de Eyring + T = 6*log(10)/c * mfp * 1/(-log(1-alpha)); + % Rango de integracion temporal (s) + t = handles.Rango * 10^(-3); + + %% Obtencion de la curvas directo y early + %% Curva del campo directo + % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl + % asociado + Dist_D = sortrows([Distancia',Dneto']); + % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos + % distancias iguales y elimina el duplicado + [C,~,idx] = unique(Dist_D(:,1),'stable'); + val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); + Dist_D = [C,val]; + % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del + % receptor mas cercano + %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); + %Dist_U = [[0;V0_0toVal]';Dist_U]; + % Separar los valores para graficar y convertirlo en vector fila + Dist = Dist_D(:,1); + Drec = Dist_D(:,2); + % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste + % (Ures) + [Dcoef,Dres]=fit(Dist,Drec,'power1'); + Dplot=Dcoef.a*Distplot.^Dcoef.b; + + %% Curva del campo early + % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl + % asociado + Dist_E = sortrows([Distancia',Eneto']); + % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos + % distancias iguales y elimina el duplicado + [C,~,idx] = unique(Dist_E(:,1),'stable'); + val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); + Dist_E = [C,val]; + % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del + % receptor mas cercano + %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); + %Dist_U = [[0;V0_0toVal]';Dist_U]; + % Separar los valores para graficar y convertirlo en vector fila + Dist = Dist_E(:,1); + Erec = Dist_E(:,2); + % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste + % (Ures) + [Ecoef,Eres]=fit(Dist,Erec,'power1'); + Eplot=Ecoef.a*Distplot.^Ecoef.b; + + % Para no mostrar errores cuando se repite el calculo de coeficientes + warning ('off','all'); + + %% Calculo de coeficiente para el campo directo + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opD = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'Lower',[0,0],... % Minimo valor de los coeficientes + 'Upper',[20,20],... % Maximo valor de los coeficientes + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'Q','W','Fac'},... + 'coefficients',{'Cd'},... + 'options',opD); + [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + + %% Calculo de coeficientes epsilon y Cl para campo late + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','t','T','c','Fac'},... + 'coefficients',{'el','Cl'}); + [fitiL,gofL,outputL] = fit(Distplot',10.^(Pplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + %% Calculo de coeficientes epsilon y Ce para campo early + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opE = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},... + 'coefficients',{'ee','Ce'},... + 'options',opE); + [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + warning ('on','all'); + + PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd)); + Peplot = 10*log10(Fac *(... + (4*W)./(S*(-log(1-alpha))*Distplot) .* ... + (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl))); + Pdeplot = 10*log10(10.^(PDplot/10)+10.^(Peplot/10)); + Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl); + + Curv(2) = plot(Distplot,10.^(Pdeplot/10)./( 10.^(Pdeplot/10) + 10.^(Plateplot/10) ),'-.r','LineWidth',1); + + % Leyendas + leyenda{2} = sprintf('D_{%s} - Te�rico',num2str(Rango)); + +end + +lgdw=legend(Curv,leyenda); +lgdw.FontSize = 11; +%lgdw.Location = 'northeastoutside'; +% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya +% que no es compatible +if ~verLessThan('matlab','8.7') + title(lgdw,'Curvas') +end +ylabel(sprintf('D_{%s} (dB)',num2str(Rango))) +xlabel('Distancia (m)') +title({sprintf('D_{%s}',num2str(Rango));... + ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]}); + +hold off + diff --git a/include/representarEcograma.m b/include/representarEcograma.m new file mode 100644 index 0000000..ad1603f --- /dev/null +++ b/include/representarEcograma.m @@ -0,0 +1,30 @@ +function representarEcograma(handles) + +axes(handles.plotfig) +Index = handles.Index; +SPLm = handles.SPLm(:,1); +SPLmTot = handles.SPLm(:,19); +Distancia = cell2mat(handles.SPLm(:,6))'; +Fuente = string(handles.SPLm(:,2)'); +Receptor = string(handles.SPLm(:,3)'); + + +% Obtener ecograma del receptor Index, sumando las octavas +Ecogra = 10*log10(sum(10.^((SPLmTot{Index}(:,2:end)')/10))); +tiempo = SPLmTot{Index}(:,1); + + + +%% Representacion grafica + + +% Ecograma +stem(tiempo,Ecogra,'Marker','none') + +title({sprintf('Ecograma del receptor: %s',Receptor(Index));... + ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]}) +xlabel('Tiempo (ms)') +ylabel('Nivel SPL (dB)') +% Limite del eje x con margen a ambos lados +xlim([-max(tiempo)/10,max(tiempo)+max(tiempo)/10]) +end \ No newline at end of file diff --git a/include/representarG.m b/include/representarG.m new file mode 100644 index 0000000..528d4d6 --- /dev/null +++ b/include/representarG.m @@ -0,0 +1,367 @@ +function representarG(hObject,handles) +% Reprsentacion del parametro sonoridad + +axes(handles.plotfig) +Rango = handles.Rango; +SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar +SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas +Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor +Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas +Fuente = string(handles.SPLm(:,2)'); +Receptor = string(handles.SPLm(:,3)'); + + +% Comprobar que bandas de frecuencias se han elegido +Bandas = []; +fsel = []; +if handles.frec125.Value==1 + Bandas = [Bandas,1]; + fsel = [fsel,125]; +end +if handles.frec250.Value==1 + Bandas = [Bandas,2]; + fsel = [fsel,250]; +end +if handles.frec500.Value==1 + Bandas = [Bandas,3]; + fsel = [fsel,500]; +end +if handles.frec1000.Value==1 + Bandas = [Bandas,4]; + fsel = [fsel,1000]; +end +if handles.frec2000.Value==1 + Bandas = [Bandas,5]; + fsel = [fsel,2000]; +end +if handles.frec4000.Value==1 + Bandas = [Bandas,6]; + fsel = [fsel,4000]; +end +if handles.frec8000.Value==1 + Bandas = [Bandas,7]; + fsel = [fsel,8000]; +end +if isempty(Bandas); Bandas = 1:7; end +if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end + +%% Procesado de datos +% Separacion e integracion de los niveles antes y despues del rango +Dneto = zeros(1,numel(SPLm)); +Eneto = zeros(1,numel(SPLm)); +Lneto = zeros(1,numel(SPLm)); +for i=1:numel(SPLm) + % Direct - Early - Late EXTRACTION + Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 1 ms + Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 1 ms a tiempo de integracion + Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito + + % Ponderacion A + % f = fsel; % Frecuencias seleccionadas + % ponderacionA = 20*log10(... + % 12194^2*f.^4 ./... + % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2; + % Dbruto = Dbruto + ponderacionA; + % Ebruto = Ebruto + ponderacionA; + % Lbruto = Lbruto + ponderacionA; + + % Suma de niveles para los dos rangos + Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10))); + Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10))); + Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10))); +end + +% Campo util es la suma del campo directo y el early +Uneto = 10*log10(10.^(Dneto/10)+10.^(Eneto/10)); + +% Temperatura +temp = handles.SPLm{handles.Index,17}; +% Velocidad del sonido +c = 331.4 + 0.6*temp; +% Densidad del aire. Presion Atm / (constante gas*Temp +% absoluta) +rho = 101325 / (287.058*(273.15+temp)); +% Impedancia acustica del aire +Z = rho*c; +% Nivel de presion total de la fuente a 1 metro +SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10))); +% Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1 +SWL = SPL - 10*log10(1/(4*pi*1)); +% Potencia de la fuente en vatios +W = 10.^(SWL/10)*10^-12; + +%% Representacion grafica del campo Util y el Perjudicial + +%% Puntos y curva de 0ms a Valor +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_U = sortrows([Distancia',Uneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_U(:,1),'stable'); +val = accumarray(idx,Dist_U(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_U = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); +%Dist_U = [[0;V0_0toVal]';Dist_U]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_U(:,1); +Urec = Dist_U(:,2); +% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste +% (Ures) +[Ucoef,Ures,Uoutput]=fit(Dist,Urec,'power1'); +Uplot=Ucoef.a*Distplot.^Ucoef.b; + + +%% Curva del campo directo +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_D = sortrows([Distancia',Dneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_D(:,1),'stable'); +val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_D = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); +%Dist_U = [[0;V0_0toVal]';Dist_U]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_D(:,1); +Drec = Dist_D(:,2); +% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste +% (Ures) +[Dcoef,Dres]=fit(Dist,Drec,'power1'); +Dplot=Dcoef.a*Distplot.^Dcoef.b; + +%% Puntos y curva de valor a infinito ms +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_P = sortrows([Distancia',Lneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_P(:,1),'stable'); +val = accumarray(idx,Dist_P(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_P = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap'); +%Dist_P = [[0;V0_0toVal]';Dist_P]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_P(:,1); +Prec = Dist_P(:,2); +% Obtener coeificentes curva polinomica de grado 1 +[Pcoef,Pres,Poutput] = fit(Dist,Prec,'poly1'); +% Crea la curva +Pplot = Pcoef.p1*Distplot+Pcoef.p2; + + +% Claridad EASE +% Muestra los puntos +plot(Dist,10*log10( (10.^(Urec/10) + 10.^(Prec/10)) ./ 10^((Dcoef.a*10^Dcoef.b)/10) ) ,'^b','MarkerFaceColor','b'),hold on +% Muestra la curva +Curv(1)=plot(Distplot,10*log10( (10.^(Uplot/10) + 10.^(Pplot/10)) ./ 10^((Dcoef.a*10^Dcoef.b)/10) ),'b','LineWidth',1.2); + +% A�ade las rejillas de las graficas +grid on +grid minor + +% Leyenda +leyenda{1} = 'G - EASE'; + +%% Teoria corregida +% Si se ha marcado el calculo de la teoria revisada corregida se calcula y +% se a�ade a la grafica +if get(handles.teoriacorregida,'value')==1 + %%% PARAMETROS + % Nivel de presion total de la fuente a 1 metro + SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10))); + % Volumen (m3) + V = handles.SPLm{handles.Index,15}; + % Superficie (m2) + S = handles.SPLm{handles.Index,16}; + % Mean Free Path + mfp = 4*V/S; + % Absorcion media + alpha = mean(handles.SPLm{handles.Index,11}); + % Absorci�n equivalente de Eyring + A = -S*log(1-alpha); + % Temperatura de la sala + temp = handles.SPLm{handles.Index,17}; + % Velocidad del sonido + c = 331.4 + 0.6*temp; + % Densidad del aire. Presion Atm / (constante gas*Temp + % absoluta) + rho = 101325 / (287.058*(273.15+temp)); + % Impedancia acustica del aire + Z = rho*c; + % Presion de referencia + pref = 2*10^(-5); + % Factor de conversion + Fac = Z/(pref^2); + % Directividad de la fuente + Q = str2double(get(handles.Qdir,'string')); + % Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1 + SWL = SPL - 10*log10(1/(4*pi*1)); + % Potencia de la fuente en vatios + W = 10.^(SWL/10)*10^-12; + % Tiempo de reverberacion de Eyring + T = 6*log(10)/c * mfp * 1/(-log(1-alpha)); + % Rango de integracion temporal (s) + t = handles.Rango * 10^(-3); + + %% Obtencion de la curvas directo y early + %% Curva del campo directo + % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl + % asociado + Dist_D = sortrows([Distancia',Dneto']); + % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos + % distancias iguales y elimina el duplicado + [C,~,idx] = unique(Dist_D(:,1),'stable'); + val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); + Dist_D = [C,val]; + % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del + % receptor mas cercano + %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); + %Dist_U = [[0;V0_0toVal]';Dist_U]; + % Separar los valores para graficar y convertirlo en vector fila + Dist = Dist_D(:,1); + Drec = Dist_D(:,2); + % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste + % (Ures) + [Dcoef,Dres]=fit(Dist,Drec,'power1'); + Dplot=Dcoef.a*Distplot.^Dcoef.b; + + %% Curva del campo early + % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl + % asociado + Dist_E = sortrows([Distancia',Eneto']); + % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos + % distancias iguales y elimina el duplicado + [C,~,idx] = unique(Dist_E(:,1),'stable'); + val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); + Dist_E = [C,val]; + % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del + % receptor mas cercano + %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); + %Dist_U = [[0;V0_0toVal]';Dist_U]; + % Separar los valores para graficar y convertirlo en vector fila + Dist = Dist_E(:,1); + Erec = Dist_E(:,2); + % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste + % (Ures) + [Ecoef,Eres]=fit(Dist,Erec,'power1'); + Eplot=Ecoef.a*Distplot.^Ecoef.b; + + % Para no mostrar errores cuando se repite el calculo de coeficientes + warning ('off','all'); + + %% Calculo de coeficiente para el campo directo + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opD = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'Lower',[0,0],... % Minimo valor de los coeficientes + 'Upper',[20,20],... % Maximo valor de los coeficientes + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'Q','W','Fac'},... + 'coefficients',{'Cd'},... + 'options',opD); + [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + + %% Calculo de coeficientes epsilon y Cl para campo late + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','t','T','c','Fac'},... + 'coefficients',{'el','Cl'}); + [fitiL,gofL,outputL] = fit(Distplot',10.^(Pplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + %% Calculo de coeficientes epsilon y Ce para campo early + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opE = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},... + 'coefficients',{'ee','Ce'},... + 'options',opE); + [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + warning ('on','all'); + + PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd)); + Peplot = 10*log10(Fac *(... + (4*W)./(S*(-log(1-alpha))*Distplot) .* ... + (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl))); + Pdeplot = 10*log10(10.^(PDplot/10)+10.^(Peplot/10)); + Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl); + + Curv(2) = plot(Distplot,10*log10( (10.^(Pdeplot/10) + 10.^(Plateplot/10)) ./ (Fac * ( W./(4*pi*10.^2)*fitiD.Cd)) ),'-.r','LineWidth',1); + + % Leyendas + leyenda{2} = 'G - Te�rico'; + +end + +lgdw=legend(Curv,leyenda); +lgdw.FontSize = 11; +%lgdw.Location = 'northeastoutside'; +% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya +% que no es compatible +if ~verLessThan('matlab','8.7') + title(lgdw,'Curvas') +end +ylabel('G (dB)') +xlabel('Distancia (m)') +title({'G';... + ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]}); + +hold off + diff --git a/include/representarSPLvsDist2.m b/include/representarSPLvsDist2.m new file mode 100644 index 0000000..59642f5 --- /dev/null +++ b/include/representarSPLvsDist2.m @@ -0,0 +1,436 @@ +function representarSPLvsDist2(hObject,handles) + +axes(handles.plotfig) +Rango = handles.Rango; +SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar +SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas +Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor +Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas +Fuente = string(handles.SPLm(:,2)'); +Receptor = string(handles.SPLm(:,3)'); + + +% Comprobar que bandas de frecuencias se han elegido +Bandas = []; +fsel = []; +if handles.frec125.Value==1 + Bandas = [Bandas,1]; + fsel = [fsel,125]; +end +if handles.frec250.Value==1 + Bandas = [Bandas,2]; + fsel = [fsel,250]; +end +if handles.frec500.Value==1 + Bandas = [Bandas,3]; + fsel = [fsel,500]; +end +if handles.frec1000.Value==1 + Bandas = [Bandas,4]; + fsel = [fsel,1000]; +end +if handles.frec2000.Value==1 + Bandas = [Bandas,5]; + fsel = [fsel,2000]; +end +if handles.frec4000.Value==1 + Bandas = [Bandas,6]; + fsel = [fsel,4000]; +end +if handles.frec8000.Value==1 + Bandas = [Bandas,7]; + fsel = [fsel,8000]; +end +if isempty(Bandas); Bandas = 1:7; end +if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end + +%% Procesado de datos +% Separacion e integracion de los niveles antes y despues del rango +Dneto = zeros(1,numel(SPLm)); +Eneto = zeros(1,numel(SPLm)); +Lneto = zeros(1,numel(SPLm)); +for i=1:numel(SPLm) + % Direct - Early - Late EXTRACTION + Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 1 ms + Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 1 ms a tiempo de integracion + Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito + + % Ponderacion A + % f = fsel; % Frecuencias seleccionadas + % ponderacionA = 20*log10(... + % 12194^2*f.^4 ./... + % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2; + % Dbruto = Dbruto + ponderacionA; + % Ebruto = Ebruto + ponderacionA; + % Lbruto = Lbruto + ponderacionA; + + % Suma de niveles para los dos rangos + Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10))); + Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10))); + Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10))); +end + +% Campo util es la suma del campo directo y el early +Uneto = 10*log10(10.^(Dneto/10)+10.^(Eneto/10)); + +%% Representacion grafica del campo Util y el Perjudicial +colores = colormap(jet(21)); +% Indices de color +iCU = 1; +iCUt = 3; +iCL = 18; +iCLt = 21; +%% Puntos y curva de 0ms a Valor +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_U = sortrows([Distancia',Uneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_U(:,1),'stable'); +val = accumarray(idx,Dist_U(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_U = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); +%Dist_U = [[0;V0_0toVal]';Dist_U]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_U(:,1); +Urec = Dist_U(:,2); +% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste +% (Ures) +[Ucoef,Ures,Uoutput]=fit(Dist,Urec,'power1'); +Uplot=Ucoef.a*Distplot.^Ucoef.b; +% Muestra los puntos +plot(Dist,Urec,'s','Color',colores(iCU,:),'MarkerFaceColor',colores(iCU,:)) +hold on +% Muestra los errores +Uerr = confint(Ucoef); +Ucurvarec = Ucoef.a*Dist.^Ucoef.b; +errorbar(Dist,Ucoef.a*Dist.^Ucoef.b,... % Curva + (Uerr(2)*Dist.^Uerr(4)) - Ucurvarec,... % Error positivo + Ucurvarec - (Uerr(1)*Dist.^Uerr(3)),... % Error negativo + 'b','LineStyle','none') +% Muestra la curva +Curv(1)=plot(Distplot,Uplot,'Color',colores(iCU,:),'LineWidth',1.2); + +%% Puntos y curva de valor a infinito ms +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_P = sortrows([Distancia',Lneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_P(:,1),'stable'); +val = accumarray(idx,Dist_P(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_P = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap'); +%Dist_P = [[0;V0_0toVal]';Dist_P]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_P(:,1); +Prec = Dist_P(:,2); +% Obtener coeificentes curva polinomica de grado 1 +[Pcoef,Pres,Poutput] = fit(Dist,Prec,'poly1'); +% Crea la curva +Pplot = Pcoef.p1*Distplot+Pcoef.p2; +% Muestra los puntos +plot(Dist,Prec,'^','Color',colores(iCL,:),'MarkerFaceColor',colores(iCL,:)) +% Muestra los errores +Perr = confint(Pcoef); +Pcurvarec = Pcoef.p1*Dist+Pcoef.p2; +errorbar(Dist,Pcoef.p1*Dist+Pcoef.p2,... % Curva + (Perr(2)*Dist+Perr(4)) - Pcurvarec,... % Error positivo + Pcurvarec - (Perr(1)*Dist+Perr(3)),... % Error negativo + 'r','LineStyle','none') +% Muestra la curva +Curv(2)=plot(Distplot,Pplot,'Color',colores(iCL,:),'LineWidth',1.2); + +% A�ade las rejillas de las graficas +grid on +grid minor + +% Obtener punto de cruce +CortesInd = find(abs(Uplot-Pplot)<=(0.01)); +if ~isnan(CortesInd) + DistCorte = Distplot(CortesInd(1)); + text(DistCorte,Uplot(CortesInd(1))+1,... + {'EASE',strcat('\bf\color{black}',[sprintf('%4.3f',DistCorte),' m'])},... + 'VerticalAlignment','bottom','HorizontalAlignment','left') +end + +%% Guarda un .dat para generar graficas en el LaTex +%guardarErrores(Ucoef,Pcoef,Distancia,Dist_P,Dist_U) +%% + +% Obtener numero de ceros decimales de las pendientes, sumarle 1 y convertir a +% string, para mostrar tantos numeros decimales en las funciones que se ven en +% la leyenda +P11 = num2str(fix(abs(log10(abs(Ucoef.b))))+2); +P21 = num2str(fix(abs(log10(abs(Pcoef.p1))))+2); + +% Colores en formato texto para el color de las funciones +ColU = [num2str(colores(iCU,1)),',',num2str(colores(iCU,2)),',',num2str(colores(iCU,3))]; +ColL = [num2str(colores(iCL,1)),',',num2str(colores(iCL,2)),',',num2str(colores(iCL,3))]; + +% Leyenda +leyenda{1} = sprintf(['\\bf0 %s %d ms\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.2f�x^{%4.',P11,'f} \n \\color{white}.'],'a',Rango,Ures.adjrsquare,ColU,Ucoef.a,Ucoef.b); +leyenda{2} = sprintf(['\\bf%d ms %s\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.',P21,'f�x+%4.2f \n \\color{white}.'],Rango,'a infinito',Pres.adjrsquare,ColL,Pcoef.p1,Pcoef.p2); + +%% Teoria corregida +% Si se ha marcado el calculo de la teoria revisada corregida se calcula y +% se a�ade a la grafica +if get(handles.teoriacorregida,'value')==1 + %%% PARAMETROS + % Nivel de presion total de la fuente a 1 metro + SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10))); + % Volumen (m3) + V = handles.SPLm{handles.Index,15}; + % Superficie (m2) + S = handles.SPLm{handles.Index,16}; + % Mean Free Path + mfp = 4*V/S; + % Absorcion media + alpha = mean(handles.SPLm{handles.Index,11}); + % Absorci�n equivalente de Eyring + A = -S*log(1-alpha); + % Temperatura de la sala + temp = handles.SPLm{handles.Index,17}; + % Velocidad del sonido + c = 331.4 + 0.6*temp; + % Densidad del aire. Presion Atm / (constante gas*Temp + % absoluta) + rho = 101325 / (287.058*(273.15+temp)); + % Impedancia acustica del aire + Z = rho*c; + % Presion de referencia + pref = 2*10^(-5); + % Factor de conversion + Fac = Z/(pref^2); + % Directividad de la fuente + Q = str2double(get(handles.Qdir,'string')); + % Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1 + SWL = SPL - 10*log10(1/(4*pi*1)); + % Potencia de la fuente en vatios + W = 10.^(SWL/10)*10^-12; + % Tiempo de reverberacion de Eyring + T = 6*log(10)/c * mfp * 1/(-log(1-alpha)); + % Rango de integracion temporal (s) + t = handles.Rango * 10^(-3); + + %% Obtencion de la curvas directo y early + %% Curva del campo directo + % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl + % asociado + Dist_D = sortrows([Distancia',Dneto']); + % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos + % distancias iguales y elimina el duplicado + [C,~,idx] = unique(Dist_D(:,1),'stable'); + val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); + Dist_D = [C,val]; + % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del + % receptor mas cercano + %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); + %Dist_U = [[0;V0_0toVal]';Dist_U]; + % Separar los valores para graficar y convertirlo en vector fila + Dist = Dist_D(:,1); + Drec = Dist_D(:,2); + % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste + % (Ures) + [Dcoef,Dres]=fit(Dist,Drec,'power1'); + Dplot=Dcoef.a*Distplot.^Dcoef.b; + + %% Curva del campo early + % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl + % asociado + Dist_E = sortrows([Distancia',Eneto']); + % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos + % distancias iguales y elimina el duplicado + [C,~,idx] = unique(Dist_E(:,1),'stable'); + val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); + Dist_E = [C,val]; + % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del + % receptor mas cercano + %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); + %Dist_U = [[0;V0_0toVal]';Dist_U]; + % Separar los valores para graficar y convertirlo en vector fila + Dist = Dist_E(:,1); + Erec = Dist_E(:,2); + % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste + % (Ures) + [Ecoef,Eres]=fit(Dist,Erec,'power1'); + Eplot=Ecoef.a*Distplot.^Ecoef.b; + + % Para no mostrar errores cuando se repite el calculo de coeficientes + warning ('off','all'); + + %% Calculo de coeficiente para el campo directo + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opD = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'Lower',[0,0],... % Minimo valor de los coeficientes + 'Upper',[20,20],... % Maximo valor de los coeficientes + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'Q','W','Fac'},... + 'coefficients',{'Cd'},... + 'options',opD); + [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + + %% Calculo de coeficientes epsilon y Cl para campo late + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','t','T','c','Fac'},... + 'coefficients',{'el','Cl'}); + [fitiL,gofL,outputL] = fit(Distplot',10.^(Pplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + %% Calculo de coeficientes epsilon y Ce para campo early + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opE = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},... + 'coefficients',{'ee','Ce'},... + 'options',opE); + [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + warning ('on','all'); + + PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd)); + Peplot = 10*log10(Fac *(... + (4*W)./(S*(-log(1-alpha))*Distplot) .* ... + (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl))); + Pdeplot = 10*log10(10.^(PDplot/10)+10.^(Peplot/10)); + Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl); + + Curv(3) = plot(Distplot,Pdeplot,'-.','Color',colores(iCUt,:),'LineWidth',1); + Curv(4) = plot(Distplot,Plateplot,'-.','Color',colores(iCLt,:),'LineWidth',1); + + % Colores en formato texto para el color de las funciones + ColUteo = [num2str(colores(iCUt,1)),',',num2str(colores(iCUt,2)),',',num2str(colores(iCUt,3))]; + ColLteo = [num2str(colores(iCLt,1)),',',num2str(colores(iCLt,2)),',',num2str(colores(iCLt,3))]; + + % Leyendas + leyenda{3} = sprintf('\\bf0 %s %d ms\\rm Teoria revisada corregida\n \\color[rgb]{%s}\\epsilon_E = %4.3f | C_E = %4.3f | R^2_{adj} = %4.2f \n C_D = %4.3f | R^2_{adj} = %4.2f \n \\color{white}.','a',Rango,ColUteo,fitiE.ee,fitiE.Ce,gofE.adjrsquare,fitiD.Cd,gofD.adjrsquare); + leyenda{4} = sprintf('\\bf%d ms %s\\rm Teoria revisada corregida\n \\color[rgb]{%s}\\epsilon_L = %4.3f | C_L = %4.3f | R^2_{adj} = %4.2f',Rango,'a infinito',ColLteo,fitiL.el,fitiL.Cl,gofL.adjrsquare); + + + % Obtener punto de cruce + CortesInd = find(abs(Pdeplot-Plateplot)<=(0.01)); + if ~isnan(CortesInd) + DistCorteTeo = Distplot(CortesInd(1)); + text(DistCorteTeo,Pdeplot(CortesInd(1))-1,... + {'Te�rica',strcat('\bf\color{black}',[sprintf('%4.3f',DistCorteTeo),' m'])},... + 'VerticalAlignment','bottom','HorizontalAlignment','right') + end + + % Almacenar variables de interes para despues exportarlas dentro del + % .mat + + % Coeficientes + handles.Elate = fitiL.el; + handles.Clate = fitiL.Cl; + handles.Eearly = fitiE.ee; + handles.Cearly = fitiE.Ce; + handles.Cdirect = fitiD.Cd; + + % Parametros + handles.SPL = SPL; % Nivel de presion a 1 metro + handles.W = W; % Potencia + handles.Q = Q; % Directividad + handles.t = t; % Rango temporal en segundos + handles.T = T; % Tiempo de reverberaci�n de Eyring + handles.c = c; % Velocidad de sonido + handles.S = S; % Superficie + handles.V = V; % Volumen + handles.alpha = alpha; % Coeficiente de absorcion medio + handles.Z = Z; % Impedancia del aire + handles.rho = rho; % Densidad del aire + handles.A = A; % Absorcion equivalente de Eyring + + % Curvas + handles.Distancia = Distplot; % Vector de distancia + handles.EaseU = Uplot; % Curva del campo util (EASE) + handles.EaseP = Pplot; % Curva del campo perjudicial (EASE) + handles.TeoU = Pdeplot; % Curva del campo util (Teorico) + handles.TeoP = Plateplot; % Curva del campo perjudicial (Teorico) + handles.EaseD = Dplot; % Curva del campo directo (EASE) + handles.EaseE = Eplot; % Curva del campo early (EASE) + handles.EaseL = Pplot; % Curva del campo late (EASE) + handles.TeoD = PDplot; % Curva del campo directo (Teorico) + handles.TeoE = Peplot; % Curva del campo early (Teorico) + handles.TeoL = Plateplot; % Curva del campo late (Teorico) + + if exist('DistCorte','var') + handles.DistCorte = DistCorte; + end + if exist('DistCorteTeo','var') + handles.DistCorteTeo = DistCorteTeo; + end + % Actualizar variables en la aplicacion + guidata(hObject, handles); + +end + +lgdw=legend(Curv,leyenda); +lgdw.FontSize = 11; +%lgdw.Location = 'northeastoutside'; +% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya +% que no es compatible +if ~verLessThan('matlab','8.7') + title(lgdw,'Curvas') +end +ylabel('Nivel de presi�n ac�stica (dB)') +xlabel('Distancia (m)') +title({['SPL seg�n rango de tiempo',sprintf(' - %d ms',Rango)];... + ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]}); + +hold off + + diff --git a/include/representarSPLvsDist3.m b/include/representarSPLvsDist3.m new file mode 100644 index 0000000..57d2c74 --- /dev/null +++ b/include/representarSPLvsDist3.m @@ -0,0 +1,421 @@ +function representarSPLvsDist3(hObject,handles) + +axes(handles.plotfig) +Rango = handles.Rango; +SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar +SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas +Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor +Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas +Fuente = string(handles.SPLm(:,2)'); +Receptor = string(handles.SPLm(:,3)'); + + +% Comprobar que bandas de frecuencias se han elegido +Bandas = []; +fsel = []; +if handles.frec125.Value==1 + Bandas = [Bandas,1]; + fsel = [fsel,125]; +end +if handles.frec250.Value==1 + Bandas = [Bandas,2]; + fsel = [fsel,250]; +end +if handles.frec500.Value==1 + Bandas = [Bandas,3]; + fsel = [fsel,500]; +end +if handles.frec1000.Value==1 + Bandas = [Bandas,4]; + fsel = [fsel,1000]; +end +if handles.frec2000.Value==1 + Bandas = [Bandas,5]; + fsel = [fsel,2000]; +end +if handles.frec4000.Value==1 + Bandas = [Bandas,6]; + fsel = [fsel,4000]; +end +if handles.frec8000.Value==1 + Bandas = [Bandas,7]; + fsel = [fsel,8000]; +end +if isempty(Bandas); Bandas = 1:7; end +if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end + +%% Procesado de datos +% Separacion e integracion de los niveles antes y despues del rango +Dneto = zeros(1,numel(SPLm)); +Eneto = zeros(1,numel(SPLm)); +Lneto = zeros(1,numel(SPLm)); +for i=1:numel(SPLm) + % Direct - Early - Late EXTRACTION + Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 2 ms + Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 2 ms a tiempo de integracion + Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito + + % Ponderacion A + % f = fsel; % Frecuencias seleccionadas + % ponderacionA = 20*log10(... + % 12194^2*f.^4 ./... + % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2; + % Dbruto = Dbruto + ponderacionA; + % Ebruto = Ebruto + ponderacionA; + % Lbruto = Lbruto + ponderacionA; + + % Suma de niveles para los dos rangos + Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10))); + Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10))); + Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10))); +end + + + +%% Representacion grafica del campo Directo/Early/Late +colores = colormap(jet(21)); +% Indices de color +iCD = 1; +iCDt = 3; +iCE = 6; +iCEt = 7; +iCL = 15; +iCLt = 16; +%% Puntos y curva del campo directo +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_D = sortrows([Distancia',Dneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_D(:,1),'stable'); +val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_D = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); +%Dist_U = [[0;V0_0toVal]';Dist_U]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_D(:,1); +Drec = Dist_D(:,2); +% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste +% (Ures) +[Dcoef,Dres,Doutput]=fit(Dist,Drec,'power1'); +Dplot=Dcoef.a*Distplot.^Dcoef.b; +% Muestra los puntos +plot(Dist,Drec,'s','Color',colores(iCD,:),'MarkerFaceColor',colores(iCD,:)),hold on +% Muestra los errores +Derr = confint(Dcoef); +Dcurvarec = Dcoef.a*Dist.^Dcoef.b; +errorbar(Dist,Dcoef.a*Dist.^Dcoef.b,... % Curva + (Derr(2)*Dist.^Derr(4)) - Dcurvarec,... % Error positivo + Dcurvarec - (Derr(1)*Dist.^Derr(3)),... % Error negativo + 'Color',colores(iCD,:),'LineStyle','none') +hold on +% Muestra la curva +Curv(1)=plot(Distplot,Dplot,'Color',colores(iCD,:),'LineWidth',1.2); + +%% Curva del campo early +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_E = sortrows([Distancia',Eneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_E(:,1),'stable'); +val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_E = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap'); +%Dist_U = [[0;V0_0toVal]';Dist_U]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_E(:,1); +Erec = Dist_E(:,2); +% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste +% (Ures) +[Ecoef,Eres,Eoutput]=fit(Dist,Erec,'power1'); +Eplot=Ecoef.a*Distplot.^Ecoef.b; +% Muestra los puntos +plot(Dist,Erec,'d','Color',colores(iCE,:),'MarkerFaceColor',colores(iCE,:)) +% Muestra los errores +Eerr = confint(Ecoef); +Ecurvarec = Ecoef.a*Dist.^Ecoef.b; +errorbar(Dist,Ecoef.a*Dist.^Ecoef.b,... % Curva + (Eerr(2)*Dist.^Eerr(4)) - Ecurvarec,... % Error positivo + Ecurvarec - (Eerr(1)*Dist.^Eerr(3)),... % Error negativo + 'Color',colores(iCE,:),'LineStyle','none') +% Muestra la curva +Curv(2)=plot(Distplot,Eplot,'Color',colores(iCE,:),'LineWidth',1.2); + +%% Puntos y curva de campor Late +% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl +% asociado +Dist_L = sortrows([Distancia',Lneto']); +% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos +% distancias iguales y elimina el duplicado +[C,~,idx] = unique(Dist_L(:,1),'stable'); +val = accumarray(idx,Dist_L(:,2),[],@(x) 10*log10(mean(10.^(x/10)))); +Dist_L = [C,val]; +% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del +% receptor mas cercano +%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap'); +%Dist_P = [[0;V0_0toVal]';Dist_P]; +% Separar los valores para graficar y convertirlo en vector fila +Dist = Dist_L(:,1); +Lrec = Dist_L(:,2); +% Obtener coeificentes curva polinomica de grado 1 +[Lcoef,Lres,Poutput] = fit(Dist,Lrec,'poly1'); +% Crea la curva +Lplot = Lcoef.p1*Distplot+Lcoef.p2; +% Muestra los puntos +plot(Dist,Lrec,'^','Color',colores(iCL,:),'MarkerFaceColor',colores(iCL,:)) +% Muestra los errores +Lerr = confint(Lcoef); +Lcurvarec = Lcoef.p1*Dist+Lcoef.p2; +errorbar(Dist,Lcoef.p1*Dist+Lcoef.p2,... % Curva + (Lerr(2)*Dist+Lerr(4)) - Lcurvarec,... % Error positivo + Lcurvarec - (Lerr(1)*Dist+Lerr(3)),... % Error negativo + 'Color',colores(iCL,:),'LineStyle','none') +% Muestra la curva +Curv(3)=plot(Distplot,Lplot,'Color',colores(iCL,:),'LineWidth',1.2); + +% A�ade las rejillas de las graficas +grid on +grid minor + +% % Obtener punto de cruce +% CortesInd = find(abs(Dplot-Lplot)<=(0.01)); +% if ~isnan(CortesInd) +% DistCorte = Distplot(CortesInd(1)); +% text(DistCorte,Dplot(CortesInd(1))+1,... +% {'EASE',strcat('\bf\color{black}',[sprintf('%4.3f',DistCorte),' m'])},... +% 'VerticalAlignment','bottom','HorizontalAlignment','left') +% end + + +% Obtener numero de ceros decimales de las pendientes, sumarle 1 y convertir a +% string, para mostrar tantos numeros decimales en las funciones que se ven en +% la leyenda +P11 = num2str(fix(abs(log10(abs(Dcoef.b))))+2); +P21 = num2str(fix(abs(log10(abs(Ecoef.b))))+2); +P31 = num2str(fix(abs(log10(abs(Lcoef.p1))))+2); + +% Colores en formato texto para el color de las funciones +ColD = [num2str(colores(iCD,1)),',',num2str(colores(iCD,2)),',',num2str(colores(iCD,3))]; +ColE = [num2str(colores(iCE,1)),',',num2str(colores(iCE,2)),',',num2str(colores(iCE,3))]; +ColL = [num2str(colores(iCL,1)),',',num2str(colores(iCL,2)),',',num2str(colores(iCL,3))]; + +% Leyendas +leyenda{1} = sprintf(['\\bf0 %s %d ms\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.2f�x^{%4.',P11,'f} \n \\color{white}.'],'a',1,Dres.adjrsquare,ColD,Dcoef.a,Dcoef.b); +leyenda{2} = sprintf(['\\bf%d ms %d ms\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.2f�x^{%4.',P21,'f} \n \\color{white}.'],1,Rango,Eres.adjrsquare,ColE,Ecoef.a,Ecoef.b); +leyenda{3} = sprintf(['\\bf%d ms %s\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.',P31,'f�x+%4.2f \n \\color{white}.'],Rango,'a infinito',Lres.adjrsquare,ColL,Lcoef.p1,Lcoef.p2); + +%% Teoria corregida +% Si se ha marcado el calculo de la teoria revisada corregida se calcula y +% se a�ade a la grafica +if get(handles.teoriacorregida,'value')==1 + %%% PARAMETROS + % Nivel total de la fuente a 1 metro + SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10))); + % Volumen (m3) + V = handles.SPLm{handles.Index,15}; + % Superficie (m2) + S = handles.SPLm{handles.Index,16}; + % Mean Free Path + mfp = 4*V/S; + % Absorcion media + alpha = mean(handles.SPLm{handles.Index,11}); + % Absorci�n equivalente de Eyring + A = -S*log(1-alpha); + % Temperatura de la sala + temp = handles.SPLm{handles.Index,17}; + % Velocidad del sonido + c = 331.4 + 0.6*temp; + % Densidad del aire. Presion Atm / (constante gas*Temp + % absoluta) + rho = 101325 / (287.058*(273.15+temp)); + % Impedancia acustica del aire + Z = rho*c; + % Presion de referencia + pref = 2*10^(-5); + % Factor de conversion + Fac = Z/(pref^2); + % Directividad de la fuente + Q = str2double(get(handles.Qdir,'string')); + % Nivel de potencia de la fuente (SPL a 1 metro). Se supone que Q=1 + SWL = SPL - 10*log10(1/(4*pi*1)); + % Potencia de la fuente en vatios + W = 10.^(SWL/10)*10^-12; + % Tiempo de reverberacion de Eyring + T = 6*log(10)/c * mfp * 1/(-log(1-alpha)); + % Rango de integracion temporal (s) + t = handles.Rango * 10^(-3); + + % Para no mostrar errores cuando se repite el calculo de coeficientes + warning ('off','all'); + + %% Calculo de coeficiente para el campo directo + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opD = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'Lower',[0,0],... % Minimo valor de los coeficientes + 'Upper',[20,20],... % Maximo valor de los coeficientes + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'Q','W','Fac'},... + 'coefficients',{'Cd'},... + 'options',opD); + [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + + %% Calculo de coeficientes epsilon y Cl para campo late + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','t','T','c','Fac'},... + 'coefficients',{'el','Cl'}); + [fitiL,gofL,outputL] = fit(Distplot',10.^(Lplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + + %% Calculo de coeficientes epsilon y Ce para campo early + for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes + try % Intenta el calculo con puntos de inicio random + opE = fitoptions('Method','NonlinearLeastSquares',... + 'Robust','LAR',... + 'MaxFunEvals',3000,... + 'MaxIter',3000,... + 'TolFun',10^-3); + fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',... + 'dependent',{'y'},... + 'independent',{'dist'},... + 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},... + 'coefficients',{'ee','Ce'},... + 'options',opE); + [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl}); + break; + catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente + if ii==str2double(get(handles.numIntentos,'string')) + hold off + ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error'); + set(ed, 'WindowStyle', 'modal'); + uiwait(ed); + return; + end + end + end + warning ('on','all'); + + PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd)); + Peplot = 10*log10(Fac *(... + (4*W)./(S*(-log(1-alpha))*(Distplot)) .* ... + (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl))); + Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl); + + Curv(4) = plot(Distplot,PDplot,'-.','Color',colores(iCDt,:),'LineWidth',1); + Curv(5) = plot(Distplot,Peplot,'-.','Color',colores(iCEt,:),'LineWidth',1); + Curv(6) = plot(Distplot,Plateplot,'-.','Color',colores(iCLt,:),'LineWidth',1); + + % Colores en formato texto para el color de las funciones + ColDteo = [num2str(colores(iCDt,1)),',',num2str(colores(iCDt,2)),',',num2str(colores(iCDt,3))]; + ColEteo = [num2str(colores(iCEt,1)),',',num2str(colores(iCEt,2)),',',num2str(colores(iCEt,3))]; + ColLteo = [num2str(colores(iCLt,1)),',',num2str(colores(iCLt,2)),',',num2str(colores(iCLt,3))]; + + % Leyendas + leyenda{4} = sprintf('\\bf0 ms %s %d ms\\rm Teoria revisada corregida\n \\color[rgb]{%s}C_D = %4.3f | R^2_{adj} = %4.2f \n \\color{white}.','a',1,ColDteo,fitiD.Cd,gofD.adjrsquare); + leyenda{5} = sprintf('\\bf%d ms %s %d ms\\rm Teoria revisada corregida\n \\color[rgb]{%s}\\epsilon_E = %4.3f | C_E = %4.3f | R^2_{adj} = %4.2f \n \\color{white}.',1,'a',Rango,ColEteo,fitiE.ee,fitiE.Ce,gofE.adjrsquare); + leyenda{6} = sprintf('\\bf%d ms %s\\rm Teoria revisada corregida\n \\color[rgb]{%s}\\epsilon_L = %4.3f | C_L = %4.3f | R^2_{adj} = %4.2f',Rango,'a infinito',ColLteo,fitiL.el,fitiL.Cl,gofL.adjrsquare); + + + % % Obtener punto de cruce + % f1a = 10*log10(Peplot); + % f2a = 10*log10(Plateplot); + % CortesInd = find(abs(f1a-f2a)<=(0.01)); + % if ~isnan(CortesInd) + % DistCorteTeo = Distplot(CortesInd(1)); + % text(DistCorteTeo,f1a(CortesInd(1))-1,... + % {'Te�rica',strcat('\bf\color{black}',[sprintf('%4.3f',DistCorteTeo),' m'])},... + % 'VerticalAlignment','bottom','HorizontalAlignment','right') + % end + + % Almacenar variables de interes para despues exportarlas dentro del + % .mat + + % Coeficientes + handles.Elate = fitiL.el; + handles.Clate = fitiL.Cl; + handles.Eearly = fitiE.ee; + handles.Cearly = fitiE.Ce; + handles.Cdirect = fitiD.Cd; + + % Parametros + handles.SPL = SPL; % Nivel de presion a 1 metro + handles.W = W; % Potencia + handles.Q = Q; % Directividad + handles.t = t; % Rango temporal en segundos + handles.T = T; % Tiempo de reverberaci�n de Eyring + handles.c = c; % Velocidad de sonido + handles.S = S; % Superficie + handles.V = V; % Volumen + handles.alpha = alpha; % Coeficiente de absorcion medio + handles.Z = Z; % Impedancia del aire + handles.rho = rho; % Densidad del aire + handles.A = A; % Absorcion equivalente de Eyring + + % Curvas + handles.Distancia = Distplot; % Vector de distancia + handles.EaseD = Dplot; % Curva del campo directo (EASE) + handles.EaseE = Eplot; % Curva del campo early (EASE) + handles.EaseL = Lplot; % Curva del campo late (EASE) + handles.TeoD = PDplot; % Curva del campo directo (Teorico) + handles.TeoE = Peplot; % Curva del campo early (Teorico) + handles.TeoL = Plateplot; % Curva del campo late (Teorico) + + % Actualizar variables en la aplicacion + guidata(hObject, handles); + +end + +lgdw=legend(Curv,leyenda); +lgdw.FontSize = 11; +lgdw.Location = 'bestoutside'; +%lgdw.Location = 'northeastoutside'; +% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya +% que no es compatible +if ~verLessThan('matlab','8.7') + title(lgdw,'Curvas') +end +ylabel('Nivel de presi�n ac�stica (dB)') +xlabel('Distancia (m)') +title({['SPL seg�n rango de tiempo',sprintf(' - %d ms',Rango)];... + ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]}); + +hold off + + -- knotmirror 0.0.1