mlmm-toolkit 0.2.2.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. hessian_ff/__init__.py +50 -0
  2. hessian_ff/analytical_hessian.py +609 -0
  3. hessian_ff/constants.py +46 -0
  4. hessian_ff/forcefield.py +339 -0
  5. hessian_ff/loaders.py +608 -0
  6. hessian_ff/native/Makefile +8 -0
  7. hessian_ff/native/__init__.py +28 -0
  8. hessian_ff/native/analytical_hessian.py +88 -0
  9. hessian_ff/native/analytical_hessian_ext.cpp +258 -0
  10. hessian_ff/native/bonded.py +82 -0
  11. hessian_ff/native/bonded_ext.cpp +640 -0
  12. hessian_ff/native/loader.py +349 -0
  13. hessian_ff/native/nonbonded.py +118 -0
  14. hessian_ff/native/nonbonded_ext.cpp +1150 -0
  15. hessian_ff/prmtop_parmed.py +23 -0
  16. hessian_ff/system.py +107 -0
  17. hessian_ff/terms/__init__.py +14 -0
  18. hessian_ff/terms/angle.py +73 -0
  19. hessian_ff/terms/bond.py +44 -0
  20. hessian_ff/terms/cmap.py +406 -0
  21. hessian_ff/terms/dihedral.py +141 -0
  22. hessian_ff/terms/nonbonded.py +209 -0
  23. hessian_ff/tests/__init__.py +0 -0
  24. hessian_ff/tests/conftest.py +75 -0
  25. hessian_ff/tests/data/small/complex.parm7 +1346 -0
  26. hessian_ff/tests/data/small/complex.pdb +125 -0
  27. hessian_ff/tests/data/small/complex.rst7 +63 -0
  28. hessian_ff/tests/test_coords_input.py +44 -0
  29. hessian_ff/tests/test_energy_force.py +49 -0
  30. hessian_ff/tests/test_hessian.py +137 -0
  31. hessian_ff/tests/test_smoke.py +18 -0
  32. hessian_ff/tests/test_validation.py +40 -0
  33. hessian_ff/workflows.py +889 -0
  34. mlmm/__init__.py +36 -0
  35. mlmm/__main__.py +7 -0
  36. mlmm/_version.py +34 -0
  37. mlmm/add_elem_info.py +374 -0
  38. mlmm/advanced_help.py +91 -0
  39. mlmm/align_freeze_atoms.py +601 -0
  40. mlmm/all.py +3535 -0
  41. mlmm/bond_changes.py +231 -0
  42. mlmm/bool_compat.py +223 -0
  43. mlmm/cli.py +574 -0
  44. mlmm/cli_utils.py +166 -0
  45. mlmm/default_group.py +337 -0
  46. mlmm/defaults.py +467 -0
  47. mlmm/define_layer.py +526 -0
  48. mlmm/dft.py +1041 -0
  49. mlmm/energy_diagram.py +253 -0
  50. mlmm/extract.py +2213 -0
  51. mlmm/fix_altloc.py +464 -0
  52. mlmm/freq.py +1406 -0
  53. mlmm/harmonic_constraints.py +140 -0
  54. mlmm/hessian_cache.py +44 -0
  55. mlmm/hessian_calc.py +174 -0
  56. mlmm/irc.py +638 -0
  57. mlmm/mlmm_calc.py +2262 -0
  58. mlmm/mm_parm.py +945 -0
  59. mlmm/oniom_export.py +1983 -0
  60. mlmm/oniom_import.py +457 -0
  61. mlmm/opt.py +1742 -0
  62. mlmm/path_opt.py +1353 -0
  63. mlmm/path_search.py +2299 -0
  64. mlmm/preflight.py +88 -0
  65. mlmm/py.typed +1 -0
  66. mlmm/pysis_runner.py +45 -0
  67. mlmm/scan.py +1047 -0
  68. mlmm/scan2d.py +1226 -0
  69. mlmm/scan3d.py +1265 -0
  70. mlmm/scan_common.py +184 -0
  71. mlmm/summary_log.py +736 -0
  72. mlmm/trj2fig.py +448 -0
  73. mlmm/tsopt.py +2871 -0
  74. mlmm/utils.py +2309 -0
  75. mlmm/xtb_embedcharge_correction.py +475 -0
  76. mlmm_toolkit-0.2.2.dev0.dist-info/METADATA +1159 -0
  77. mlmm_toolkit-0.2.2.dev0.dist-info/RECORD +372 -0
  78. mlmm_toolkit-0.2.2.dev0.dist-info/WHEEL +5 -0
  79. mlmm_toolkit-0.2.2.dev0.dist-info/entry_points.txt +2 -0
  80. mlmm_toolkit-0.2.2.dev0.dist-info/licenses/LICENSE +674 -0
  81. mlmm_toolkit-0.2.2.dev0.dist-info/top_level.txt +4 -0
  82. pysisyphus/Geometry.py +1667 -0
  83. pysisyphus/LICENSE +674 -0
  84. pysisyphus/TableFormatter.py +63 -0
  85. pysisyphus/TablePrinter.py +74 -0
  86. pysisyphus/__init__.py +12 -0
  87. pysisyphus/calculators/AFIR.py +452 -0
  88. pysisyphus/calculators/AnaPot.py +20 -0
  89. pysisyphus/calculators/AnaPot2.py +48 -0
  90. pysisyphus/calculators/AnaPot3.py +12 -0
  91. pysisyphus/calculators/AnaPot4.py +20 -0
  92. pysisyphus/calculators/AnaPotBase.py +337 -0
  93. pysisyphus/calculators/AnaPotCBM.py +25 -0
  94. pysisyphus/calculators/AtomAtomTransTorque.py +154 -0
  95. pysisyphus/calculators/CFOUR.py +250 -0
  96. pysisyphus/calculators/Calculator.py +844 -0
  97. pysisyphus/calculators/CerjanMiller.py +24 -0
  98. pysisyphus/calculators/Composite.py +123 -0
  99. pysisyphus/calculators/ConicalIntersection.py +171 -0
  100. pysisyphus/calculators/DFTBp.py +430 -0
  101. pysisyphus/calculators/DFTD3.py +66 -0
  102. pysisyphus/calculators/DFTD4.py +84 -0
  103. pysisyphus/calculators/Dalton.py +61 -0
  104. pysisyphus/calculators/Dimer.py +681 -0
  105. pysisyphus/calculators/Dummy.py +20 -0
  106. pysisyphus/calculators/EGO.py +76 -0
  107. pysisyphus/calculators/EnergyMin.py +224 -0
  108. pysisyphus/calculators/ExternalPotential.py +264 -0
  109. pysisyphus/calculators/FakeASE.py +35 -0
  110. pysisyphus/calculators/FourWellAnaPot.py +28 -0
  111. pysisyphus/calculators/FreeEndNEBPot.py +39 -0
  112. pysisyphus/calculators/Gaussian09.py +18 -0
  113. pysisyphus/calculators/Gaussian16.py +726 -0
  114. pysisyphus/calculators/HardSphere.py +159 -0
  115. pysisyphus/calculators/IDPPCalculator.py +49 -0
  116. pysisyphus/calculators/IPIClient.py +133 -0
  117. pysisyphus/calculators/IPIServer.py +234 -0
  118. pysisyphus/calculators/LEPSBase.py +24 -0
  119. pysisyphus/calculators/LEPSExpr.py +139 -0
  120. pysisyphus/calculators/LennardJones.py +80 -0
  121. pysisyphus/calculators/MOPAC.py +219 -0
  122. pysisyphus/calculators/MullerBrownSympyPot.py +51 -0
  123. pysisyphus/calculators/MultiCalc.py +85 -0
  124. pysisyphus/calculators/NFK.py +45 -0
  125. pysisyphus/calculators/OBabel.py +87 -0
  126. pysisyphus/calculators/ONIOMv2.py +1129 -0
  127. pysisyphus/calculators/ORCA.py +893 -0
  128. pysisyphus/calculators/ORCA5.py +6 -0
  129. pysisyphus/calculators/OpenMM.py +88 -0
  130. pysisyphus/calculators/OpenMolcas.py +281 -0
  131. pysisyphus/calculators/OverlapCalculator.py +908 -0
  132. pysisyphus/calculators/Psi4.py +218 -0
  133. pysisyphus/calculators/PyPsi4.py +37 -0
  134. pysisyphus/calculators/PySCF.py +341 -0
  135. pysisyphus/calculators/PyXTB.py +73 -0
  136. pysisyphus/calculators/QCEngine.py +106 -0
  137. pysisyphus/calculators/Rastrigin.py +22 -0
  138. pysisyphus/calculators/Remote.py +76 -0
  139. pysisyphus/calculators/Rosenbrock.py +15 -0
  140. pysisyphus/calculators/SocketCalc.py +97 -0
  141. pysisyphus/calculators/TIP3P.py +111 -0
  142. pysisyphus/calculators/TransTorque.py +161 -0
  143. pysisyphus/calculators/Turbomole.py +965 -0
  144. pysisyphus/calculators/VRIPot.py +37 -0
  145. pysisyphus/calculators/WFOWrapper.py +333 -0
  146. pysisyphus/calculators/WFOWrapper2.py +341 -0
  147. pysisyphus/calculators/XTB.py +418 -0
  148. pysisyphus/calculators/__init__.py +81 -0
  149. pysisyphus/calculators/cosmo_data.py +139 -0
  150. pysisyphus/calculators/parser.py +150 -0
  151. pysisyphus/color.py +19 -0
  152. pysisyphus/config.py +133 -0
  153. pysisyphus/constants.py +65 -0
  154. pysisyphus/cos/AdaptiveNEB.py +230 -0
  155. pysisyphus/cos/ChainOfStates.py +725 -0
  156. pysisyphus/cos/FreeEndNEB.py +25 -0
  157. pysisyphus/cos/FreezingString.py +103 -0
  158. pysisyphus/cos/GrowingChainOfStates.py +71 -0
  159. pysisyphus/cos/GrowingNT.py +309 -0
  160. pysisyphus/cos/GrowingString.py +508 -0
  161. pysisyphus/cos/NEB.py +189 -0
  162. pysisyphus/cos/SimpleZTS.py +64 -0
  163. pysisyphus/cos/__init__.py +22 -0
  164. pysisyphus/cos/stiffness.py +199 -0
  165. pysisyphus/drivers/__init__.py +17 -0
  166. pysisyphus/drivers/afir.py +855 -0
  167. pysisyphus/drivers/barriers.py +271 -0
  168. pysisyphus/drivers/birkholz.py +138 -0
  169. pysisyphus/drivers/cluster.py +318 -0
  170. pysisyphus/drivers/diabatization.py +133 -0
  171. pysisyphus/drivers/merge.py +368 -0
  172. pysisyphus/drivers/merge_mol2.py +322 -0
  173. pysisyphus/drivers/opt.py +375 -0
  174. pysisyphus/drivers/perf.py +91 -0
  175. pysisyphus/drivers/pka.py +52 -0
  176. pysisyphus/drivers/precon_pos_rot.py +669 -0
  177. pysisyphus/drivers/rates.py +480 -0
  178. pysisyphus/drivers/replace.py +219 -0
  179. pysisyphus/drivers/scan.py +212 -0
  180. pysisyphus/drivers/spectrum.py +166 -0
  181. pysisyphus/drivers/thermo.py +31 -0
  182. pysisyphus/dynamics/Gaussian.py +103 -0
  183. pysisyphus/dynamics/__init__.py +20 -0
  184. pysisyphus/dynamics/colvars.py +136 -0
  185. pysisyphus/dynamics/driver.py +297 -0
  186. pysisyphus/dynamics/helpers.py +256 -0
  187. pysisyphus/dynamics/lincs.py +105 -0
  188. pysisyphus/dynamics/mdp.py +364 -0
  189. pysisyphus/dynamics/rattle.py +121 -0
  190. pysisyphus/dynamics/thermostats.py +128 -0
  191. pysisyphus/dynamics/wigner.py +266 -0
  192. pysisyphus/elem_data.py +3473 -0
  193. pysisyphus/exceptions.py +2 -0
  194. pysisyphus/filtertrj.py +69 -0
  195. pysisyphus/helpers.py +623 -0
  196. pysisyphus/helpers_pure.py +649 -0
  197. pysisyphus/init_logging.py +50 -0
  198. pysisyphus/intcoords/Bend.py +69 -0
  199. pysisyphus/intcoords/Bend2.py +25 -0
  200. pysisyphus/intcoords/BondedFragment.py +32 -0
  201. pysisyphus/intcoords/Cartesian.py +41 -0
  202. pysisyphus/intcoords/CartesianCoords.py +140 -0
  203. pysisyphus/intcoords/Coords.py +56 -0
  204. pysisyphus/intcoords/DLC.py +197 -0
  205. pysisyphus/intcoords/DistanceFunction.py +34 -0
  206. pysisyphus/intcoords/DummyImproper.py +70 -0
  207. pysisyphus/intcoords/DummyTorsion.py +72 -0
  208. pysisyphus/intcoords/LinearBend.py +105 -0
  209. pysisyphus/intcoords/LinearDisplacement.py +80 -0
  210. pysisyphus/intcoords/OutOfPlane.py +59 -0
  211. pysisyphus/intcoords/PrimTypes.py +286 -0
  212. pysisyphus/intcoords/Primitive.py +137 -0
  213. pysisyphus/intcoords/RedundantCoords.py +659 -0
  214. pysisyphus/intcoords/RobustTorsion.py +59 -0
  215. pysisyphus/intcoords/Rotation.py +147 -0
  216. pysisyphus/intcoords/Stretch.py +31 -0
  217. pysisyphus/intcoords/Torsion.py +101 -0
  218. pysisyphus/intcoords/Torsion2.py +25 -0
  219. pysisyphus/intcoords/Translation.py +45 -0
  220. pysisyphus/intcoords/__init__.py +61 -0
  221. pysisyphus/intcoords/augment_bonds.py +126 -0
  222. pysisyphus/intcoords/derivatives.py +10512 -0
  223. pysisyphus/intcoords/eval.py +80 -0
  224. pysisyphus/intcoords/exceptions.py +37 -0
  225. pysisyphus/intcoords/findiffs.py +48 -0
  226. pysisyphus/intcoords/generate_derivatives.py +414 -0
  227. pysisyphus/intcoords/helpers.py +235 -0
  228. pysisyphus/intcoords/logging_conf.py +10 -0
  229. pysisyphus/intcoords/mp_derivatives.py +10836 -0
  230. pysisyphus/intcoords/setup.py +962 -0
  231. pysisyphus/intcoords/setup_fast.py +176 -0
  232. pysisyphus/intcoords/update.py +272 -0
  233. pysisyphus/intcoords/valid.py +89 -0
  234. pysisyphus/interpolate/Geodesic.py +93 -0
  235. pysisyphus/interpolate/IDPP.py +55 -0
  236. pysisyphus/interpolate/Interpolator.py +116 -0
  237. pysisyphus/interpolate/LST.py +70 -0
  238. pysisyphus/interpolate/Redund.py +152 -0
  239. pysisyphus/interpolate/__init__.py +9 -0
  240. pysisyphus/interpolate/helpers.py +34 -0
  241. pysisyphus/io/__init__.py +22 -0
  242. pysisyphus/io/aomix.py +178 -0
  243. pysisyphus/io/cjson.py +24 -0
  244. pysisyphus/io/crd.py +101 -0
  245. pysisyphus/io/cube.py +220 -0
  246. pysisyphus/io/fchk.py +184 -0
  247. pysisyphus/io/hdf5.py +49 -0
  248. pysisyphus/io/hessian.py +72 -0
  249. pysisyphus/io/mol2.py +146 -0
  250. pysisyphus/io/molden.py +293 -0
  251. pysisyphus/io/orca.py +189 -0
  252. pysisyphus/io/pdb.py +269 -0
  253. pysisyphus/io/psf.py +79 -0
  254. pysisyphus/io/pubchem.py +31 -0
  255. pysisyphus/io/qcschema.py +34 -0
  256. pysisyphus/io/sdf.py +29 -0
  257. pysisyphus/io/xyz.py +61 -0
  258. pysisyphus/io/zmat.py +175 -0
  259. pysisyphus/irc/DWI.py +108 -0
  260. pysisyphus/irc/DampedVelocityVerlet.py +134 -0
  261. pysisyphus/irc/Euler.py +22 -0
  262. pysisyphus/irc/EulerPC.py +345 -0
  263. pysisyphus/irc/GonzalezSchlegel.py +187 -0
  264. pysisyphus/irc/IMKMod.py +164 -0
  265. pysisyphus/irc/IRC.py +878 -0
  266. pysisyphus/irc/IRCDummy.py +10 -0
  267. pysisyphus/irc/Instanton.py +307 -0
  268. pysisyphus/irc/LQA.py +53 -0
  269. pysisyphus/irc/ModeKill.py +136 -0
  270. pysisyphus/irc/ParamPlot.py +53 -0
  271. pysisyphus/irc/RK4.py +36 -0
  272. pysisyphus/irc/__init__.py +31 -0
  273. pysisyphus/irc/initial_displ.py +219 -0
  274. pysisyphus/linalg.py +411 -0
  275. pysisyphus/line_searches/Backtracking.py +88 -0
  276. pysisyphus/line_searches/HagerZhang.py +184 -0
  277. pysisyphus/line_searches/LineSearch.py +232 -0
  278. pysisyphus/line_searches/StrongWolfe.py +108 -0
  279. pysisyphus/line_searches/__init__.py +9 -0
  280. pysisyphus/line_searches/interpol.py +15 -0
  281. pysisyphus/modefollow/NormalMode.py +40 -0
  282. pysisyphus/modefollow/__init__.py +10 -0
  283. pysisyphus/modefollow/davidson.py +199 -0
  284. pysisyphus/modefollow/lanczos.py +95 -0
  285. pysisyphus/optimizers/BFGS.py +99 -0
  286. pysisyphus/optimizers/BacktrackingOptimizer.py +113 -0
  287. pysisyphus/optimizers/ConjugateGradient.py +98 -0
  288. pysisyphus/optimizers/CubicNewton.py +75 -0
  289. pysisyphus/optimizers/FIRE.py +113 -0
  290. pysisyphus/optimizers/HessianOptimizer.py +1176 -0
  291. pysisyphus/optimizers/LBFGS.py +228 -0
  292. pysisyphus/optimizers/LayerOpt.py +411 -0
  293. pysisyphus/optimizers/MicroOptimizer.py +169 -0
  294. pysisyphus/optimizers/NCOptimizer.py +90 -0
  295. pysisyphus/optimizers/Optimizer.py +1084 -0
  296. pysisyphus/optimizers/PreconLBFGS.py +260 -0
  297. pysisyphus/optimizers/PreconSteepestDescent.py +7 -0
  298. pysisyphus/optimizers/QuickMin.py +74 -0
  299. pysisyphus/optimizers/RFOptimizer.py +181 -0
  300. pysisyphus/optimizers/RSA.py +99 -0
  301. pysisyphus/optimizers/StabilizedQNMethod.py +248 -0
  302. pysisyphus/optimizers/SteepestDescent.py +23 -0
  303. pysisyphus/optimizers/StringOptimizer.py +173 -0
  304. pysisyphus/optimizers/__init__.py +41 -0
  305. pysisyphus/optimizers/closures.py +301 -0
  306. pysisyphus/optimizers/cls_map.py +58 -0
  307. pysisyphus/optimizers/exceptions.py +6 -0
  308. pysisyphus/optimizers/gdiis.py +280 -0
  309. pysisyphus/optimizers/guess_hessians.py +311 -0
  310. pysisyphus/optimizers/hessian_updates.py +355 -0
  311. pysisyphus/optimizers/poly_fit.py +285 -0
  312. pysisyphus/optimizers/precon.py +153 -0
  313. pysisyphus/optimizers/restrict_step.py +24 -0
  314. pysisyphus/pack.py +172 -0
  315. pysisyphus/peakdetect.py +948 -0
  316. pysisyphus/plot.py +1031 -0
  317. pysisyphus/run.py +2106 -0
  318. pysisyphus/socket_helper.py +74 -0
  319. pysisyphus/stocastic/FragmentKick.py +132 -0
  320. pysisyphus/stocastic/Kick.py +81 -0
  321. pysisyphus/stocastic/Pipeline.py +303 -0
  322. pysisyphus/stocastic/__init__.py +21 -0
  323. pysisyphus/stocastic/align.py +127 -0
  324. pysisyphus/testing.py +96 -0
  325. pysisyphus/thermo.py +156 -0
  326. pysisyphus/trj.py +824 -0
  327. pysisyphus/tsoptimizers/RSIRFOptimizer.py +56 -0
  328. pysisyphus/tsoptimizers/RSPRFOptimizer.py +182 -0
  329. pysisyphus/tsoptimizers/TRIM.py +59 -0
  330. pysisyphus/tsoptimizers/TSHessianOptimizer.py +463 -0
  331. pysisyphus/tsoptimizers/__init__.py +23 -0
  332. pysisyphus/wavefunction/Basis.py +239 -0
  333. pysisyphus/wavefunction/DIIS.py +76 -0
  334. pysisyphus/wavefunction/__init__.py +25 -0
  335. pysisyphus/wavefunction/build_ext.py +42 -0
  336. pysisyphus/wavefunction/cart2sph.py +190 -0
  337. pysisyphus/wavefunction/diabatization.py +304 -0
  338. pysisyphus/wavefunction/excited_states.py +435 -0
  339. pysisyphus/wavefunction/gen_ints.py +1811 -0
  340. pysisyphus/wavefunction/helpers.py +104 -0
  341. pysisyphus/wavefunction/ints/__init__.py +0 -0
  342. pysisyphus/wavefunction/ints/boys.py +193 -0
  343. pysisyphus/wavefunction/ints/boys_table_N_64_xasym_27.1_step_0.01.npy +0 -0
  344. pysisyphus/wavefunction/ints/cart_gto3d.py +176 -0
  345. pysisyphus/wavefunction/ints/coulomb3d.py +25928 -0
  346. pysisyphus/wavefunction/ints/diag_quadrupole3d.py +10036 -0
  347. pysisyphus/wavefunction/ints/dipole3d.py +8762 -0
  348. pysisyphus/wavefunction/ints/int2c2e3d.py +7198 -0
  349. pysisyphus/wavefunction/ints/int3c2e3d_sph.py +65040 -0
  350. pysisyphus/wavefunction/ints/kinetic3d.py +8240 -0
  351. pysisyphus/wavefunction/ints/ovlp3d.py +3777 -0
  352. pysisyphus/wavefunction/ints/quadrupole3d.py +15054 -0
  353. pysisyphus/wavefunction/ints/self_ovlp3d.py +198 -0
  354. pysisyphus/wavefunction/localization.py +458 -0
  355. pysisyphus/wavefunction/multipole.py +159 -0
  356. pysisyphus/wavefunction/normalization.py +36 -0
  357. pysisyphus/wavefunction/pop_analysis.py +134 -0
  358. pysisyphus/wavefunction/shells.py +1171 -0
  359. pysisyphus/wavefunction/wavefunction.py +504 -0
  360. pysisyphus/wrapper/__init__.py +11 -0
  361. pysisyphus/wrapper/exceptions.py +2 -0
  362. pysisyphus/wrapper/jmol.py +120 -0
  363. pysisyphus/wrapper/mwfn.py +169 -0
  364. pysisyphus/wrapper/packmol.py +71 -0
  365. pysisyphus/xyzloader.py +168 -0
  366. pysisyphus/yaml_mods.py +45 -0
  367. thermoanalysis/LICENSE +674 -0
  368. thermoanalysis/QCData.py +244 -0
  369. thermoanalysis/__init__.py +0 -0
  370. thermoanalysis/config.py +3 -0
  371. thermoanalysis/constants.py +20 -0
  372. thermoanalysis/thermo.py +1011 -0
