2017년 11월 30일 목요일

두서없이 써본 파이썬 built-in functions

locals()
     현재 범위에서 사용할 수 있는 이름들을 반환한다.

reset -sf
     메모리에 있는 모든 변수를 삭제한다.

pow(a,b)
     a의 b승. a**b와 같다.

run
     ipython console창에서 파이썬 스크립트를 실행시킨다.
     (예) In [1]: run gogoletsgo.py

sorted
     입력값을 오름차순으로 정렬한 후 리스트로 반환

2017년 11월 29일 수요일

파일 입출력

파이썬의 기본 입력 매커니즘은 라인을 기반으로 한다. 데이터를 텍스트 파일에서 프로그램으로 읽어들이면 한 번에 한 라인씩 가져온다.

     data = open('head_first.txt')
     print(data.readline(), end='')
   
open으로 연 파일은 한 라인씩 읽어들이는 것이 기본이고, readline() 메서드로 파일에서 한 라인을 읽어 올 수 있다.
print 함수는 기본적으로 줄바꿈을 수행하지만 줄을 바꾸지 않으려면 end=''을 사용한다.


open() : 파일을 읽고 쓰기위해 아래의 모드를 지정해야 한다.
            r : 읽기 모드. 기본 모드이므로 생략 가능하다.
            w : 쓰기 모드. 기존에 파일이 있었다면 모든 내용이 지워진다.
            w+ : 파일의 내용을 지우지 않고 읽고 쓰기 위한 모드
            a : 파일의 끝에 추가하기 위한 모드
             

print() : 데이터를 파일로 출력하기 위해서 file 인자에 데이터 파일 객체를 지정해야 한다.
           fID = open('data.out', 'w')
           print('Nothing changes unless you change yourself.', file = fID)

문자열 매서드

strip()  문자열 앞뒤의 불필요한 공백을 제거

2017년 11월 28일 화요일

Spectral flatness

Spectral flatness or tonality coefficient,[1][2] also known as Wiener entropy,[3][4] is a measure used in digital signal processing to characterize an audio spectrum. Spectral flatness is typically measured in decibels, and provides a way to quantify how noise-like a sound is, as opposed to being tone-like.[2]

The meaning of tonal in this context is in the sense of the amount of peaks or resonant structure in a power spectrum, as opposed to flat spectrum of a white noise. A high spectral flatness (approaching 1.0 for white noise) indicates that the spectrum has a similar amount of power in all spectral bands — this would sound similar to white noise, and the graph of the spectrum would appear relatively flat and smooth. A low spectral flatness (approaching 0.0 for a pure tone) indicates that the spectral power is concentrated in a relatively small number of bands — this would typically sound like a mixture of sine waves, and the spectrum would appear "spiky".[5]
The spectral flatness is calculated by dividing the geometric mean of the power spectrum by the arithmetic mean of the power spectrum, i.e.:


where x(n) represents the magnitude of bin number n. Note that a single (or more) empty bin yields a flatness of 0, so this measure is most useful when bins are generally not empty.
The ratio produced by this calculation is often converted to a decibel scale for reporting, with a maximum of 0 dB and a minimum of ∞ dB.
The spectral flatness can also be measured within a specified subband, rather than across the whole band.


출처: <https://en.wikipedia.org/wiki/Spectral_flatness

Spectral centroid

The spectral centroid is a measure used in digital signal processing to characterise a spectrum. It indicates where the "center of mass" of the spectrum is. Perceptually, it has a robust connection with the impression of "brightness" of a sound.[1]

It is calculated as the weighted mean of the frequencies present in the signal, determined using a Fourier transform, with their magnitudes as the weights:[2]


where x(n) represents the weighted frequency value, or magnitude, of bin number n, and f(n) represents the center frequency of that bin.


출처: <https://en.wikipedia.org/wiki/Spectral_centroid

감마톤 필터

gammatone filter is a linear filter described by an impulse response that is the product of a gamma distributionand sinusoidal tone. It is a widely used model of auditory filters in the auditory system.


출처: <https://en.wikipedia.org/wiki/Gammatone_filter>

감마톤 필터 대역폭은 1.01일 때와 필터 차수 4일 때 청각 특성을 가장 잘 반영한다.(한국음향학회 논문). 아래 매트랩 툴박스의 감마톤 필터의 필터 차수는 4, 대역폭은 1.019 설정되어있다. (gammatoneFast.m파일 참고)

Matlab Toolbox - need to install

bm = gammatoneFast(x,cfs,fs) 
bm = gammatoneFast(...,align) 
[bm,env] = gammatoneFast(...) 
[bm,env,delay] = gammatoneFast(...)
NOTE: this function is now available from the IoSR Matlab Toolbox as iosr.auditory.gammatoneFast. 

