├── setup.cfg ├── docs ├── mdfreader.pdf ├── mdf │ └── index.rst ├── mdfinfo3 │ └── index.rst ├── mdfinfo4 │ └── index.rst ├── channel │ └── index.rst ├── mdf3reader │ └── index.rst ├── mdf4reader │ └── index.rst ├── mdfreader │ └── index.rst ├── index.rst ├── Makefile └── conf.py ├── mdfreader ├── __main__.py ├── __init__.py ├── mdf.py └── mdfinfo3.py ├── .issues └── .properties ├── MANIFEST.in ├── .gitignore ├── mdfconverter ├── mdfconverter.py ├── __init__.py ├── Ui_mdfreaderui5.py ├── mdfreaderui.ui ├── Ui_mdfreaderui4.py ├── mdfreaderui5.py └── mdfreaderui4.py ├── ISSUE_TEMPLATE.md ├── LICENSE ├── mdfForVeuszPlugin.py ├── setup.py ├── README.md ├── mdfreader.e4p └── COPYING /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | [build_ext] 4 | inplace=1 -------------------------------------------------------------------------------- /docs/mdfreader.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratal/mdfreader/HEAD/docs/mdfreader.pdf -------------------------------------------------------------------------------- /mdfreader/__main__.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from warnings import warn 3 | import sys 4 | import mdfreader 5 | warn(sys.argv[1:][0]) 6 | mdfreader.Mdf(sys.argv[1:][0]) 7 | -------------------------------------------------------------------------------- /docs/mdf/index.rst: -------------------------------------------------------------------------------- 1 | mdf module documentation 2 | ===================================== 3 | 4 | .. automodule:: mdfreader.mdf 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/mdfinfo3/index.rst: -------------------------------------------------------------------------------- 1 | mdfinfo3 module documentation 2 | ===================================== 3 | 4 | .. automodule:: mdfreader.mdfinfo3 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/mdfinfo4/index.rst: -------------------------------------------------------------------------------- 1 | mdfinfo4 module documentation 2 | ===================================== 3 | 4 | .. automodule:: mdfreader.mdfinfo4 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/channel/index.rst: -------------------------------------------------------------------------------- 1 | channel module documentation 2 | ===================================== 3 | 4 | .. automodule:: mdfreader.channel 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | -------------------------------------------------------------------------------- /docs/mdf3reader/index.rst: -------------------------------------------------------------------------------- 1 | mdf3reader module documentation 2 | ===================================== 3 | 4 | .. automodule:: mdfreader.mdf3reader 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/mdf4reader/index.rst: -------------------------------------------------------------------------------- 1 | mdf4reader module documentation 2 | ===================================== 3 | 4 | .. automodule:: mdfreader.mdf4reader 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/mdfreader/index.rst: -------------------------------------------------------------------------------- 1 | mdfreader module documentation 2 | ===================================== 3 | 4 | .. automodule:: mdfreader.mdfreader 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /.issues/.properties: -------------------------------------------------------------------------------- 1 | [Category] 2 | 3 | [State] 4 | new = 5 | assigned = 6 | investigating = 7 | scheduled = 8 | testing = 9 | closed = 10 | 11 | [Resolution] 12 | fixed = 13 | rejected = 14 | duplicate = 15 | cannot reproduce = 16 | 17 | [Assigned-To] 18 | 19 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | #documentation 2 | recursive-include docs/build/html * 3 | recursive-include docs/build/latex mdfreader.pdf 4 | 5 | #example files 6 | #include test/mdf3/* 7 | #include test/MDF4/* 8 | 9 | #Misc 10 | #include CHANGES 11 | include LICENSE 12 | include README 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .eric6project/ 2 | _eric6project/ 3 | .eric5project/ 4 | _eric5project/ 5 | .eric4project/ 6 | _eric4project/ 7 | .ropeproject/ 8 | _ropeproject/ 9 | .directory/ 10 | *.pyc 11 | *.pyo 12 | *.orig 13 | *.bak 14 | *.rej 15 | *~ 16 | cur/ 17 | tmp/ 18 | __pycache__/ 19 | *.DS_Store 20 | /dist/ 21 | /*.egg-info 22 | -------------------------------------------------------------------------------- /mdfconverter/mdfconverter.py: -------------------------------------------------------------------------------- 1 | from sys import argv, exit, path 2 | from os.path import dirname, abspath 3 | root = dirname(abspath(__file__)) 4 | path.append(root) 5 | 6 | from multiprocessing import freeze_support 7 | 8 | try: # first try pyQt4 9 | from PyQt4.QtGui import QApplication 10 | from mdfreaderui4 import MainWindow 11 | except ImportError: # if Qt4 not existing, looking for Qt5 12 | from PyQt5.QtWidgets import QApplication 13 | from mdfreaderui5 import MainWindow 14 | 15 | def main(): 16 | freeze_support() 17 | app = QApplication(argv) 18 | myapp = MainWindow() 19 | myapp.show() 20 | exit(app.exec_()) 21 | 22 | if __name__ == "__main__": 23 | main() 24 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. mdfreader documentation master file, created by 2 | sphinx-quickstart on Wed Dec 10 23:56:46 2014. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to mdfreader's documentation! 7 | ===================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 3 13 | 14 | mdfreader/index 15 | 16 | mdf/index 17 | 18 | mdf3reader/index 19 | 20 | mdfinfo3/index 21 | 22 | mdf4reader/index 23 | 24 | mdfinfo4/index 25 | 26 | channel/index 27 | 28 | Indices and tables 29 | ================== 30 | 31 | * :ref:`genindex` 32 | * :ref:`modindex` 33 | * :ref:`search` 34 | 35 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # Python version 2 | Please write here the output of printing ``sys.version`` 3 | 4 | # Platform information 5 | Please write here the output of printing ``platform.platform()`` 6 | 7 | # Numpy version 8 | Please write here the output of printing ``numpy.__version__`` 9 | 10 | # mdfreader version 11 | Please write here the output of printing ``mdfreader.__version__`` 12 | 13 | # Description 14 | Please describe the issue pr error stack here and eventually script used to use mdfreader 15 | 16 | Also mentioning version of mdf file will be helpful (using mdfvalidator or mdfreader if functional for reading) 17 | 18 | print of issue related variables at the errors location and eventually mdfvalidator screenshots can help troubleshooting complicated issues 19 | -------------------------------------------------------------------------------- /mdfconverter/__init__.py: -------------------------------------------------------------------------------- 1 | # ---------------------------------------------------------------------- 2 | # This program is free software: you can redistribute it and/or modify 3 | # it under the terms of the GNU General Public License version 3 as 4 | # published by the Free Software Foundation. 5 | # 6 | # This program is distributed in the hope that it will be useful, 7 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 8 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 9 | # See the GNU General Public License for more details. 10 | # 11 | # You should have received a copy of the GNU General Public License 12 | # along with this program. If not, see http://www.gnu.org/licenses. 13 | # 14 | # ---------------------------------------------------------------------- 15 | __version__ = "4.2" 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | mdfreader is a tool written in pyhon to read mdf (Measured Data Format) files version 3.x and 4.x 2 | 3 | Copyright (C) 2015 Aymeric Rateau 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | -------------------------------------------------------------------------------- /mdfreader/__init__.py: -------------------------------------------------------------------------------- 1 | # ---------------------------------------------------------------------- 2 | # This program is free software: you can redistribute it and/or modify 3 | # it under the terms of the GNU General Public License version 3 as 4 | # published by the Free Software Foundation. 5 | # 6 | # This program is distributed in the hope that it will be useful, 7 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 8 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 9 | # See the GNU General Public License for more details. 10 | # 11 | # You should have received a copy of the GNU General Public License 12 | # along with this program. If not, see http://www.gnu.org/licenses. 13 | # 14 | # ---------------------------------------------------------------------- 15 | 16 | __author__ = 'Aymeric Rateau (aymeric.rateau@gmail.com)' 17 | __copyright__ = 'Copyright (c) 2017 Aymeric Rateau' 18 | __license__ = 'GPLV3' 19 | __version__ = "4.2" 20 | 21 | from .mdfreader import Mdf, MdfInfo 22 | 23 | __all__ = [ 24 | 'Mdf', 25 | 'MdfInfo' 26 | ] 27 | -------------------------------------------------------------------------------- /mdfForVeuszPlugin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' Veusz data plugin for mdf format 3 | 4 | Created on 18 nov. 2010 5 | 6 | @author: Aymeric Rateau ; aymeric.rateau@gmail.com 7 | 8 | Veusz version confirmed : from 1.16 9 | 10 | Installation instructions : 11 | ---------------------------------- 12 | 1. copy or link mdfForVeuszPlugin.py into the plugins directory of Veusz 13 | 2. link mdfreader.py in root or plugin directory of Veusz 14 | 3. Go in Veusz ; Edit / Preferences / Plugins tab and add mdfForVeuszPlugins.py 15 | ''' 16 | from veusz.plugins import * 17 | from veusz.plugins.datasetplugin import Dataset1D as ImportDataset1D 18 | from veusz.plugins.field import FieldFloat as ImportFieldFloat 19 | try: 20 | from mdfreader import Mdf 21 | from mdfreader import MdfInfo 22 | except ImportError: 23 | try: 24 | from veusz.plugins.mdfreader import mdf 25 | from veusz.plugins.mdfreader import mdfinfo 26 | except ImportError: 27 | import sys 28 | import os 29 | import os.path 30 | sys.path.append(os.getcwdu()) 31 | print(os.path.join(os.getcwdu(), 'plugins')) 32 | from mdfreader import Mdf 33 | from mdfreader import MdfInfo 34 | 35 | 36 | class ImportPlugin(MdfInfo): 37 | 38 | """Define a plugin to read data in a particular format. 39 | 40 | override doImport and optionally getPreview to define a new plugin 41 | register the class by adding to the importpluginregistry list 42 | """ 43 | 44 | name = 'Import plugin' 45 | author = 'Aymeric Rateau' 46 | description = 'Import MDF files' 47 | promote_tab = 'MDF' 48 | file_extensions = set(['.dat', '.mf4', '.mdf']) 49 | 50 | def __init__(self): 51 | """Override this to declare a list of input fields if required.""" 52 | # a list of ImportField objects to display 53 | self.fields = [] 54 | 55 | def getPreview(self, params): 56 | """Get data to show in a text box to show a preview. 57 | params is a ImportPluginParams object. 58 | Returns (text, okaytoimport) 59 | """ 60 | 61 | info = MdfInfo() 62 | 63 | if info.mdfversion < 400: 64 | f = '' 65 | f += 'Time: ' + info['HDBlock']['Date'] + ' ' 66 | f += info['HDBlock']['Time'] + '\n' 67 | f += 'Author: ' + info['HDBlock']['Author'] + '\n' 68 | f += 'Organisation: ' + info['HDBlock']['Organization'] + '\n' 69 | f += 'Project Name: ' + info['HDBlock']['ProjectName'] + '\n' 70 | f += 'Subject: ' + info['HDBlock']['Subject'] + '\n' + 'Channel List:\n' 71 | else: 72 | from time import gmtime, strftime 73 | fileDateTime = gmtime(info['HDBlock']['hd_start_time_ns'] / 1000000000) 74 | date = strftime('%Y-%m-%d', fileDateTime) 75 | time = strftime('%H:%M:%S', fileDateTime) 76 | f = '' 77 | f += 'Date Time: ' + date + ' ' + time + '\n' 78 | if 'Comment' in info['HDBlock']: 79 | Comment = info['HDBlock']['Comment'] 80 | if 'author' in Comment: 81 | f += 'Author: ' + Comment['author'] + '\n' 82 | if 'department' in Comment: 83 | f += 'Organisation: ' + Comment['department'] + '\n' 84 | if 'project' in Comment: 85 | f += 'Project Name: ' + Comment['project'] + '\n' 86 | if 'subject' in Comment: 87 | f += 'Subject: ' + Comment['subject'] + '\n' + 'Channel List:\n' 88 | for channelName in info.list_channels(): 89 | f += ' ' + channelName + '\n' 90 | return f, True 91 | 92 | def doImport(self, params): 93 | """Actually import data 94 | params is a ImportPluginParams object. 95 | Return a list of ImportDataset1D, ImportDataset2D objects 96 | """ 97 | return [] 98 | 99 | 100 | class MdfImportPlugin(ImportPlugin, Mdf): 101 | 102 | """Plugin to import mdf (Mostly ETAS INCA or CANape files)""" 103 | 104 | name = "MDFImport plugin" 105 | author = "Aymeric Rateau" 106 | description = "Reads MDF files from INCA or CANAPE" 107 | 108 | def __init__(self): 109 | ImportPlugin.__init__(self) 110 | self.fields = [ImportFieldFloat("mult", descr="Sampling", default=0.1)] 111 | 112 | def doImport(self, params): 113 | """Actually import data 114 | params is a ImportPluginParams object. 115 | Return a list of ImportDataset1D, ImportDataset2D objects 116 | """ 117 | 118 | data = Mdf(params.filename) 119 | data.resample(sampling_time=params.field_results['mult']) 120 | List = [] 121 | for channelName in list(data.keys()): 122 | if len(data[channelName]['data']) > 0 and not data[channelName]['data'].dtype.kind in ['S', 'U']: 123 | # print( data[channelName]['data'].dtype ) 124 | List.append(ImportDataset1D(channelName, data[channelName]['data'])) 125 | return List 126 | 127 | importpluginregistry.append(MdfImportPlugin()) 128 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # distutils: language=c++ 2 | from setuptools import setup, find_packages 3 | from codecs import open # To use a consistent encoding 4 | from os import path 5 | from distutils.extension import Extension 6 | from warnings import warn 7 | # cython: language_level=3, boundscheck=False 8 | 9 | try: # numpy and cython installed 10 | from Cython.Build import cythonize 11 | # If we successfully imported Cython, look for a .pyx file 12 | import numpy 13 | ext_modules = cythonize('dataRead.pyx', include_path=[numpy.get_include()], gdb_debug=True) 14 | except ImportError: 15 | # If we couldn't import Cython, use the normal setuptools 16 | # and look for a pre-compiled .c file instead of a .pyx file 17 | from setuptools.command.build_ext import build_ext 18 | ext_modules = [Extension("dataRead", ["dataRead.c"])] 19 | 20 | 21 | name = 'mdfreader' 22 | version = '4.2' 23 | 24 | description = 'A Measured Data Format file parser' 25 | 26 | here = path.abspath(path.dirname(__file__)) 27 | # Get the long description from the relevant file 28 | with open(path.join(here, 'README.md'), encoding='utf-8') as f: 29 | long_description = f.read() 30 | long_description = long_description 31 | 32 | # The project's main homepage. 33 | url = 'https://github.com/ratal/mdfreader' 34 | 35 | # Author details 36 | author = 'Aymeric Rateau' 37 | author_email = 'aymeric.rateau@gmail.com' 38 | 39 | # Choose your license 40 | license = 'GPL3' 41 | 42 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers 43 | classifiers = [ 44 | # How mature is this project? Common values are 45 | # 3 - Alpha 46 | # 4 - Beta 47 | # 5 - Production/Stable 48 | 'Development Status :: 4 - Beta', 49 | 50 | # Indicate who your project is intended for 51 | 'Intended Audience :: Science/Research', 52 | 'Topic :: Scientific/Engineering', 53 | 54 | # Pick your license as you wish (should match "license" above) 55 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 56 | 57 | # Specify the Python versions you support here. 58 | 'Programming Language :: Python :: 3.5', 59 | 'Programming Language :: Python :: 3.6', 60 | 'Programming Language :: Python :: 3.7', 61 | 'Programming Language :: Python :: 3.8' 62 | ] 63 | 64 | # What does your project relate to? 65 | keywords = 'Parser MDF file' 66 | 67 | # You can just specify the packages manually here if your project is 68 | # simple. Or you can use find_packages(). 69 | packages = find_packages(exclude=['contrib', 'docs', 'tests*']) 70 | 71 | # List run-time dependencies here. These will be installed by pip when your 72 | # project is installed. For an analysis of "install_requires" vs pip's 73 | # requirements files see: 74 | # https://packaging.python.org/en/latest/technical.html#install-requires-vs-requirements-files 75 | install_requires = ['numpy>=1.14', 'sympy', 'lxml'] 76 | 77 | # List additional groups of dependencies here (e.g. development dependencies). 78 | # You can install these using the following syntax, for example: 79 | # $ pip install -e .[dev,test] 80 | extras_require = { 81 | 'export': ['hdf5storage', 'h5py', 'scipy', 'xlwt', 'xlwt3', 'openpyxl>2.0', 'pandas', 'fastparquet'], 82 | 'plot': ['matplotlib', 'mpldatacursor'], 83 | 'converter': ['PyQt5'], 84 | 'experimental': ['bitarray'], 85 | 'compression': ['blosc'], 86 | } 87 | 88 | # If there are data files included in your packages that need to be 89 | # installed, specify them here. If using Python 2.6 or less, then these 90 | # have to be included in MANIFEST.in as well. 91 | # package_data={ 92 | # 'sample': ['package_data.dat'], 93 | # }, 94 | 95 | # Although 'package_data' is the preferred approach, in some case you may 96 | # need to place data files outside of your packages. 97 | # see http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files 98 | # In this case, 'data_file' will be installed into '/my_data' 99 | # data_files=[('my_data', ['data/data_file'])], 100 | 101 | # To provide executable scripts, use entry points in preference to the 102 | # "scripts" keyword. Entry points provide cross-platform support and allow 103 | # pip to create the appropriate form of executable for the target platform. 104 | entry_points = { 105 | 'console_scripts': ['mdfconverter=mdfconverter.mdfconverter:main', ], 106 | } 107 | 108 | try: # try compiling module with cython or c code with numpy and cython already installed 109 | setup(name=name, version=version, description=description, long_description=long_description, 110 | long_description_content_type='text/markdown', 111 | url=url, author=author, author_email=author_email, license=license, classifiers=classifiers, 112 | keywords=keywords, packages=packages, install_requires=install_requires, extras_require=extras_require, 113 | entry_points=entry_points, ext_modules=ext_modules, include_dirs=[numpy.get_include()]) 114 | except: # could not compile extension dataRead 115 | import sys 116 | print("Unexpected error:", sys.exc_info()) 117 | extras_require.pop('experimental') 118 | install_requires.append('bitarray') # replaces cython requirement by bitarray 119 | setup(name=name, version=version, description=description, long_description=long_description, 120 | long_description_content_type='text/markdown', 121 | url=url, author=author, author_email=author_email, license=license, classifiers=classifiers, 122 | keywords=keywords, packages=packages, install_requires=install_requires, extras_require=extras_require, 123 | entry_points=entry_points) 124 | warn('It is strongly advised to install Cython along with compilation environment ' 125 | 'for performance and robustness purpose') 126 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) ../docs 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) ../docs 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/mdfreader.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/mdfreader.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/mdfreader" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/mdfreader" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **MDFREADER** 2 | ************** 3 | 4 | Abstract: 5 | ========= 6 | This Module imports MDF files (Measured Data Format V3.x and V4.x), typically from INCA (ETAS), CANape or CANOe. It is widely used in automotive industry to record data from ECUs. The main module mdfreader.py inherits from 2 modules (One pair for each MDF version X) : The first one to read the file's blocks descriptions (mdfinfoX) and the second (mdfXreader) to read the raw data from the file. It can optionally run multithreaded. It was built in mind to process efficiently big amount of data in a batch, endurance evaluation files for data mining. 7 | 8 | The structure of the mdf object inheriting from python dict 9 | =========================================================== 10 | for each channel: mdf[channelName] below keys exist 11 | * data: numpy array 12 | * unit: unit name 13 | * master : master channel name of channelName 14 | * masterType : type of master channel (time, angle, distance, etc.) 15 | * description : description of channel 16 | * conversion: (exist when reading with convertAfterRead=False) dictionary describing how to convert raw data into meaningful/physical data 17 | 18 | mdf object main attribute: masterChannelList, a dict containing a list of channel names per datagroup 19 | 20 | 21 | Mdfreader module methods: 22 | ========================= 23 | * resample channels to one sampling frequency 24 | * merge files 25 | * plot one channel, several channels on one graph (list) or several channels on subplots (list of lists) 26 | 27 | It is also possible to export mdf data into: 28 | * CSV file (excel dialect by default) 29 | * NetCDF file for a compatibility with Uniplot for instance (needs netcdf4, Scientific.IO) 30 | * HDF5 (needs h5py) 31 | * Excel 95 to 2003 (needs xlwt, extremely slooow, be careful about data size) 32 | * Excel 2007/2010 (needs openpyxl, can be also slow with big files) 33 | * Matlab .mat (needs hdf5storage) 34 | * MDF file. It allows you to create, convert or modify data, units, description and save it again. 35 | * Pandas dataframe(s) (only in command line, not in mdfconverter). One dataframe per raster. 36 | 37 | Compatibility: 38 | ============== 39 | This code is compatible for python 3.4+ 40 | Evaluated for Windows and Linux platforms (x86 and AMD64) 41 | 42 | Requirements: 43 | ============= 44 | Mdfreader is mostly relying on numpy/scipy/matplotlib and lxml for parsing the metadata in mdf version 4.x files 45 | 46 | Reading channels defined by a formula will require sympy. 47 | 48 | Cython is strongly advised and allows to compile dataRead module for reading quickly exotic data (not byte aligned or containing hidden bytes) or only a list of channels. However, if cython compilation fails, bitarray becomes required (slower, pure python and maybe not so robust as not so much tested). 49 | 50 | Export requirements (optional): scipy, csv, h5py, hdf5storage, xlwt(3), openpyxl, pandas 51 | 52 | Blosc for data compression (optional) 53 | 54 | Mdfconverter graphical user interface requires PyQt (versions 4 or 5) 55 | 56 | Installation: 57 | ============= 58 | pip package existing: 59 | ```shell 60 | pip install mdfreader 61 | ``` 62 | or from source cloned from github from instance 63 | ```shell 64 | python setup.py develop 65 | ``` 66 | 67 | Graphical interface: mdfconverter (PyQt4 and PyQt5) 68 | ================================== 69 | User interface in PyQt4 or PyQt5 to convert batch of files is part of package. You can launch it with command 'mdfconverter' from shell. By right clicking a channel in the interface list, you can plot it. You can also drag-drop channels between columns to tune import list. Channel list from a .lab text file can be imported. You can optionally merge several files into one and even resample all of them. 70 | 71 | Others: 72 | ======= 73 | In the case of big files or lack of memory, you can optionally: 74 | * Read only a channel list (argument channel_list = ['channel', 'list'], you can get the file channel list without loading data with mdfinfo) 75 | * Keep raw data as stored in mdf without data type conversion (argument convert_after_read=False). Data will then be converted on the fly by the other functions (plot, export_to..., get_channel_data, etc.) but raw data type will remain as in mdf file along with conversion information. 76 | * Compress data in memory with blosc with argument compression. Default compression level is 9. 77 | * Create a mdf dict with its metadata but without data (argument no_data_loading=True). Data will be read from file on demand by mdfreader methods (in general by get_channel_data method) 78 | 79 | For great data visualization, dataPlugin for Veusz (from 1.16, http://home.gna.org/veusz/) is also existing ; please follow instructions from Veusz documentation and plugin file's header. 80 | 81 | Command example in ipython: 82 | =========================== 83 | ```python 84 | import mdfreader 85 | # loads whole mdf file content in yop mdf object. 86 | yop=mdfreader.Mdf('NameOfFile') 87 | # you can print file content in ipython with a simple: 88 | yop 89 | # alternatively, for max speed and smaller memory footprint, read only few channels 90 | yop=mdfreader.Mdf('NameOfFile', channel_list=['channel1', 'channel2'], convert_after_read=False) 91 | # also possible to keep data compressed for small memory footprint, using Blosc module 92 | yop=mdfreader.Mdf('NameOfFile', compression=True) 93 | # for interactive file exploration, possible to read the file but not its data to save memory 94 | yop=mdfreader.Mdf('NameOfFile', no_data_loading=True) # channel data will be loaded from file if needed 95 | # parsing xml metadata from mdf4.x for many channels can take more than just reading data. 96 | # You can reduce to minimum metadata reading with below argument (no source information, attachment, etc.) 97 | yop=mdfreader.Mdf('NameOfFile', metadata=0) # 0: full, 2: minimal 98 | # only for mdf4.x, you can search for the mdf key of a channel name that can have been recorded by different sources 99 | yop.get_channel_name4('channelName', 'source path or name') # returns list of mdf keys 100 | # to yield one channel and keep its content in mdf object 101 | yop.get_channel('channelName') 102 | # to yield one channel numpy array 103 | yop.get_channel_data('channelName') 104 | # to get file mdf version 105 | yop.MDFVersionNumber 106 | # to get file structure or attachments, you can create a mdfinfo instance 107 | info=mdfreader.MdfInfo() 108 | info.list_channels('NameOfFile') # returns only the list of channels 109 | info.read_info('NameOfFile') # complete file structure object 110 | yop.info # same class is stored in mdfreader class 111 | # to list channels names after reading 112 | yop.keys() 113 | # to list channels names grouped by raster, below dict mdf attribute contains 114 | # pairs (key=masterChannelName : value=listOfChannelNamesForThisMaster) 115 | yop.masterChannelList 116 | # quick plot or subplot (with lists) of channel(s) 117 | yop.plot(['channel1',['channel2','channel3']]) 118 | # file manipulations 119 | yop.resample(0.1) 120 | # or 121 | yop.resample(master_channel='master3') 122 | # keep only data between begin and end 123 | yop.cut(begin=10, end=15) 124 | # export to other file formats : 125 | yop.export_to_csv(sampling=0.01) 126 | yop.export_to_NetCDF() 127 | yop.export_to_hdf5() 128 | yop.export_to_matlab() 129 | yop.export_to_xlsx() 130 | yop.export_to_parquet() 131 | # return pandas dataframe from master channel name 132 | yop.return_pandas_dataframe('master_channel_name') 133 | # converts data groups into pandas dataframes and keeps it in mdf object 134 | yop.convert_to_pandas() 135 | # drops all the channels except the one in argument 136 | yop.keep_channels({'channel1','channel2','channel3'}) 137 | # merge 2 files 138 | yop2=mdfreader.Mdf('NameOfFile_2') 139 | yop.merge_mdf(yop2) 140 | # can write mdf file after modifications or creation from scratch 141 | # write4 and write3 also allow to convert file versions 142 | yop.write('NewNameOfFile') # write in same version as original file after modifications 143 | yop.write4('NameOfFile', compression=True) # write mdf version 4.1 file, data compressed 144 | yop.write3() # write mdf version 3 file 145 | yop.attachments # to get attachments, embedded or paths to files 146 | ``` 147 | 148 | Coverity Scan Build Status 150 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # mdfreader documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Dec 10 23:56:46 2014. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | sys.path.insert(0, os.path.abspath('..')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'numpydoc', 'sphinx.ext.intersphinx', 29 | 'sphinx.ext.coverage'] 30 | 31 | # Add any paths that contain templates here, relative to this directory. 32 | templates_path = ['_templates'] 33 | 34 | # The suffix of source filenames. 35 | source_suffix = '.rst' 36 | 37 | # The encoding of source files. 38 | #source_encoding = 'utf-8-sig' 39 | 40 | # The master toctree document. 41 | master_doc = 'index' 42 | 43 | # General information about the project. 44 | project = u'mdfreader' 45 | copyright = u'2018, Aymeric Rateau' 46 | 47 | # The version info for the project you're documenting, acts as replacement for 48 | # |version| and |release|, also used in various other places throughout the 49 | # built documents. 50 | # 51 | # The short X.Y version. 52 | version = '4.0' 53 | # The full version, including alpha/beta/rc tags. 54 | release = '4.0' 55 | 56 | # The language for content autogenerated by Sphinx. Refer to documentation 57 | # for a list of supported languages. 58 | #language = None 59 | 60 | # There are two options for replacing |today|: either, you set today to some 61 | # non-false value, then it is used: 62 | #today = '' 63 | # Else, today_fmt is used as the format for a strftime call. 64 | #today_fmt = '%B %d, %Y' 65 | 66 | # List of patterns, relative to source directory, that match files and 67 | # directories to ignore when looking for source files. 68 | exclude_patterns = [] 69 | 70 | # The reST default role (used for this markup: `text`) to use for all documents. 71 | #default_role = None 72 | 73 | # If true, '()' will be appended to :func: etc. cross-reference text. 74 | #add_function_parentheses = True 75 | 76 | # If true, the current module name will be prepended to all description 77 | # unit titles (such as .. function::). 78 | #add_module_names = True 79 | 80 | # If true, sectionauthor and moduleauthor directives will be shown in the 81 | # output. They are ignored by default. 82 | #show_authors = False 83 | 84 | # The name of the Pygments (syntax highlighting) style to use. 85 | pygments_style = 'sphinx' 86 | 87 | # A list of ignored prefixes for module index sorting. 88 | #modindex_common_prefix = [] 89 | 90 | 91 | # -- Options for HTML output --------------------------------------------------- 92 | 93 | # The theme to use for HTML and HTML Help pages. See the documentation for 94 | # a list of builtin themes. 95 | html_theme = 'default' 96 | 97 | # Theme options are theme-specific and customize the look and feel of a theme 98 | # further. For a list of options available for each theme, see the 99 | # documentation. 100 | #html_theme_options = {} 101 | 102 | # Add any paths that contain custom themes here, relative to this directory. 103 | #html_theme_path = [] 104 | 105 | # The name for this set of Sphinx documents. If None, it defaults to 106 | # " v documentation". 107 | #html_title = None 108 | 109 | # A shorter title for the navigation bar. Default is the same as html_title. 110 | #html_short_title = None 111 | 112 | # The name of an image file (relative to this directory) to place at the top 113 | # of the sidebar. 114 | #html_logo = None 115 | 116 | # The name of an image file (within the static path) to use as favicon of the 117 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 118 | # pixels large. 119 | #html_favicon = None 120 | 121 | # Add any paths that contain custom static files (such as style sheets) here, 122 | # relative to this directory. They are copied after the builtin static files, 123 | # so a file named "default.css" will overwrite the builtin "default.css". 124 | html_static_path = ['_static'] 125 | 126 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 127 | # using the given strftime format. 128 | #html_last_updated_fmt = '%b %d, %Y' 129 | 130 | # If true, SmartyPants will be used to convert quotes and dashes to 131 | # typographically correct entities. 132 | #html_use_smartypants = True 133 | 134 | # Custom sidebar templates, maps document names to template names. 135 | #html_sidebars = {} 136 | 137 | # Additional templates that should be rendered to pages, maps page names to 138 | # template names. 139 | #html_additional_pages = {} 140 | 141 | # If false, no module index is generated. 142 | #html_domain_indices = True 143 | 144 | # If false, no index is generated. 145 | #html_use_index = True 146 | 147 | # If true, the index is split into individual pages for each letter. 148 | #html_split_index = False 149 | 150 | # If true, links to the reST sources are added to the pages. 151 | #html_show_sourcelink = True 152 | 153 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 154 | #html_show_sphinx = True 155 | 156 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 157 | #html_show_copyright = True 158 | 159 | # If true, an OpenSearch description file will be output, and all pages will 160 | # contain a tag referring to it. The value of this option must be the 161 | # base URL from which the finished HTML is served. 162 | #html_use_opensearch = '' 163 | 164 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 165 | #html_file_suffix = None 166 | 167 | # Output file base name for HTML help builder. 168 | htmlhelp_basename = 'mdfreaderdoc' 169 | 170 | 171 | # -- Options for LaTeX output -------------------------------------------------- 172 | 173 | latex_elements = { 174 | # The paper size ('letterpaper' or 'a4paper'). 175 | #'papersize': 'letterpaper', 176 | 177 | # The font size ('10pt', '11pt' or '12pt'). 178 | #'pointsize': '10pt', 179 | 180 | # Additional stuff for the LaTeX preamble. 181 | #'preamble': '', 182 | } 183 | 184 | # Grouping the document tree into LaTeX files. List of tuples 185 | # (source start file, target name, title, author, documentclass [howto/manual]). 186 | latex_documents = [ 187 | ('index', 'mdfreader.tex', u'mdfreader Documentation', 188 | u'Aymeric Rateau', 'manual'), 189 | ] 190 | 191 | # The name of an image file (relative to this directory) to place at the top of 192 | # the title page. 193 | #latex_logo = None 194 | 195 | # For "manual" documents, if this is true, then toplevel headings are parts, 196 | # not chapters. 197 | #latex_use_parts = False 198 | 199 | # If true, show page references after internal links. 200 | #latex_show_pagerefs = False 201 | 202 | # If true, show URL addresses after external links. 203 | #latex_show_urls = False 204 | 205 | # Documents to append as an appendix to all manuals. 206 | #latex_appendices = [] 207 | 208 | # If false, no module index is generated. 209 | #latex_domain_indices = True 210 | 211 | 212 | # -- Options for manual page output -------------------------------------------- 213 | 214 | # One entry per manual page. List of tuples 215 | # (source start file, name, description, authors, manual section). 216 | man_pages = [ 217 | ('index', 'mdfreader', u'mdfreader Documentation', 218 | [u'Aymeric Rateau'], 1) 219 | ] 220 | 221 | # If true, show URL addresses after external links. 222 | #man_show_urls = False 223 | 224 | 225 | # -- Options for Texinfo output ------------------------------------------------ 226 | 227 | # Grouping the document tree into Texinfo files. List of tuples 228 | # (source start file, target name, title, author, 229 | # dir menu entry, description, category) 230 | texinfo_documents = [ 231 | ('index', 'mdfreader', u'mdfreader Documentation', 232 | u'Aymeric Rateau', 'mdfreader', 'One line description of project.', 233 | 'Miscellaneous'), 234 | ] 235 | 236 | # Documents to append as an appendix to all manuals. 237 | #texinfo_appendices = [] 238 | 239 | # If false, no module index is generated. 240 | #texinfo_domain_indices = True 241 | 242 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 243 | #texinfo_show_urls = 'footnote' 244 | 245 | pdf_documents = [('index', u'mdfreader', u'mdfreader documentation', u'Aymeric Rateau'),] 246 | 247 | # index - master document 248 | # rst2pdf - name of the generated pdf 249 | # Sample rst2pdf doc - title of the pdf 250 | # Your Name - author name in the pdf 251 | 252 | napoleon_numpy_docstring = True 253 | numpydoc_show_class_members = False -------------------------------------------------------------------------------- /mdfconverter/Ui_mdfreaderui5.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Form implementation generated from reading ui file 'mdfreaderui.ui' 4 | # 5 | # Created by: PyQt5 UI code generator 5.7 6 | # 7 | # WARNING! All changes made in this file will be lost! 8 | 9 | from PyQt5 import QtCore, QtGui, QtWidgets 10 | 11 | class Ui_MainWindow(object): 12 | def setupUi(self, MainWindow): 13 | MainWindow.setObjectName("MainWindow") 14 | MainWindow.resize(800, 653) 15 | self.TopLayout = QtWidgets.QWidget(MainWindow) 16 | self.TopLayout.setObjectName("TopLayout") 17 | self.gridLayout = QtWidgets.QGridLayout(self.TopLayout) 18 | self.gridLayout.setObjectName("gridLayout") 19 | self.label_2 = QtWidgets.QLabel(self.TopLayout) 20 | font = QtGui.QFont() 21 | font.setPointSize(10) 22 | font.setBold(True) 23 | font.setWeight(75) 24 | self.label_2.setFont(font) 25 | self.label_2.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 26 | self.label_2.setObjectName("label_2") 27 | self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1) 28 | self.label = QtWidgets.QLabel(self.TopLayout) 29 | font = QtGui.QFont() 30 | font.setPointSize(10) 31 | font.setBold(True) 32 | font.setWeight(75) 33 | self.label.setFont(font) 34 | self.label.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 35 | self.label.setObjectName("label") 36 | self.gridLayout.addWidget(self.label, 0, 1, 1, 1) 37 | self.label_3 = QtWidgets.QLabel(self.TopLayout) 38 | font = QtGui.QFont() 39 | font.setPointSize(10) 40 | font.setBold(True) 41 | font.setWeight(75) 42 | self.label_3.setFont(font) 43 | self.label_3.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 44 | self.label_3.setObjectName("label_3") 45 | self.gridLayout.addWidget(self.label_3, 0, 2, 1, 1) 46 | self.Lists = QtWidgets.QSplitter(self.TopLayout) 47 | self.Lists.setOrientation(QtCore.Qt.Horizontal) 48 | self.Lists.setObjectName("Lists") 49 | self.FileList = QtWidgets.QListWidget(self.Lists) 50 | self.FileList.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) 51 | self.FileList.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 52 | self.FileList.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) 53 | self.FileList.setDragEnabled(True) 54 | self.FileList.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) 55 | self.FileList.setDefaultDropAction(QtCore.Qt.MoveAction) 56 | self.FileList.setAlternatingRowColors(True) 57 | self.FileList.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) 58 | self.FileList.setProperty("isWrapping", False) 59 | self.FileList.setResizeMode(QtWidgets.QListView.Adjust) 60 | self.FileList.setObjectName("FileList") 61 | self.channelList = QtWidgets.QListWidget(self.Lists) 62 | self.channelList.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) 63 | self.channelList.setAcceptDrops(True) 64 | self.channelList.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 65 | self.channelList.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) 66 | self.channelList.setDragEnabled(True) 67 | self.channelList.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) 68 | self.channelList.setDefaultDropAction(QtCore.Qt.MoveAction) 69 | self.channelList.setAlternatingRowColors(True) 70 | self.channelList.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) 71 | self.channelList.setObjectName("channelList") 72 | self.SelectedChannelList = QtWidgets.QListWidget(self.Lists) 73 | self.SelectedChannelList.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) 74 | self.SelectedChannelList.setAcceptDrops(True) 75 | self.SelectedChannelList.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 76 | self.SelectedChannelList.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) 77 | self.SelectedChannelList.setDragEnabled(True) 78 | self.SelectedChannelList.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) 79 | self.SelectedChannelList.setDefaultDropAction(QtCore.Qt.MoveAction) 80 | self.SelectedChannelList.setAlternatingRowColors(True) 81 | self.SelectedChannelList.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) 82 | self.SelectedChannelList.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectItems) 83 | self.SelectedChannelList.setObjectName("SelectedChannelList") 84 | self.gridLayout.addWidget(self.Lists, 1, 0, 4, 3) 85 | self.browse = QtWidgets.QPushButton(self.TopLayout) 86 | self.browse.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 87 | self.browse.setAutoDefault(False) 88 | self.browse.setDefault(False) 89 | self.browse.setObjectName("browse") 90 | self.gridLayout.addWidget(self.browse, 1, 3, 1, 1) 91 | self.Options = QtWidgets.QSplitter(self.TopLayout) 92 | self.Options.setOrientation(QtCore.Qt.Vertical) 93 | self.Options.setObjectName("Options") 94 | self.splitter = QtWidgets.QSplitter(self.Options) 95 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Expanding) 96 | sizePolicy.setHorizontalStretch(0) 97 | sizePolicy.setVerticalStretch(0) 98 | sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth()) 99 | self.splitter.setSizePolicy(sizePolicy) 100 | self.splitter.setOrientation(QtCore.Qt.Vertical) 101 | self.splitter.setObjectName("splitter") 102 | self.verticalLayoutWidget = QtWidgets.QWidget(self.splitter) 103 | self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") 104 | self.ConvertSelect = QtWidgets.QVBoxLayout(self.verticalLayoutWidget) 105 | self.ConvertSelect.setContentsMargins(0, 0, 0, 0) 106 | self.ConvertSelect.setObjectName("ConvertSelect") 107 | self.matlab = QtWidgets.QRadioButton(self.verticalLayoutWidget) 108 | self.matlab.setEnabled(True) 109 | self.matlab.setChecked(True) 110 | self.matlab.setObjectName("matlab") 111 | self.ConvertSelect.addWidget(self.matlab) 112 | self.netcdf = QtWidgets.QRadioButton(self.verticalLayoutWidget) 113 | self.netcdf.setObjectName("netcdf") 114 | self.ConvertSelect.addWidget(self.netcdf) 115 | self.hdf5 = QtWidgets.QRadioButton(self.verticalLayoutWidget) 116 | self.hdf5.setChecked(False) 117 | self.hdf5.setObjectName("hdf5") 118 | self.ConvertSelect.addWidget(self.hdf5) 119 | self.csv = QtWidgets.QRadioButton(self.verticalLayoutWidget) 120 | self.csv.setObjectName("csv") 121 | self.ConvertSelect.addWidget(self.csv) 122 | self.excel = QtWidgets.QRadioButton(self.verticalLayoutWidget) 123 | self.excel.setObjectName("excel") 124 | self.ConvertSelect.addWidget(self.excel) 125 | self.excel2010 = QtWidgets.QRadioButton(self.verticalLayoutWidget) 126 | self.excel2010.setObjectName("excel2010") 127 | self.ConvertSelect.addWidget(self.excel2010) 128 | self.mdf3 = QtWidgets.QRadioButton(self.verticalLayoutWidget) 129 | self.mdf3.setObjectName("mdf3") 130 | self.ConvertSelect.addWidget(self.mdf3) 131 | self.horizontalLayoutWidget = QtWidgets.QWidget(self.splitter) 132 | self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget") 133 | self.Resample = QtWidgets.QVBoxLayout(self.horizontalLayoutWidget) 134 | self.Resample.setContentsMargins(0, 0, 0, 0) 135 | self.Resample.setObjectName("Resample") 136 | self.resample = QtWidgets.QCheckBox(self.horizontalLayoutWidget) 137 | self.resample.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 138 | self.resample.setChecked(True) 139 | self.resample.setObjectName("resample") 140 | self.Resample.addWidget(self.resample) 141 | self.resampleValue = QtWidgets.QLineEdit(self.horizontalLayoutWidget) 142 | self.resampleValue.setEnabled(True) 143 | self.resampleValue.setInputMethodHints(QtCore.Qt.ImhFormattedNumbersOnly|QtCore.Qt.ImhPreferNumbers) 144 | self.resampleValue.setObjectName("resampleValue") 145 | self.Resample.addWidget(self.resampleValue) 146 | self.layoutWidget = QtWidgets.QWidget(self.splitter) 147 | self.layoutWidget.setObjectName("layoutWidget") 148 | self.LabFile_2 = QtWidgets.QVBoxLayout(self.layoutWidget) 149 | self.LabFile_2.setContentsMargins(0, 0, 0, 0) 150 | self.LabFile_2.setObjectName("LabFile_2") 151 | self.LabFileBrowse = QtWidgets.QPushButton(self.layoutWidget) 152 | self.LabFileBrowse.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 153 | self.LabFileBrowse.setObjectName("LabFileBrowse") 154 | self.LabFile_2.addWidget(self.LabFileBrowse) 155 | self.LabFile = QtWidgets.QLineEdit(self.layoutWidget) 156 | self.LabFile.setEnabled(True) 157 | self.LabFile.setObjectName("LabFile") 158 | self.LabFile_2.addWidget(self.LabFile) 159 | self.MergeFiles = QtWidgets.QCheckBox(self.Options) 160 | self.MergeFiles.setEnabled(True) 161 | self.MergeFiles.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 162 | self.MergeFiles.setChecked(True) 163 | self.MergeFiles.setObjectName("MergeFiles") 164 | self.gridLayout.addWidget(self.Options, 2, 3, 1, 1) 165 | self.Convert = QtWidgets.QPushButton(self.TopLayout) 166 | self.Convert.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 167 | self.Convert.setObjectName("Convert") 168 | self.gridLayout.addWidget(self.Convert, 3, 3, 1, 1) 169 | spacerItem = QtWidgets.QSpacerItem(113, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) 170 | self.gridLayout.addItem(spacerItem, 4, 3, 1, 1) 171 | MainWindow.setCentralWidget(self.TopLayout) 172 | self.label_2.setBuddy(self.FileList) 173 | self.label.setBuddy(self.channelList) 174 | self.label_3.setBuddy(self.SelectedChannelList) 175 | 176 | self.retranslateUi(MainWindow) 177 | QtCore.QMetaObject.connectSlotsByName(MainWindow) 178 | 179 | def retranslateUi(self, MainWindow): 180 | _translate = QtCore.QCoreApplication.translate 181 | MainWindow.setWindowTitle(_translate("MainWindow", "MDF Converter")) 182 | self.label_2.setText(_translate("MainWindow", "File List")) 183 | self.label.setText(_translate("MainWindow", "File Channel List")) 184 | self.label_3.setText(_translate("MainWindow", "Selected Channel List")) 185 | self.FileList.setWhatsThis(_translate("MainWindow", "File list to be converted")) 186 | self.FileList.setSortingEnabled(False) 187 | self.channelList.setWhatsThis(_translate("MainWindow", "Channel list inside the selected file")) 188 | self.channelList.setSortingEnabled(True) 189 | self.SelectedChannelList.setWhatsThis(_translate("MainWindow", "Selected channel list to be exported")) 190 | self.SelectedChannelList.setSortingEnabled(True) 191 | self.browse.setToolTip(_translate("MainWindow", "Click and select MDF file for conversion")) 192 | self.browse.setWhatsThis(_translate("MainWindow", "Click to browse for MDF files to be converted")) 193 | self.browse.setText(_translate("MainWindow", "Browse")) 194 | self.matlab.setText(_translate("MainWindow", "Matlab .mat")) 195 | self.netcdf.setText(_translate("MainWindow", "netCDF")) 196 | self.hdf5.setText(_translate("MainWindow", "HDF5")) 197 | self.csv.setText(_translate("MainWindow", "CSV")) 198 | self.excel.setText(_translate("MainWindow", "Excel 2003")) 199 | self.excel2010.setText(_translate("MainWindow", "Excel 2010")) 200 | self.mdf3.setText(_translate("MainWindow", "MDF3.3")) 201 | self.resample.setWhatsThis(_translate("MainWindow", "Click to resample according to below sampling time in seconds")) 202 | self.resample.setText(_translate("MainWindow", "Resample")) 203 | self.resampleValue.setWhatsThis(_translate("MainWindow", "Resampling time in seconds")) 204 | self.resampleValue.setText(_translate("MainWindow", "1.0")) 205 | self.LabFileBrowse.setWhatsThis(_translate("MainWindow", "Click to selected file containing channel list")) 206 | self.LabFileBrowse.setText(_translate("MainWindow", "Lab file")) 207 | self.LabFile.setWhatsThis(_translate("MainWindow", "Chosen lab file")) 208 | self.MergeFiles.setText(_translate("MainWindow", "MergeFiles")) 209 | self.Convert.setWhatsThis(_translate("MainWindow", "Click to convert all files according your selected options")) 210 | self.Convert.setText(_translate("MainWindow", "Convert")) 211 | 212 | if __name__ == "__main__": 213 | import sys 214 | app = QtGui.QApplication(sys.argv) 215 | MainWindow = QtGui.QMainWindow() 216 | ui = Ui_MainWindow() 217 | ui.setupUi(MainWindow) 218 | MainWindow.show() 219 | sys.exit(app.exec_()) -------------------------------------------------------------------------------- /mdfreader.e4p: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | en 8 | a4292a9bac002b3553cfe312b60bdcab5d0a8287 9 | Python3 10 | Qt5 11 | Utility to read MDF data format and convert to several other data formats 12 | 13 13 | Aymeric Rateau 14 | aymeric.rateau@gmail.com 15 | 16 | LICENSE 17 | README 18 | mdfForVeuszPlugin.py 19 | mdfconverter/Ui_mdfreaderui.py 20 | mdfconverter/Ui_mdfreaderui4.py 21 | mdfconverter/Ui_mdfreaderui5.py 22 | mdfconverter/__init__.py 23 | mdfconverter/mdfconverter.py 24 | mdfconverter/mdfreaderui4.py 25 | mdfconverter/mdfreaderui5.py 26 | mdfreader/__init__.py 27 | mdfreader/__main__.py 28 | mdfreader/dataRead.pyx 29 | mdfreader/mdf.py 30 | mdfreader/mdf3reader.py 31 | mdfreader/mdf4reader.py 32 | mdfreader/mdfinfo3.py 33 | mdfreader/mdfinfo4.py 34 | mdfreader/mdfreader.py 35 | mdfreader/tests/tests.py 36 | setup.py 37 | 38 | 39 |
mdfconverter/mdfreaderui.ui
40 |
41 | 42 | 43 | 44 | 45 | .issues 46 | MANIFEST.in 47 | setup.cfg 48 | 49 | mdfreader/mdfreader.py 50 | 51 | Git 52 | 53 | 54 | 55 | add 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | checkout 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | commit 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | diff 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | export 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | global 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | history 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | log 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | remove 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | status 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | tag 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | update 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | standardLayout 156 | 157 | 158 | True 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | ERIC4API 179 | 180 | 181 | 182 | 183 | ignoreFilePatterns 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | languages 192 | 193 | 194 | 195 | Python2 196 | 197 | 198 | 199 | outputFile 200 | 201 | 202 | doc/doc 203 | 204 | 205 | 206 | 207 | ERIC4DOC 208 | 209 | 210 | 211 | 212 | cssFile 213 | 214 | 215 | %PYTHON%/eric5/CSSs/blue.css 216 | 217 | 218 | ignoreFilePatterns 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | outputDirectory 227 | 228 | 229 | doc 230 | 231 | 232 | qtHelpEnabled 233 | 234 | 235 | False 236 | 237 | 238 | sourceExtensions 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | PYLINT 255 | 256 | 257 | 258 | 259 | dialogReport 260 | 261 | 262 | True 263 | 264 | 265 | disabledMessages 266 | 267 | 268 | 269 | 270 | 271 | enableBasic 272 | 273 | 274 | True 275 | 276 | 277 | enableClasses 278 | 279 | 280 | True 281 | 282 | 283 | enableDesign 284 | 285 | 286 | True 287 | 288 | 289 | enableExceptions 290 | 291 | 292 | True 293 | 294 | 295 | enableFormat 296 | 297 | 298 | False 299 | 300 | 301 | enableImports 302 | 303 | 304 | False 305 | 306 | 307 | enableLogging 308 | 309 | 310 | True 311 | 312 | 313 | enableMetrics 314 | 315 | 316 | True 317 | 318 | 319 | enableMiscellaneous 320 | 321 | 322 | True 323 | 324 | 325 | enableNewstyle 326 | 327 | 328 | True 329 | 330 | 331 | enableSimilarities 332 | 333 | 334 | True 335 | 336 | 337 | enableStringFormat 338 | 339 | 340 | True 341 | 342 | 343 | enableTypecheck 344 | 345 | 346 | True 347 | 348 | 349 | enableVariables 350 | 351 | 352 | True 353 | 354 | 355 | enabledMessages 356 | 357 | 358 | 359 | 360 | 361 | htmlReport 362 | 363 | 364 | False 365 | 366 | 367 | txtReport 368 | 369 | 370 | False 371 | 372 | 373 | 374 | 375 | Pep8Checker 376 | 377 | 378 | 379 | 380 | DocstringType 381 | 382 | 383 | pep257 384 | 385 | 386 | ExcludeFiles 387 | 388 | 389 | 390 | 391 | 392 | ExcludeMessages 393 | 394 | 395 | E123,E226,E24,E501 396 | 397 | 398 | FixCodes 399 | 400 | 401 | 402 | 403 | 404 | FixIssues 405 | 406 | 407 | False 408 | 409 | 410 | HangClosing 411 | 412 | 413 | False 414 | 415 | 416 | IncludeMessages 417 | 418 | 419 | 420 | 421 | 422 | MaxLineLength 423 | 424 | 425 | 79 426 | 427 | 428 | NoFixCodes 429 | 430 | 431 | E501 432 | 433 | 434 | RepeatMessages 435 | 436 | 437 | False 438 | 439 | 440 | ShowIgnored 441 | 442 | 443 | False 444 | 445 | 446 | 447 | 448 | 449 | 450 |
451 | -------------------------------------------------------------------------------- /mdfconverter/mdfreaderui.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | MainWindow 4 | 5 | 6 | 7 | 0 8 | 0 9 | 800 10 | 653 11 | 12 | 13 | 14 | MDF Converter 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 10 23 | 75 24 | true 25 | 26 | 27 | 28 | 29 | 30 | 31 | File List 32 | 33 | 34 | FileList 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 10 43 | 75 44 | true 45 | 46 | 47 | 48 | 49 | 50 | 51 | File Channel List 52 | 53 | 54 | channelList 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 10 63 | 75 64 | true 65 | 66 | 67 | 68 | 69 | 70 | 71 | Selected Channel List 72 | 73 | 74 | SelectedChannelList 75 | 76 | 77 | 78 | 79 | 80 | 81 | Qt::Horizontal 82 | 83 | 84 | 85 | Qt::ActionsContextMenu 86 | 87 | 88 | File list to be converted 89 | 90 | 91 | 92 | 93 | 94 | QAbstractItemView::NoEditTriggers 95 | 96 | 97 | true 98 | 99 | 100 | QAbstractItemView::DragDrop 101 | 102 | 103 | Qt::MoveAction 104 | 105 | 106 | true 107 | 108 | 109 | QAbstractItemView::ExtendedSelection 110 | 111 | 112 | false 113 | 114 | 115 | QListView::Adjust 116 | 117 | 118 | false 119 | 120 | 121 | 122 | 123 | Qt::ActionsContextMenu 124 | 125 | 126 | true 127 | 128 | 129 | Channel list inside the selected file 130 | 131 | 132 | 133 | 134 | 135 | QAbstractItemView::NoEditTriggers 136 | 137 | 138 | true 139 | 140 | 141 | QAbstractItemView::DragDrop 142 | 143 | 144 | Qt::MoveAction 145 | 146 | 147 | true 148 | 149 | 150 | QAbstractItemView::ExtendedSelection 151 | 152 | 153 | true 154 | 155 | 156 | 157 | 158 | Qt::ActionsContextMenu 159 | 160 | 161 | true 162 | 163 | 164 | Selected channel list to be exported 165 | 166 | 167 | 168 | 169 | 170 | QAbstractItemView::NoEditTriggers 171 | 172 | 173 | true 174 | 175 | 176 | QAbstractItemView::DragDrop 177 | 178 | 179 | Qt::MoveAction 180 | 181 | 182 | true 183 | 184 | 185 | QAbstractItemView::ExtendedSelection 186 | 187 | 188 | QAbstractItemView::SelectItems 189 | 190 | 191 | true 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | Click and select MDF file for conversion 200 | 201 | 202 | Click to browse for MDF files to be converted 203 | 204 | 205 | 206 | 207 | 208 | Browse 209 | 210 | 211 | false 212 | 213 | 214 | false 215 | 216 | 217 | 218 | 219 | 220 | 221 | Qt::Vertical 222 | 223 | 224 | 225 | 226 | 0 227 | 0 228 | 229 | 230 | 231 | Qt::Vertical 232 | 233 | 234 | 235 | 236 | 237 | 238 | true 239 | 240 | 241 | Matlab .mat 242 | 243 | 244 | true 245 | 246 | 247 | 248 | 249 | 250 | 251 | netCDF 252 | 253 | 254 | 255 | 256 | 257 | 258 | HDF5 259 | 260 | 261 | false 262 | 263 | 264 | 265 | 266 | 267 | 268 | CSV 269 | 270 | 271 | 272 | 273 | 274 | 275 | Excel 2003 276 | 277 | 278 | 279 | 280 | 281 | 282 | Excel 2010 283 | 284 | 285 | 286 | 287 | 288 | 289 | MDF3.3 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | Click to resample according to below sampling time in seconds 301 | 302 | 303 | 304 | 305 | 306 | Resample 307 | 308 | 309 | true 310 | 311 | 312 | 313 | 314 | 315 | 316 | true 317 | 318 | 319 | Resampling time in seconds 320 | 321 | 322 | Qt::ImhFormattedNumbersOnly|Qt::ImhPreferNumbers 323 | 324 | 325 | 1.0 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | Click to selected file containing channel list 337 | 338 | 339 | 340 | 341 | 342 | Lab file 343 | 344 | 345 | 346 | 347 | 348 | 349 | true 350 | 351 | 352 | Chosen lab file 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | true 362 | 363 | 364 | 365 | 366 | 367 | MergeFiles 368 | 369 | 370 | true 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | Click to convert all files according your selected options 379 | 380 | 381 | 382 | 383 | 384 | Convert 385 | 386 | 387 | 388 | 389 | 390 | 391 | Qt::Horizontal 392 | 393 | 394 | QSizePolicy::Preferred 395 | 396 | 397 | 398 | 113 399 | 20 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | -------------------------------------------------------------------------------- /mdfconverter/Ui_mdfreaderui4.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Form implementation generated from reading ui file '/home/ratal/workspace/mdfreader/mdfreaderui.ui' 4 | # 5 | # Created: Sat Apr 12 00:13:31 2014 6 | # by: PyQt4 UI code generator 4.9.3 7 | # 8 | # WARNING! All changes made in this file will be lost! 9 | 10 | from PyQt4 import QtCore, QtGui 11 | 12 | try: 13 | _fromUtf8 = QtCore.QString.fromUtf8 14 | except AttributeError: 15 | _fromUtf8 = lambda s: s 16 | 17 | 18 | class Ui_MainWindow(object): 19 | 20 | def setupUi(self, MainWindow): 21 | MainWindow.setObjectName(_fromUtf8("MainWindow")) 22 | MainWindow.resize(800, 653) 23 | self.TopLayout = QtGui.QWidget(MainWindow) 24 | self.TopLayout.setObjectName(_fromUtf8("TopLayout")) 25 | self.gridLayout = QtGui.QGridLayout(self.TopLayout) 26 | self.gridLayout.setObjectName(_fromUtf8("gridLayout")) 27 | self.label_2 = QtGui.QLabel(self.TopLayout) 28 | font = QtGui.QFont() 29 | font.setPointSize(10) 30 | font.setBold(True) 31 | font.setWeight(75) 32 | self.label_2.setFont(font) 33 | self.label_2.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 34 | self.label_2.setObjectName(_fromUtf8("label_2")) 35 | self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1) 36 | self.label = QtGui.QLabel(self.TopLayout) 37 | font = QtGui.QFont() 38 | font.setPointSize(10) 39 | font.setBold(True) 40 | font.setWeight(75) 41 | self.label.setFont(font) 42 | self.label.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 43 | self.label.setObjectName(_fromUtf8("label")) 44 | self.gridLayout.addWidget(self.label, 0, 1, 1, 1) 45 | self.label_3 = QtGui.QLabel(self.TopLayout) 46 | font = QtGui.QFont() 47 | font.setPointSize(10) 48 | font.setBold(True) 49 | font.setWeight(75) 50 | self.label_3.setFont(font) 51 | self.label_3.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 52 | self.label_3.setObjectName(_fromUtf8("label_3")) 53 | self.gridLayout.addWidget(self.label_3, 0, 2, 1, 1) 54 | self.Lists = QtGui.QSplitter(self.TopLayout) 55 | self.Lists.setOrientation(QtCore.Qt.Horizontal) 56 | self.Lists.setObjectName(_fromUtf8("Lists")) 57 | self.FileList = QtGui.QListWidget(self.Lists) 58 | self.FileList.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) 59 | self.FileList.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 60 | self.FileList.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) 61 | self.FileList.setDragEnabled(True) 62 | self.FileList.setDragDropMode(QtGui.QAbstractItemView.DragDrop) 63 | self.FileList.setDefaultDropAction(QtCore.Qt.MoveAction) 64 | self.FileList.setAlternatingRowColors(True) 65 | self.FileList.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) 66 | self.FileList.setProperty("isWrapping", False) 67 | self.FileList.setResizeMode(QtGui.QListView.Adjust) 68 | self.FileList.setObjectName(_fromUtf8("FileList")) 69 | self.channelList = QtGui.QListWidget(self.Lists) 70 | self.channelList.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) 71 | self.channelList.setAcceptDrops(True) 72 | self.channelList.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 73 | self.channelList.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) 74 | self.channelList.setDragEnabled(True) 75 | self.channelList.setDragDropMode(QtGui.QAbstractItemView.DragDrop) 76 | self.channelList.setDefaultDropAction(QtCore.Qt.MoveAction) 77 | self.channelList.setAlternatingRowColors(True) 78 | self.channelList.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) 79 | self.channelList.setObjectName(_fromUtf8("channelList")) 80 | self.SelectedChannelList = QtGui.QListWidget(self.Lists) 81 | self.SelectedChannelList.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) 82 | self.SelectedChannelList.setAcceptDrops(True) 83 | self.SelectedChannelList.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 84 | self.SelectedChannelList.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) 85 | self.SelectedChannelList.setDragEnabled(True) 86 | self.SelectedChannelList.setDragDropMode(QtGui.QAbstractItemView.DragDrop) 87 | self.SelectedChannelList.setDefaultDropAction(QtCore.Qt.MoveAction) 88 | self.SelectedChannelList.setAlternatingRowColors(True) 89 | self.SelectedChannelList.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) 90 | self.SelectedChannelList.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems) 91 | self.SelectedChannelList.setObjectName(_fromUtf8("SelectedChannelList")) 92 | self.gridLayout.addWidget(self.Lists, 1, 0, 4, 3) 93 | self.browse = QtGui.QPushButton(self.TopLayout) 94 | self.browse.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 95 | self.browse.setAutoDefault(False) 96 | self.browse.setDefault(False) 97 | self.browse.setObjectName(_fromUtf8("browse")) 98 | self.gridLayout.addWidget(self.browse, 1, 3, 1, 1) 99 | self.Options = QtGui.QSplitter(self.TopLayout) 100 | self.Options.setOrientation(QtCore.Qt.Vertical) 101 | self.Options.setObjectName(_fromUtf8("Options")) 102 | self.splitter = QtGui.QSplitter(self.Options) 103 | sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding) 104 | sizePolicy.setHorizontalStretch(0) 105 | sizePolicy.setVerticalStretch(0) 106 | sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth()) 107 | self.splitter.setSizePolicy(sizePolicy) 108 | self.splitter.setOrientation(QtCore.Qt.Vertical) 109 | self.splitter.setObjectName(_fromUtf8("splitter")) 110 | self.verticalLayoutWidget = QtGui.QWidget(self.splitter) 111 | self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget")) 112 | self.ConvertSelect = QtGui.QVBoxLayout(self.verticalLayoutWidget) 113 | self.ConvertSelect.setMargin(0) 114 | self.ConvertSelect.setObjectName(_fromUtf8("ConvertSelect")) 115 | self.matlab = QtGui.QRadioButton(self.verticalLayoutWidget) 116 | self.matlab.setEnabled(True) 117 | self.matlab.setChecked(True) 118 | self.matlab.setObjectName(_fromUtf8("matlab")) 119 | self.ConvertSelect.addWidget(self.matlab) 120 | self.netcdf = QtGui.QRadioButton(self.verticalLayoutWidget) 121 | self.netcdf.setObjectName(_fromUtf8("netcdf")) 122 | self.ConvertSelect.addWidget(self.netcdf) 123 | self.hdf5 = QtGui.QRadioButton(self.verticalLayoutWidget) 124 | self.hdf5.setChecked(False) 125 | self.hdf5.setObjectName(_fromUtf8("hdf5")) 126 | self.ConvertSelect.addWidget(self.hdf5) 127 | self.csv = QtGui.QRadioButton(self.verticalLayoutWidget) 128 | self.csv.setObjectName(_fromUtf8("csv")) 129 | self.ConvertSelect.addWidget(self.csv) 130 | self.excel = QtGui.QRadioButton(self.verticalLayoutWidget) 131 | self.excel.setObjectName(_fromUtf8("excel")) 132 | self.ConvertSelect.addWidget(self.excel) 133 | self.excel2010 = QtGui.QRadioButton(self.verticalLayoutWidget) 134 | self.excel2010.setObjectName(_fromUtf8("excel2010")) 135 | self.ConvertSelect.addWidget(self.excel2010) 136 | self.mdf3 = QtGui.QRadioButton(self.verticalLayoutWidget) 137 | self.mdf3.setObjectName(_fromUtf8("mdf3")) 138 | self.ConvertSelect.addWidget(self.mdf3) 139 | self.horizontalLayoutWidget = QtGui.QWidget(self.splitter) 140 | self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget")) 141 | self.Resample = QtGui.QVBoxLayout(self.horizontalLayoutWidget) 142 | self.Resample.setMargin(0) 143 | self.Resample.setObjectName(_fromUtf8("Resample")) 144 | self.resample = QtGui.QCheckBox(self.horizontalLayoutWidget) 145 | self.resample.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 146 | self.resample.setChecked(True) 147 | self.resample.setObjectName(_fromUtf8("resample")) 148 | self.Resample.addWidget(self.resample) 149 | self.resampleValue = QtGui.QLineEdit(self.horizontalLayoutWidget) 150 | self.resampleValue.setEnabled(True) 151 | self.resampleValue.setInputMethodHints(QtCore.Qt.ImhFormattedNumbersOnly | QtCore.Qt.ImhPreferNumbers) 152 | self.resampleValue.setObjectName(_fromUtf8("resampleValue")) 153 | self.Resample.addWidget(self.resampleValue) 154 | self.layoutWidget = QtGui.QWidget(self.splitter) 155 | self.layoutWidget.setObjectName(_fromUtf8("layoutWidget")) 156 | self.LabFile_2 = QtGui.QVBoxLayout(self.layoutWidget) 157 | self.LabFile_2.setMargin(0) 158 | self.LabFile_2.setObjectName(_fromUtf8("LabFile_2")) 159 | self.LabFileBrowse = QtGui.QPushButton(self.layoutWidget) 160 | self.LabFileBrowse.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 161 | self.LabFileBrowse.setObjectName(_fromUtf8("LabFileBrowse")) 162 | self.LabFile_2.addWidget(self.LabFileBrowse) 163 | self.LabFile = QtGui.QLineEdit(self.layoutWidget) 164 | self.LabFile.setEnabled(True) 165 | self.LabFile.setObjectName(_fromUtf8("LabFile")) 166 | self.LabFile_2.addWidget(self.LabFile) 167 | self.MergeFiles = QtGui.QCheckBox(self.Options) 168 | self.MergeFiles.setEnabled(True) 169 | self.MergeFiles.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 170 | self.MergeFiles.setChecked(True) 171 | self.MergeFiles.setObjectName(_fromUtf8("MergeFiles")) 172 | self.gridLayout.addWidget(self.Options, 2, 3, 1, 1) 173 | self.Convert = QtGui.QPushButton(self.TopLayout) 174 | self.Convert.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Belgium)) 175 | self.Convert.setObjectName(_fromUtf8("Convert")) 176 | self.gridLayout.addWidget(self.Convert, 3, 3, 1, 1) 177 | spacerItem = QtGui.QSpacerItem(113, 20, QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum) 178 | self.gridLayout.addItem(spacerItem, 4, 3, 1, 1) 179 | MainWindow.setCentralWidget(self.TopLayout) 180 | self.label_2.setBuddy(self.FileList) 181 | self.label.setBuddy(self.channelList) 182 | self.label_3.setBuddy(self.SelectedChannelList) 183 | 184 | self.retranslateUi(MainWindow) 185 | QtCore.QMetaObject.connectSlotsByName(MainWindow) 186 | 187 | def retranslateUi(self, MainWindow): 188 | MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MDF Converter", None, QtGui.QApplication.UnicodeUTF8)) 189 | self.label_2.setText(QtGui.QApplication.translate("MainWindow", "File List", None, QtGui.QApplication.UnicodeUTF8)) 190 | self.label.setText(QtGui.QApplication.translate("MainWindow", "File Channel List", None, QtGui.QApplication.UnicodeUTF8)) 191 | self.label_3.setText(QtGui.QApplication.translate("MainWindow", "Selected Channel List", None, QtGui.QApplication.UnicodeUTF8)) 192 | self.FileList.setWhatsThis(QtGui.QApplication.translate("MainWindow", "File list to be converted", None, QtGui.QApplication.UnicodeUTF8)) 193 | self.FileList.setSortingEnabled(False) 194 | self.channelList.setWhatsThis(QtGui.QApplication.translate("MainWindow", "Channel list inside the selected file", None, QtGui.QApplication.UnicodeUTF8)) 195 | self.channelList.setSortingEnabled(True) 196 | self.SelectedChannelList.setWhatsThis(QtGui.QApplication.translate("MainWindow", "Selected channel list to be exported", None, QtGui.QApplication.UnicodeUTF8)) 197 | self.SelectedChannelList.setSortingEnabled(True) 198 | self.browse.setToolTip(QtGui.QApplication.translate("MainWindow", "Click and select MDF file for conversion", None, QtGui.QApplication.UnicodeUTF8)) 199 | self.browse.setWhatsThis(QtGui.QApplication.translate("MainWindow", "Click to browse for MDF files to be converted", None, QtGui.QApplication.UnicodeUTF8)) 200 | self.browse.setText(QtGui.QApplication.translate("MainWindow", "Browse", None, QtGui.QApplication.UnicodeUTF8)) 201 | self.matlab.setText(QtGui.QApplication.translate("MainWindow", "Matlab .mat", None, QtGui.QApplication.UnicodeUTF8)) 202 | self.netcdf.setText(QtGui.QApplication.translate("MainWindow", "netCDF", None, QtGui.QApplication.UnicodeUTF8)) 203 | self.hdf5.setText(QtGui.QApplication.translate("MainWindow", "HDF5", None, QtGui.QApplication.UnicodeUTF8)) 204 | self.csv.setText(QtGui.QApplication.translate("MainWindow", "CSV", None, QtGui.QApplication.UnicodeUTF8)) 205 | self.excel.setText(QtGui.QApplication.translate("MainWindow", "Excel 2003", None, QtGui.QApplication.UnicodeUTF8)) 206 | self.excel2010.setText(QtGui.QApplication.translate("MainWindow", "Excel 2010", None, QtGui.QApplication.UnicodeUTF8)) 207 | self.mdf3.setText(QtGui.QApplication.translate("MainWindow", "MDF3.3", None, QtGui.QApplication.UnicodeUTF8)) 208 | self.resample.setWhatsThis(QtGui.QApplication.translate("MainWindow", "Click to resample according to below sampling time in seconds", None, QtGui.QApplication.UnicodeUTF8)) 209 | self.resample.setText(QtGui.QApplication.translate("MainWindow", "Resample", None, QtGui.QApplication.UnicodeUTF8)) 210 | self.resampleValue.setWhatsThis(QtGui.QApplication.translate("MainWindow", "Resampling time in seconds", None, QtGui.QApplication.UnicodeUTF8)) 211 | self.resampleValue.setText(QtGui.QApplication.translate("MainWindow", "1.0", None, QtGui.QApplication.UnicodeUTF8)) 212 | self.LabFileBrowse.setWhatsThis(QtGui.QApplication.translate("MainWindow", "Click to selected file containing channel list", None, QtGui.QApplication.UnicodeUTF8)) 213 | self.LabFileBrowse.setText(QtGui.QApplication.translate("MainWindow", "Lab file", None, QtGui.QApplication.UnicodeUTF8)) 214 | self.LabFile.setWhatsThis(QtGui.QApplication.translate("MainWindow", "Chosen lab file", None, QtGui.QApplication.UnicodeUTF8)) 215 | self.MergeFiles.setText(QtGui.QApplication.translate("MainWindow", "MergeFiles", None, QtGui.QApplication.UnicodeUTF8)) 216 | self.Convert.setWhatsThis(QtGui.QApplication.translate("MainWindow", "Click to convert all files according your selected options", None, QtGui.QApplication.UnicodeUTF8)) 217 | self.Convert.setText(QtGui.QApplication.translate("MainWindow", "Convert", None, QtGui.QApplication.UnicodeUTF8)) 218 | 219 | 220 | if __name__ == "__main__": 221 | import sys 222 | app = QtGui.QApplication(sys.argv) 223 | MainWindow = QtGui.QMainWindow() 224 | ui = Ui_MainWindow() 225 | ui.setupUi(MainWindow) 226 | MainWindow.show() 227 | sys.exit(app.exec_()) 228 | -------------------------------------------------------------------------------- /mdfconverter/mdfreaderui5.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Module implementing MainWindow. 5 | """ 6 | 7 | from sys import version_info, path 8 | from os.path import dirname, abspath 9 | root = dirname(abspath(__file__)) 10 | path.append(root) 11 | 12 | from io import open 13 | from multiprocessing import Pool, cpu_count 14 | import mdfreader 15 | 16 | from PyQt5.QtWidgets import QMainWindow, QFileDialog, QAction 17 | from Ui_mdfreaderui5 import Ui_MainWindow 18 | 19 | PythonVersion = version_info 20 | PythonVersion = PythonVersion[0] 21 | MultiProc = True # multiprocess switch, for debug purpose put False 22 | 23 | 24 | class MainWindow(QMainWindow, Ui_MainWindow, QFileDialog): 25 | 26 | """ 27 | Class documentation goes here. 28 | """ 29 | 30 | def __init__(self, parent=None): 31 | """ 32 | Constructor 33 | """ 34 | QMainWindow.__init__(self, parent) 35 | self.setupUi(self) 36 | self.fileNames = [] # files to convert 37 | self.mdfClass = mdfreader.Mdf() # instance of mdf 38 | self.mdfinfoClass = mdfreader.MdfInfo() # instance of mdfinfo 39 | self.convertSelection = 'Matlab' # by default Matlab conversion is selected 40 | self.MergeFiles = False # by default 41 | self.labFileName = [] # .lab file name 42 | self.defaultPath = None # default path to open for browsing files 43 | self.actionPlotSelectedChannel = QAction("Plot", self.SelectedChannelList) # context menu to allow plot of channel 44 | self.SelectedChannelList.addAction(self.actionPlotSelectedChannel) 45 | self.actionPlotSelectedChannel.triggered.connect(self.plotSelected) 46 | self.actionPlotChannel = QAction("Plot", self.channelList) # context menu to allow plot of channel 47 | self.channelList.addAction(self.actionPlotChannel) 48 | self.actionPlotChannel.triggered.connect(self.plot) 49 | self.actionFileRemove = QAction("Delete", self.FileList) # context menu to remove selected file from list 50 | self.FileList.addAction(self.actionFileRemove) 51 | self.actionFileRemove.triggered.connect(self.FileRemove) 52 | 53 | def on_browse_clicked(self): 54 | """ 55 | Will open a dialog to browse for files 56 | """ 57 | if self.defaultPath is None: 58 | self.fileNames = QFileDialog.getOpenFileNames(self, "Select Measurement Files", filter=("MDF file (*.dat *.mdf *.mf4 *.mfx *.mfxz)"))[0] 59 | self.defaultPath = dirname(str(self.fileNames[0])) 60 | else: 61 | self.fileNames = QFileDialog.getOpenFileNames(self, "Select Measurement Files", self.defaultPath, filter=("MDF file (*.dat *.mdf *.mf4 *.mfx *.mfxz)"))[0] 62 | if not len(self.fileNames) == 0: 63 | self.FileList.addItems(self.fileNames) 64 | self.mdfinfoClass.__init__() 65 | self.cleanChannelList() 66 | self.cleanSelectedChannelList() 67 | ChannelList = convertChannelList(self.mdfinfoClass.list_channels(str(self.fileNames[0]))) 68 | self.SelectedChannelList.addItems(ChannelList) 69 | self.FileList.item(0).setSelected(True) 70 | 71 | def cleanSelectedChannelList(self): 72 | # remove all items from list 73 | self.SelectedChannelList.clear() 74 | [self.SelectedChannelList.takeItem(0) for i in range(self.SelectedChannelList.count())] 75 | 76 | def cleanChannelList(self): 77 | # remove all items from list 78 | self.channelList.clear() 79 | [self.channelList.takeItem(0) for i in range(self.channelList.count())] 80 | 81 | def on_Convert_clicked(self): 82 | """ 83 | Will convert mdf files into selected format 84 | """ 85 | # create list of channels to be converted for all files 86 | channelList = [] 87 | [channelList.append(str(self.SelectedChannelList.item(i).text())) for i in range(self.SelectedChannelList.count())] 88 | channelList = list(set(channelList)) # remove duplicates 89 | # Process all mdf files recursively 90 | if self.FileList.count() > 0: # not empty list 91 | ncpu = cpu_count() # to still have response from PC 92 | if ncpu < 1: 93 | ncpu = 1 94 | pool = Pool(processes=ncpu) 95 | if self.MergeFiles or self.FileList.count() < 2: # export all files separately, inverted bool 96 | convertFlag = True 97 | convertSelection = self.convertSelection 98 | resampleValue = float(self.resampleValue.text()) 99 | # re-sample if requested 100 | if self.resample.checkState(): 101 | if not len(self.resampleValue.text()) == 0: 102 | resampleFlag = True 103 | else: 104 | raise Exception('Empty field for resampling') 105 | else: 106 | resampleFlag = False 107 | args = [(str(self.FileList.takeItem(0).text()), channelList, resampleFlag, resampleValue, convertFlag, convertSelection) for i in range(self.FileList.count())] 108 | if MultiProc: 109 | result = pool.map_async(processMDFstar, args) 110 | result.get() # waits until finished 111 | else: 112 | result = list(map(processMDFstar, args)) 113 | self.cleanChannelList() 114 | elif self.FileList.count() >= 2: # Stack files data if min 2 files in list 115 | # import first file 116 | fileNameList = [] 117 | if len(self.resampleValue.text()) == 0: 118 | raise Exception('Wrong value for re-sampling') 119 | convertFlag = False 120 | convertSelection = self.convertSelection 121 | resampleValue = float(self.resampleValue.text()) 122 | resampleFlag = True # always re-sample when merging 123 | fileName = str(self.FileList.item(0).text()) # Uses first file name for the converted file 124 | # list filenames 125 | args = [(str(self.FileList.takeItem(0).text()), channelList, resampleFlag, resampleValue, convertFlag, convertSelection) for i in range(self.FileList.count())] 126 | if MultiProc: 127 | res = pool.map_async(processMDFstar, args) 128 | result = res.get() 129 | else: 130 | result = map(processMDFstar, args) # no multiprocess, for debug 131 | # Merge results 132 | self.mdfClass.__init__() # clear memory 133 | self.mdfClass.fileName = fileName # First filename will be used for exported file name 134 | self.mdfClass.multiProc = False # do not use multiproc inside mdfreader while already using from mdfreaderui level 135 | buffer = self.mdfClass.copy() # create/copy empty class in buffer 136 | res = result.pop(0) # extract first file data from processed list 137 | self.mdfClass.update(res[0]) # initialize mdfclass wih first file data 138 | self.mdfClass.masterChannelList = res[1] # initialize masterChannelList 139 | fileNameList.append(res[2]) # record merged file in list 140 | for res in result: # Merge 141 | buffer.__init__() # clean buffer class 142 | buffer.update(res[0]) # assigns next class to buffer 143 | buffer.masterChannelList = res[1] 144 | fileNameList.append(res[2]) 145 | self.mdfClass.concat_mdf(buffer) # merge buffer to merged class mdfClass 146 | # Export 147 | if self.convertSelection == 'Matlab': 148 | self.mdfClass.export_to_matlab() 149 | elif self.convertSelection == 'csv': 150 | self.mdfClass.export_to_csv() 151 | elif self.convertSelection == 'netcdf': 152 | self.mdfClass.export_to_NetCDF() 153 | elif self.convertSelection == 'hdf5': 154 | self.mdfClass.export_to_hdf5() 155 | elif self.convertSelection == 'excel': 156 | self.mdfClass.export_to_excel() 157 | elif self.convertSelection == 'excel2010': 158 | self.mdfClass.export_to_xlsx() 159 | elif self.convertSelection == 'mdf3': 160 | self.mdfClass.write(fileName + '_new') 161 | self.cleanChannelList() 162 | print('File list merged :') 163 | for file in fileNameList: # prints files merged for checking 164 | print(file) 165 | self.mdfClass.__init__() # clear memory 166 | 167 | def on_FileList_itemClicked(self, item): 168 | """ 169 | If user click on file list 170 | """ 171 | # Refresh list of channels from selected file 172 | self.mdfinfoClass.__init__() 173 | # self.mdfinfoClass.readinfo(item) 174 | self.cleanChannelList() 175 | ChannelList = convertChannelList(self.mdfinfoClass.list_channels(str(item.text()))) 176 | self.channelList.addItems(ChannelList) 177 | self.mdfinfoClass.__init__() # clean object to free memory 178 | 179 | def on_matlab_clicked(self): 180 | """ 181 | Selects Matlab conversion 182 | """ 183 | self.convertSelection = 'Matlab' 184 | 185 | def on_netcdf_clicked(self): 186 | """ 187 | Selects netcdf conversion. 188 | """ 189 | self.convertSelection = 'netcdf' 190 | 191 | def on_hdf5_clicked(self): 192 | """ 193 | Selects hdf5 conversion. 194 | """ 195 | self.convertSelection = 'hdf5' 196 | 197 | def on_csv_clicked(self): 198 | """ 199 | Selects csv conversion. 200 | """ 201 | self.convertSelection = 'csv' 202 | 203 | def on_excel_clicked(self): 204 | """ 205 | Selects excel conversion. 206 | """ 207 | self.convertSelection = 'excel' 208 | 209 | def on_excel2010_clicked(self): 210 | """ 211 | Selects excel conversion. 212 | """ 213 | self.convertSelection = 'excel2010' 214 | 215 | def on_mdf3_clicked(self): 216 | """ 217 | Selects MDF3.3 conversion. 218 | """ 219 | self.convertSelection = 'mdf3' 220 | 221 | def on_LabFileBrowse_clicked(self): 222 | """ 223 | selects lab file from browser. 224 | """ 225 | self.labFileName = QFileDialog.getOpenFileName(self, "Select Lab Files", filter=("Lab file (*.lab)"))[0] 226 | if not len(self.labFileName) == 0: 227 | self.LabFile.del_() # clear linedit 228 | self.LabFile.insert(str(self.labFileName)) # replace linedit field by browsed file name 229 | # read lab file 230 | labfile = open(str(self.labFileName), 'r') 231 | self.labChannelList = [] 232 | line = labfile.readline() # read first line [lab] 233 | while True: 234 | line = labfile.readline() 235 | if not line: 236 | break 237 | self.labChannelList.append(line.replace('\n', '')) 238 | self.cleanSelectedChannelList() # Clear Selected file list 239 | self.SelectedChannelList.addItems(self.labChannelList) 240 | 241 | def plot(self): 242 | # Finds selected file and read it 243 | selectedFile = self.FileList.selectedItems() 244 | self.mdfClass.__init__(str(selectedFile[0].text())) # read file 245 | # list items selected in listWidget 246 | Channels = self.channelList.selectedItems() 247 | selectedChannels = [] 248 | [selectedChannels.append(str(Channels[i].text())) for i in range(len(Channels))] 249 | # plot channels 250 | self.mdfClass.plot(selectedChannels) 251 | 252 | def plotSelected(self): 253 | # plots channels from selected list 254 | selectedFile = self.FileList.selectedItems() 255 | if not len(selectedFile) == 0: 256 | self.mdfClass.__init__(str(selectedFile[0].text())) # read file 257 | else: 258 | self.mdfClass.__init__(str(self.FileList[0].text())) # read file 259 | # list items selected in listWidget 260 | Channels = self.SelectedChannelList.selectedItems() 261 | selectedChannels = [] 262 | [selectedChannels.append(str(Channels[i].text())) for i in range(len(Channels))] 263 | # plot channels 264 | self.mdfClass.plot(selectedChannels) 265 | 266 | def FileRemove(self): 267 | # removes selected file 268 | selectionList = self.FileList.selectedItems() 269 | [self.FileList.takeItem(self.FileList.row(selectionList[i])) for i in range(len(selectionList))] 270 | 271 | def on_SelectedChannelList_dropEvent(self): 272 | # avoids to have duplicates in list when channel is dropped 273 | channelList = [] 274 | [channelList.append(str(self.SelectedChannelList.item(i).text())) for i in range(self.SelectedChannelList.count())] 275 | channelList = list(set(channelList)) # removeDuplicates 276 | self.SelectedChannelList.clear() 277 | self.SelectedChannelList.addItems(channelList) 278 | 279 | def on_MergeFiles_toggled(self): 280 | """ 281 | Slot documentation goes here. 282 | """ 283 | # toggle flag to merge files 284 | self.MergeFiles = not self.MergeFiles 285 | if self.MergeFiles: 286 | self.resample.setCheckState(2) 287 | 288 | 289 | def processMDF(fileName, channelist, resampleFlag, resampleValue, convertFlag, convertSelection): 290 | # Will process file according to defined options 291 | yop = mdfreader.Mdf() 292 | yop.multiProc = False # already multiprocessed 293 | yop.convertAfterRead = True 294 | yop.read(fileName) # reads complete file 295 | yop.keep_channels(channelist) # removes unnecessary channels 296 | if resampleFlag: 297 | yop.resample(sampling=resampleValue) 298 | if convertFlag: 299 | if convertSelection == 'Matlab': 300 | yop.export_to_matlab() 301 | elif convertSelection == 'csv': 302 | yop.export_to_csv() 303 | elif convertSelection == 'netcdf': 304 | yop.export_to_NetCDF() 305 | elif convertSelection == 'hdf5': 306 | yop.export_to_hdf5() 307 | elif convertSelection == 'excel': 308 | yop.export_to_excel() 309 | elif convertSelection == 'excel2010': 310 | yop.export_to_xlsx() 311 | elif convertSelection == 'mdf3': 312 | yop.write(fileName + '_new') 313 | yopPicklable = {} # picklable dict and not object 314 | for channel in list(yop.keys()): 315 | yopPicklable[channel] = yop[channel] 316 | return [yopPicklable, yop.masterChannelList, yop.fileName] 317 | 318 | 319 | def processMDFstar(args): 320 | try: 321 | return processMDF(*args) 322 | except: 323 | print('Error, following file might be corrupted : ' + args[0]) # Shows fileName and parameters to help finding corrupted files 324 | raise Exception('Please re-try by removing this file from the list and restart mdfconverter to kill processes and clean memory') 325 | 326 | 327 | def convertChannelList(channelList): 328 | if PythonVersion < 3: 329 | return [str(name) for name in channelList] 330 | else: 331 | return [(name) for name in channelList] 332 | -------------------------------------------------------------------------------- /mdfconverter/mdfreaderui4.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Module implementing MainWindow. 5 | """ 6 | 7 | from sys import version_info, path 8 | from os.path import dirname, abspath 9 | root = dirname(abspath(__file__)) 10 | path.append(root) 11 | 12 | from io import open 13 | from multiprocessing import Pool, cpu_count 14 | from mdfreader import * 15 | 16 | from PyQt4.QtGui import QMainWindow, QFileDialog, QAction 17 | from PyQt4.QtCore import pyqtSignature, SIGNAL 18 | from Ui_mdfreaderui4 import Ui_MainWindow 19 | 20 | PythonVersion = version_info 21 | PythonVersion = PythonVersion[0] 22 | MultiProc = True # multiprocess switch, for debug purpose put False 23 | 24 | 25 | class MainWindow(QMainWindow, Ui_MainWindow, QFileDialog): 26 | 27 | """ 28 | Class documentation goes here. 29 | """ 30 | 31 | def __init__(self, parent=None): 32 | """ 33 | Constructor 34 | """ 35 | QMainWindow.__init__(self, parent) 36 | self.setupUi(self) 37 | self.fileNames = [] # files to convert 38 | self.mdfClass = Mdf() # instance of mdf 39 | self.mdfinfoClass = MdfInfo() # instance of mdfinfo 40 | self.convertSelection = 'Matlab' # by default Matlab conversion is selected 41 | self.MergeFiles = False # by default 42 | self.labFileName = [] # .lab file name 43 | self.defaultPath = None # default path to open for browsing files 44 | self.actionPlotSelectedChannel = QAction("Plot", self.SelectedChannelList) # context menu to allow plot of channel 45 | self.SelectedChannelList.addAction(self.actionPlotSelectedChannel) 46 | self.connect(self.actionPlotSelectedChannel, SIGNAL("triggered()"), self.plotSelected) 47 | self.actionPlotChannel = QAction("Plot", self.channelList) # context menu to allow plot of channel 48 | self.channelList.addAction(self.actionPlotChannel) 49 | self.connect(self.actionPlotChannel, SIGNAL("triggered()"), self.plot) 50 | self.actionFileRemove = QAction("Delete", self.FileList) # context menu to remove selected file from list 51 | self.FileList.addAction(self.actionFileRemove) 52 | self.connect(self.actionFileRemove, SIGNAL("triggered()"), self.FileRemove) 53 | 54 | @pyqtSignature("") 55 | def on_browse_clicked(self): 56 | """ 57 | Will open a dialog to browse for files 58 | """ 59 | if self.defaultPath is None: 60 | self.fileNames = QFileDialog.getOpenFileNames(self, "Select Measurement Files", filter=("MDF file (*.dat *.mdf *.mf4 *.mfx *.mfxz)")) 61 | self.defaultPath = dirname(str(self.fileNames[0])) 62 | else: 63 | self.fileNames = QFileDialog.getOpenFileNames(self, "Select Measurement Files", self.defaultPath, filter=("MDF file (*.dat *.mdf *.mf4 *.mfx *.mfxz)")) 64 | if not len(self.fileNames) == 0: 65 | self.FileList.addItems(self.fileNames) 66 | self.mdfinfoClass.__init__() 67 | self.cleanChannelList() 68 | self.cleanSelectedChannelList() 69 | ChannelList = convertChannelList(self.mdfinfoClass.list_channels(str(self.fileNames[0]))) 70 | self.SelectedChannelList.addItems(ChannelList) 71 | self.FileList.setItemSelected(self.FileList.item(0), True) 72 | 73 | def cleanSelectedChannelList(self): 74 | # remove all items from list 75 | self.SelectedChannelList.clear() 76 | [self.SelectedChannelList.takeItem(0) for i in range(self.SelectedChannelList.count())] 77 | 78 | def cleanChannelList(self): 79 | # remove all items from list 80 | self.channelList.clear() 81 | [self.channelList.takeItem(0) for i in range(self.channelList.count())] 82 | 83 | @pyqtSignature("") 84 | def on_Convert_clicked(self): 85 | """ 86 | Will convert mdf files into selected format 87 | """ 88 | # create list of channels to be converted for all files 89 | channelList = [] 90 | [channelList.append(str(self.SelectedChannelList.item(i).text())) for i in range(self.SelectedChannelList.count())] 91 | channelList = list(set(channelList)) # remove duplicates 92 | # Process all mdf files recursively 93 | if self.FileList.count() > 0: # not empty list 94 | ncpu = cpu_count() # to still have response from PC 95 | if ncpu < 1: 96 | ncpu = 1 97 | pool = Pool(processes=ncpu) 98 | if self.MergeFiles or self.FileList.count() < 2: # export all files separately, inverted bool 99 | convertFlag = True 100 | convertSelection = self.convertSelection 101 | resampleValue = float(self.resampleValue.text()) 102 | # re-sample if requested 103 | if self.resample.checkState(): 104 | if not len(self.resampleValue.text()) == 0: 105 | resampleFlag = True 106 | else: 107 | raise Exception('Empty field for resampling') 108 | else: 109 | resampleFlag = False 110 | args = [(str(self.FileList.takeItem(0).text()), channelList, resampleFlag, resampleValue, convertFlag, convertSelection) for i in range(self.FileList.count())] 111 | if MultiProc: 112 | result = pool.map_async(processMDFstar, args) 113 | result.get() # waits until finished 114 | else: 115 | result = list(map(processMDFstar, args)) 116 | self.cleanChannelList() 117 | elif self.FileList.count() >= 2: # Stack files data if min 2 files in list 118 | # import first file 119 | fileNameList = [] 120 | if len(self.resampleValue.text()) == 0: 121 | raise Exception('Wrong value for re-sampling') 122 | convertFlag = False 123 | convertSelection = self.convertSelection 124 | resampleValue = float(self.resampleValue.text()) 125 | resampleFlag = True # always re-sample when merging 126 | fileName = str(self.FileList.item(0).text()) # Uses first file name for the converted file 127 | # list filenames 128 | args = [(str(self.FileList.takeItem(0).text()), channelList, resampleFlag, resampleValue, convertFlag, convertSelection) for i in range(self.FileList.count())] 129 | if MultiProc: 130 | res = pool.map_async(processMDFstar, args) 131 | result = res.get() 132 | else: 133 | result = map(processMDFstar, args) # no multiprocess, for debug 134 | # Merge results 135 | self.mdfClass.__init__() # clear memory 136 | self.mdfClass.fileName = fileName # First filename will be used for exported file name 137 | self.mdfClass.multiProc = False # do not use multiproc inside mdfreader while already using from mdfreaderui level 138 | buffer = self.mdfClass.copy() # create/copy empty class in buffer 139 | res = result.pop(0) # extract first file data from processed list 140 | self.mdfClass.update(res[0]) # initialize mdfclass wih first file data 141 | self.mdfClass.masterChannelList = res[1] # initialize masterChannelList 142 | fileNameList.append(res[2]) # record merged file in list 143 | for res in result: # Merge 144 | buffer.__init__() # clean buffer class 145 | buffer.update(res[0]) # assigns next class to buffer 146 | buffer.masterChannelList = res[1] 147 | fileNameList.append(res[2]) 148 | self.mdfClass.concat_mdf(buffer) # merge buffer to merged class mdfClass 149 | # Export 150 | if self.convertSelection == 'Matlab': 151 | self.mdfClass.export_to_matlab() 152 | elif self.convertSelection == 'csv': 153 | self.mdfClass.export_to_csv() 154 | elif self.convertSelection == 'netcdf': 155 | self.mdfClass.export_to_NetCDF() 156 | elif self.convertSelection == 'hdf5': 157 | self.mdfClass.export_to_hdf5() 158 | elif self.convertSelection == 'excel': 159 | self.mdfClass.export_to_excel() 160 | elif self.convertSelection == 'excel2010': 161 | self.mdfClass.export_to_xlsx() 162 | elif self.convertSelection == 'mdf3': 163 | self.mdfClass.write(fileName + '_new') 164 | self.cleanChannelList() 165 | print('File list merged :') 166 | for file in fileNameList: # prints files merged for checking 167 | print(file) 168 | self.mdfClass.__init__() # clear memory 169 | 170 | @pyqtSignature("QListWidgetItem*") 171 | def on_FileList_itemClicked(self, item): 172 | """ 173 | If user click on file list 174 | """ 175 | # Refresh list of channels from selected file 176 | self.mdfinfoClass.__init__() 177 | # self.mdfinfoClass.readinfo(item) 178 | self.cleanChannelList() 179 | ChannelList = convertChannelList(self.mdfinfoClass.list_channels(str(item.text()))) 180 | self.channelList.addItems(ChannelList) 181 | self.mdfinfoClass.__init__() # clean object to free memory 182 | 183 | @pyqtSignature("bool") 184 | def on_matlab_clicked(self, checked): 185 | """ 186 | Selects Matlab conversion 187 | """ 188 | self.convertSelection = 'Matlab' 189 | 190 | @pyqtSignature("bool") 191 | def on_netcdf_clicked(self, checked): 192 | """ 193 | Selects netcdf conversion. 194 | """ 195 | self.convertSelection = 'netcdf' 196 | 197 | @pyqtSignature("bool") 198 | def on_hdf5_clicked(self, checked): 199 | """ 200 | Selects hdf5 conversion. 201 | """ 202 | self.convertSelection = 'hdf5' 203 | 204 | @pyqtSignature("bool") 205 | def on_csv_clicked(self, checked): 206 | """ 207 | Selects csv conversion. 208 | """ 209 | self.convertSelection = 'csv' 210 | 211 | @pyqtSignature("bool") 212 | def on_excel_clicked(self, checked): 213 | """ 214 | Selects excel conversion. 215 | """ 216 | self.convertSelection = 'excel' 217 | 218 | @pyqtSignature("bool") 219 | def on_excel2010_clicked(self, checked): 220 | """ 221 | Selects excel conversion. 222 | """ 223 | self.convertSelection = 'excel2010' 224 | 225 | @pyqtSignature("bool") 226 | def on_mdf3_clicked(self, checked): 227 | """ 228 | Selects MDF3.3 conversion. 229 | """ 230 | self.convertSelection = 'mdf3' 231 | 232 | @pyqtSignature("") 233 | def on_LabFileBrowse_clicked(self): 234 | """ 235 | selects lab file from browser. 236 | """ 237 | self.labFileName = QFileDialog.getOpenFileName(self, "Select Lab Files", filter=("Lab file (*.lab)")) 238 | if not len(self.labFileName) == 0: 239 | self.LabFile.del_() # clear linedit 240 | self.LabFile.insert(str(self.labFileName)) # replace linedit field by browsed file name 241 | # read lab file 242 | labfile = open(str(self.labFileName), 'r') 243 | self.labChannelList = [] 244 | line = labfile.readline() # read first line [lab] 245 | while True: 246 | line = labfile.readline() 247 | if not line: 248 | break 249 | self.labChannelList.append(line.replace('\n', '')) 250 | self.cleanSelectedChannelList() # Clear Selected file list 251 | self.SelectedChannelList.addItems(self.labChannelList) 252 | 253 | def plot(self): 254 | # Finds selected file and read it 255 | selectedFile = self.FileList.selectedItems() 256 | self.mdfClass.__init__(str(selectedFile[0].text())) # read file 257 | # list items selected in listWidget 258 | Channels = self.channelList.selectedItems() 259 | selectedChannels = [] 260 | [selectedChannels.append(str(Channels[i].text())) for i in range(len(Channels))] 261 | # plot channels 262 | self.mdfClass.plot(selectedChannels) 263 | 264 | def plotSelected(self): 265 | # plots channels from selected list 266 | selectedFile = self.FileList.selectedItems() 267 | if not len(selectedFile) == 0: 268 | self.mdfClass.__init__(str(selectedFile[0].text())) # read file 269 | else: 270 | self.mdfClass.__init__(str(self.FileList[0].text())) # read file 271 | # list items selected in listWidget 272 | Channels = self.SelectedChannelList.selectedItems() 273 | selectedChannels = [] 274 | [selectedChannels.append(str(Channels[i].text())) for i in range(len(Channels))] 275 | # plot channels 276 | self.mdfClass.plot(selectedChannels) 277 | 278 | def FileRemove(self): 279 | # removes selected file 280 | selectionList = self.FileList.selectedItems() 281 | [self.FileList.takeItem(self.FileList.row(selectionList[i])) for i in range(len(selectionList))] 282 | 283 | def on_SelectedChannelList_dropEvent(self): 284 | # avoids to have duplicates in list when channel is dropped 285 | channelList = [] 286 | [channelList.append(str(self.SelectedChannelList.item(i).text())) for i in range(self.SelectedChannelList.count())] 287 | channelList = list(set(channelList)) # removeDuplicates 288 | self.SelectedChannelList.clear() 289 | self.SelectedChannelList.addItems(channelList) 290 | 291 | @pyqtSignature("bool") 292 | def on_MergeFiles_toggled(self, checked): 293 | """ 294 | Slot documentation goes here. 295 | """ 296 | # toggle flag to merge files 297 | self.MergeFiles = not self.MergeFiles 298 | if self.MergeFiles: 299 | self.resample.setCheckState(2) 300 | 301 | 302 | def processMDF(fileName, channelist, resampleFlag, resampleValue, convertFlag, convertSelection): 303 | # Will process file according to defined options 304 | yop = Mdf() 305 | yop.multiProc = False # already multiprocessed 306 | yop.convertAfterRead = True 307 | yop.read(fileName) # reads complete file 308 | yop.keep_channels(channelist) # removes unnecessary channels 309 | if resampleFlag: 310 | yop.resample(sampling=resampleValue) 311 | if convertFlag: 312 | if convertSelection == 'Matlab': 313 | yop.export_to_matlab() 314 | elif convertSelection == 'csv': 315 | yop.export_to_csv() 316 | elif convertSelection == 'netcdf': 317 | yop.export_to_NetCDF() 318 | elif convertSelection == 'hdf5': 319 | yop.export_to_hdf5() 320 | elif convertSelection == 'excel': 321 | yop.export_to_excel() 322 | elif convertSelection == 'excel2010': 323 | yop.export_to_xlsx() 324 | elif convertSelection == 'mdf3': 325 | yop.write(fileName + '_new') 326 | yopPicklable = {} # picklable dict and not object 327 | for channel in list(yop.keys()): 328 | yopPicklable[channel] = yop[channel] 329 | return [yopPicklable, yop.masterChannelList, yop.fileName] 330 | 331 | 332 | def processMDFstar(args): 333 | try: 334 | return processMDF(*args) 335 | except: 336 | print('Error, following file might be corrupted : ' + args[0]) # Shows fileName and parameters to help finding corrupted files 337 | raise Exception('Please re-try by removing this file from the list and restart mdfconverter to kill processes and clean memory') 338 | 339 | 340 | def convertChannelList(channelList): 341 | if PythonVersion < 3: 342 | return [str(name) for name in channelList] 343 | else: 344 | return [(name) for name in channelList] 345 | -------------------------------------------------------------------------------- /mdfreader/mdf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ mdf_skeleton module describing basic mdf structure and methods 3 | 4 | Created on Thu Sept 24 2015 5 | 6 | :Author: `Aymeric Rateau `__ 7 | 8 | 9 | Dependencies 10 | ------------------- 11 | - Python >3.4 12 | - Numpy >1.6 13 | 14 | 15 | mdf 16 | -------------------------- 17 | """ 18 | from io import open 19 | from zipfile import is_zipfile, ZipFile 20 | from itertools import chain 21 | from random import choice 22 | from string import ascii_letters 23 | from collections import OrderedDict, defaultdict 24 | from time import time 25 | from warnings import warn 26 | from numpy import array_repr, set_printoptions, recarray, fromstring 27 | try: 28 | from pandas import set_option 29 | except ImportError: 30 | warn('Pandas export will not be possible', ImportWarning) 31 | set_printoptions(threshold=100, edgeitems=1) 32 | _notAllowedChannelNames = set(dir(recarray)) 33 | try: 34 | CompressionPossible = True 35 | from blosc import compress, decompress 36 | except ImportError: 37 | # Cannot compress data, please install bcolz and blosc 38 | CompressionPossible = False 39 | 40 | descriptionField = 'description' 41 | unitField = 'unit' 42 | dataField = 'data' 43 | masterField = 'master' 44 | masterTypeField = 'masterType' 45 | conversionField = 'conversion' 46 | attachmentField = 'attachment' 47 | idField = 'id' 48 | invalidPosField = 'invalid_bit' 49 | invalidChannel = 'invalid_channel' 50 | 51 | 52 | class MdfSkeleton(dict): 53 | __slots__ = ['masterChannelList', 'fileName', 'MDFVersionNumber', 'multiProc', 54 | 'convertAfterRead', 'filterChannelNames', 'fileMetadata', 'convertTables', 55 | '_pandasframe', 'info', '_compression_level', '_noDataLoading', 56 | 'fid', 'zipfile'] 57 | """ MdfSkeleton class 58 | 59 | Attributes 60 | -------------- 61 | fileName : str 62 | file name 63 | MDFVersionNumber : int 64 | mdf file version number 65 | masterChannelList : dict 66 | Represents data structure: a key per master channel with corresponding value containing a list of channels 67 | One key or master channel represents then a data group having same sampling interval. 68 | multiProc : bool 69 | Flag to request channel conversion multi processed for performance improvement. 70 | One thread per data group. 71 | convertAfterRead : bool 72 | flag to convert raw data to physical just after read 73 | filterChannelNames : bool 74 | flag to filter long channel names from its module names separated by '.' 75 | fileMetadata : dict 76 | file metadata with minimum keys : author, organisation, project, subject, comment, time, date 77 | 78 | Methods 79 | ------------ 80 | add_channel(channel_name, data, master_channel, master_type=1, unit='', description='', conversion=None) 81 | adds channel to mdf dict 82 | remove_channel(channel_name) 83 | removes channel from mdf dict and returns its content 84 | rename_channel(channel_name, new_channel_name) 85 | renames a channel and returns its content 86 | copy() 87 | copy a mdf class 88 | add_metadata(author, organisation, project, subject, comment, date, time) 89 | adds basic metadata from file 90 | """ 91 | 92 | def __init__(self, file_name=None, channel_list=None, convert_after_read=True, 93 | filter_channel_names=False, no_data_loading=False, 94 | compression=False, convert_tables=False, metadata=2): 95 | """ mdf_skeleton class constructor. 96 | 97 | Parameters 98 | ---------------- 99 | file_name : str, optional 100 | file name 101 | 102 | channel_list : list of str, optional 103 | list of channel names to be read. 104 | If you use channelList, reading might be much slower but it will 105 | save you memory. Can be used to read big files. 106 | 107 | convert_after_read : bool, optional 108 | flag to convert channel after read, True by default. 109 | If you use convertAfterRead by setting it to false, all data from 110 | channels will be kept raw, no conversion applied. 111 | If many float are stored in file, you can gain from 3 to 4 times 112 | memory footprint. 113 | To calculate value from channel, you can then use 114 | method .get_channel_data() 115 | 116 | filter_channel_names : bool, optional 117 | flag to filter long channel names from its module names 118 | separated by '.' 119 | 120 | compression : bool optional 121 | flag to compress data in memory. 122 | 123 | convert_tables : bool, optional, default False 124 | flag to convert or not only conversions with tables. 125 | These conversions types take generally long time and memory. 126 | """ 127 | self.masterChannelList = OrderedDict() 128 | # flag to control multiprocessing, default deactivate, 129 | # giving priority to mdfconverter 130 | self.multiProc = False 131 | self.fileMetadata = dict() 132 | self.fileMetadata['author'] = '' 133 | self.fileMetadata['organisation'] = '' 134 | self.fileMetadata['project'] = '' 135 | self.fileMetadata['subject'] = '' 136 | self.fileMetadata['comment'] = '' 137 | self.fileMetadata['time'] = time() # time in seconds since epoch, floating 138 | self.MDFVersionNumber = 300 139 | self.filterChannelNames = filter_channel_names 140 | # by default, do not convert table conversion types, taking lot of time and memory 141 | self.convertTables = convert_tables 142 | self._pandasframe = False 143 | self.info = None 144 | self._compression_level = 9 # default compression level 145 | self._noDataLoading = False # in case reading with this argument activated 146 | # clears class from previous reading and avoid to mess up 147 | self.clear() 148 | self.fileName = file_name 149 | if file_name is not None: 150 | self.read(file_name, channel_list=channel_list, 151 | convert_after_read=convert_after_read, 152 | filter_channel_names=filter_channel_names, 153 | no_data_loading=no_data_loading, 154 | compression=compression, 155 | metadata=metadata) 156 | 157 | def add_channel(self, channel_name, data, master_channel, master_type=1, unit='', description='', conversion=None, 158 | info=None, compression=False, identifier=None): 159 | """ adds channel to mdf dict. 160 | 161 | Parameters 162 | ---------------- 163 | channel_name : str 164 | channel name 165 | data : numpy array 166 | numpy array of channel's data 167 | master_channel : str 168 | master channel name 169 | master_type : int, optional 170 | master channel type : 0=None, 1=Time, 2=Angle, 3=Distance, 4=index 171 | unit : str, optional 172 | unit description 173 | description : str, optional 174 | channel description 175 | conversion : info class, optional 176 | conversion description from info class 177 | info : info class for CNBlock, optional 178 | used for CABlock axis creation and channel conversion 179 | compression : bool 180 | flag to ask for channel data compression 181 | identifier : tuple 182 | tuple of int and str following below structure: 183 | (data group number, channel group number, channel number), 184 | (channel name, channel source, channel path), 185 | (group name, group source, group path) 186 | """ 187 | if not self._noDataLoading: 188 | self[channel_name] = {} 189 | if master_channel not in self.masterChannelList: 190 | self.masterChannelList[master_channel] = [] 191 | self.masterChannelList[master_channel].append(channel_name) 192 | self.set_channel_unit(channel_name, unit) 193 | self.set_channel_desc(channel_name, description) 194 | self.set_channel_master(channel_name, master_channel) 195 | if self.MDFVersionNumber < 400: # mdf3 196 | self.set_channel_master_type(channel_name, 1) 197 | else: # mdf4 198 | self.set_channel_master_type(channel_name, master_type) 199 | self.set_channel_data(channel_name, data, compression) 200 | if conversion is not None: 201 | self[channel_name]['conversion'] = {} 202 | self[channel_name]['conversion']['type'] = conversion['cc_type'] 203 | self[channel_name]['conversion']['parameters'] = {} 204 | if self.MDFVersionNumber < 400: # mdf3 205 | if 'conversion' in conversion: 206 | self[channel_name]['conversion']['parameters'] = \ 207 | conversion['conversion'] 208 | if conversion['cc_type'] == 0 and \ 209 | 'P2' in self[channel_name]['conversion']['parameters'] and \ 210 | (self[channel_name]['conversion']['parameters']['P2'] == 1.0 and 211 | self[channel_name]['conversion']['parameters']['P1'] in (0.0, -0.0)): 212 | self[channel_name].pop('conversion') 213 | else: # mdf4 214 | if 'cc_val' in conversion: 215 | self[channel_name]['conversion']['parameters']['cc_val'] = \ 216 | conversion['cc_val'] 217 | if 'cc_ref' in conversion: 218 | self[channel_name]['conversion']['parameters']['cc_ref'] = \ 219 | conversion['cc_ref'] 220 | if info is not None: # axis from CABlock 221 | ca_block = info 222 | axis = [] 223 | while 'CABlock' in ca_block: 224 | ca_block = ca_block['CABlock'] 225 | if 'ca_axis_value' in ca_block: 226 | if type(ca_block['ca_dim_size']) is list: 227 | index = 0 228 | for ndim in ca_block['ca_dim_size']: 229 | axis.append(tuple(ca_block['ca_axis_value'][index:index+ndim])) 230 | index += ndim 231 | else: 232 | axis = ca_block['ca_axis_value'] 233 | self[channel_name]['axis'] = axis 234 | if identifier is not None: 235 | self[channel_name]['id'] = identifier 236 | 237 | def remove_channel(self, channel_name): 238 | """ removes channel from mdf dict. 239 | 240 | Parameters 241 | ---------------- 242 | channel_name : str 243 | channel name 244 | 245 | Returns 246 | ------- 247 | value of mdf dict key=channel_name 248 | """ 249 | self.masterChannelList[self.get_channel_master(channel_name)].remove(channel_name) 250 | return self.pop(channel_name) 251 | 252 | def rename_channel(self, channel_name, new_name): 253 | """Modifies name of channel 254 | 255 | Parameters 256 | ---------------- 257 | channel_name : str 258 | channel name 259 | new_name : str 260 | new channel name 261 | """ 262 | if channel_name in self and new_name not in self: 263 | # add the new name to the same master 264 | self.masterChannelList[self.get_channel_master(channel_name)].append(new_name) 265 | # remove the old name 266 | self.masterChannelList[self.get_channel_master(channel_name)].remove(channel_name) 267 | self[new_name] = self.pop(channel_name) # copy the data 268 | if channel_name in self.masterChannelList: # it is a master channel 269 | self.masterChannelList[new_name] = self.masterChannelList.pop(channel_name) 270 | for channel in self.masterChannelList[new_name]: 271 | self.set_channel_master(channel, new_name) 272 | return self[new_name] 273 | else: 274 | return None 275 | 276 | def remove_channel_conversion(self, channel_name): 277 | """ removes conversion key from mdf channel dict. 278 | 279 | Parameters 280 | ---------------- 281 | channel_name : str 282 | channel name 283 | 284 | Returns 285 | ------- 286 | removed value from dict 287 | """ 288 | return self._remove_channel_field(channel_name, conversionField) 289 | 290 | def _remove_channel_field(self, channel_name, field): 291 | """general purpose function to remove key from channel dict in mdf 292 | 293 | Parameters 294 | ---------------- 295 | channel_name : str 296 | channel name 297 | field : str 298 | channel dict key 299 | 300 | Returns 301 | ------- 302 | removed value from dict 303 | """ 304 | if field in self.get_channel(channel_name): 305 | return self[channel_name].pop(field) 306 | 307 | def get_channel_unit(self, channel_name): 308 | """Returns channel unit string 309 | Implemented for a future integration of pint 310 | 311 | Parameters 312 | ---------------- 313 | channel_name : str 314 | channel name 315 | 316 | Returns 317 | ----------- 318 | str 319 | unit string description 320 | """ 321 | temp = self._get_channel_field(channel_name, field=unitField) 322 | if isinstance(temp, (dict, defaultdict)): 323 | try: 324 | return temp['Comment'] 325 | except KeyError: 326 | return '' 327 | return temp 328 | 329 | def get_channel_desc(self, channel_name): 330 | """Extract channel description information from mdf structure 331 | 332 | Parameters 333 | ---------------- 334 | channel_name : str 335 | channel name 336 | 337 | Returns 338 | ------- 339 | channel description string 340 | """ 341 | return self._get_channel_field(channel_name, field=descriptionField) 342 | 343 | def get_channel_master(self, channel_name): 344 | """Extract channel master name from mdf structure 345 | 346 | Parameters 347 | ---------------- 348 | channel_name : str 349 | channel name 350 | 351 | Returns 352 | ------- 353 | channel master name string 354 | """ 355 | return self._get_channel_field(channel_name, field=masterField) 356 | 357 | def get_channel_master_type(self, channel_name): 358 | """Extract channel master type information from mdf structure 359 | 360 | Parameters 361 | ---------------- 362 | channel_name : str 363 | channel name 364 | 365 | Returns 366 | ------- 367 | channel mater type integer : 0=None, 1=Time, 2=Angle, 3=Distance, 4=index 368 | """ 369 | return self._get_channel_field(channel_name, field=masterTypeField) 370 | 371 | def get_channel_conversion(self, channel_name): 372 | """Extract channel conversion dict from mdf structure 373 | 374 | Parameters 375 | ---------------- 376 | channel_name : str 377 | channel name 378 | 379 | Returns 380 | ------- 381 | channel conversion dict 382 | """ 383 | return self._get_channel_field(channel_name, field=conversionField) 384 | 385 | def get_invalid_bit(self, channel_name): 386 | return self._get_channel_field(channel_name, field=invalidPosField) 387 | 388 | def get_invalid_channel(self, channel_name): 389 | return self._get_channel_field(channel_name, field=invalidChannel) 390 | 391 | def get_channel(self, channel_name): 392 | """Extract channel dict from mdf structure 393 | 394 | Parameters 395 | ---------------- 396 | channel_name : str 397 | channel name 398 | 399 | Returns 400 | ------- 401 | channel dictionnary containing data, description, unit, etc. 402 | """ 403 | try: 404 | return self[channel_name] 405 | except KeyError: 406 | return None 407 | 408 | def _get_channel_field(self, channel_name, field=None): 409 | """General purpose function to extract channel dict key value from mdf class 410 | 411 | Parameters 412 | ---------------- 413 | channel_name : str 414 | channel name 415 | field : str 416 | channel dict key 417 | 418 | Returns 419 | ------- 420 | channel description string 421 | """ 422 | channel = self.get_channel(channel_name) 423 | if channel is not None: 424 | try: 425 | return channel[field] 426 | except KeyError: 427 | return '' 428 | else: 429 | return None 430 | 431 | def set_channel_unit(self, channel_name, unit): 432 | """Modifies unit of channel 433 | 434 | Parameters 435 | ---------------- 436 | channel_name : str 437 | channel name 438 | unit : str 439 | channel unit 440 | """ 441 | self._set_channel(channel_name, unit, field=unitField) 442 | 443 | def set_channel_data(self, channel_name, data, compression=False): 444 | """Modifies data of channel 445 | 446 | Parameters 447 | ---------------- 448 | channel_name : str 449 | channel name 450 | data : numpy array 451 | channel data 452 | compression : bool or str 453 | trigger for data compression 454 | """ 455 | if compression and CompressionPossible: 456 | temp = CompressedData() 457 | temp.compression(data) 458 | self._set_channel(channel_name, temp, field=dataField) 459 | else: 460 | self._set_channel(channel_name, data, field=dataField) 461 | 462 | def set_channel_desc(self, channel_name, desc): 463 | """Modifies description of channel 464 | 465 | Parameters 466 | ---------------- 467 | channel_name : str 468 | channel name 469 | desc : str 470 | channel description 471 | """ 472 | self._set_channel(channel_name, desc, field=descriptionField) 473 | 474 | def set_channel_master(self, channel_name, master): 475 | """Modifies channel master name 476 | 477 | Parameters 478 | ---------------- 479 | channel_name : str 480 | channel name 481 | master : str 482 | master channel name 483 | """ 484 | self._set_channel(channel_name, master, field=masterField) 485 | 486 | def set_channel_master_type(self, channel_name, master_type): 487 | """Modifies master channel type 488 | 489 | Parameters 490 | ---------------- 491 | channel_name : str 492 | channel name 493 | master_type : int 494 | master channel type 495 | """ 496 | self._set_channel(channel_name, master_type, field=masterTypeField) 497 | 498 | def set_channel_conversion(self, channel_name, conversion): 499 | """Modifies conversion dict of channel 500 | 501 | Parameters 502 | ---------------- 503 | channel_name : str 504 | channel name 505 | conversion : dict 506 | conversion dictionary 507 | """ 508 | self._set_channel(channel_name, conversion, field=conversionField) 509 | 510 | def set_channel_attachment(self, channel_name, attachment): 511 | """Modifies channel attachment 512 | 513 | Parameters 514 | ---------------- 515 | channel_name : str 516 | channel name 517 | attachment 518 | channel attachment 519 | """ 520 | self._set_channel(channel_name, attachment, field=attachmentField) 521 | 522 | def set_invalid_bit(self, channel_name, bit_position): 523 | """returns the invalid bit position of channel 524 | 525 | Parameters 526 | ---------------- 527 | channel_name : str 528 | channel name 529 | bit_position 530 | invalid bit position of channel within invalid channel bytes 531 | Returns 532 | ------- 533 | bit position 534 | """ 535 | self[channel_name][invalidPosField] = bit_position 536 | 537 | def set_invalid_channel(self, channel_name, invalid_channel): 538 | self[channel_name][invalidChannel] = invalid_channel 539 | 540 | def _set_channel(self, channel_name, item, field=None): 541 | """General purpose method to modify channel values 542 | 543 | Parameters 544 | ---------------- 545 | channel_name : str 546 | channel name 547 | item 548 | new replacing item 549 | field : str 550 | channel dict key of item 551 | """ 552 | try: 553 | self[channel_name][field] = item 554 | except KeyError: 555 | warn('Channel {} not in dictionary'.format(channel_name)) 556 | 557 | def _channel_in_mdf(self, channel_name): 558 | """Efficiently assess if channel is already in mdf 559 | 560 | Parameters 561 | ---------------- 562 | channel_name : str 563 | channel name 564 | 565 | Returns 566 | ------- 567 | bool 568 | """ 569 | return channel_name in self.masterChannelList[masterField] or channel_name in self.masterChannelList 570 | 571 | def add_metadata(self, author='', organisation='', project='', 572 | subject='', comment='', time=''): 573 | """adds basic metadata to mdf class 574 | 575 | Parameters 576 | ---------------- 577 | author : str 578 | author of file 579 | organisation : str 580 | organisation of author 581 | project : str 582 | subject : str 583 | comment : str 584 | time : float (epoch) 585 | 586 | Notes 587 | ===== 588 | All fields are optional, default being empty string 589 | """ 590 | self.fileMetadata['author'] = author 591 | self.fileMetadata['organisation'] = organisation 592 | self.fileMetadata['project'] = project 593 | self.fileMetadata['subject'] = subject 594 | self.fileMetadata['comment'] = comment 595 | self.fileMetadata['time'] = time 596 | 597 | def __str__(self): 598 | """representation a mdf_skeleton class data structure 599 | 600 | Returns 601 | ------------ 602 | string of mdf class ordered as below 603 | "master_channel_name 604 | channel_name description 605 | numpy_array unit" 606 | """ 607 | output = list() 608 | if self.fileName is not None: 609 | output.append('file name : {}\n'.format(self.fileName)) 610 | else: 611 | output.append('') 612 | for m in self.fileMetadata: 613 | if self.fileMetadata[m] is not None: 614 | output.append('{} : {}\n'.format(m, self.fileMetadata[m])) 615 | if not self._pandasframe: 616 | output.append('\nchannels listed by data groups:\n') 617 | for d in self.masterChannelList: 618 | if d is not None: 619 | output.append('{}\n'.format(d)) 620 | for c in self.masterChannelList[d]: 621 | output.append(' {} : '.format(c)) 622 | desc = self.get_channel_desc(c) 623 | if desc is not None: 624 | try: 625 | output.append(str(desc)) 626 | except: 627 | pass 628 | output.append('\n ') 629 | data = self.get_channel_data(c) 630 | # not byte, impossible to represent 631 | if data.dtype.kind != 'V': 632 | output.append(array_repr(data[:], 633 | precision=3, suppress_small=True)) 634 | unit = self.get_channel_unit(c) 635 | if unit is not None: 636 | output.append(' {}\n'.format(unit)) 637 | return ''.join(output) 638 | else: 639 | set_option('max_rows', 3) 640 | set_option('expand_frame_repr', True) 641 | set_option('max_colwidth', 6) 642 | for master in self.masterGroups: 643 | output.append(master) 644 | output.append(str(self[master])) 645 | return ''.join(output) 646 | 647 | def copy(self): 648 | """copy a mdf class 649 | 650 | Returns 651 | ------------ 652 | mdf_skeleton: class instance 653 | copy of a mdf_skeleton class 654 | """ 655 | yop = MdfSkeleton() 656 | yop.multiProc = self.multiProc 657 | yop.fileName = self.fileName 658 | yop.masterChannelList = self.masterChannelList 659 | yop.fileMetadata = self.fileMetadata 660 | yop.MDFVersionNumber = self.MDFVersionNumber 661 | yop.filterChannelNames = self.filterChannelNames 662 | yop.convertTables = self.convertTables 663 | for channel in self: 664 | yop[channel] = self[channel] 665 | return yop 666 | 667 | 668 | def _open_mdf(file_name): 669 | """ Opens mdf, make a few checks and returns fid 670 | 671 | Parameters 672 | ----------- 673 | file_name : str 674 | filename string 675 | 676 | Returns 677 | -------- 678 | fid 679 | file identifier 680 | """ 681 | 682 | try: 683 | fid = open(file_name, 'rb') 684 | except IOError: 685 | raise Exception('Can not find file {}'.format(file_name)) 686 | zipfile = False 687 | # Check whether file is MDF file -- assumes that every MDF file starts 688 | # with the letters MDF 689 | if fid.read(3) not in ('MDF', b'MDF'): 690 | if is_zipfile(file_name): 691 | # this is .mfxz file, compressed zip file 692 | zipfile = True 693 | fid.close() 694 | zip_class = ZipFile(file_name, 'r') 695 | zip_name = zip_class.namelist()[0] # there should be only one file 696 | zip_name = zip_class.extract(zip_name) # locally extracts file 697 | fid = open(zip_name, 'rb') 698 | file_name = zip_name 699 | else: 700 | raise Exception('file {} is not an MDF file!'.format(file_name)) 701 | return (fid, file_name, zipfile) 702 | 703 | 704 | def _bits_to_bytes_aligned(n_bits, numeric=True): 705 | """ Converts number of bits into number of aligned bytes 706 | 707 | Parameters 708 | ------------- 709 | n_bits : int 710 | number of bits 711 | numeric: bool 712 | flag to indicate channel is numeric 713 | 714 | Returns 715 | ---------- 716 | number of equivalent aligned bytes 717 | """ 718 | if numeric: 719 | if n_bits == 0: 720 | n_bytes = 0 721 | elif n_bits <= 8: 722 | n_bytes = 1 723 | elif n_bits <= 16: 724 | n_bytes = 2 725 | elif n_bits <= 32: 726 | n_bytes = 4 727 | elif n_bits <= 64: 728 | n_bytes = 8 729 | else: 730 | warn('error converting bits into bytes for a numeric channel, too many bits') 731 | n_bytes = _bits_to_bytes_not_aligned(n_bits) 732 | else: 733 | n_bytes = _bits_to_bytes_not_aligned(n_bits) 734 | return n_bytes 735 | 736 | 737 | def _bits_to_bytes_not_aligned(n_bits): 738 | """ Converts number of bits into number of not aligned bytes 739 | 740 | Parameters 741 | ------------- 742 | n_bits : int 743 | number of bits 744 | 745 | Returns 746 | ---------- 747 | number of equivalent not aligned bytes 748 | """ 749 | n_bytes = n_bits // 8 750 | if not n_bits % 8 == 0: 751 | n_bytes += 1 752 | return n_bytes 753 | 754 | 755 | def _convert_name(channel_name): 756 | """ Check if channelName is valid python identifier 757 | to be removed with next function if no more need 758 | """ 759 | 760 | if channel_name.isidentifier(): 761 | return channel_name 762 | else: 763 | channel_identifier = str(_sanitize_identifier(channel_name)) 764 | # all characters of channel are not compliant to python 765 | if not channel_identifier: 766 | # generate random name for recarray 767 | channel_identifier = ''.join([choice(ascii_letters) for n in range(32)]) 768 | if channel_identifier in _notAllowedChannelNames: 769 | # limitation from recarray object attribute 770 | channel_identifier = ''.join([channel_identifier, '_']) 771 | return channel_identifier 772 | 773 | 774 | def _gen_valid_identifier(seq): 775 | # get an iterator 776 | itr = iter(seq) 777 | # pull characters until we get a legal one for first in identifier 778 | for ch in itr: 779 | if ch == '_' or ch.isalpha(): 780 | yield ch 781 | break 782 | elif ch.isdigit(): 783 | itr = chain(itr, ch) 784 | 785 | # pull remaining characters and yield legal ones for identifier 786 | for ch in itr: 787 | if ch == '_' or ch.isalpha() or ch.isdigit(): 788 | yield ch 789 | else: 790 | yield '_' 791 | 792 | 793 | def _sanitize_identifier(name): 794 | return ''.join(_gen_valid_identifier(name)) 795 | 796 | 797 | class CompressedData: 798 | __slots__ = ['data', 'dtype'] 799 | """ class to represent compressed data by blosc 800 | """ 801 | def __init__(self): 802 | """ data compression method 803 | 804 | Attributes 805 | ------------- 806 | data : numpy array compressed 807 | compressed data 808 | dtype : numpy dtype object 809 | numpy array dtype 810 | """ 811 | self.data = None 812 | self.dtype = None 813 | 814 | def compression(self, a): 815 | """ data compression method 816 | 817 | Parameters 818 | ------------- 819 | a : numpy array 820 | data to be compresses 821 | """ 822 | self.data = compress(a.tobytes()) 823 | self.dtype = a.dtype 824 | 825 | def decompression(self): 826 | """ data decompression 827 | 828 | Returns 829 | ------------- 830 | uncompressed numpy array 831 | """ 832 | return fromstring(decompress(self.data), dtype=self.dtype) 833 | 834 | def __str__(self): 835 | """ prints compressed_data object content 836 | """ 837 | return self.decompression() 838 | -------------------------------------------------------------------------------- /mdfreader/mdfinfo3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ Measured Data Format blocks parser for version 3.x 3 | 4 | Created on Thu Dec 9 12:57:28 2014 5 | 6 | :Author: `Aymeric Rateau `__ 7 | 8 | 9 | Dependencies 10 | ------------------- 11 | - Python >3.4 12 | - Numpy >1.14 13 | 14 | mdfinfo3 15 | -------------------------- 16 | """ 17 | from warnings import warn 18 | from numpy import sort, zeros 19 | from struct import unpack, Struct 20 | from .mdf import dataField, descriptionField, unitField, masterField, masterTypeField, idField 21 | 22 | cn_struct = Struct('<2sH5IH32s128s4H3d2IH') 23 | tx_struct = Struct('<2sH') 24 | cc_struct = Struct('<2s2H2d20s2H') 25 | dg_struct = Struct('<2sH4I2H') 26 | cg_struct = Struct('<2sH3I3HI') 27 | ce_struct = Struct('<2s2H') 28 | 29 | 30 | class Info3(dict): 31 | __slots__ = ['fileName', 'fid', 'filterChannelNames'] 32 | """ mdf file info class version 3.x 33 | MDFINFO is a class information about an MDF (Measure Data Format) file 34 | Based on following specification http://powertrainnvh.com/nvh/MDFspecificationv03.pdf 35 | 36 | Attributes 37 | -------------- 38 | filterChannelNames : bool, optional 39 | flag to filter long channel names including module names separated by a '.' 40 | fileName : str 41 | name of file 42 | fid : 43 | file identifier 44 | 45 | Notes 46 | -------- 47 | mdfinfo(FILENAME) contains a dict of structures, for 48 | each data group, containing key information about all channels in each 49 | group. FILENAME is a string that specifies the name of the MDF file. 50 | General dictionary structure is the following 51 | 52 | - mdfinfo['HDBlock'] header block 53 | - mdfinfo['DGBlock'][dataGroup] Data Group block 54 | - mdfinfo['CGBlock'][dataGroup][channelGroup] Channel Group block 55 | - mdfinfo['CNBlock'][dataGroup][channelGroup][channel] Channel block including text blocks for comment and identifier 56 | - mdfinfo['CCBlock'][dataGroup][channelGroup][channel] Channel conversion information 57 | """ 58 | 59 | def __init__(self, file_name=None, fid=None, filter_channel_names=False, minimal=0): 60 | """ info3 class constructor 61 | 62 | Parameters 63 | ---------------- 64 | file_name : str, optional 65 | name of file 66 | fid : float, optional 67 | file identifier 68 | filter_channel_names : bool, optional 69 | flag to filter long channel names including module names separated by a '.' 70 | minimal : int 71 | 0 will load every metadata 72 | 1 will load DG, CG, CN and CC 73 | 2 will load only DG 74 | 75 | Notes 76 | -------- 77 | If fileName is given it will read file blocks directly by calling method readinfo3 78 | """ 79 | self['IDBlock'] = dict() # Identifier Block 80 | self['HDBlock'] = dict() # Header Block 81 | self['DGBlock'] = dict() # Data Group Block 82 | self['CGBlock'] = dict() # Channel Group Block 83 | self['CNBlock'] = dict() # Channel Block 84 | self['CCBlock'] = dict() # Conversion block 85 | self['allChannelList'] = set() # all channels 86 | self['ChannelNamesByDG'] = dict() 87 | self.filterChannelNames = filter_channel_names 88 | self.fileName = file_name 89 | self.fid = None 90 | if file_name is not None and fid is None: 91 | try: 92 | self.fid = open(self.fileName, 'rb') 93 | except IOError: 94 | raise IOError('Can not find file ' + self.fileName) 95 | self.read_info3(self.fid, minimal) 96 | elif file_name is None and fid is not None: 97 | self.read_info3(fid, minimal) 98 | 99 | def read_info3(self, fid, minimal=0): 100 | """ read all file blocks except data 101 | 102 | Parameters 103 | ---------------- 104 | fid : float 105 | file identifier 106 | minimal : int 107 | 0 will load every metadata 108 | 1 will load DG, CG, CN and CC 109 | 2 will load only DG 110 | """ 111 | # reads IDBlock 112 | fid.seek(24) 113 | (self['IDBlock']['ByteOrder'], 114 | self['IDBlock']['FloatingPointFormat'], 115 | self['IDBlock']['id_ver'], 116 | self['IDBlock']['CodePageNumber']) = unpack('<4H', fid.read(8)) 117 | 118 | # Read header block (HDBlock) information 119 | # Read Header block info into structure, HD pointer at 64 as mentioned in specification 120 | self['HDBlock'] = read_hd_block(fid, 64, self['IDBlock']['id_ver']) 121 | 122 | # Read text block (TXBlock) information 123 | self['HDBlock']['TXBlock'] = read_tx_block(fid, self['HDBlock']['pointerToTXBlock']) 124 | 125 | # Read text block (PRBlock) information 126 | self['HDBlock']['PRBlock'] = read_tx_block(fid, self['HDBlock']['pointerToPRBlock']) 127 | 128 | # Read Data Group blocks (DGBlock) information 129 | # Get pointer to first Data Group block 130 | dg_pointer = self['HDBlock']['pointerToFirstDGBlock'] 131 | for dg in range(self['HDBlock']['numberOfDataGroups']): 132 | 133 | # Read data Data Group block info into structure 134 | self['DGBlock'][dg] = read_dg_block(fid, dg_pointer) 135 | # Get pointer to next Data Group block 136 | dg_pointer = self['DGBlock'][dg]['pointerToNextDGBlock'] 137 | self['ChannelNamesByDG'][dg] = set() 138 | if minimal < 2: 139 | self.read_cg_block(fid, dg, minimal) 140 | 141 | # Close the file 142 | fid.close() 143 | 144 | def read_cg_block(self, fid, dg, minimal=0): 145 | """ read all CG blocks and relying CN & CC 146 | 147 | Parameters 148 | ---------------- 149 | fid : float 150 | file identifier 151 | dg : int 152 | data group number 153 | minimal : int 154 | 0 will load every metadata 155 | 1 will load DG, CG, CN and CC 156 | 2 will load only DG 157 | """ 158 | # Read Channel Group block (CGBlock) information - offset set already 159 | 160 | # Read data Channel Group block info into structure 161 | cg_pointer = self['DGBlock'][dg]['pointerToNextCGBlock'] 162 | self['CGBlock'][dg] = dict() 163 | self['CNBlock'][dg] = dict() 164 | self['CCBlock'][dg] = dict() 165 | for cg in range(self['DGBlock'][dg]['numberOfChannelGroups']): 166 | self['CNBlock'][dg][cg] = dict() 167 | self['CCBlock'][dg][cg] = dict() 168 | self['CGBlock'][dg][cg] = read_cg_block(fid, cg_pointer) 169 | cg_pointer = self['CGBlock'][dg][cg]['pointerToNextCGBlock'] 170 | 171 | # Read data Text block info into structure 172 | self['CGBlock'][dg][cg]['TXBlock'] = \ 173 | read_tx_block(fid, self['CGBlock'][dg][cg]['pointerToChannelGroupCommentText']) 174 | 175 | # Get pointer to next first Channel block 176 | cn_pointer = self['CGBlock'][dg][cg]['pointerToFirstCNBlock'] 177 | 178 | # For each Channel 179 | for channel in range(self['CGBlock'][dg][cg]['numberOfChannels']): 180 | 181 | # Read data Channel block info into structure 182 | 183 | self['CNBlock'][dg][cg][channel] = read_cn_block(fid, cn_pointer) 184 | cn_pointer = self['CNBlock'][dg][cg][channel]['pointerToNextCNBlock'] 185 | 186 | # Read Channel text blocks (TXBlock) 187 | 188 | # Clean signal name 189 | short_signal_name = self['CNBlock'][dg][cg][channel]['signalName'] # short name of signal 190 | # keep original non unique channel name 191 | self['CNBlock'][dg][cg][channel]['orig_name'] = short_signal_name 192 | 193 | if self['CNBlock'][dg][cg][channel]['pointerToASAMNameBlock'] > 0: 194 | # long name of signal 195 | long_signal_name = \ 196 | read_tx_block(fid, self['CNBlock'][dg][cg][channel]['pointerToASAMNameBlock']) 197 | if len(long_signal_name) > len(short_signal_name): # long name should be used 198 | signal_name = long_signal_name 199 | else: 200 | signal_name = short_signal_name 201 | else: 202 | signal_name = short_signal_name 203 | signal_name = signal_name.split('\\') 204 | if len(signal_name) > 1: 205 | self['CNBlock'][dg][cg][channel]['deviceName'] = signal_name[1] 206 | signal_name = signal_name[0] 207 | if self.filterChannelNames: 208 | signal_name = signal_name.split('.')[-1] # filters channels modules 209 | 210 | if signal_name in self['ChannelNamesByDG'][dg]: # for unsorted data 211 | pointer = self['CNBlock'][dg][cg][channel]['pointerToCEBlock'] 212 | if pointer: 213 | temp = read_ce_block(fid, pointer) 214 | else: 215 | temp = dict() 216 | temp['tail'] = channel 217 | self['CNBlock'][dg][cg][channel]['signalName'] = \ 218 | '{0}_{1}_{2}_{3}'.format(signal_name, dg, cg, temp['tail']) 219 | elif signal_name in self['allChannelList']: 220 | # doublon name or master channel 221 | pointer = self['CNBlock'][dg][cg][channel]['pointerToCEBlock'] 222 | if pointer: 223 | temp = read_ce_block(fid, pointer) 224 | else: 225 | temp = dict() 226 | temp['tail'] = dg 227 | if '{0}_{1}'.format(signal_name, temp['tail']) not in self['allChannelList']: 228 | self['CNBlock'][dg][cg][channel]['signalName'] = '{0}_{1}'.format(signal_name, temp['tail']) 229 | else: 230 | self['CNBlock'][dg][cg][channel]['signalName'] = '{0}_{1}_{2}'.format(signal_name, 231 | dg, temp['tail']) 232 | else: 233 | self['CNBlock'][dg][cg][channel]['signalName'] = signal_name 234 | self['ChannelNamesByDG'][dg].add(self['CNBlock'][dg][cg][channel]['signalName']) 235 | self['allChannelList'].add(self['CNBlock'][dg][cg][channel]['signalName']) 236 | 237 | # Read channel description 238 | self['CNBlock'][dg][cg][channel]['ChannelCommentBlock'] = \ 239 | read_tx_block(fid, self['CNBlock'][dg][cg][channel]['pointerToChannelCommentBlock']) 240 | 241 | # Read data Text block info into structure 242 | self['CNBlock'][dg][cg][channel]['SignalIdentifierBlock'] = \ 243 | read_tx_block(fid, self['CNBlock'][dg][cg][channel]['pointerToSignalIdentifierBlock']) 244 | 245 | # Read Channel Conversion block (CCBlock) 246 | if self['CNBlock'][dg][cg][channel]['pointerToConversionFormula'] == 0: 247 | # If no conversion formula, set to 1:1 248 | self['CCBlock'][dg][cg][channel] = {} 249 | self['CCBlock'][dg][cg][channel]['cc_type'] = 65535 250 | else: # Otherwise get conversion formula, parameters and physical units 251 | # Read data Channel Conversion block info into structure 252 | self['CCBlock'][dg][cg][channel] = \ 253 | read_cc_block(fid, self['CNBlock'][dg][cg][channel]['pointerToConversionFormula']) 254 | 255 | # reorder channel blocks and related blocks based on first bit position 256 | # this reorder is meant to improve performance while parsing records using core.records.fromfile 257 | # as it will not use cn_byte_offset 258 | # first, calculate new mapping/order 259 | n_channel = len(self['CNBlock'][dg][cg]) 260 | Map = zeros(shape=len(self['CNBlock'][dg][cg]), dtype=[('index', 'u4'), ('first_bit', 'u4')]) 261 | for cn in range(n_channel): 262 | Map[cn] = (cn, self['CNBlock'][dg][cg][cn]['numberOfTheFirstBits']) 263 | ordered_map = sort(Map, order='first_bit') 264 | 265 | to_change_index = Map == ordered_map 266 | for cn in range(n_channel): 267 | if not to_change_index[cn]: 268 | # offset all indexes of indexes to be moved 269 | self['CNBlock'][dg][cg][cn + n_channel] = self['CNBlock'][dg][cg].pop(cn) 270 | self['CCBlock'][dg][cg][cn + n_channel] = self['CCBlock'][dg][cg].pop(cn) 271 | for cn in range(n_channel): 272 | if not to_change_index[cn]: 273 | # change to ordered index 274 | self['CNBlock'][dg][cg][cn] = self['CNBlock'][dg][cg].pop(ordered_map[cn][0] + n_channel) 275 | self['CCBlock'][dg][cg][cn] = self['CCBlock'][dg][cg].pop(ordered_map[cn][0] + n_channel) 276 | 277 | def clean_dg_info(self, dg): 278 | """ delete CN,CC and CG blocks related to data group 279 | 280 | Parameters 281 | ---------------- 282 | dg : int 283 | data group number 284 | """ 285 | try: 286 | self['CNBlock'][dg] = {} 287 | except KeyError: 288 | pass 289 | try: 290 | self['CCBlock'][dg] = {} 291 | except KeyError: 292 | pass 293 | try: 294 | self['CGBlock'][dg] = {} 295 | except KeyError: 296 | pass 297 | 298 | def list_channels3(self, file_name=None, fid=None): 299 | """ reads data, channel group and channel blocks to list channel names 300 | 301 | Attributes 302 | -------------- 303 | file_name : str 304 | file name 305 | 306 | Returns 307 | ----------- 308 | list of channel names 309 | """ 310 | # Read MDF file and extract its complete structure 311 | if file_name is not None: 312 | self.fileName = file_name 313 | # Open file 314 | if fid is None and file_name is not None: 315 | fid = open(self.fileName, 'rb') 316 | channel_name_list = [] 317 | 318 | # Read header block (HDBlock) information 319 | # Set file pointer to start of HDBlock 320 | hd_pointer = 64 321 | # Read Header block info into structure 322 | self['HDBlock'] = read_hd_block(fid, hd_pointer) 323 | 324 | # Read Data Group blocks (DGBlock) information 325 | # Get pointer to first Data Group block 326 | dg_pointer = self['HDBlock']['pointerToFirstDGBlock'] 327 | for dataGroup in range(self['HDBlock']['numberOfDataGroups']): 328 | 329 | # Read data Data Group block info into structure 330 | self['DGBlock'][dataGroup] = read_dg_block(fid, dg_pointer) 331 | # Get pointer to next Data Group block 332 | dg_pointer = self['DGBlock'][dataGroup]['pointerToNextDGBlock'] 333 | 334 | # Read Channel Group block (CGBlock) information - offset set already 335 | 336 | # Read data Channel Group block info into structure 337 | cg_pointer = self['DGBlock'][dataGroup]['pointerToNextCGBlock'] 338 | self['CGBlock'][dataGroup] = {} 339 | self['CNBlock'][dataGroup] = {} 340 | self['CCBlock'][dataGroup] = {} 341 | for channelGroup in range(self['DGBlock'][dataGroup]['numberOfChannelGroups']): 342 | self['CNBlock'][dataGroup][channelGroup] = {} 343 | self['CCBlock'][dataGroup][channelGroup] = {} 344 | self['CGBlock'][dataGroup][channelGroup] = read_cg_block(fid, cg_pointer) 345 | cg_pointer = self['CGBlock'][dataGroup][channelGroup]['pointerToNextCGBlock'] 346 | 347 | # Get pointer to next first Channel block 348 | cn_pointer = self['CGBlock'][dataGroup][channelGroup]['pointerToFirstCNBlock'] 349 | 350 | names_set = set() 351 | # For each Channel 352 | for channel in range(self['CGBlock'][dataGroup][channelGroup]['numberOfChannels']): 353 | 354 | # Read Channel block (CNBlock) information 355 | # self.numberOfChannels += 1 356 | # Read data Channel block info into structure 357 | self['CNBlock'][dataGroup][channelGroup][channel] = read_cn_block(fid, cn_pointer) 358 | cn_pointer = self['CNBlock'][dataGroup][channelGroup][channel]['pointerToNextCNBlock'] 359 | 360 | # Read Channel text blocks (TXBlock) 361 | 362 | # Clean signal name 363 | short_signal_name = self['CNBlock'][dataGroup][channelGroup][channel]['signalName'] 364 | cn_tx_pointer = self['CNBlock'][dataGroup][channelGroup][channel]['pointerToASAMNameBlock'] 365 | if cn_tx_pointer > 0: 366 | long_signal_name = read_tx_block(fid, cn_tx_pointer) # long name of signal 367 | if len(long_signal_name) > len(short_signal_name): # long name should be used 368 | signal_name = long_signal_name 369 | else: 370 | signal_name = short_signal_name 371 | else: 372 | signal_name = short_signal_name 373 | signal_name = signal_name.split('\\') 374 | signal_name = signal_name[0] 375 | if self.filterChannelNames: 376 | signal_name = signal_name.split('.')[-1] 377 | 378 | if signal_name in names_set: 379 | pointer = self['CNBlock'][dataGroup][channelGroup][channel]['pointerToCEBlock'] 380 | if pointer: 381 | temp = read_ce_block(fid, pointer) 382 | else: 383 | temp = dict() 384 | temp['tail'] = channel 385 | self['CNBlock'][dataGroup][channelGroup][channel]['signalName'] = \ 386 | '{0}_{1}'.format(signal_name, temp['tail']) 387 | warn('WARNING added number to duplicate signal name: {}'. 388 | format(self['CNBlock'][dataGroup][channelGroup][channel]['signalName'])) 389 | else: 390 | self['CNBlock'][dataGroup][channelGroup][channel]['signalName'] = signal_name 391 | names_set.add(signal_name) 392 | 393 | channel_name_list.append(signal_name) 394 | 395 | # CLose the file 396 | fid.close() 397 | return channel_name_list 398 | 399 | 400 | def read_hd_block(fid, pointer, version=0): 401 | """ header block reading """ 402 | if pointer != 0 and pointer is not None: 403 | temp = dict() 404 | fid.seek(pointer) 405 | if version < 320: 406 | (temp['BlockType'], 407 | temp['BlockSize'], 408 | temp['pointerToFirstDGBlock'], 409 | temp['pointerToTXBlock'], 410 | temp['pointerToPRBlock'], 411 | temp['numberOfDataGroups'], 412 | temp['Date'], 413 | temp['Time'], 414 | temp['Author'], 415 | temp['Organization'], 416 | temp['ProjectName'], 417 | temp['Subject']) = unpack('<2sH3IH10s8s32s32s32s32s', fid.read(164)) 418 | else: 419 | (temp['BlockType'], 420 | temp['BlockSize'], 421 | temp['pointerToFirstDGBlock'], 422 | temp['pointerToTXBlock'], 423 | temp['pointerToPRBlock'], 424 | temp['numberOfDataGroups'], 425 | temp['Date'], 426 | temp['Time'], 427 | temp['Author'], 428 | temp['Organization'], 429 | temp['ProjectName'], 430 | temp['Subject'], 431 | temp['TimeStamp'], 432 | temp['UTCTimeOffset'], 433 | temp['TimeQualityClass'], 434 | temp['TimeIdentification']) = unpack('<2sH3IH10s8s32s32s32s32sQhH32s', fid.read(208)) 435 | temp['TimeIdentification'] = temp['TimeIdentification'].rstrip(b'\x00').decode('latin1', 'replace') 436 | temp['Date'] = temp['Date'].rstrip(b'\x00').decode('latin1', 'replace') 437 | temp['Time'] = temp['Time'].rstrip(b'\x00').decode('latin1', 'replace') 438 | temp['Author'] = temp['Author'].rstrip(b'\x00').decode('latin1', 'replace') 439 | temp['Organization'] = temp['Organization'].rstrip(b'\x00').decode('latin1', 'replace') 440 | temp['ProjectName'] = temp['ProjectName'].rstrip(b'\x00').decode('latin1', 'replace') 441 | temp['Subject'] = temp['Subject'].rstrip(b'\x00').decode('latin1', 'replace') 442 | return temp 443 | else: 444 | return None 445 | 446 | 447 | def read_dg_block(fid, pointer): 448 | """ data group block reading """ 449 | if pointer != 0 and pointer is not None: 450 | temp = dict() 451 | fid.seek(pointer) 452 | (temp['BlockType'], 453 | temp['BlockSize'], 454 | temp['pointerToNextDGBlock'], 455 | temp['pointerToNextCGBlock'], 456 | temp['reserved'], 457 | temp['pointerToDataRecords'], 458 | temp['numberOfChannelGroups'], 459 | temp['numberOfRecordIDs']) = dg_struct.unpack(fid.read(24)) 460 | return temp 461 | else: 462 | return None 463 | 464 | 465 | def read_cg_block(fid, pointer): 466 | """ channel block reading """ 467 | if pointer != 0 and pointer is not None: 468 | temp = dict() 469 | fid.seek(pointer) 470 | (temp['BlockType'], 471 | temp['BlockSize'], 472 | temp['pointerToNextCGBlock'], 473 | temp['pointerToFirstCNBlock'], 474 | temp['pointerToChannelGroupCommentText'], 475 | temp['recordID'], 476 | temp['numberOfChannels'], 477 | temp['dataRecordSize'], 478 | temp['numberOfRecords']) = cg_struct.unpack(fid.read(26)) 479 | return temp 480 | else: 481 | return None 482 | 483 | 484 | def read_cn_block(fid, pointer): 485 | """ channel block reading """ 486 | if pointer != 0 and pointer is not None: 487 | temp = dict() 488 | fid.seek(pointer) 489 | (temp['BlockType'], 490 | temp['BlockSize'], 491 | temp['pointerToNextCNBlock'], 492 | temp['pointerToConversionFormula'], 493 | temp['pointerToCEBlock'], 494 | temp['pointerToCDBlock'], 495 | temp['pointerToChannelCommentBlock'], 496 | temp['channelType'], 497 | temp['signalName'], 498 | temp['signalDescription'], 499 | temp['numberOfTheFirstBits'], 500 | temp['numberOfBits'], 501 | temp['signalDataType'], 502 | temp['valueRangeKnown'], 503 | temp['valueRangeMinimum'], 504 | temp['valueRangeMaximum'], 505 | temp['rateVariableSampled'], 506 | temp['pointerToASAMNameBlock'], 507 | temp['pointerToSignalIdentifierBlock'], 508 | temp['ByteOffset']) = cn_struct.unpack(fid.read(228)) 509 | 510 | temp['signalName'] = temp['signalName'].rstrip(b'\x00').decode('latin1', 'replace') 511 | temp['signalDescription'] = temp['signalDescription'].rstrip(b'\x00').decode('latin1', 'replace') 512 | return temp 513 | else: 514 | return None 515 | 516 | 517 | def read_cc_block(fid, pointer): 518 | """ channel conversion block reading """ 519 | if pointer != 0 and pointer is not None: 520 | temp = dict() 521 | fid.seek(pointer) 522 | (temp['BlockType'], 523 | temp['BlockSize'], 524 | temp['valueRangeKnown'], 525 | temp['valueRangeMinimum'], 526 | temp['valueRangeMaximum'], 527 | temp['physicalUnit'], 528 | temp['cc_type'], 529 | temp['numberOfValuePairs']) = cc_struct.unpack(fid.read(46)) 530 | temp['physicalUnit'] = temp['physicalUnit'].rstrip(b'\x00').decode('latin1', 'replace') 531 | temp['conversion'] = dict() 532 | 533 | if temp['cc_type'] == 0: # Parametric, Linear: Physical = Integer*P2 + P1 534 | (temp['conversion']['P1'], 535 | temp['conversion']['P2']) = unpack('2d', fid.read(16)) 536 | 537 | elif temp['cc_type'] in (1, 2): # Table look up with or without interpolation 538 | for pair in range(temp['numberOfValuePairs']): 539 | temp['conversion'][pair] = dict() 540 | (temp['conversion'][pair]['int'], 541 | temp['conversion'][pair]['phys']) = unpack('2d', fid.read(16)) 542 | 543 | elif temp['cc_type'] in (6, 9): # Polynomial or rational 544 | (temp['conversion']['P1'], 545 | temp['conversion']['P2'], 546 | temp['conversion']['P3'], 547 | temp['conversion']['P4'], 548 | temp['conversion']['P5'], 549 | temp['conversion']['P6']) = unpack('6d', fid.read(48)) 550 | 551 | elif temp['cc_type'] in (7, 8): # Exponential or logarithmic 552 | (temp['conversion']['P1'], 553 | temp['conversion']['P2'], 554 | temp['conversion']['P3'], 555 | temp['conversion']['P4'], 556 | temp['conversion']['P5'], 557 | temp['conversion']['P6'], 558 | temp['conversion']['P7']) = unpack('7d', fid.read(56)) 559 | 560 | elif temp['cc_type'] == 10: # Text Formula 561 | temp['conversion']['textFormula'] = \ 562 | unpack('256s', fid.read(256))[0].rstrip(b'\x00').decode('latin1', 'replace') 563 | 564 | elif temp['cc_type'] == 11: # ASAM-MCD2 text table 565 | for pair in range(temp['numberOfValuePairs']): 566 | temp['conversion'][pair] = dict() 567 | (temp['conversion'][pair]['int'], 568 | temp['conversion'][pair]['text']) = unpack('d32s', fid.read(40)) 569 | temp['conversion'][pair]['text'] = \ 570 | temp['conversion'][pair]['text'].rstrip(b'\x00').decode('latin1', 'replace') 571 | 572 | elif temp['cc_type'] == 12: # Text range table 573 | for pair in range(temp['numberOfValuePairs']): 574 | temp['conversion'][pair] = dict() 575 | (temp['conversion'][pair]['lowerRange'], 576 | temp['conversion'][pair]['upperRange'], 577 | temp['conversion'][pair]['pointerToTXBlock']) = unpack('2dI', fid.read(20)) 578 | for pair in range(temp['numberOfValuePairs']): # get text range 579 | # Read corresponding text 580 | try: 581 | temp['conversion'][pair]['Textrange'] = read_tx_block(fid, temp['conversion'][pair]['pointerToTXBlock']) 582 | except: 583 | temp['conversion'][pair]['Textrange'] = "" 584 | 585 | elif temp['cc_type'] == 65535: # No conversion int=phys 586 | pass 587 | else: 588 | # Give warning that conversion formula is not being 589 | # made 590 | warn('Conversion Formula type (cc_type={})not supported.'.format(temp['cc_type'])) 591 | 592 | return temp 593 | else: 594 | return None 595 | 596 | 597 | def read_tx_block(fid, pointer): 598 | """ reads text block """ 599 | if pointer != 0 and pointer is not None: 600 | fid.seek(pointer) 601 | (block_type, 602 | block_size) = tx_struct.unpack(fid.read(4)) 603 | text = unpack('{}s'.format(block_size - 4), fid.read(block_size - 4))[0] 604 | 605 | return text.rstrip(b'\x00').decode('latin1', 'replace') 606 | 607 | 608 | def read_ce_block(fid, pointer): 609 | """ reads source block """ 610 | if pointer != 0 and pointer is not None: 611 | fid.seek(pointer) 612 | temp = dict() 613 | (block_type, 614 | block_size, 615 | temp['extension_type']) = ce_struct.unpack(fid.read(6)) 616 | if temp['extension_type'] == 2: 617 | (temp['n_module'], 618 | temp['address'], 619 | temp['description'], 620 | temp['ECU_id']) = unpack('HI80s32s', fid.read(120)) 621 | temp['ECU_id'] = temp['ECU_id'].rstrip(b'\x00').decode('latin1', 'replace') 622 | temp['description'] = temp['description'].rstrip(b'\x00').decode('latin1', 'replace') 623 | temp['tail'] = temp['ECU_id'] 624 | elif temp['extension_type'] == 19: 625 | (temp['CAN_id'], 626 | temp['CAN_channel_id'], 627 | temp['message'], 628 | temp['sender']) = unpack('2I36s36s', fid.read(80)) 629 | temp['message'] = temp['message'].rstrip(b'\x00').decode('latin1', 'replace') 630 | temp['sender'] = temp['sender'].rstrip(b'\x00').decode('latin1', 'replace') 631 | temp['tail'] = temp['message'] 632 | else: 633 | return None 634 | return temp 635 | 636 | 637 | def _generate_dummy_mdf3(info, channel_list): 638 | """ computes MasterChannelList and mdf dummy dict from an info object 639 | 640 | Parameters 641 | ---------------- 642 | info : info object 643 | information structure of file 644 | 645 | channel_list : list of str 646 | list of channel names 647 | 648 | Returns 649 | ----------- 650 | a dict which keys are master channels in files with values a list of related channels of the raster 651 | """ 652 | master_channel_list = {} 653 | all_channel_list = set() 654 | mdf_dict = {} 655 | for dg in info['DGBlock']: 656 | master = '' 657 | master_type = 0 658 | channel_names_by_dg = set() 659 | for cg in info['CGBlock'][dg]: 660 | channel_name_list = [] 661 | for cn in info['CNBlock'][dg][cg]: 662 | name = info['CNBlock'][dg][cg][cn]['signalName'] 663 | if name in channel_names_by_dg: 664 | name = '{0}_{1}_{2}_{3}'.format(name, dg, cg, cn) 665 | elif name in all_channel_list: 666 | name = ''.join([name, '_{}'.format(dg)]) 667 | if channel_list is None or name in channel_list: 668 | channel_name_list.append(name) 669 | all_channel_list.add(name) 670 | channel_names_by_dg.add(name) 671 | # create mdf channel 672 | mdf_dict[name] = {} 673 | mdf_dict[name][dataField] = None 674 | if 'signalDescription' in info['CNBlock'][dg][cg][cn]: 675 | mdf_dict[name][descriptionField] = \ 676 | info['CNBlock'][dg][cg][cn]['signalDescription'] 677 | else: 678 | mdf_dict[name][descriptionField] = '' 679 | if 'physicalUnit' in info['CCBlock'][dg][cg][cn]: 680 | mdf_dict[name][unitField] = info['CCBlock'][dg][cg][cn]['physicalUnit'] 681 | else: 682 | mdf_dict[name][unitField] = '' 683 | mdf_dict[name][masterField] = 0 # default is time 684 | mdf_dict[name][masterTypeField] = None 685 | mdf_dict[name][idField] = (dg, cg, cn) 686 | if info['CNBlock'][dg][cg][cn]['channelType']: # master channel of cg 687 | master = name 688 | master_type = info['CNBlock'][dg][cg][cn]['channelType'] 689 | for chan in channel_name_list: 690 | mdf_dict[chan][masterField] = master 691 | mdf_dict[chan][masterTypeField] = master_type 692 | master_channel_list[master] = channel_name_list 693 | return (master_channel_list, mdf_dict) 694 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------