@@ -0,0 +1,948 @@
1
+ #!/usr/bin/python2
2
+
3
+
4
+ # Copyright (C) 2016 Sixten Bergman
5
+ # License WTFPL
6
+ #
7
+ # This program is free software. It comes without any warranty, to the extent
8
+ # permitted by applicable law.
9
+ # You can redistribute it and/or modify it under the terms of the Do What The
10
+ # Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See
11
+ # http://www.wtfpl.net/ for more details.
12
+ #
13
+ # note that the function peakdetect is derived from code which was released to
14
+ # public domain see: http://billauer.co.il/peakdet.html
15
+ #
16
+
17
+ import logging
18
+ from math import pi, log
19
+ import numpy as np
20
+ import pylab
21
+
22
+ # They seem to have changed it at one point
23
+ try:
24
+ from scipy import fft, ifft
25
+ except ImportError:
26
+ from scipy.fft import fft, ifft
27
+ from scipy.optimize import curve_fit
28
+ from scipy.signal import cspline1d_eval, cspline1d
29
+
30
+ __all__ = [
31
+ "peakdetect",
32
+ "peakdetect_fft",
33
+ "peakdetect_parabola",
34
+ "peakdetect_sine",
35
+ "peakdetect_sine_locked",
36
+ "peakdetect_spline",
37
+ "peakdetect_zero_crossing",
38
+ "zero_crossings",
39
+ "zero_crossings_sine_fit",
40
+ ]
41
+
42
+
43
+ def _datacheck_peakdetect(x_axis, y_axis):
44
+ if x_axis is None:
45
+ x_axis = range(len(y_axis))
46
+
47
+ if len(y_axis) != len(x_axis):
48
+ raise ValueError("Input vectors y_axis and x_axis must have same length")
49
+
50
+ # needs to be a numpy array
51
+ y_axis = np.array(y_axis)
52
+ x_axis = np.array(x_axis)
53
+ return x_axis, y_axis
54
+
55
+
56
+ def _pad(fft_data, pad_len):
57
+ """
58
+ Pads fft data to interpolate in time domain
59
+
60
+ keyword arguments:
61
+ fft_data -- the fft
62
+ pad_len -- By how many times the time resolution should be increased by
63
+
64
+ return: padded list
65
+ """
66
+ l = len(fft_data)
67
+ n = _n(l * pad_len)
68
+ fft_data = list(fft_data)
69
+
70
+ return fft_data[: l // 2] + [0] * (2**n - l) + fft_data[l // 2 :]
71
+
72
+
73
+ def _n(x):
74
+ """
75
+ Find the smallest value for n, which fulfils 2**n >= x
76
+
77
+ keyword arguments:
78
+ x -- the value, which 2**n must surpass
79
+
80
+ return: the integer n
81
+ """
82
+ return int(log(x) / log(2)) + 1
83
+
84
+
85
+ def _peakdetect_parabola_fitter(raw_peaks, x_axis, y_axis, points):
86
+ """
87
+ Performs the actual parabola fitting for the peakdetect_parabola function.
88
+
89
+ keyword arguments:
90
+ raw_peaks -- A list of either the maxima or the minima peaks, as given
91
+ by the peakdetect functions, with index used as x-axis
92
+
93
+ x_axis -- A numpy array of all the x values
94
+
95
+ y_axis -- A numpy array of all the y values
96
+
97
+ points -- How many points around the peak should be used during curve
98
+ fitting, must be odd.
99
+
100
+
101
+ return: A list giving all the peaks and the fitted waveform, format:
102
+ [[x, y, [fitted_x, fitted_y]]]
103
+
104
+ """
105
+ func = lambda x, a, tau, c: a * ((x - tau) ** 2) + c
106
+ fitted_peaks = []
107
+ distance = abs(x_axis[raw_peaks[1][0]] - x_axis[raw_peaks[0][0]]) / 4
108
+ for peak in raw_peaks:
109
+ index = peak[0]
110
+ x_data = x_axis[index - points // 2 : index + points // 2 + 1]
111
+ y_data = y_axis[index - points // 2 : index + points // 2 + 1]
112
+ # get a first approximation of tau (peak position in time)
113
+ tau = x_axis[index]
114
+ # get a first approximation of peak amplitude
115
+ c = peak[1]
116
+ a = np.sign(c) * (-1) * (np.sqrt(abs(c)) / distance) ** 2
117
+ """Derived from ABC formula to result in a solution where A=(rot(c)/t)**2"""
118
+
119
+ # build list of approximations
120
+
121
+ p0 = (a, tau, c)
122
+ popt, pcov = curve_fit(func, x_data, y_data, p0)
123
+ # retrieve tau and c i.e x and y value of peak
124
+ x, y = popt[1:3]
125
+
126
+ # create a high resolution data set for the fitted waveform
127
+ x2 = np.linspace(x_data[0], x_data[-1], points * 10)
128
+ y2 = func(x2, *popt)
129
+
130
+ fitted_peaks.append([x, y, [x2, y2]])
131
+
132
+ return fitted_peaks
133
+
134
+
135
+ def peakdetect_parabole(*args, **kwargs):
136
+ """
137
+ Misspelling of peakdetect_parabola
138
+ function is deprecated please use peakdetect_parabola
139
+ """
140
+ logging.warn(
141
+ "peakdetect_parabole is deprecated due to misspelling use: peakdetect_parabola"
142
+ )
143
+
144
+ return peakdetect_parabola(*args, **kwargs)
145
+
146
+
147
+ def peakdetect(y_axis, x_axis=None, lookahead=200, delta=0):
148
+ """
149
+ Converted from/based on a MATLAB script at:
150
+ http://billauer.co.il/peakdet.html
151
+
152
+ function for detecting local maxima and minima in a signal.
153
+ Discovers peaks by searching for values which are surrounded by lower
154
+ or larger values for maxima and minima respectively
155
+
156
+ keyword arguments:
157
+ y_axis -- A list containing the signal over which to find peaks
158
+
159
+ x_axis -- A x-axis whose values correspond to the y_axis list and is used
160
+ in the return to specify the position of the peaks. If omitted an
161
+ index of the y_axis is used.
162
+ (default: None)
163
+
164
+ lookahead -- distance to look ahead from a peak candidate to determine if
165
+ it is the actual peak
166
+ (default: 200)
167
+ '(samples / period) / f' where '4 >= f >= 1.25' might be a good value
168
+
169
+ delta -- this specifies a minimum difference between a peak and
170
+ the following points, before a peak may be considered a peak. Useful
171
+ to hinder the function from picking up false peaks towards to end of
172
+ the signal. To work well delta should be set to delta >= RMSnoise * 5.
173
+ (default: 0)
174
+ When omitted delta function causes a 20% decrease in speed.
175
+ When used Correctly it can double the speed of the function
176
+
177
+
178
+ return: two lists [max_peaks, min_peaks] containing the positive and
179
+ negative peaks respectively. Each cell of the lists contains a tuple
180
+ of: (position, peak_value)
181
+ to get the average peak value do: np.mean(max_peaks, 0)[1] on the
182
+ results to unpack one of the lists into x, y coordinates do:
183
+ x, y = zip(*max_peaks)
184
+ """
185
+ max_peaks = []
186
+ min_peaks = []
187
+ dump = [] # Used to pop the first hit which almost always is false
188
+
189
+ # check input data
190
+ x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
191
+ # store data length for later use
192
+ length = len(y_axis)
193
+
194
+ # perform some checks
195
+ if lookahead < 1:
196
+ raise ValueError("Lookahead must be '1' or above in value")
197
+ if not (np.isscalar(delta) and delta >= 0):
198
+ raise ValueError("delta must be a positive number")
199
+
200
+ # maxima and minima candidates are temporarily stored in
201
+ # mx and mn respectively
202
+ mn, mx = np.inf, -np.inf
203
+
204
+ # Only detect peak if there is 'lookahead' amount of points after it
205
+ for index, (x, y) in enumerate(zip(x_axis[:-lookahead], y_axis[:-lookahead])):
206
+ if y > mx:
207
+ mx = y
208
+ mxpos = x
209
+ if y < mn:
210
+ mn = y
211
+ mnpos = x
212
+
213
+ ####look for max####
214
+ if y < mx - delta and mx != np.inf:
215
+ # Maxima peak candidate found
216
+ # look ahead in signal to ensure that this is a peak and not jitter
217
+ if y_axis[index : index + lookahead].max() < mx:
218
+ max_peaks.append([mxpos, mx])
219
+ dump.append(True)
220
+ # set algorithm to only find minima now
221
+ mx = np.inf
222
+ mn = np.inf
223
+ if index + lookahead >= length:
224
+ # end is within lookahead no more peaks can be found
225
+ break
226
+ continue
227
+ # else: #slows shit down this does
228
+ # mx = ahead
229
+ # mxpos = x_axis[np.where(y_axis[index:index+lookahead]==mx)]
230
+
231
+ ####look for min####
232
+ if y > mn + delta and mn != -np.inf:
233
+ # Minima peak candidate found
234
+ # look ahead in signal to ensure that this is a peak and not jitter
235
+ if y_axis[index : index + lookahead].min() > mn:
236
+ min_peaks.append([mnpos, mn])
237
+ dump.append(False)
238
+ # set algorithm to only find maxima now
239
+ mn = -np.inf
240
+ mx = -np.inf
241
+ if index + lookahead >= length:
242
+ # end is within lookahead no more peaks can be found
243
+ break
244
+ # else: #slows shit down this does
245
+ # mn = ahead
246
+ # mnpos = x_axis[np.where(y_axis[index:index+lookahead]==mn)]
247
+
248
+ # Remove the false hit on the first value of the y_axis
249
+ try:
250
+ if dump[0]:
251
+ max_peaks.pop(0)
252
+ else:
253
+ min_peaks.pop(0)
254
+ del dump
255
+ except IndexError:
256
+ # no peaks were found, should the function return empty lists?
257
+ pass
258
+
259
+ return [max_peaks, min_peaks]
260
+
261
+
262
+ def peakdetect_fft(y_axis, x_axis, pad_len=20):
263
+ """
264
+ Performs a FFT calculation on the data and zero-pads the results to
265
+ increase the time domain resolution after performing the inverse fft and
266
+ send the data to the 'peakdetect' function for peak
267
+ detection.
268
+
269
+ Omitting the x_axis is forbidden as it would make the resulting x_axis
270
+ value silly if it was returned as the index 50.234 or similar.
271
+
272
+ Will find at least 1 less peak then the 'peakdetect_zero_crossing'
273
+ function, but should result in a more precise value of the peak as
274
+ resolution has been increased. Some peaks are lost in an attempt to
275
+ minimize spectral leakage by calculating the fft between two zero
276
+ crossings for n amount of signal periods.
277
+
278
+ The biggest time eater in this function is the ifft and thereafter it's
279
+ the 'peakdetect' function which takes only half the time of the ifft.
280
+ Speed improvements could include to check if 2**n points could be used for
281
+ fft and ifft or change the 'peakdetect' to the 'peakdetect_zero_crossing',
282
+ which is maybe 10 times faster than 'peakdetct'. The pro of 'peakdetect'
283
+ is that it results in one less lost peak. It should also be noted that the
284
+ time used by the ifft function can change greatly depending on the input.
285
+
286
+ keyword arguments:
287
+ y_axis -- A list containing the signal over which to find peaks
288
+
289
+ x_axis -- A x-axis whose values correspond to the y_axis list and is used
290
+ in the return to specify the position of the peaks.
291
+
292
+ pad_len -- By how many times the time resolution should be
293
+ increased by, e.g. 1 doubles the resolution. The amount is rounded up
294
+ to the nearest 2**n amount
295
+ (default: 20)
296
+
297
+
298
+ return: two lists [max_peaks, min_peaks] containing the positive and
299
+ negative peaks respectively. Each cell of the lists contains a tuple
300
+ of: (position, peak_value)
301
+ to get the average peak value do: np.mean(max_peaks, 0)[1] on the
302
+ results to unpack one of the lists into x, y coordinates do:
303
+ x, y = zip(*max_peaks)
304
+ """
305
+ # check input data
306
+ x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
307
+ zero_indices = zero_crossings(y_axis, window_len=11)
308
+ # select a n amount of periods
309
+ last_indice = -1 - (1 - len(zero_indices) & 1)
310
+ ###
311
+ # Calculate the fft between the first and last zero crossing
312
+ # this method could be ignored if the beginning and the end of the signal
313
+ # are unnecessary as any errors induced from not using whole periods
314
+ # should mainly manifest in the beginning and the end of the signal, but
315
+ # not in the rest of the signal
316
+ # this is also unnecessary if the given data is an amount of whole periods
317
+ ###
318
+ fft_data = fft(y_axis[zero_indices[0] : zero_indices[last_indice]])
319
+ padd = lambda x, c: x[: len(x) // 2] + [0] * c + x[len(x) // 2 :]
320
+ n = lambda x: int(log(x) / log(2)) + 1
321
+ # pads to 2**n amount of samples
322
+ fft_padded = padd(list(fft_data), 2 ** n(len(fft_data) * pad_len) - len(fft_data))
323
+
324
+ # There is amplitude decrease directly proportional to the sample increase
325
+ sf = len(fft_padded) / float(len(fft_data))
326
+ # There might be a leakage giving the result an imaginary component
327
+ # Return only the real component
328
+ y_axis_ifft = ifft(fft_padded).real * sf # (pad_len + 1)
329
+ x_axis_ifft = np.linspace(
330
+ x_axis[zero_indices[0]], x_axis[zero_indices[last_indice]], len(y_axis_ifft)
331
+ )
332
+ # get the peaks to the interpolated waveform
333
+ max_peaks, min_peaks = peakdetect(
334
+ y_axis_ifft, x_axis_ifft, 500, delta=abs(np.diff(y_axis).max() * 2)
335
+ )
336
+ # max_peaks, min_peaks = peakdetect_zero_crossing(y_axis_ifft, x_axis_ifft)
337
+
338
+ # store one 20th of a period as waveform data
339
+ data_len = int(np.diff(zero_indices).mean()) / 10
340
+ data_len += 1 - data_len & 1
341
+
342
+ return [max_peaks, min_peaks]
343
+
344
+
345
+ def peakdetect_parabola(y_axis, x_axis, points=31):
346
+ """
347
+ Function for detecting local maxima and minima in a signal.
348
+ Discovers peaks by fitting the model function: y = k (x - tau) ** 2 + m
349
+ to the peaks. The amount of points used in the fitting is set by the
350
+ points argument.
351
+
352
+ Omitting the x_axis is forbidden as it would make the resulting x_axis
353
+ value silly, if it was returned as index 50.234 or similar.
354
+
355
+ will find the same amount of peaks as the 'peakdetect_zero_crossing'
356
+ function, but might result in a more precise value of the peak.
357
+
358
+ keyword arguments:
359
+ y_axis -- A list containing the signal over which to find peaks
360
+
361
+ x_axis -- A x-axis whose values correspond to the y_axis list and is used
362
+ in the return to specify the position of the peaks.
363
+
364
+ points -- How many points around the peak should be used during curve
365
+ fitting (default: 31)
366
+
367
+
368
+ return: two lists [max_peaks, min_peaks] containing the positive and
369
+ negative peaks respectively. Each cell of the lists contains a tuple
370
+ of: (position, peak_value)
371
+ to get the average peak value do: np.mean(max_peaks, 0)[1] on the
372
+ results to unpack one of the lists into x, y coordinates do:
373
+ x, y = zip(*max_peaks)
374
+ """
375
+ # check input data
376
+ x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
377
+ # make the points argument odd
378
+ points += 1 - points % 2
379
+ # points += 1 - int(points) & 1 slower when int conversion needed
380
+
381
+ # get raw peaks
382
+ max_raw, min_raw = peakdetect_zero_crossing(y_axis)
383
+
384
+ # define output variable
385
+ max_peaks = []
386
+ min_peaks = []
387
+
388
+ max_ = _peakdetect_parabola_fitter(max_raw, x_axis, y_axis, points)
389
+ min_ = _peakdetect_parabola_fitter(min_raw, x_axis, y_axis, points)
390
+
391
+ max_peaks = map(lambda x: [x[0], x[1]], max_)
392
+ max_fitted = map(lambda x: x[-1], max_)
393
+ min_peaks = map(lambda x: [x[0], x[1]], min_)
394
+ min_fitted = map(lambda x: x[-1], min_)
395
+
396
+ return [max_peaks, min_peaks]
397
+
398
+
399
+ def peakdetect_sine(y_axis, x_axis, points=31, lock_frequency=False):
400
+ """
401
+ Function for detecting local maxima and minima in a signal.
402
+ Discovers peaks by fitting the model function:
403
+ y = A * sin(2 * pi * f * (x - tau)) to the peaks. The amount of points used
404
+ in the fitting is set by the points argument.
405
+
406
+ Omitting the x_axis is forbidden as it would make the resulting x_axis
407
+ value silly if it was returned as index 50.234 or similar.
408
+
409
+ will find the same amount of peaks as the 'peakdetect_zero_crossing'
410
+ function, but might result in a more precise value of the peak.
411
+
412
+ The function might have some problems if the sine wave has a
413
+ non-negligible total angle i.e. a k*x component, as this messes with the
414
+ internal offset calculation of the peaks, might be fixed by fitting a
415
+ y = k * x + m function to the peaks for offset calculation.
416
+
417
+ keyword arguments:
418
+ y_axis -- A list containing the signal over which to find peaks
419
+
420
+ x_axis -- A x-axis whose values correspond to the y_axis list and is used
421
+ in the return to specify the position of the peaks.
422
+
423
+ points -- How many points around the peak should be used during curve
424
+ fitting (default: 31)
425
+
426
+ lock_frequency -- Specifies if the frequency argument of the model
427
+ function should be locked to the value calculated from the raw peaks
428
+ or if optimization process may tinker with it.
429
+ (default: False)
430
+
431
+
432
+ return: two lists [max_peaks, min_peaks] containing the positive and
433
+ negative peaks respectively. Each cell of the lists contains a tuple
434
+ of: (position, peak_value)
435
+ to get the average peak value do: np.mean(max_peaks, 0)[1] on the
436
+ results to unpack one of the lists into x, y coordinates do:
437
+ x, y = zip(*max_peaks)
438
+ """
439
+ # check input data
440
+ x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
441
+ # make the points argument odd
442
+ points += 1 - points % 2
443
+ # points += 1 - int(points) & 1 slower when int conversion needed
444
+
445
+ # get raw peaks
446
+ max_raw, min_raw = peakdetect_zero_crossing(y_axis)
447
+
448
+ # define output variable
449
+ max_peaks = []
450
+ min_peaks = []
451
+
452
+ # get global offset
453
+ offset = np.mean([np.mean(max_raw, 0)[1], np.mean(min_raw, 0)[1]])
454
+ # fitting a k * x + m function to the peaks might be better
455
+ # offset_func = lambda x, k, m: k * x + m
456
+
457
+ # calculate an approximate frequency of the signal
458
+ Hz_h_peak = np.diff(zip(*max_raw)[0]).mean()
459
+ Hz_l_peak = np.diff(zip(*min_raw)[0]).mean()
460
+ Hz = 1 / np.mean([Hz_h_peak, Hz_l_peak])
461
+
462
+ # model function
463
+ # if cosine is used then tau could equal the x position of the peak
464
+ # if sine were to be used then tau would be the first zero crossing
465
+ if lock_frequency:
466
+ func = lambda x_ax, A, tau: A * np.sin(2 * pi * Hz * (x_ax - tau) + pi / 2)
467
+ else:
468
+ func = lambda x_ax, A, Hz, tau: A * np.sin(2 * pi * Hz * (x_ax - tau) + pi / 2)
469
+ # func = lambda x_ax, A, Hz, tau: A * np.cos(2 * pi * Hz * (x_ax - tau))
470
+
471
+ # get peaks
472
+ fitted_peaks = []
473
+ for raw_peaks in [max_raw, min_raw]:
474
+ peak_data = []
475
+ for peak in raw_peaks:
476
+ index = peak[0]
477
+ x_data = x_axis[index - points // 2 : index + points // 2 + 1]
478
+ y_data = y_axis[index - points // 2 : index + points // 2 + 1]
479
+ # get a first approximation of tau (peak position in time)
480
+ tau = x_axis[index]
481
+ # get a first approximation of peak amplitude
482
+ A = peak[1]
483
+
484
+ # build list of approximations
485
+ if lock_frequency:
486
+ p0 = (A, tau)
487
+ else:
488
+ p0 = (A, Hz, tau)
489
+
490
+ # subtract offset from wave-shape
491
+ y_data -= offset
492
+ popt, pcov = curve_fit(func, x_data, y_data, p0)
493
+ # retrieve tau and A i.e x and y value of peak
494
+ x = popt[-1]
495
+ y = popt[0]
496
+
497
+ # create a high resolution data set for the fitted waveform
498
+ x2 = np.linspace(x_data[0], x_data[-1], points * 10)
499
+ y2 = func(x2, *popt)
500
+
501
+ # add the offset to the results
502
+ y += offset
503
+ y2 += offset
504
+ y_data += offset
505
+
506
+ peak_data.append([x, y, [x2, y2]])
507
+
508
+ fitted_peaks.append(peak_data)
509
+
510
+ # structure date for output
511
+ max_peaks = map(lambda x: [x[0], x[1]], fitted_peaks[0])
512
+ max_fitted = map(lambda x: x[-1], fitted_peaks[0])
513
+ min_peaks = map(lambda x: [x[0], x[1]], fitted_peaks[1])
514
+ min_fitted = map(lambda x: x[-1], fitted_peaks[1])
515
+
516
+ return [max_peaks, min_peaks]
517
+
518
+
519
+ def peakdetect_sine_locked(y_axis, x_axis, points=31):
520
+ """
521
+ Convenience function for calling the 'peakdetect_sine' function with
522
+ the lock_frequency argument as True.
523
+
524
+ keyword arguments:
525
+ y_axis -- A list containing the signal over which to find peaks
526
+ x_axis -- A x-axis whose values correspond to the y_axis list and is used
527
+ in the return to specify the position of the peaks.
528
+ points -- How many points around the peak should be used during curve
529
+ fitting (default: 31)
530
+
531
+ return: see the function 'peakdetect_sine'
532
+ """
533
+ return peakdetect_sine(y_axis, x_axis, points, True)
534
+
535
+
536
+ def peakdetect_spline(y_axis, x_axis, pad_len=20):
537
+ """
538
+ Performs a b-spline interpolation on the data to increase resolution and
539
+ send the data to the 'peakdetect_zero_crossing' function for peak
540
+ detection.
541
+
542
+ Omitting the x_axis is forbidden as it would make the resulting x_axis
543
+ value silly if it was returned as the index 50.234 or similar.
544
+
545
+ will find the same amount of peaks as the 'peakdetect_zero_crossing'
546
+ function, but might result in a more precise value of the peak.
547
+
548
+ keyword arguments:
549
+ y_axis -- A list containing the signal over which to find peaks
550
+
551
+ x_axis -- A x-axis whose values correspond to the y_axis list and is used
552
+ in the return to specify the position of the peaks.
553
+ x-axis must be equally spaced.
554
+
555
+ pad_len -- By how many times the time resolution should be increased by,
556
+ e.g. 1 doubles the resolution.
557
+ (default: 20)
558
+
559
+
560
+ return: two lists [max_peaks, min_peaks] containing the positive and
561
+ negative peaks respectively. Each cell of the lists contains a tuple
562
+ of: (position, peak_value)
563
+ to get the average peak value do: np.mean(max_peaks, 0)[1] on the
564
+ results to unpack one of the lists into x, y coordinates do:
565
+ x, y = zip(*max_peaks)
566
+ """
567
+ # check input data
568
+ x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
569
+ # could perform a check if x_axis is equally spaced
570
+ # if np.std(np.diff(x_axis)) > 1e-15: raise ValueError
571
+ # perform spline interpolations
572
+ dx = x_axis[1] - x_axis[0]
573
+ x_interpolated = np.linspace(
574
+ x_axis.min(), x_axis.max(), len(x_axis) * (pad_len + 1)
575
+ )
576
+ cj = cspline1d(y_axis)
577
+ y_interpolated = cspline1d_eval(cj, x_interpolated, dx=dx, x0=x_axis[0])
578
+ # get peaks
579
+ max_peaks, min_peaks = peakdetect_zero_crossing(y_interpolated, x_interpolated)
580
+
581
+ return [max_peaks, min_peaks]
582
+
583
+
584
+ def peakdetect_zero_crossing(y_axis, x_axis=None, window=11):
585
+ """
586
+ Function for detecting local maxima and minima in a signal.
587
+ Discovers peaks by dividing the signal into bins and retrieving the
588
+ maximum and minimum value of each the even and odd bins respectively.
589
+ Division into bins is performed by smoothing the curve and finding the
590
+ zero crossings.
591
+
592
+ Suitable for repeatable signals, where some noise is tolerated. Executes
593
+ faster than 'peakdetect', although this function will break if the offset
594
+ of the signal is too large. It should also be noted that the first and
595
+ last peak will probably not be found, as this function only can find peaks
596
+ between the first and last zero crossing.
597
+
598
+ keyword arguments:
599
+ y_axis -- A list containing the signal over which to find peaks
600
+
601
+ x_axis -- A x-axis whose values correspond to the y_axis list
602
+ and is used in the return to specify the position of the peaks. If
603
+ omitted an index of the y_axis is used.
604
+ (default: None)
605
+
606
+ window -- the dimension of the smoothing window; should be an odd integer
607
+ (default: 11)
608
+
609
+
610
+ return: two lists [max_peaks, min_peaks] containing the positive and
611
+ negative peaks respectively. Each cell of the lists contains a tuple
612
+ of: (position, peak_value)
613
+ to get the average peak value do: np.mean(max_peaks, 0)[1] on the
614
+ results to unpack one of the lists into x, y coordinates do:
615
+ x, y = zip(*max_peaks)
616
+ """
617
+ # check input data
618
+ x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
619
+
620
+ zero_indices = zero_crossings(y_axis, window_len=window)
621
+ period_lengths = np.diff(zero_indices)
622
+
623
+ bins_y = [
624
+ y_axis[index : index + diff]
625
+ for index, diff in zip(zero_indices, period_lengths)
626
+ ]
627
+ bins_x = [
628
+ x_axis[index : index + diff]
629
+ for index, diff in zip(zero_indices, period_lengths)
630
+ ]
631
+
632
+ even_bins_y = bins_y[::2]
633
+ odd_bins_y = bins_y[1::2]
634
+ even_bins_x = bins_x[::2]
635
+ odd_bins_x = bins_x[1::2]
636
+ hi_peaks_x = []
637
+ lo_peaks_x = []
638
+
639
+ # check if even bin contains maxima
640
+ if abs(even_bins_y[0].max()) > abs(even_bins_y[0].min()):
641
+ hi_peaks = [bin.max() for bin in even_bins_y]
642
+ lo_peaks = [bin.min() for bin in odd_bins_y]
643
+ # get x values for peak
644
+ for bin_x, bin_y, peak in zip(even_bins_x, even_bins_y, hi_peaks):
645
+ hi_peaks_x.append(bin_x[np.where(bin_y == peak)[0][0]])
646
+ for bin_x, bin_y, peak in zip(odd_bins_x, odd_bins_y, lo_peaks):
647
+ lo_peaks_x.append(bin_x[np.where(bin_y == peak)[0][0]])
648
+ else:
649
+ hi_peaks = [bin.max() for bin in odd_bins_y]
650
+ lo_peaks = [bin.min() for bin in even_bins_y]
651
+ # get x values for peak
652
+ for bin_x, bin_y, peak in zip(odd_bins_x, odd_bins_y, hi_peaks):
653
+ hi_peaks_x.append(bin_x[np.where(bin_y == peak)[0][0]])
654
+ for bin_x, bin_y, peak in zip(even_bins_x, even_bins_y, lo_peaks):
655
+ lo_peaks_x.append(bin_x[np.where(bin_y == peak)[0][0]])
656
+
657
+ max_peaks = [[x, y] for x, y in zip(hi_peaks_x, hi_peaks)]
658
+ min_peaks = [[x, y] for x, y in zip(lo_peaks_x, lo_peaks)]
659
+
660
+ return [max_peaks, min_peaks]
661
+
662
+
663
+ def _smooth(x, window_len=11, window="hanning"):
664
+ """
665
+ smooth the data using a window of the requested size.
666
+
667
+ This method is based on the convolution of a scaled window on the signal.
668
+ The signal is prepared by introducing reflected copies of the signal
669
+ (with the window size) in both ends so that transient parts are minimized
670
+ in the beginning and end part of the output signal.
671
+
672
+ keyword arguments:
673
+ x -- the input signal
674
+
675
+ window_len -- the dimension of the smoothing window; should be an odd
676
+ integer (default: 11)
677
+
678
+ window -- the type of window from 'flat', 'hanning', 'hamming',
679
+ 'bartlett', 'blackman', where flat is a moving average
680
+ (default: 'hanning')
681
+
682
+
683
+ return: the smoothed signal
684
+
685
+ example:
686
+
687
+ t = linspace(-2,2,0.1)
688
+ x = sin(t)+randn(len(t))*0.1
689
+ y = _smooth(x)
690
+
691
+ see also:
692
+
693
+ numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman,
694
+ numpy.convolve, scipy.signal.lfilter
695
+ """
696
+ if x.ndim != 1:
697
+ raise ValueError("smooth only accepts 1 dimension arrays.")
698
+
699
+ if x.size < window_len:
700
+ raise ValueError("Input vector needs to be bigger than window size.")
701
+
702
+ if window_len < 3:
703
+ return x
704
+ # declare valid windows in a dictionary
705
+ window_funcs = {
706
+ "flat": lambda _len: np.ones(_len, "d"),
707
+ "hanning": np.hanning,
708
+ "hamming": np.hamming,
709
+ "bartlett": np.bartlett,
710
+ "blackman": np.blackman,
711
+ }
712
+
713
+ s = np.r_[x[window_len - 1 : 0 : -1], x, x[-1:-window_len:-1]]
714
+ try:
715
+ w = window_funcs[window](window_len)
716
+ except KeyError:
717
+ raise ValueError(
718
+ "Window is not one of '{0}', '{1}', '{2}', '{3}', '{4}'".format(
719
+ *window_funcs.keys()
720
+ )
721
+ )
722
+
723
+ y = np.convolve(w / w.sum(), s, mode="valid")
724
+
725
+ return y
726
+
727
+
728
+ def zero_crossings(y_axis, window_len=11, window_f="hanning", offset_corrected=False):
729
+ """
730
+ Algorithm to find zero crossings. Smooths the curve and finds the
731
+ zero-crossings by looking for a sign change.
732
+
733
+
734
+ keyword arguments:
735
+ y_axis -- A list containing the signal over which to find zero-crossings
736
+
737
+ window_len -- the dimension of the smoothing window; should be an odd
738
+ integer (default: 11)
739
+
740
+ window_f -- the type of window from 'flat', 'hanning', 'hamming',
741
+ 'bartlett', 'blackman' (default: 'hanning')
742
+
743
+ offset_corrected -- Used for recursive calling to remove offset when needed
744
+
745
+
746
+ return: the index for each zero-crossing
747
+ """
748
+ # smooth the curve
749
+ length = len(y_axis)
750
+
751
+ # discard tail of smoothed signal
752
+ y_axis = _smooth(y_axis, window_len, window_f)[:length]
753
+ indices = np.where(np.diff(np.sign(y_axis)))[0]
754
+
755
+ # check if zero-crossings are valid
756
+ diff = np.diff(indices)
757
+ if diff.std() / diff.mean() > 0.1:
758
+ # Possibly bad zero crossing, see if it's offsets
759
+ if (
760
+ (diff[::2].std() / diff[::2].mean()) < 0.1
761
+ and (diff[1::2].std() / diff[1::2].mean()) < 0.1
762
+ and not offset_corrected
763
+ ):
764
+ # offset present attempt to correct by subtracting the average
765
+ offset = np.mean([y_axis.max(), y_axis.min()])
766
+ return zero_crossings(y_axis - offset, window_len, window_f, True)
767
+ # Invalid zero crossings and the offset has been removed
768
+ print(diff.std() / diff.mean())
769
+ print(np.diff(indices))
770
+ raise ValueError(
771
+ "False zero-crossings found, indicates problem {0!s} or {1!s}".format(
772
+ "with smoothing window", "unhandled problem with offset"
773
+ )
774
+ )
775
+ # check if any zero crossings were found
776
+ if len(indices) < 1:
777
+ raise ValueError("No zero crossings found")
778
+ # remove offset from indices due to filter function when returning
779
+ return indices - (window_len // 2 - 1)
780
+ # used this to test the fft function's sensitivity to spectral leakage
781
+ # return indices + np.asarray(30 * np.random.randn(len(indices)), int)
782
+
783
+
784
+ ############################Frequency calculation#############################
785
+ # diff = np.diff(indices)
786
+ # time_p_period = diff.mean()
787
+ #
788
+ # if diff.std() / time_p_period > 0.1:
789
+ # raise ValueError(
790
+ # "smoothing window too small, false zero-crossing found")
791
+ #
792
+ # #return frequency
793
+ # return 1.0 / time_p_period
794
+ ##############################################################################
795
+
796
+
797
+ def zero_crossings_sine_fit(y_axis, x_axis, fit_window=None, smooth_window=11):
798
+ """
799
+ Detects the zero crossings of a signal by fitting a sine model function
800
+ around the zero crossings:
801
+ y = A * sin(2 * pi * Hz * (x - tau)) + k * x + m
802
+ Only tau (the zero crossing) is varied during fitting.
803
+
804
+ Offset and a linear drift of offset is accounted for by fitting a linear
805
+ function the negative respective positive raw peaks of the wave-shape and
806
+ the amplitude is calculated using data from the offset calculation i.e.
807
+ the 'm' constant from the negative peaks is subtracted from the positive
808
+ one to obtain amplitude.
809
+
810
+ Frequency is calculated using the mean time between raw peaks.
811
+
812
+ Algorithm seems to be sensitive to first guess e.g. a large smooth_window
813
+ will give an error in the results.
814
+
815
+
816
+ keyword arguments:
817
+ y_axis -- A list containing the signal over which to find peaks
818
+
819
+ x_axis -- A x-axis whose values correspond to the y_axis list
820
+ and is used in the return to specify the position of the peaks. If
821
+ omitted an index of the y_axis is used. (default: None)
822
+
823
+ fit_window -- Number of points around the approximate zero crossing that
824
+ should be used when fitting the sine wave. Must be small enough that
825
+ no other zero crossing will be seen. If set to none then the mean
826
+ distance between zero crossings will be used (default: None)
827
+
828
+ smooth_window -- the dimension of the smoothing window; should be an odd
829
+ integer (default: 11)
830
+
831
+
832
+ return: A list containing the positions of all the zero crossings.
833
+ """
834
+ # check input data
835
+ x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
836
+ # get first guess
837
+ zero_indices = zero_crossings(y_axis, window_len=smooth_window)
838
+ # modify fit_window to show distance per direction
839
+ if fit_window == None:
840
+ fit_window = np.diff(zero_indices).mean() // 3
841
+ else:
842
+ fit_window = fit_window // 2
843
+
844
+ # x_axis is a np array, use the indices to get a subset with zero crossings
845
+ approx_crossings = x_axis[zero_indices]
846
+
847
+ # get raw peaks for calculation of offsets and frequency
848
+ raw_peaks = peakdetect_zero_crossing(y_axis, x_axis)
849
+ # Use mean time between peaks for frequency
850
+ ext = lambda x: list(zip(*x)[0])
851
+ _diff = map(np.diff, map(ext, raw_peaks))
852
+
853
+ Hz = 1 / np.mean(map(np.mean, _diff))
854
+ # Hz = 1 / np.diff(approx_crossings).mean() #probably bad precision
855
+
856
+ # offset model function
857
+ offset_func = lambda x, k, m: k * x + m
858
+ k = []
859
+ m = []
860
+ amplitude = []
861
+
862
+ for peaks in raw_peaks:
863
+ # get peak data as nparray
864
+ x_data, y_data = map(np.asarray, zip(*peaks))
865
+ # x_data = np.asarray(x_data)
866
+ # y_data = np.asarray(y_data)
867
+ # calc first guess
868
+ A = np.mean(y_data)
869
+ p0 = (0, A)
870
+ popt, pcov = curve_fit(offset_func, x_data, y_data, p0)
871
+ # append results
872
+ k.append(popt[0])
873
+ m.append(popt[1])
874
+ amplitude.append(abs(A))
875
+
876
+ # store offset constants
877
+ p_offset = (np.mean(k), np.mean(m))
878
+ A = m[0] - m[1]
879
+ # define model function to fit to zero crossing
880
+ # y = A * sin(2*pi * Hz * (x - tau)) + k * x + m
881
+ func = lambda x, tau: A * np.sin(2 * pi * Hz * (x - tau)) + offset_func(
882
+ x, *p_offset
883
+ )
884
+
885
+ # get true crossings
886
+ true_crossings = []
887
+ for indice, crossing in zip(zero_indices, approx_crossings):
888
+ p0 = (crossing,)
889
+ subset_start = max(indice - fit_window, 0.0)
890
+ subset_end = min(indice + fit_window + 1, len(x_axis) - 1.0)
891
+ x_subset = np.asarray(x_axis[subset_start:subset_end])
892
+ y_subset = np.asarray(y_axis[subset_start:subset_end])
893
+ # fit
894
+ popt, pcov = curve_fit(func, x_subset, y_subset, p0)
895
+
896
+ true_crossings.append(popt[0])
897
+
898
+ return true_crossings
899
+
900
+
901
+ def _test_zero():
902
+ _max, _min = peakdetect_zero_crossing(y, x)
903
+
904
+
905
+ def _test():
906
+ _max, _min = peakdetect(y, x, delta=0.30)
907
+
908
+
909
+ def _test_graph_cross(window=11):
910
+ i = 10000
911
+ x = np.linspace(0, 8.7 * pi, i)
912
+ y = 2 * np.sin(x) + 0.006 * np.random.randn(i)
913
+ y *= -1
914
+ pylab.plot(x, y)
915
+ # pylab.show()
916
+
917
+ crossings = zero_crossings_sine_fit(y, x, smooth_window=window)
918
+ y_cross = [0] * len(crossings)
919
+
920
+ plot = pylab.plot(x, y)
921
+ pylab.hold(True)
922
+ pylab.plot(crossings, y_cross, "b+")
923
+ pylab.show()
924
+
925
+
926
+ if __name__ == "__main__":
927
+ i = 10000
928
+ x = np.linspace(0, 3.7 * pi, i)
929
+ y = (
930
+ 0.3 * np.sin(x)
931
+ + np.sin(1.3 * x)
932
+ + 0.9 * np.sin(4.2 * x)
933
+ + 0.06 * np.random.randn(i)
934
+ )
935
+ y *= -1
936
+
937
+ _max, _min = peakdetect(y, x, 750, 0.30)
938
+ xm = [p[0] for p in _max]
939
+ ym = [p[1] for p in _max]
940
+ xn = [p[0] for p in _min]
941
+ yn = [p[1] for p in _min]
942
+
943
+ plot = pylab.plot(x, y)
944
+ pylab.hold(True)
945
+ pylab.plot(xm, ym, "r+")
946
+ pylab.plot(xn, yn, "g+")
947
+
948
+ pylab.show()