<Example>
fs = 48000; % sample rate 
numchans = 8; % number of frequency channels 
t = -0.005:1/fs:0.025; % time (s)
% impulse 
imp = zeros(numel(t), 1); 
imp(t==0) = 1;
% centre frequencies 
cfs = iosr.auditory.makeErbCFs(500, 7500, numchans);
% calculate impulse response fine structure 
x1 = iosr.auditory.gammatoneFast(imp, cfs, fs); 
x2 = iosr.auditory.gammatoneFast(imp, cfs, fs, true);
% normalise each frequency for plotting 
for c = 1:numchans 
x1(:, c) = x1(:, c) ./ max(abs(x1(:, c))); 
x2(:, c) = x2(:, c) ./ max(abs(x2(:, c))); 
end
% draw 
figure 
% non-phase aligned 
subplot(1, 2, 1), iosr.figures.multiwaveplot(t*1000, 1:numchans, x1') 
h = gca; 
% phase aligned 
subplot(1, 2, 2), iosr.figures.multiwaveplot(t*1000, 1:numchans, x2') 
h(2) = gca; 
% plot settings 
set(h, 'yticklabel', num2str(round(cfs)')) 
for n = 1:2 
xlabel(h(n), 'Time [ms]'); 
ylabel(h(n), 'Frequency [Hz]'); 
end 
title(h(1), 'Non-phase-aligned gammatone filterbank') 
title(h(2), 'Phase-aligned gammatone filterbank')


출처: <https://kr.mathworks.com/matlabcentral/fileexchange/32212-gammatone-filterbank>

파고율(Crest factor)

크레스트 팩터는 교류 또는 사운드 와 같은 파형의 측정 값으로, 피크 값과 실효 값의 비율을 나타냅니다. , 파고율은 파고가 파형에 얼마나 극단적인지 나타냅니다. 크레스트 팩터 1은 직류와 같이 피크가 없음을 나타냅니다 . 더 높은 크레스트 팩터는 피크를 나타내며, 예를 들어 음파는 높은 크레스트 팩터를 갖는 경향이 있습니다. 파고율은 파형의 피크 진폭을 파형의 RMS 값으로 나눈 값입니다.


소음 및 음향 공학

음향 및 오디오 엔지니어링에서 크레스트 팩터는 일반적으로 데시벨  표시되므로 RMS와 파형의 최고 값 사이의 레벨 차이로 정의됩니다 . 예를 들어, 사인파의 경우 1.414 비율은 20log(1.414) 또는 3dB입니다. 대부분의 주변 소음은 약 10dB의 파고율을 가지지만 총소리와 같은 임펄스성 소리는 30dB 이상의 파고율을 가질 수 있습니다

왜도(비대칭도)

확률 이론 및 통계학에서, 비대칭도(非對稱度, skewness) 또는 왜도(歪度)는 실수 값 확률 변수 확률 분포 비대칭성을 나타내는 지표이다. 왜도의 값은 양수나 음수가 될 수 있으며 정의되지 않을 수도 있다. 왜도가 음수일 경우에는 확률밀도함수의 왼쪽 부분에 긴 꼬리를 가지며 중앙값을 포함한 자료가 오른쪽에 더 많이 분포해 있다. 왜도가 양수일 때는 확률밀도함수의 오른쪽 부분에 긴 꼬리를 가지며 자료가 왼쪽에 더 많이 분포해 있다는 것을 나타낸다. 평균과 중앙값이 같으면 왜도는 0이 된다.


출처: <https://ko.wikipedia.org/wiki/%EB%B9%84%EB%8C%80%EC%B9%AD%EB%8F%84>

Matlab document


출처: <https://kr.mathworks.com/help/releases/R2017a/stats/skewness.html

첨도

첨도(尖度, 영어: kurtosis 커토시스)는 확률분포의 뾰족한 정도를 나타내는 척도이다. 관측치들이 어느 정도 집중적으로 중심에 몰려 있는가를 측정할 때 사용된다. 첨도값(K)이 3에 가까우면 산포도가 정규분포에 가깝다. 3보다 작을 경우에는(K<3) 정규분포보다 더 완만하게 납작한 분포로 판단할 수 있으며, 첨도값이 3보다 큰 양수이면(K>3) 산포는 정규분포보다 더 뾰족한 분포로 생각할 수 있다.


출처: <https://ko.wikipedia.org/wiki/%EC%B2%A8%EB%8F%84>

Matlab document

출처: <https://www.mathworks.com/help/releases/R2017a/stats/kurtosis.html?doclanguage=ko-KR&nocookie=true&prodfilter=BI+CO+MJ+CT+CF+DA+DM+DS+EL+FL+GD+IP+IA+IC+MG+ML+ME+NN+OP+SG+SS+MS+SL+SD+SF+ST+SM+VP&addons=arduinoio&docviewer=helpbrowser&docrelease=R2017a&s_cid=pl_webdoc>


람다 표현식 (Lambda expression)

람다 표현식(Lambda expression)  람다 표현식으로 함수를 정의하고, 이를 변수에 할당하여 변수를 함수처럼 사용한다. (1) 람다 표현식       lambda <매개변수> : 수식      ※ 람다식을 실행하...