picadae calibration programs
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

plot_seq_1.py 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. ##| Copyright: (C) 2019-2020 Kevin Larke <contact AT larke DOT org>
  2. ##| License: GNU GPL version 3.0 or above. See the accompanying LICENSE file.
  3. import os, sys,json
  4. import matplotlib.pyplot as plt
  5. import numpy as np
  6. from common import parse_yaml_cfg
  7. import rms_analysis
  8. import elbow
  9. def fit_to_reference( pkL, refTakeId ):
  10. us_outL = []
  11. db_outL = []
  12. dur_outL = []
  13. tid_outL = []
  14. dbL,usL,durMsL,takeIdL = tuple(zip(*pkL))
  15. us_refL,db_refL,dur_refL = zip(*[(usL[i],dbL[i],durMsL[i]) for i in range(len(usL)) if takeIdL[i]==refTakeId])
  16. for takeId in set(takeIdL):
  17. us0L,db0L,dur0L = zip(*[(usL[i],dbL[i],durMsL[i]) for i in range(len(usL)) if takeIdL[i]==takeId ])
  18. if takeId == refTakeId:
  19. db_outL += db0L
  20. else:
  21. db1V = elbow.fit_points_to_reference(us0L,db0L,us_refL,db_refL)
  22. db_outL += db1V.tolist()
  23. us_outL += us0L
  24. dur_outL+= dur0L
  25. tid_outL+= [takeId] * len(us0L)
  26. return zip(db_outL,us_outL,dur_outL,tid_outL)
  27. def get_merged_pulse_db_measurements( inDir, midi_pitch, analysisArgsD ):
  28. inDir = os.path.join(inDir,"%i" % (midi_pitch))
  29. takeDirL = os.listdir(inDir)
  30. pkL = []
  31. usRefL = None
  32. dbRefL = None
  33. # for each take in this directory
  34. for take_number in range(len(takeDirL)):
  35. # analyze this takes audio and locate the note peaks
  36. r = rms_analysis.rms_analysis_main( os.path.join(inDir,str(take_number)), midi_pitch, **analysisArgsD )
  37. # store the peaks in pkL[ (db,us) ]
  38. for db,us,stats in zip(r.pkDbL,r.pkUsL,r.statsL):
  39. pkL.append( (db,us,stats.durMs,take_number) )
  40. pkL = fit_to_reference( pkL, 0 )
  41. # sort the peaks on increasing attack pulse microseconds
  42. pkL = sorted( pkL, key= lambda x: x[1] )
  43. # merge sample points that separated by less than 'minSampleDistUs' milliseconds
  44. #pkL = merge_close_sample_points( pkL, analysisArgsD['minSampleDistUs'] )
  45. # split pkL
  46. pkDbL,pkUsL,durMsL,takeIdL = tuple(zip(*pkL))
  47. return pkUsL,pkDbL,durMsL,takeIdL,r.holdDutyPctL
  48. def select_resample_reference_indexes( noiseIdxL ):
  49. resampleIdxS = set()
  50. # for each noisy sample index store that index and the index
  51. # before and after it
  52. for i in noiseIdxL:
  53. resampleIdxS.add( i )
  54. if i+1 < len(noiseIdxL):
  55. resampleIdxS.add( i+1 )
  56. if i-1 >= 0:
  57. resampleIdxS.add( i-1 )
  58. resampleIdxL = list(resampleIdxS)
  59. # if a single sample point is left out of a region of
  60. # contiguous sample points then include this as a resample point also
  61. for i in resampleIdxL:
  62. if i + 1 not in resampleIdxL and i + 2 in resampleIdxL: # BUG BUG BUG: Hardcoded constant
  63. if i+1 < len(noiseIdxL):
  64. resampleIdxL.append(i+1)
  65. return resampleIdxL
  66. def locate_resample_regions( usL, dbL, resampleIdxL ):
  67. # locate regions of points to resample
  68. regionL = [] # (bi,ei)
  69. inRegionFl = False
  70. bi = None
  71. for i in range(len(usL)):
  72. if inRegionFl:
  73. if i not in resampleIdxL:
  74. regionL.append((bi,i-1))
  75. inRegionFl = False
  76. bi = None
  77. else:
  78. if i in resampleIdxL:
  79. inRegionFl = True
  80. bi = i
  81. if bi is not None:
  82. regionL.append((bi,len(usL)-1))
  83. # select points around and within the resample regions
  84. # to resample
  85. reUsL = []
  86. reDbL = []
  87. for bi,ei in regionL:
  88. for i in range(bi,ei+2):
  89. if i == 0:
  90. us = usL[i]
  91. db = dbL[i]
  92. elif i >= len(usL):
  93. us = usL[i-1]
  94. db = dbL[i-1]
  95. else:
  96. us = usL[i-1] + (usL[i]-usL[i-1])/2
  97. db = dbL[i-1] + (dbL[i]-dbL[i-1])/2
  98. reUsL.append(us)
  99. reDbL.append(db)
  100. return reUsL,reDbL
  101. def get_dur_skip_indexes( durMsL, dbL, takeIdL, scoreL, minDurMs, minDb, noiseLimitPct ):
  102. firstAudibleIdx = None
  103. firstNonSkipIdx = None
  104. # get the indexes of samples which do not meet the duration, db level, or noise criteria
  105. skipIdxL = [ i for i,(ms,db,score) in enumerate(zip(durMsL,dbL,scoreL)) if ms < minDurMs or db < minDb or score > noiseLimitPct ]
  106. # if a single sample point is left out of a region of
  107. # contiguous skipped points then skip this point also
  108. for i in range(len(durMsL)):
  109. if i not in skipIdxL and i-1 in skipIdxL and i+1 in skipIdxL:
  110. skipIdxL.append(i)
  111. # find the first set of 3 contiguous samples that
  112. # are greater than minDurMs - all samples prior
  113. # to these will be skipped
  114. xL = []
  115. for i in range(len(durMsL)):
  116. if i in skipIdxL:
  117. xL = []
  118. else:
  119. xL.append(i)
  120. if len(xL) == 3: # BUG BUG BUG: Hardcoded constant
  121. firstAudibleIdx = xL[0]
  122. break
  123. # decrease by one decibel to locate the first non-skip
  124. # TODO: what if no note exists that is one decibel less
  125. # The recordings of very quiet notes do not give reliabel decibel measures
  126. # so this may not be the best backup criteria
  127. if firstAudibleIdx is not None:
  128. i = firstAudibleIdx-1
  129. while abs(dbL[i] - dbL[firstAudibleIdx]) < 1.0: # BUG BUG BUG: Hardcoded constant
  130. i -= 1
  131. firstNonSkipIdx = i
  132. return skipIdxL, firstAudibleIdx, firstNonSkipIdx
  133. def get_resample_points( usL, dbL, durMsL, takeIdL, minDurMs, minDb, noiseLimitPct ):
  134. scoreV = np.abs( rms_analysis.samples_to_linear_residual( usL, dbL) * 100.0 / dbL )
  135. skipIdxL, firstAudibleIdx, firstNonSkipIdx = get_dur_skip_indexes( durMsL, dbL, takeIdL, scoreV.tolist(), minDurMs, minDb, noiseLimitPct )
  136. skipL = [ (usL[i],dbL[i]) for i in skipIdxL ]
  137. noiseIdxL = [ i for i in range(scoreV.shape[0]) if scoreV[i] > noiseLimitPct ]
  138. noiseL = [ (usL[i],dbL[i]) for i in noiseIdxL ]
  139. resampleIdxL = select_resample_reference_indexes( noiseIdxL )
  140. if firstNonSkipIdx is not None:
  141. resampleIdxL = [ i for i in resampleIdxL if i >= firstNonSkipIdx ]
  142. resampleL = [ (usL[i],dbL[i]) for i in resampleIdxL ]
  143. reUsL,reDbL = locate_resample_regions( usL, dbL, resampleIdxL )
  144. return reUsL, reDbL, noiseL, resampleL, skipL, firstAudibleIdx, firstNonSkipIdx
  145. def get_resample_points_wrap( inDir, midi_pitch, analysisArgsD ):
  146. usL, dbL, durMsL,_,_ = get_merged_pulse_db_measurements( inDir, midi_pitch, analysisArgsD['rmsAnalysisArgs'] )
  147. reUsL,_,_,_,_,_,_ = get_resample_points( usL, dbL, durMsL, analysisArgsD['resampleMinDurMs'], analysisArgsD['resampleMinDb'], analysisArgsD['resampleNoiseLimitPct'] )
  148. return reUsL
  149. def plot_us_db_curves( ax, inDir, keyMapD, midi_pitch, analysisArgsD, plotResamplePointsFl=False, plotTakesFl=True, usMax=None ):
  150. usL, dbL, durMsL, takeIdL, holdDutyPctL = get_merged_pulse_db_measurements( inDir, midi_pitch, analysisArgsD['rmsAnalysisArgs'] )
  151. reUsL, reDbL, noiseL, resampleL, skipL, firstAudibleIdx, firstNonSkipIdx = get_resample_points( usL, dbL, durMsL, takeIdL, analysisArgsD['resampleMinDurMs'], analysisArgsD['resampleMinDb'], analysisArgsD['resampleNoiseLimitPct'] )
  152. # plot first audible and non-skip position
  153. if False:
  154. if firstNonSkipIdx is not None:
  155. ax.plot( usL[firstNonSkipIdx], dbL[firstNonSkipIdx], markersize=15, marker='+', linestyle='None', color='red')
  156. if firstAudibleIdx is not None:
  157. ax.plot( usL[firstAudibleIdx], dbL[firstAudibleIdx], markersize=15, marker='*', linestyle='None', color='red')
  158. # plot the resample points
  159. if plotResamplePointsFl:
  160. ax.plot( reUsL, reDbL, markersize=13, marker='x', linestyle='None', color='green')
  161. # plot the noisy sample positions
  162. if noiseL:
  163. nUsL,nDbL = zip(*noiseL)
  164. ax.plot( nUsL, nDbL, marker='o', markersize=9, linestyle='None', color='black')
  165. # plot the noisy sample positions and the neighbors included in the noisy region
  166. if resampleL:
  167. nUsL,nDbL = zip(*resampleL)
  168. ax.plot( nUsL, nDbL, marker='+', markersize=8, linestyle='None', color='red')
  169. # plot actual sample points
  170. elbow_us = None
  171. elbow_db = None
  172. elbow_len = None
  173. usL,dbL,takeIdL = zip(*[(us,dbL[i],takeIdL[i]) for i,us in enumerate(usL) if usMax is None or us <= usMax])
  174. if plotTakesFl:
  175. for takeId in list(set(takeIdL)):
  176. # get the us,db points included in this take
  177. xL,yL = zip(*[(usL[i],dbL[i]) for i in range(len(usL)) if takeIdL[i]==takeId ])
  178. ax.plot(xL,yL, marker='.',label=takeId)
  179. for i,(x,y) in enumerate(zip(xL,yL)):
  180. ax.text(x,y,str(i))
  181. #if elbow_len is None or len(xL) > elbow_len:
  182. if takeId+1 == len(set(takeIdL)):
  183. elbow_us,elbow_db = elbow.find_elbow(xL,yL)
  184. elbow_len = len(xL)
  185. else:
  186. ax.plot(usL, dbL, marker='.')
  187. ax.plot([elbow_us],[elbow_db],marker='*',markersize=12,color='red',linestyle='None')
  188. # plot the skip points in yellow
  189. if False:
  190. if skipL:
  191. nUsL,nDbL = zip(*skipL)
  192. ax.plot( nUsL, nDbL, marker='.', linestyle='None', color='yellow')
  193. # plot the locations where the hold duty cycle changes with vertical black lines
  194. for us_duty in holdDutyPctL:
  195. us,duty = tuple(us_duty)
  196. if us > 0:
  197. ax.axvline(us,color='black')
  198. # plot the 'minDb' reference line
  199. ax.axhline(analysisArgsD['resampleMinDb'] ,color='black')
  200. if os.path.isfile("minInterpDb.json"):
  201. with open("minInterpDb.json","r") as f:
  202. r = json.load(f)
  203. if midi_pitch in r['pitchL']:
  204. ax.axhline( r['minDbL'][ r['pitchL'].index(midi_pitch) ], color='blue' )
  205. ax.axhline( r['maxDbL'][ r['pitchL'].index(midi_pitch) ], color='blue' )
  206. ax.set_ylabel( "%i %s %s" % (midi_pitch, keyMapD[midi_pitch]['type'],keyMapD[midi_pitch]['class']))
  207. def plot_us_db_curves_main( inDir, cfg, pitchL, plotTakesFl=True, usMax=None ):
  208. analysisArgsD = cfg.analysisArgs
  209. keyMapD = { d['midi']:d for d in cfg.key_mapL }
  210. axN = len(pitchL)
  211. fig,axL = plt.subplots(axN,1,sharex=True)
  212. if axN == 1:
  213. axL = [axL]
  214. fig.set_size_inches(18.5, 10.5*axN)
  215. for ax,midi_pitch in zip(axL,pitchL):
  216. plot_us_db_curves( ax,inDir, keyMapD, midi_pitch, analysisArgsD, plotTakesFl=plotTakesFl, usMax=usMax )
  217. if plotTakesFl:
  218. plt.legend()
  219. plt.show()
  220. def plot_all_noise_curves( inDir, cfg, pitchL=None ):
  221. pitchFolderL = os.listdir(inDir)
  222. if pitchL is None:
  223. pitchL = [ int( int(pitchFolder) ) for pitchFolder in pitchFolderL ]
  224. fig,ax = plt.subplots()
  225. for midi_pitch in pitchL:
  226. print(midi_pitch)
  227. usL, dbL, durMsL, takeIdL, holdDutyPctL = get_merged_pulse_db_measurements( inDir, midi_pitch, cfg.analysisArgs['rmsAnalysisArgs'] )
  228. scoreV = np.abs( rms_analysis.samples_to_linear_residual( usL, dbL) * 100.0 / dbL )
  229. minDurMs = cfg.analysisArgs['resampleMinDurMs']
  230. minDb = cfg.analysisArgs['resampleMinDb'],
  231. noiseLimitPct = cfg.analysisArgs['resampleNoiseLimitPct']
  232. skipIdxL, firstAudibleIdx, firstNonSkipIdx = get_dur_skip_indexes( durMsL, dbL, scoreV.tolist(), takeIdL, minDurMs, minDb, noiseLimitPct )
  233. if False:
  234. ax.plot( usL[firstAudibleIdx], scoreV[firstAudibleIdx], markersize=10, marker='*', linestyle='None', color='red')
  235. ax.plot( usL, scoreV, label="%i"%(midi_pitch) )
  236. ax.set_xlabel('us')
  237. else:
  238. xL = [ (score,db,i) for i,(score,db) in enumerate(zip(scoreV,dbL)) ]
  239. xL = sorted(xL, key=lambda x: x[1] )
  240. scoreV,dbL,idxL = zip(*xL)
  241. ax.plot( dbL[idxL[firstAudibleIdx]], scoreV[idxL[firstAudibleIdx]], markersize=10, marker='*', linestyle='None', color='red')
  242. ax.plot( dbL, scoreV, label="%i"%(midi_pitch) )
  243. ax.set_xlabel('db')
  244. ax.set_ylabel("noise db %")
  245. plt.legend()
  246. plt.show()
  247. def plot_min_max_2_db( inDir, cfg, pitchL=None, takeId=2 ):
  248. pitchFolderL = os.listdir(inDir)
  249. if pitchL is None:
  250. pitchL = [ int( int(pitchFolder) ) for pitchFolder in pitchFolderL ]
  251. okL = []
  252. outPitchL = []
  253. minDbL = []
  254. maxDbL = []
  255. for midi_pitch in pitchL:
  256. print(midi_pitch)
  257. usL, dbL, durMsL, takeIdL, holdDutyPctL = get_merged_pulse_db_measurements( inDir, midi_pitch, cfg.analysisArgs['rmsAnalysisArgs'] )
  258. okL.append(False)
  259. takeId = len(set(takeIdL))-1
  260. db_maxL = sorted(dbL)
  261. maxDbL.append( np.mean(db_maxL[-5:]) )
  262. usL,dbL = zip(*[(usL[i],dbL[i]) for i in range(len(usL)) if takeIdL[i]==takeId ])
  263. if len(set(takeIdL)) == 3:
  264. okL[-1] = True
  265. elbow_us,elbow_db = elbow.find_elbow(usL,dbL)
  266. minDbL.append(elbow_db)
  267. outPitchL.append(midi_pitch)
  268. p_dL = sorted( zip(outPitchL,minDbL,maxDbL,okL), key=lambda x: x[0] )
  269. outPitchL,minDbL,maxDbL,okL = zip(*p_dL)
  270. fig,ax = plt.subplots()
  271. ax.plot(outPitchL,minDbL)
  272. ax.plot(outPitchL,maxDbL)
  273. keyMapD = { d['midi']:d for d in cfg.key_mapL }
  274. for pitch,min_db,max_db,okFl in zip(outPitchL,minDbL,maxDbL,okL):
  275. c = 'black' if okFl else 'red'
  276. ax.text( pitch, min_db, "%i %s %s" % (pitch, keyMapD[pitch]['type'],keyMapD[pitch]['class']), color=c)
  277. ax.text( pitch, max_db, "%i %s %s" % (pitch, keyMapD[pitch]['type'],keyMapD[pitch]['class']), color=c)
  278. plt.show()
  279. def plot_min_db_manual( inDir, cfg ):
  280. pitchL = list(cfg.manualMinD.keys())
  281. outPitchL = []
  282. maxDbL = []
  283. minDbL = []
  284. okL = []
  285. anchorMinDbL = []
  286. anchorMaxDbL = []
  287. for midi_pitch in pitchL:
  288. manual_take_id = cfg.manualMinD[midi_pitch][0]
  289. manual_sample_idx = cfg.manualMinD[midi_pitch][1]
  290. usL, dbL, durMsL, takeIdL, holdDutyPctL = get_merged_pulse_db_measurements( inDir, midi_pitch, cfg.analysisArgs['rmsAnalysisArgs'] )
  291. okL.append(False)
  292. takeId = len(set(takeIdL))-1
  293. # maxDb is computed on all takes (not just the specified take)
  294. db_maxL = sorted(dbL)
  295. max_db = np.mean(db_maxL[-4:])
  296. maxDbL.append( max_db )
  297. # get the us,db values for the specified take
  298. usL,dbL = zip(*[(usL[i],dbL[i]) for i in range(len(usL)) if takeIdL[i]==manual_take_id ])
  299. # most pitches have 3 sample takes that do not
  300. if len(set(takeIdL)) == 3 and manual_take_id == takeId:
  301. okL[-1] = True
  302. # min db from the sample index manually specified in cfg
  303. manualMinDb = dbL[ manual_sample_idx ]
  304. minDbL.append( manualMinDb )
  305. outPitchL.append(midi_pitch)
  306. if midi_pitch in cfg.manualAnchorPitchMinDbL:
  307. anchorMinDbL.append( manualMinDb )
  308. if midi_pitch in cfg.manualAnchorPitchMaxDbL:
  309. anchorMaxDbL.append( max_db )
  310. # Form the complete set of min/max db levels for each pitch by interpolating the
  311. # db values between the manually selected anchor points.
  312. interpMinDbL = np.interp( pitchL, cfg.manualAnchorPitchMinDbL, anchorMinDbL )
  313. interpMaxDbL = np.interp( pitchL, cfg.manualAnchorPitchMaxDbL, anchorMaxDbL )
  314. fig,ax = plt.subplots()
  315. ax.plot(outPitchL,minDbL) # plot the manually selected minDb values
  316. ax.plot(outPitchL,maxDbL) # plot the max db values
  317. # plot the interpolated minDb/maxDb values
  318. ax.plot(pitchL,interpMinDbL)
  319. ax.plot(pitchL,interpMaxDbL)
  320. keyMapD = { d['midi']:d for d in cfg.key_mapL }
  321. for pitch,min_db,max_db,okFl in zip(outPitchL,minDbL,maxDbL,okL):
  322. c = 'black' if okFl else 'red'
  323. ax.text( pitch, min_db, "%i %s %s" % (pitch, keyMapD[pitch]['type'],keyMapD[pitch]['class']), color=c)
  324. ax.text( pitch, max_db, "%i %s %s" % (pitch, keyMapD[pitch]['type'],keyMapD[pitch]['class']), color=c)
  325. with open("minInterpDb.json",'w') as f:
  326. json.dump( { "pitchL":pitchL, "minDbL":list(interpMinDbL), "maxDbL":list(interpMaxDbL) }, f )
  327. plt.show()
  328. def plot_min_max_db( inDir, cfg, pitchL=None ):
  329. pitchFolderL = os.listdir(inDir)
  330. if pitchL is None:
  331. pitchL = [ int( int(pitchFolder) ) for pitchFolder in pitchFolderL ]
  332. maxDbL = []
  333. minDbL = []
  334. for midi_pitch in pitchL:
  335. print(midi_pitch)
  336. usL, dbL, durMsL, takeIdL, holdDutyPctL = get_merged_pulse_db_measurements( inDir, midi_pitch, cfg.analysisArgs['rmsAnalysisArgs'] )
  337. scoreV = np.abs( rms_analysis.samples_to_linear_residual( usL, dbL) * 100.0 / dbL )
  338. minDurMs = cfg.analysisArgs['resampleMinDurMs']
  339. minDb = cfg.analysisArgs['resampleMinDb'],
  340. noiseLimitPct = cfg.analysisArgs['resampleNoiseLimitPct']
  341. skipIdxL, firstAudibleIdx, firstNonSkipIdx = get_dur_skip_indexes( durMsL, dbL, takeIdL, scoreV.tolist(), minDurMs, minDb, noiseLimitPct )
  342. minDbL.append( dbL[firstAudibleIdx] )
  343. dbL = sorted(dbL)
  344. x = np.mean(dbL[-3:])
  345. x = np.max(dbL)
  346. maxDbL.append( x )
  347. fig,ax = plt.subplots()
  348. fig.set_size_inches(18.5, 10.5)
  349. p_dL = sorted( zip(pitchL,maxDbL), key=lambda x: x[0] )
  350. pitchL,maxDbL = zip(*p_dL)
  351. ax.plot(pitchL,maxDbL)
  352. ax.plot(pitchL,minDbL)
  353. for pitch,db in zip(pitchL,maxDbL):
  354. keyMapD = { d['midi']:d for d in cfg.key_mapL }
  355. ax.text( pitch, db, "%i %s %s" % (pitch, keyMapD[pitch]['type'],keyMapD[pitch]['class']))
  356. plt.show()
  357. def estimate_us_to_db_map( inDir, cfg, minMapDb=16.0, maxMapDb=26.0, incrMapDb=0.5, pitchL=None ):
  358. pitchFolderL = os.listdir(inDir)
  359. if pitchL is None:
  360. pitchL = [ int( int(pitchFolder) ) for pitchFolder in pitchFolderL ]
  361. mapD = {} # pitch:{ loDb: { hiDb, us_avg, us_cls, us_std, us_min, us_max, db_avg, db_std, cnt }}
  362. # where: cnt=count of valid sample points in this db range
  363. # us_cls=us of closest point to center of db range
  364. dbS = set() # { (loDb,hiDb) } track the set of db ranges
  365. for pitch in pitchL:
  366. print(pitch)
  367. # get the sample measurements for pitch
  368. usL, dbL, durMsL, takeIdL, holdDutyPctL = get_merged_pulse_db_measurements( inDir, pitch, cfg.analysisArgs['rmsAnalysisArgs'] )
  369. # calc the fit to local straight line curve fit at each point
  370. scoreV = np.abs( rms_analysis.samples_to_linear_residual( usL, dbL) * 100.0 / dbL )
  371. minDurMs = cfg.analysisArgs['resampleMinDurMs']
  372. minDb = cfg.analysisArgs['resampleMinDb'],
  373. noiseLimitPct = cfg.analysisArgs['resampleNoiseLimitPct']
  374. # get the set of samples that are not valid (too short, too quiet, too noisy)
  375. skipIdxL, firstAudibleIdx, firstNonSkipIdx = get_dur_skip_indexes( durMsL, dbL, takeIdL, scoreV.tolist(), minDurMs, minDb, noiseLimitPct )
  376. mapD[ pitch ] = {}
  377. # get the count of db ranges
  378. N = int(round((maxMapDb - minMapDb) / incrMapDb)) + 1
  379. # for each db range
  380. for i in range(N):
  381. loDb = minMapDb + (i*incrMapDb)
  382. hiDb = loDb + incrMapDb
  383. dbS.add((loDb,hiDb))
  384. # get the valid (pulse,db) pairs for this range
  385. u_dL = [(us,db) for i,(us,db) in enumerate(zip(usL,dbL)) if i not in skipIdxL and loDb<=db and db<hiDb ]
  386. us_avg = 0
  387. us_cls = 0
  388. us_std = 0
  389. us_min = 0
  390. us_max = 0
  391. db_avg = 0
  392. db_std = 0
  393. if len(u_dL) == 0:
  394. print("No valid samples for pitch:",pitch," db range:",loDb,hiDb)
  395. else:
  396. us0L,db0L = zip(*u_dL)
  397. if len(us0L) == 1:
  398. us_avg = us0L[0]
  399. us_cls = us_avg
  400. us_min = us_avg
  401. us_max = us_avg
  402. db_avg = db0L[0]
  403. elif len(us0L) > 1:
  404. us_avg = np.mean(us0L)
  405. us_cls = us0L[ np.argmin(np.abs(np.array(db0L)-(loDb - (hiDb-loDb)/2.0 ))) ]
  406. us_min = np.min(us0L)
  407. us_max = np.max(us0L)
  408. us_std = np.std(us0L)
  409. db_avg = np.mean(db0L)
  410. db_std = np.std(db0L)
  411. us_avg = int(round(us_avg))
  412. mapD[pitch][loDb] = { 'hiDb':hiDb, 'us_avg':us_avg, 'us_cls':us_cls, 'us_std':us_std,'us_min':us_min,'us_max':us_max, 'db_avg':db_avg, 'db_std':db_std, 'cnt':len(u_dL) }
  413. return mapD, list(dbS)
  414. def plot_us_to_db_map( inDir, cfg, minMapDb=16.0, maxMapDb=26.0, incrMapDb=1.0, pitchL=None ):
  415. fig,ax = plt.subplots()
  416. mapD, dbRefL = estimate_us_to_db_map( inDir, cfg, minMapDb, maxMapDb, incrMapDb, pitchL )
  417. # for each pitch
  418. for pitch, dbD in mapD.items():
  419. u_dL = [ (d['us_avg'],d['us_cls'],d['db_avg'],d['us_std'],d['us_min'],d['us_max'],d['db_std']) for loDb, d in dbD.items() if d['us_avg'] != 0 ]
  420. # get the us/db lists for this pitch
  421. usL,uscL,dbL,ussL,usnL,usxL,dbsL = zip(*u_dL)
  422. # plot central curve and std dev's
  423. p = ax.plot(usL,dbL, marker='.', label=str(pitch))
  424. ax.plot(uscL,dbL, marker='x', label=str(pitch), color=p[0].get_color(), linestyle='None')
  425. ax.plot(usL,np.array(dbL)+dbsL, color=p[0].get_color(), alpha=0.3)
  426. ax.plot(usL,np.array(dbL)-dbsL, color=p[0].get_color(), alpha=0.3)
  427. # plot us error bars
  428. for db,us,uss,us_min,us_max in zip(dbL,usL,ussL,usnL,usxL):
  429. ax.plot([us_min,us_max],[db,db], color=p[0].get_color(), alpha=0.3 )
  430. ax.plot([us-uss,us+uss],[db,db], color=p[0].get_color(), alpha=0.3, marker='.', linestyle='None' )
  431. plt.legend()
  432. plt.show()
  433. def report_take_ids( inDir ):
  434. pitchDirL = os.listdir(inDir)
  435. for pitch in pitchDirL:
  436. pitchDir = os.path.join(inDir,pitch)
  437. takeDirL = os.listdir(pitchDir)
  438. if len(takeDirL) == 0:
  439. print(pitch," directory empty")
  440. else:
  441. with open( os.path.join(pitchDir,'0','seq.json'), "rb") as f:
  442. r = json.load(f)
  443. if len(r['eventTimeL']) != 81:
  444. print(pitch," ",len(r['eventTimeL']))
  445. if len(takeDirL) != 3:
  446. print("***",pitch,len(takeDirL))
  447. def cache_us_db( inDir, cfg, outFn ):
  448. pitch_usDbD = {}
  449. pitchDirL = os.listdir(inDir)
  450. for pitch in pitchDirL:
  451. pitch = int(pitch)
  452. print(pitch)
  453. usL, dbL, durMsL, takeIdL, holdDutyPctL = get_merged_pulse_db_measurements( inDir, pitch, cfg.analysisArgs['rmsAnalysisArgs'] )
  454. pitch_usDbD[pitch] = { 'usL':usL, 'dbL':dbL, 'durMsL':durMsL, 'takeIdL':takeIdL, 'holdDutyPctL': holdDutyPctL }
  455. with open(outFn,"w") as f:
  456. json.dump(pitch_usDbD,f)
  457. def gen_vel_map( inDir, cfg, minMaxDbFn, dynLevelN, cacheFn ):
  458. velMapD = {} # { pitch:[ us ] }
  459. pitchDirL = os.listdir(inDir)
  460. with open(cacheFn,"r") as f:
  461. pitchUsDbD = json.load(f)
  462. with open("minInterpDb.json","r") as f:
  463. r = json.load(f)
  464. minMaxDbD = { pitch:(minDb,maxDb) for pitch,minDb,maxDb in zip(r['pitchL'],r['minDbL'],r['maxDbL']) }
  465. pitchL = sorted( [ int(pitch) for pitch in pitchUsDbD.keys()] )
  466. for pitch in pitchL:
  467. d = pitchUsDbD[str(pitch)]
  468. usL = d['usL']
  469. dbL = np.array(d['dbL'])
  470. velMapD[pitch] = []
  471. for i in range(dynLevelN+1):
  472. db = minMaxDbD[pitch][0] + (i * (minMaxDbD[pitch][1] - minMaxDbD[pitch][0])/ dynLevelN)
  473. usIdx = np.argmin( np.abs(dbL - db) )
  474. velMapD[pitch].append( (usL[ usIdx ],db) )
  475. with open("velMapD.json","w") as f:
  476. json.dump(velMapD,f)
  477. mtx = np.zeros((len(velMapD),dynLevelN+1))
  478. print(mtx.shape)
  479. for i,(pitch,usDbL) in enumerate(velMapD.items()):
  480. for j in range(len(usDbL)):
  481. mtx[i,j] = usDbL[j][1]
  482. fig,ax = plt.subplots()
  483. ax.plot(pitchL,mtx)
  484. plt.show()
  485. if __name__ == "__main__":
  486. inDir = sys.argv[1]
  487. cfgFn = sys.argv[2]
  488. mode = sys.argv[3]
  489. if len(sys.argv) <= 4:
  490. pitchL = None
  491. else:
  492. pitchL = [ int(sys.argv[i]) for i in range(4,len(sys.argv)) ]
  493. cfg = parse_yaml_cfg( cfgFn )
  494. if mode == 'us_db':
  495. plot_us_db_curves_main( inDir, cfg, pitchL, plotTakesFl=True,usMax=None )
  496. elif mode == 'noise':
  497. plot_all_noise_curves( inDir, cfg, pitchL )
  498. elif mode == 'min_max':
  499. plot_min_max_db( inDir, cfg, pitchL )
  500. elif mode == 'min_max_2':
  501. plot_min_max_2_db( inDir, cfg, pitchL )
  502. elif mode == 'us_db_map':
  503. plot_us_to_db_map( inDir, cfg, pitchL=pitchL )
  504. elif mode == 'audacity':
  505. rms_analysis.write_audacity_label_files( inDir, cfg.analysisArgs['rmsAnalysisArgs'] )
  506. elif mode == 'rpt_take_ids':
  507. report_take_ids( inDir )
  508. elif mode == 'manual_db':
  509. plot_min_db_manual( inDir, cfg )
  510. elif mode == 'gen_vel_map':
  511. gen_vel_map( inDir, cfg, "minInterpDb.json", 9, "cache_us_db.json" )
  512. elif mode == 'cache_us_db':
  513. cache_us_db( inDir, cfg, "cache_us_db.json")
  514. else:
  515. print("Unknown mode:",mode)