diff --git a/.ci_support/linux_64_numpy1.18python3.8.____cpython.yaml b/.ci_support/linux_64_numpy1.18python3.8.____cpython.yaml index 93f754153ed..44b7c87543e 100644 --- a/.ci_support/linux_64_numpy1.18python3.8.____cpython.yaml +++ b/.ci_support/linux_64_numpy1.18python3.8.____cpython.yaml @@ -20,6 +20,8 @@ docker_image: - quay.io/condaforge/linux-anvil-comp7 fftw: - '3' +fmt: +- '8' gmp: - '6' gsl: @@ -44,6 +46,8 @@ pin_run_as_build: max_pin: x.x qt: max_pin: x.x + spdlog: + max_pin: x.x zeromq: max_pin: x.x pybind11_abi: @@ -54,6 +58,8 @@ qt: - '5.12' soapysdr: - '0.8' +spdlog: +- '1.8' target_platform: - linux-64 uhd: diff --git a/.ci_support/osx_64_numpy1.18python3.8.____cpython.yaml b/.ci_support/osx_64_numpy1.18python3.8.____cpython.yaml index 5713d1df527..353a7d7d72a 100644 --- a/.ci_support/osx_64_numpy1.18python3.8.____cpython.yaml +++ b/.ci_support/osx_64_numpy1.18python3.8.____cpython.yaml @@ -18,6 +18,8 @@ cxx_compiler_version: - '11' fftw: - '3' +fmt: +- '8' gmp: - '6' gsl: @@ -42,6 +44,8 @@ pin_run_as_build: max_pin: x.x qt: max_pin: x.x + spdlog: + max_pin: x.x zeromq: max_pin: x.x pybind11_abi: @@ -52,6 +56,8 @@ qt: - '5.12' soapysdr: - '0.8' +spdlog: +- '1.8' target_platform: - osx-64 uhd: diff --git a/.ci_support/win_64_numpy1.18python3.8.____cpython.yaml b/.ci_support/win_64_numpy1.18python3.8.____cpython.yaml index 9aae25a37b7..4909ba07d98 100644 --- a/.ci_support/win_64_numpy1.18python3.8.____cpython.yaml +++ b/.ci_support/win_64_numpy1.18python3.8.____cpython.yaml @@ -10,6 +10,8 @@ cxx_compiler: - vs2017 fftw: - '3' +fmt: +- '8' gsl: - '2.6' libiio: @@ -26,6 +28,8 @@ pin_run_as_build: max_pin: x.x qt: max_pin: x.x + spdlog: + max_pin: x.x zeromq: max_pin: x.x.x pybind11_abi: @@ -36,6 +40,8 @@ qt: - '5.12' soapysdr: - '0.8' +spdlog: +- '1.8' target_platform: - win-64 uhd: diff --git a/.github/workflows/make-test.yml b/.github/workflows/make-test.yml index 1c93c19e20b..98c1e2c21e4 100644 --- a/.github/workflows/make-test.yml +++ b/.github/workflows/make-test.yml @@ -19,6 +19,14 @@ jobs: source: '.' exclude: './volk' extensions: 'h,hpp,cpp,cc,cc.in' + check-python-formatting: + name: Check Python Formatting + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: quentinguidee/pep8-action@v1 + with: + arguments: '--max-line-length=120 --ignore E265,E266,E402,E501,E704,E712,E713,E714,E711,E722,E741,W504,W605 --exclude *.yml.py' # Doxygen gets built separately. It has a lot of output and its own weirdness. doxygen: name: Doxygen @@ -36,7 +44,7 @@ jobs: run: 'cd /build && make doxygen_target' linux-docker: # All of these shall depend on the formatting check (needs: check-formatting) - needs: check-formatting + needs: [check-formatting, check-python-formatting] runs-on: ubuntu-latest # The GH default is 360 minutes (it's also the max as of Feb-2021). However # we should fail sooner. The only reason to exceed this time is if a test diff --git a/.packaging/conda_recipe/build.sh b/.packaging/conda_recipe/build.sh index d7ec9a4da9b..5eacf930ace 100644 --- a/.packaging/conda_recipe/build.sh +++ b/.packaging/conda_recipe/build.sh @@ -19,7 +19,6 @@ cmake --build . --config Release --target install if [[ $target_platform == linux* ]] ; then SKIP_TESTS=( - qa_agc qa_cpp_py_binding qa_cpp_py_binding_set qa_ctrlport_probes @@ -30,7 +29,6 @@ if [[ $target_platform == linux* ]] ; then else SKIP_TESTS=( qa_add_system_time - qa_agc qa_block_gateway qa_cpp_py_binding qa_cpp_py_binding_set @@ -42,6 +40,8 @@ else qa_header_payload_demux qa_hier_block2 qa_hier_block2_message_connections + qa_message_debug + qa_message_strobe qa_python_message_passing qa_rotator_cc qa_tcp_server_sink diff --git a/.packaging/conda_recipe/meta.yaml b/.packaging/conda_recipe/meta.yaml index 156789488c9..367ab14c1f4 100644 --- a/.packaging/conda_recipe/meta.yaml +++ b/.packaging/conda_recipe/meta.yaml @@ -58,13 +58,13 @@ requirements: # use codec2 1.0.0 because 1.0.1 has header which fails on Windows (complex.h) - codec2 1.0.0* - fftw + - fmt - gmp # [not win] - gsl # blas needed to link with gsl - libcblas # [linux] - libsndfile - libthrift # [not win] - - log4cpp - mako - mpir # [win] - numpy @@ -72,6 +72,7 @@ requirements: - pybind11 - pybind11-abi - python + - spdlog - thrift # [not win] - volk # gnuradio.audio @@ -88,7 +89,7 @@ requirements: # gnuradio.qtgui - pyqt - qt - - qwt <6.2 + - qwt # gnuradio.soapy - soapysdr # gnuradio.uhd diff --git a/.scripts/build_steps.sh b/.scripts/build_steps.sh index 3df2ed0cf5c..fd1a632464f 100755 --- a/.scripts/build_steps.sh +++ b/.scripts/build_steps.sh @@ -47,6 +47,7 @@ source run_conda_forge_build_setup make_build_number "${FEEDSTOCK_ROOT}" "${RECIPE_ROOT}" "${CONFIG_FILE}" + ( endgroup "Configuring conda" ) 2> /dev/null if [[ "${BUILD_WITH_CONDA_DEBUG:-0}" == 1 ]]; then diff --git a/.scripts/run_docker_build.sh b/.scripts/run_docker_build.sh index ffd4d975072..f4be220441a 100755 --- a/.scripts/run_docker_build.sh +++ b/.scripts/run_docker_build.sh @@ -76,6 +76,7 @@ fi export UPLOAD_PACKAGES="${UPLOAD_PACKAGES:-True}" export IS_PR_BUILD="${IS_PR_BUILD:-False}" +docker pull "${DOCKER_IMAGE}" docker run ${DOCKER_RUN_ARGS} \ -v "${RECIPE_ROOT}":/home/conda/recipe_root:rw,z,delegated \ -v "${FEEDSTOCK_ROOT}":/home/conda/feedstock_root:rw,z,delegated \ @@ -91,9 +92,9 @@ docker run ${DOCKER_RUN_ARGS} \ -e BUILD_WITH_CONDA_DEBUG \ -e BUILD_OUTPUT_ID \ -e BINSTAR_TOKEN \ - $DOCKER_IMAGE \ + "${DOCKER_IMAGE}" \ bash \ - /home/conda/feedstock_root/${PROVIDER_DIR}/build_steps.sh + "/home/conda/feedstock_root/${PROVIDER_DIR}/build_steps.sh" # verify that the end of the script was reached test -f "$DONE_CANARY" diff --git a/CMakeLists.txt b/CMakeLists.txt index 830b27f6806..de3aa940983 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -380,11 +380,6 @@ else() endif() endif() -######################################################################## -# Configure Log4CPP -######################################################################## -find_package(LOG4CPP REQUIRED) - ######################################################################## # Setup Native Capabilities Flag ######################################################################## diff --git a/cmake/Modules/FindLOG4CPP.cmake b/cmake/Modules/FindLOG4CPP.cmake deleted file mode 100644 index 61d58134a01..00000000000 --- a/cmake/Modules/FindLOG4CPP.cmake +++ /dev/null @@ -1,62 +0,0 @@ -# - Find Log4cpp -# Find the native LOG4CPP includes and library -# -# LOG4CPP_INCLUDE_DIR - where to find LOG4CPP.h, etc. -# LOG4CPP_LIBRARIES - List of libraries when using LOG4CPP. -# LOG4CPP_FOUND - True if LOG4CPP found. - - -if (LOG4CPP_INCLUDE_DIR) - # Already in cache, be silent - set(LOG4CPP_FIND_QUIETLY TRUE) -endif () - -find_path(LOG4CPP_INCLUDE_DIR log4cpp/Category.hh - /usr/include - /usr/local/include - /opt/local/include -) - -set(LOG4CPP_NAMES log4cpp) -find_library(LOG4CPP_LIBRARY - NAMES ${LOG4CPP_NAMES} - PATHS /usr/lib /usr/lib64 /usr/local/lib /usr/local/lib64 /opt/local/lib /opt/local/lib64 -) - - -if (LOG4CPP_INCLUDE_DIR AND LOG4CPP_LIBRARY) - set(LOG4CPP_FOUND TRUE) - set(LOG4CPP_LIBRARIES ${LOG4CPP_LIBRARY} CACHE INTERNAL "" FORCE) - set(LOG4CPP_INCLUDE_DIRS ${LOG4CPP_INCLUDE_DIR} CACHE INTERNAL "" FORCE) -else () - set(LOG4CPP_FOUND FALSE CACHE INTERNAL "" FORCE) - set(LOG4CPP_LIBRARY "" CACHE INTERNAL "" FORCE) - set(LOG4CPP_LIBRARIES "" CACHE INTERNAL "" FORCE) - set(LOG4CPP_INCLUDE_DIR "" CACHE INTERNAL "" FORCE) - set(LOG4CPP_INCLUDE_DIRS "" CACHE INTERNAL "" FORCE) -endif () - -if (LOG4CPP_FOUND) - if (NOT LOG4CPP_FIND_QUIETLY) - message(STATUS "Found LOG4CPP: ${LOG4CPP_LIBRARIES}") - endif () -else () - if (LOG4CPP_FIND_REQUIRED) - message(STATUS "Looked for LOG4CPP libraries named ${LOG4CPP_NAMES}.") - message(FATAL_ERROR "Could NOT find LOG4CPP library") - endif () -endif () - - -if (LOG4CPP_FOUND AND NOT TARGET Log4Cpp::log4cpp) - add_library(Log4Cpp::log4cpp INTERFACE IMPORTED) - set_target_properties(Log4Cpp::log4cpp PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES "${LOG4CPP_INCLUDE_DIRS}" - INTERFACE_LINK_LIBRARIES "${LOG4CPP_LIBRARIES}" - ) -endif() - -mark_as_advanced( - LOG4CPP_LIBRARIES - LOG4CPP_INCLUDE_DIRS -) diff --git a/cmake/Modules/GnuradioConfig.cmake.in b/cmake/Modules/GnuradioConfig.cmake.in index 463c02262ff..04cb5e350f4 100644 --- a/cmake/Modules/GnuradioConfig.cmake.in +++ b/cmake/Modules/GnuradioConfig.cmake.in @@ -10,7 +10,7 @@ include(CMakeFindDependencyMacro) # Allows us to use all .cmake files in this directory list(INSERT CMAKE_MODULE_PATH 0 "${CMAKE_CURRENT_LIST_DIR}") -find_dependency(LOG4CPP) +find_dependency(spdlog) find_dependency(MPLIB) set(BOOST_REQUIRED_COMPONENTS @@ -97,7 +97,11 @@ set(GR_COMPONENTS ) foreach(target ${GR_COMPONENTS}) - if (${target} IN_LIST Gnuradio_FIND_COMPONENTS) - include("${CMAKE_CURRENT_LIST_DIR}/gnuradio-${target}Config.cmake") + set(GR_COMPONENT_INCLUDE_FILE + "${CMAKE_CURRENT_LIST_DIR}/gnuradio-${target}Config.cmake") + if(${target} IN_LIST Gnuradio_FIND_COMPONENTS + AND (EXISTS ${GR_COMPONENT_INCLUDE_FILE} + OR "${Gnuradio_FIND_REQUIRED_${target}}")) + include(${GR_COMPONENT_INCLUDE_FILE}) endif() endforeach(target) diff --git a/cmake/Modules/GrTest.cmake b/cmake/Modules/GrTest.cmake index 8a98478974c..7be65492ee0 100644 --- a/cmake/Modules/GrTest.cmake +++ b/cmake/Modules/GrTest.cmake @@ -61,6 +61,10 @@ function(GR_ADD_TEST test_name) # Keep the original path conversion for pypath - the above commented line breaks CI tests file(TO_NATIVE_PATH "${GR_TEST_PYTHON_DIRS}" pypath) #ok to use on dir list? + # add test module directory to PYTHONPATH to allow CTest to find QA test modules. + # We add it to the beginning of the list to use locally-built modules before installed ones. + list(INSERT pypath 0 "${CMAKE_BINARY_DIR}/test_modules") + set(environs "VOLK_GENERIC=1" "GR_DONT_LOAD_PREFS=1" "srcdir=${srcdir}" "GR_CONF_CONTROLPORT_ON=False") list(APPEND environs ${GR_TEST_ENVIRONS}) diff --git a/docs/doxygen/doxyxml/__init__.py b/docs/doxygen/doxyxml/__init__.py index d07ccb828bc..0aec639eb53 100644 --- a/docs/doxygen/doxyxml/__init__.py +++ b/docs/doxygen/doxyxml/__init__.py @@ -54,6 +54,7 @@ from .doxyindex import DoxyIndex, DoxyFunction, DoxyParam, DoxyClass, DoxyFile, DoxyNamespace, DoxyGroup, DoxyFriend, DoxyOther + def _test(): import os this_dir = os.path.dirname(globals()['__file__']) @@ -65,6 +66,6 @@ def _test(): import doctest return doctest.testmod() + if __name__ == "__main__": _test() - diff --git a/docs/doxygen/doxyxml/base.py b/docs/doxygen/doxyxml/base.py index 845cee92274..d3d68c701d9 100644 --- a/docs/doxygen/doxyxml/base.py +++ b/docs/doxygen/doxyxml/base.py @@ -83,8 +83,8 @@ def get_cls(self, mem): for cls in self.mem_classes: if cls.can_parse(mem): return cls - raise Exception(("Did not find a class for object '%s'." \ - % (mem.get_name()))) + raise Exception(("Did not find a class for object '%s'." + % (mem.get_name()))) def convert_mem(self, mem): try: diff --git a/docs/doxygen/doxyxml/doxyindex.py b/docs/doxygen/doxyxml/doxyindex.py index 5354830a637..1c75ed04581 100644 --- a/docs/doxygen/doxyxml/doxyindex.py +++ b/docs/doxygen/doxyxml/doxyindex.py @@ -17,6 +17,7 @@ from .base import Base from .text import description + class DoxyIndex(Base): """ Parses a doxygen xml directory. @@ -47,7 +48,6 @@ def _parse(self): class DoxyCompMem(Base): - kind = None def __init__(self, *args, **kwargs): @@ -83,9 +83,11 @@ def set_parameters(self, data): class DoxyCompound(DoxyCompMem): pass + class DoxyMember(DoxyCompMem): pass + class DoxyFunction(DoxyMember): __module__ = "gnuradio.utils.doxyxml" @@ -106,9 +108,11 @@ def _parse(self): self._data['params'].append(DoxyParam(prm)) brief_description = property(lambda self: self.data()['brief_description']) - detailed_description = property(lambda self: self.data()['detailed_description']) + detailed_description = property( + lambda self: self.data()['detailed_description']) params = property(lambda self: self.data()['params']) + Base.mem_classes.append(DoxyFunction) @@ -133,9 +137,11 @@ def description(self): return '\n\n'.join(descriptions) brief_description = property(lambda self: self.data()['brief_description']) - detailed_description = property(lambda self: self.data()['detailed_description']) + detailed_description = property( + lambda self: self.data()['detailed_description']) name = property(lambda self: self.data()['declname']) + class DoxyParameterItem(DoxyMember): """A different representation of a parameter in Doxygen.""" @@ -177,9 +183,11 @@ def _parse(self): self.process_memberdefs() brief_description = property(lambda self: self.data()['brief_description']) - detailed_description = property(lambda self: self.data()['detailed_description']) + detailed_description = property( + lambda self: self.data()['detailed_description']) params = property(lambda self: self.data()['params']) + Base.mem_classes.append(DoxyClass) @@ -200,7 +208,9 @@ def _parse(self): self.process_memberdefs() brief_description = property(lambda self: self.data()['brief_description']) - detailed_description = property(lambda self: self.data()['detailed_description']) + detailed_description = property( + lambda self: self.data()['detailed_description']) + Base.mem_classes.append(DoxyFile) @@ -221,6 +231,7 @@ def _parse(self): return self.process_memberdefs() + Base.mem_classes.append(DoxyNamespace) @@ -264,6 +275,7 @@ class DoxyFriend(DoxyMember): kind = 'friend' + Base.mem_classes.append(DoxyFriend) @@ -278,4 +290,5 @@ class DoxyOther(Base): def can_parse(cls, obj): return obj.kind in cls.kinds + Base.mem_classes.append(DoxyOther) diff --git a/docs/doxygen/doxyxml/generated/compound.py b/docs/doxygen/doxyxml/generated/compound.py index 294f0216e78..321328bcb7e 100644 --- a/docs/doxygen/doxyxml/generated/compound.py +++ b/docs/doxygen/doxyxml/generated/compound.py @@ -22,13 +22,15 @@ def find(self, details): return self.compounddef.find(details) + supermod.DoxygenType.subclass = DoxygenTypeSub # end class DoxygenTypeSub class compounddefTypeSub(supermod.compounddefType): def __init__(self, kind=None, prot=None, id=None, compoundname='', title='', basecompoundref=None, derivedcompoundref=None, includes=None, includedby=None, incdepgraph=None, invincdepgraph=None, innerdir=None, innerfile=None, innerclass=None, innernamespace=None, innerpage=None, innergroup=None, templateparamlist=None, sectiondef=None, briefdescription=None, detaileddescription=None, inheritancegraph=None, collaborationgraph=None, programlisting=None, location=None, listofallmembers=None): - supermod.compounddefType.__init__(self, kind, prot, id, compoundname, title, basecompoundref, derivedcompoundref, includes, includedby, incdepgraph, invincdepgraph, innerdir, innerfile, innerclass, innernamespace, innerpage, innergroup, templateparamlist, sectiondef, briefdescription, detaileddescription, inheritancegraph, collaborationgraph, programlisting, location, listofallmembers) + supermod.compounddefType.__init__(self, kind, prot, id, compoundname, title, basecompoundref, derivedcompoundref, includes, includedby, incdepgraph, invincdepgraph, innerdir, innerfile, innerclass, + innernamespace, innerpage, innergroup, templateparamlist, sectiondef, briefdescription, detaileddescription, inheritancegraph, collaborationgraph, programlisting, location, listofallmembers) def find(self, details): @@ -48,13 +50,18 @@ def find(self, details): class listofallmembersTypeSub(supermod.listofallmembersType): def __init__(self, member=None): supermod.listofallmembersType.__init__(self, member) + + supermod.listofallmembersType.subclass = listofallmembersTypeSub # end class listofallmembersTypeSub class memberRefTypeSub(supermod.memberRefType): def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope='', name=''): - supermod.memberRefType.__init__(self, virt, prot, refid, ambiguityscope, scope, name) + supermod.memberRefType.__init__( + self, virt, prot, refid, ambiguityscope, scope, name) + + supermod.memberRefType.subclass = memberRefTypeSub # end class memberRefTypeSub @@ -62,6 +69,8 @@ def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope= class compoundRefTypeSub(supermod.compoundRefType): def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): supermod.compoundRefType.__init__(self, mixedclass_, content_) + + supermod.compoundRefType.subclass = compoundRefTypeSub # end class compoundRefTypeSub @@ -69,6 +78,8 @@ def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=No class reimplementTypeSub(supermod.reimplementType): def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): supermod.reimplementType.__init__(self, mixedclass_, content_) + + supermod.reimplementType.subclass = reimplementTypeSub # end class reimplementTypeSub @@ -76,6 +87,8 @@ def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): class incTypeSub(supermod.incType): def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, content_=None): supermod.incType.__init__(self, mixedclass_, content_) + + supermod.incType.subclass = incTypeSub # end class incTypeSub @@ -83,23 +96,26 @@ def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, conten class refTypeSub(supermod.refType): def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): supermod.refType.__init__(self, mixedclass_, content_) + + supermod.refType.subclass = refTypeSub # end class refTypeSub - class refTextTypeSub(supermod.refTextType): def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): supermod.refTextType.__init__(self, mixedclass_, content_) + supermod.refTextType.subclass = refTextTypeSub # end class refTextTypeSub -class sectiondefTypeSub(supermod.sectiondefType): +class sectiondefTypeSub(supermod.sectiondefType): def __init__(self, kind=None, header='', description=None, memberdef=None): - supermod.sectiondefType.__init__(self, kind, header, description, memberdef) + supermod.sectiondefType.__init__( + self, kind, header, description, memberdef) def find(self, details): @@ -116,7 +132,10 @@ def find(self, details): class memberdefTypeSub(supermod.memberdefType): def __init__(self, initonly=None, kind=None, volatile=None, const=None, raise_=None, virt=None, readable=None, prot=None, explicit=None, new=None, final=None, writable=None, add=None, static=None, remove=None, sealed=None, mutable=None, gettable=None, inline=None, settable=None, id=None, templateparamlist=None, type_=None, definition='', argsstring='', name='', read='', write='', bitfield='', reimplements=None, reimplementedby=None, param=None, enumvalue=None, initializer=None, exceptions=None, briefdescription=None, detaileddescription=None, inbodydescription=None, location=None, references=None, referencedby=None): - supermod.memberdefType.__init__(self, initonly, kind, volatile, const, raise_, virt, readable, prot, explicit, new, final, writable, add, static, remove, sealed, mutable, gettable, inline, settable, id, templateparamlist, type_, definition, argsstring, name, read, write, bitfield, reimplements, reimplementedby, param, enumvalue, initializer, exceptions, briefdescription, detaileddescription, inbodydescription, location, references, referencedby) + supermod.memberdefType.__init__(self, initonly, kind, volatile, const, raise_, virt, readable, prot, explicit, new, final, writable, add, static, remove, sealed, mutable, gettable, inline, settable, id, templateparamlist, type_, + definition, argsstring, name, read, write, bitfield, reimplements, reimplementedby, param, enumvalue, initializer, exceptions, briefdescription, detaileddescription, inbodydescription, location, references, referencedby) + + supermod.memberdefType.subclass = memberdefTypeSub # end class memberdefTypeSub @@ -124,6 +143,8 @@ def __init__(self, initonly=None, kind=None, volatile=None, const=None, raise_=N class descriptionTypeSub(supermod.descriptionType): def __init__(self, title='', para=None, sect1=None, internal=None, mixedclass_=None, content_=None): supermod.descriptionType.__init__(self, mixedclass_, content_) + + supermod.descriptionType.subclass = descriptionTypeSub # end class descriptionTypeSub @@ -131,6 +152,8 @@ def __init__(self, title='', para=None, sect1=None, internal=None, mixedclass_=N class enumvalueTypeSub(supermod.enumvalueType): def __init__(self, prot=None, id=None, name='', initializer=None, briefdescription=None, detaileddescription=None, mixedclass_=None, content_=None): supermod.enumvalueType.__init__(self, mixedclass_, content_) + + supermod.enumvalueType.subclass = enumvalueTypeSub # end class enumvalueTypeSub @@ -138,13 +161,18 @@ def __init__(self, prot=None, id=None, name='', initializer=None, briefdescripti class templateparamlistTypeSub(supermod.templateparamlistType): def __init__(self, param=None): supermod.templateparamlistType.__init__(self, param) + + supermod.templateparamlistType.subclass = templateparamlistTypeSub # end class templateparamlistTypeSub class paramTypeSub(supermod.paramType): def __init__(self, type_=None, declname='', defname='', array='', defval=None, briefdescription=None): - supermod.paramType.__init__(self, type_, declname, defname, array, defval, briefdescription) + supermod.paramType.__init__( + self, type_, declname, defname, array, defval, briefdescription) + + supermod.paramType.subclass = paramTypeSub # end class paramTypeSub @@ -152,6 +180,8 @@ def __init__(self, type_=None, declname='', defname='', array='', defval=None, b class linkedTextTypeSub(supermod.linkedTextType): def __init__(self, ref=None, mixedclass_=None, content_=None): supermod.linkedTextType.__init__(self, mixedclass_, content_) + + supermod.linkedTextType.subclass = linkedTextTypeSub # end class linkedTextTypeSub @@ -159,6 +189,8 @@ def __init__(self, ref=None, mixedclass_=None, content_=None): class graphTypeSub(supermod.graphType): def __init__(self, node=None): supermod.graphType.__init__(self, node) + + supermod.graphType.subclass = graphTypeSub # end class graphTypeSub @@ -166,6 +198,8 @@ def __init__(self, node=None): class nodeTypeSub(supermod.nodeType): def __init__(self, id=None, label='', link=None, childnode=None): supermod.nodeType.__init__(self, id, label, link, childnode) + + supermod.nodeType.subclass = nodeTypeSub # end class nodeTypeSub @@ -173,6 +207,8 @@ def __init__(self, id=None, label='', link=None, childnode=None): class childnodeTypeSub(supermod.childnodeType): def __init__(self, relation=None, refid=None, edgelabel=None): supermod.childnodeType.__init__(self, relation, refid, edgelabel) + + supermod.childnodeType.subclass = childnodeTypeSub # end class childnodeTypeSub @@ -180,6 +216,8 @@ def __init__(self, relation=None, refid=None, edgelabel=None): class linkTypeSub(supermod.linkType): def __init__(self, refid=None, external=None, valueOf_=''): supermod.linkType.__init__(self, refid, external) + + supermod.linkType.subclass = linkTypeSub # end class linkTypeSub @@ -187,13 +225,18 @@ def __init__(self, refid=None, external=None, valueOf_=''): class listingTypeSub(supermod.listingType): def __init__(self, codeline=None): supermod.listingType.__init__(self, codeline) + + supermod.listingType.subclass = listingTypeSub # end class listingTypeSub class codelineTypeSub(supermod.codelineType): def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None): - supermod.codelineType.__init__(self, external, lineno, refkind, refid, highlight) + supermod.codelineType.__init__( + self, external, lineno, refkind, refid, highlight) + + supermod.codelineType.subclass = codelineTypeSub # end class codelineTypeSub @@ -201,6 +244,8 @@ def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlig class highlightTypeSub(supermod.highlightType): def __init__(self, class_=None, sp=None, ref=None, mixedclass_=None, content_=None): supermod.highlightType.__init__(self, mixedclass_, content_) + + supermod.highlightType.subclass = highlightTypeSub # end class highlightTypeSub @@ -208,13 +253,18 @@ def __init__(self, class_=None, sp=None, ref=None, mixedclass_=None, content_=No class referenceTypeSub(supermod.referenceType): def __init__(self, endline=None, startline=None, refid=None, compoundref=None, valueOf_='', mixedclass_=None, content_=None): supermod.referenceType.__init__(self, mixedclass_, content_) + + supermod.referenceType.subclass = referenceTypeSub # end class referenceTypeSub class locationTypeSub(supermod.locationType): def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file=None, valueOf_=''): - supermod.locationType.__init__(self, bodystart, line, bodyend, bodyfile, file) + supermod.locationType.__init__( + self, bodystart, line, bodyend, bodyfile, file) + + supermod.locationType.subclass = locationTypeSub # end class locationTypeSub @@ -222,6 +272,8 @@ def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file= class docSect1TypeSub(supermod.docSect1Type): def __init__(self, id=None, title='', para=None, sect2=None, internal=None, mixedclass_=None, content_=None): supermod.docSect1Type.__init__(self, mixedclass_, content_) + + supermod.docSect1Type.subclass = docSect1TypeSub # end class docSect1TypeSub @@ -229,6 +281,8 @@ def __init__(self, id=None, title='', para=None, sect2=None, internal=None, mixe class docSect2TypeSub(supermod.docSect2Type): def __init__(self, id=None, title='', para=None, sect3=None, internal=None, mixedclass_=None, content_=None): supermod.docSect2Type.__init__(self, mixedclass_, content_) + + supermod.docSect2Type.subclass = docSect2TypeSub # end class docSect2TypeSub @@ -236,6 +290,8 @@ def __init__(self, id=None, title='', para=None, sect3=None, internal=None, mixe class docSect3TypeSub(supermod.docSect3Type): def __init__(self, id=None, title='', para=None, sect4=None, internal=None, mixedclass_=None, content_=None): supermod.docSect3Type.__init__(self, mixedclass_, content_) + + supermod.docSect3Type.subclass = docSect3TypeSub # end class docSect3TypeSub @@ -243,6 +299,8 @@ def __init__(self, id=None, title='', para=None, sect4=None, internal=None, mixe class docSect4TypeSub(supermod.docSect4Type): def __init__(self, id=None, title='', para=None, internal=None, mixedclass_=None, content_=None): supermod.docSect4Type.__init__(self, mixedclass_, content_) + + supermod.docSect4Type.subclass = docSect4TypeSub # end class docSect4TypeSub @@ -250,6 +308,8 @@ def __init__(self, id=None, title='', para=None, internal=None, mixedclass_=None class docInternalTypeSub(supermod.docInternalType): def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): supermod.docInternalType.__init__(self, mixedclass_, content_) + + supermod.docInternalType.subclass = docInternalTypeSub # end class docInternalTypeSub @@ -257,6 +317,8 @@ def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): class docInternalS1TypeSub(supermod.docInternalS1Type): def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): supermod.docInternalS1Type.__init__(self, mixedclass_, content_) + + supermod.docInternalS1Type.subclass = docInternalS1TypeSub # end class docInternalS1TypeSub @@ -264,6 +326,8 @@ def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): class docInternalS2TypeSub(supermod.docInternalS2Type): def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): supermod.docInternalS2Type.__init__(self, mixedclass_, content_) + + supermod.docInternalS2Type.subclass = docInternalS2TypeSub # end class docInternalS2TypeSub @@ -271,6 +335,8 @@ def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): class docInternalS3TypeSub(supermod.docInternalS3Type): def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): supermod.docInternalS3Type.__init__(self, mixedclass_, content_) + + supermod.docInternalS3Type.subclass = docInternalS3TypeSub # end class docInternalS3TypeSub @@ -278,6 +344,8 @@ def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): class docInternalS4TypeSub(supermod.docInternalS4Type): def __init__(self, para=None, mixedclass_=None, content_=None): supermod.docInternalS4Type.__init__(self, mixedclass_, content_) + + supermod.docInternalS4Type.subclass = docInternalS4TypeSub # end class docInternalS4TypeSub @@ -285,6 +353,8 @@ def __init__(self, para=None, mixedclass_=None, content_=None): class docURLLinkSub(supermod.docURLLink): def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): supermod.docURLLink.__init__(self, mixedclass_, content_) + + supermod.docURLLink.subclass = docURLLinkSub # end class docURLLinkSub @@ -292,6 +362,8 @@ def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): class docAnchorTypeSub(supermod.docAnchorType): def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): supermod.docAnchorType.__init__(self, mixedclass_, content_) + + supermod.docAnchorType.subclass = docAnchorTypeSub # end class docAnchorTypeSub @@ -299,6 +371,8 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): class docFormulaTypeSub(supermod.docFormulaType): def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): supermod.docFormulaType.__init__(self, mixedclass_, content_) + + supermod.docFormulaType.subclass = docFormulaTypeSub # end class docFormulaTypeSub @@ -306,6 +380,8 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): class docIndexEntryTypeSub(supermod.docIndexEntryType): def __init__(self, primaryie='', secondaryie=''): supermod.docIndexEntryType.__init__(self, primaryie, secondaryie) + + supermod.docIndexEntryType.subclass = docIndexEntryTypeSub # end class docIndexEntryTypeSub @@ -313,6 +389,8 @@ def __init__(self, primaryie='', secondaryie=''): class docListTypeSub(supermod.docListType): def __init__(self, listitem=None): supermod.docListType.__init__(self, listitem) + + supermod.docListType.subclass = docListTypeSub # end class docListTypeSub @@ -320,6 +398,8 @@ def __init__(self, listitem=None): class docListItemTypeSub(supermod.docListItemType): def __init__(self, para=None): supermod.docListItemType.__init__(self, para) + + supermod.docListItemType.subclass = docListItemTypeSub # end class docListItemTypeSub @@ -327,6 +407,8 @@ def __init__(self, para=None): class docSimpleSectTypeSub(supermod.docSimpleSectType): def __init__(self, kind=None, title=None, para=None): supermod.docSimpleSectType.__init__(self, kind, title, para) + + supermod.docSimpleSectType.subclass = docSimpleSectTypeSub # end class docSimpleSectTypeSub @@ -334,6 +416,8 @@ def __init__(self, kind=None, title=None, para=None): class docVarListEntryTypeSub(supermod.docVarListEntryType): def __init__(self, term=None): supermod.docVarListEntryType.__init__(self, term) + + supermod.docVarListEntryType.subclass = docVarListEntryTypeSub # end class docVarListEntryTypeSub @@ -341,6 +425,8 @@ def __init__(self, term=None): class docRefTextTypeSub(supermod.docRefTextType): def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): supermod.docRefTextType.__init__(self, mixedclass_, content_) + + supermod.docRefTextType.subclass = docRefTextTypeSub # end class docRefTextTypeSub @@ -348,6 +434,8 @@ def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedcl class docTableTypeSub(supermod.docTableType): def __init__(self, rows=None, cols=None, row=None, caption=None): supermod.docTableType.__init__(self, rows, cols, row, caption) + + supermod.docTableType.subclass = docTableTypeSub # end class docTableTypeSub @@ -355,6 +443,8 @@ def __init__(self, rows=None, cols=None, row=None, caption=None): class docRowTypeSub(supermod.docRowType): def __init__(self, entry=None): supermod.docRowType.__init__(self, entry) + + supermod.docRowType.subclass = docRowTypeSub # end class docRowTypeSub @@ -362,6 +452,8 @@ def __init__(self, entry=None): class docEntryTypeSub(supermod.docEntryType): def __init__(self, thead=None, para=None): supermod.docEntryType.__init__(self, thead, para) + + supermod.docEntryType.subclass = docEntryTypeSub # end class docEntryTypeSub @@ -369,6 +461,8 @@ def __init__(self, thead=None, para=None): class docHeadingTypeSub(supermod.docHeadingType): def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): supermod.docHeadingType.__init__(self, mixedclass_, content_) + + supermod.docHeadingType.subclass = docHeadingTypeSub # end class docHeadingTypeSub @@ -376,6 +470,8 @@ def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): class docImageTypeSub(supermod.docImageType): def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', mixedclass_=None, content_=None): supermod.docImageType.__init__(self, mixedclass_, content_) + + supermod.docImageType.subclass = docImageTypeSub # end class docImageTypeSub @@ -383,6 +479,8 @@ def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', class docDotFileTypeSub(supermod.docDotFileType): def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): supermod.docDotFileType.__init__(self, mixedclass_, content_) + + supermod.docDotFileType.subclass = docDotFileTypeSub # end class docDotFileTypeSub @@ -390,6 +488,8 @@ def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): class docTocItemTypeSub(supermod.docTocItemType): def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): supermod.docTocItemType.__init__(self, mixedclass_, content_) + + supermod.docTocItemType.subclass = docTocItemTypeSub # end class docTocItemTypeSub @@ -397,6 +497,8 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): class docTocListTypeSub(supermod.docTocListType): def __init__(self, tocitem=None): supermod.docTocListType.__init__(self, tocitem) + + supermod.docTocListType.subclass = docTocListTypeSub # end class docTocListTypeSub @@ -404,6 +506,8 @@ def __init__(self, tocitem=None): class docLanguageTypeSub(supermod.docLanguageType): def __init__(self, langid=None, para=None): supermod.docLanguageType.__init__(self, langid, para) + + supermod.docLanguageType.subclass = docLanguageTypeSub # end class docLanguageTypeSub @@ -411,13 +515,18 @@ def __init__(self, langid=None, para=None): class docParamListTypeSub(supermod.docParamListType): def __init__(self, kind=None, parameteritem=None): supermod.docParamListType.__init__(self, kind, parameteritem) + + supermod.docParamListType.subclass = docParamListTypeSub # end class docParamListTypeSub class docParamListItemSub(supermod.docParamListItem): def __init__(self, parameternamelist=None, parameterdescription=None): - supermod.docParamListItem.__init__(self, parameternamelist, parameterdescription) + supermod.docParamListItem.__init__( + self, parameternamelist, parameterdescription) + + supermod.docParamListItem.subclass = docParamListItemSub # end class docParamListItemSub @@ -425,6 +534,8 @@ def __init__(self, parameternamelist=None, parameterdescription=None): class docParamNameListSub(supermod.docParamNameList): def __init__(self, parametername=None): supermod.docParamNameList.__init__(self, parametername) + + supermod.docParamNameList.subclass = docParamNameListSub # end class docParamNameListSub @@ -432,6 +543,8 @@ def __init__(self, parametername=None): class docParamNameSub(supermod.docParamName): def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): supermod.docParamName.__init__(self, mixedclass_, content_) + + supermod.docParamName.subclass = docParamNameSub # end class docParamNameSub @@ -439,6 +552,8 @@ def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): class docXRefSectTypeSub(supermod.docXRefSectType): def __init__(self, id=None, xreftitle=None, xrefdescription=None): supermod.docXRefSectType.__init__(self, id, xreftitle, xrefdescription) + + supermod.docXRefSectType.subclass = docXRefSectTypeSub # end class docXRefSectTypeSub @@ -446,6 +561,8 @@ def __init__(self, id=None, xreftitle=None, xrefdescription=None): class docCopyTypeSub(supermod.docCopyType): def __init__(self, link=None, para=None, sect1=None, internal=None): supermod.docCopyType.__init__(self, link, para, sect1, internal) + + supermod.docCopyType.subclass = docCopyTypeSub # end class docCopyTypeSub @@ -453,9 +570,12 @@ def __init__(self, link=None, para=None, sect1=None, internal=None): class docCharTypeSub(supermod.docCharType): def __init__(self, char=None, valueOf_=''): supermod.docCharType.__init__(self, char) + + supermod.docCharType.subclass = docCharTypeSub # end class docCharTypeSub + class docParaTypeSub(supermod.docParaType): def __init__(self, char=None, valueOf_=''): supermod.docParaType.__init__(self, char) @@ -469,7 +589,7 @@ def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == "ref": @@ -492,7 +612,6 @@ def buildChildren(self, child_, nodeName_): # end class docParaTypeSub - def parse(inFilename): doc = minidom.parse(inFilename) rootNode = doc.documentElement diff --git a/docs/doxygen/doxyxml/generated/compoundsuper.py b/docs/doxygen/doxyxml/generated/compoundsuper.py index 05c49281fe9..40f548aab02 100644 --- a/docs/doxygen/doxyxml/generated/compoundsuper.py +++ b/docs/doxygen/doxyxml/generated/compoundsuper.py @@ -24,12 +24,16 @@ class GeneratedsSuper(object): def format_string(self, input_data, input_name=''): return input_data + def format_integer(self, input_data, input_name=''): return '%d' % input_data + def format_float(self, input_data, input_name=''): return '%f' % input_data + def format_double(self, input_data, input_name=''): return '%e' % input_data + def format_boolean(self, input_data, input_name=''): return '%s' % input_data @@ -41,9 +45,9 @@ def format_boolean(self, input_data, input_name=''): ## from IPython.Shell import IPShellEmbed ## args = '' -## ipshell = IPShellEmbed(args, +# ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') +# exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: @@ -59,10 +63,12 @@ def format_boolean(self, input_data, input_name=''): # Support/utility functions. # + def showIndent(outfile, level): for idx in range(level): outfile.write(' ') + def quote_xml(inStr): s1 = (isinstance(inStr, str) and inStr or '%s' % inStr) @@ -71,6 +77,7 @@ def quote_xml(inStr): s1 = s1.replace('>', '>') return s1 + def quote_attrib(inStr): s1 = (isinstance(inStr, str) and inStr or '%s' % inStr) @@ -86,6 +93,7 @@ def quote_attrib(inStr): s1 = '"%s"' % s1 return s1 + def quote_python(inStr): s1 = inStr if s1.find("'") == -1: @@ -117,26 +125,33 @@ class MixedContainer(object): TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 + def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value + def getCategory(self): return self.category + def getContenttype(self, content_type): return self.content_type + def getValue(self): return self.value + def getName(self): return self.name + def export(self, outfile, level, name, namespace): if self.category == MixedContainer.CategoryText: outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex - self.value.export(outfile, level, namespace,name) + self.value.export(outfile, level, namespace, name) + def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: outfile.write('<%s>%s' % (self.name, self.value, self.name)) @@ -148,19 +163,20 @@ def exportSimple(self, outfile, level, name): outfile.write('<%s>%f' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: outfile.write('<%s>%g' % (self.name, self.value, self.name)) + def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) + outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % + (self.category, self.content_type, self.name, self.value)) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) + outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % + (self.category, self.content_type, self.name, self.value)) else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s",\n' % \ - (self.category, self.content_type, self.name,)) + outfile.write('MixedContainer(%d, %d, "%s",\n' % + (self.category, self.content_type, self.name,)) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) outfile.write(')\n') @@ -171,6 +187,7 @@ def __init__(self, name='', data_type='', container=0): self.name = name self.data_type = data_type self.container = container + def set_name(self, name): self.name = name def get_name(self): return self.name def set_data_type(self, data_type): self.data_type = data_type @@ -186,9 +203,11 @@ def get_container(self): return self.container class DoxygenType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, version=None, compounddef=None): self.version = version self.compounddef = compounddef + def factory(*args_, **kwargs_): if DoxygenType.subclass: return DoxygenType.subclass(*args_, **kwargs_) @@ -199,6 +218,7 @@ def get_compounddef(self): return self.compounddef def set_compounddef(self, compounddef): self.compounddef = compounddef def get_version(self): return self.version def set_version(self, version): self.version = version + def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -210,27 +230,34 @@ def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='DoxygenType'): outfile.write(' version=%s' % (quote_attrib(self.version), )) + def exportChildren(self, outfile, level, namespace_='', name_='DoxygenType'): if self.compounddef: - self.compounddef.export(outfile, level, namespace_, name_='compounddef') + self.compounddef.export( + outfile, level, namespace_, name_='compounddef') + def hasContent_(self): if ( self.compounddef is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='DoxygenType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.version is not None: showIndent(outfile, level) outfile.write('version = "%s",\n' % (self.version,)) + def exportLiteralChildren(self, outfile, level, name_): if self.compounddef: showIndent(outfile, level) @@ -238,18 +265,21 @@ def exportLiteralChildren(self, outfile, level, name_): self.compounddef.exportLiteral(outfile, level, name_='compounddef') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('version'): self.version = attrs.get('version').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'compounddef': + nodeName_ == 'compounddef': obj_ = compounddefType.factory() obj_.build(child_) self.set_compounddef(obj_) @@ -259,6 +289,7 @@ def buildChildren(self, child_, nodeName_): class compounddefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, prot=None, id=None, compoundname=None, title=None, basecompoundref=None, derivedcompoundref=None, includes=None, includedby=None, incdepgraph=None, invincdepgraph=None, innerdir=None, innerfile=None, innerclass=None, innernamespace=None, innerpage=None, innergroup=None, templateparamlist=None, sectiondef=None, briefdescription=None, detaileddescription=None, inheritancegraph=None, collaborationgraph=None, programlisting=None, location=None, listofallmembers=None): self.kind = kind self.prot = prot @@ -319,6 +350,7 @@ def __init__(self, kind=None, prot=None, id=None, compoundname=None, title=None, self.programlisting = programlisting self.location = location self.listofallmembers = listofallmembers + def factory(*args_, **kwargs_): if compounddefType.subclass: return compounddefType.subclass(*args_, **kwargs_) @@ -330,13 +362,23 @@ def set_compoundname(self, compoundname): self.compoundname = compoundname def get_title(self): return self.title def set_title(self, title): self.title = title def get_basecompoundref(self): return self.basecompoundref - def set_basecompoundref(self, basecompoundref): self.basecompoundref = basecompoundref + def set_basecompoundref( + self, basecompoundref): self.basecompoundref = basecompoundref + def add_basecompoundref(self, value): self.basecompoundref.append(value) - def insert_basecompoundref(self, index, value): self.basecompoundref[index] = value + def insert_basecompoundref( + self, index, value): self.basecompoundref[index] = value + def get_derivedcompoundref(self): return self.derivedcompoundref - def set_derivedcompoundref(self, derivedcompoundref): self.derivedcompoundref = derivedcompoundref - def add_derivedcompoundref(self, value): self.derivedcompoundref.append(value) - def insert_derivedcompoundref(self, index, value): self.derivedcompoundref[index] = value + + def set_derivedcompoundref( + self, derivedcompoundref): self.derivedcompoundref = derivedcompoundref + + def add_derivedcompoundref( + self, value): self.derivedcompoundref.append(value) + def insert_derivedcompoundref( + self, index, value): self.derivedcompoundref[index] = value + def get_includes(self): return self.includes def set_includes(self, includes): self.includes = includes def add_includes(self, value): self.includes.append(value) @@ -348,7 +390,9 @@ def insert_includedby(self, index, value): self.includedby[index] = value def get_incdepgraph(self): return self.incdepgraph def set_incdepgraph(self, incdepgraph): self.incdepgraph = incdepgraph def get_invincdepgraph(self): return self.invincdepgraph - def set_invincdepgraph(self, invincdepgraph): self.invincdepgraph = invincdepgraph + def set_invincdepgraph( + self, invincdepgraph): self.invincdepgraph = invincdepgraph + def get_innerdir(self): return self.innerdir def set_innerdir(self, innerdir): self.innerdir = innerdir def add_innerdir(self, value): self.innerdir.append(value) @@ -362,9 +406,13 @@ def set_innerclass(self, innerclass): self.innerclass = innerclass def add_innerclass(self, value): self.innerclass.append(value) def insert_innerclass(self, index, value): self.innerclass[index] = value def get_innernamespace(self): return self.innernamespace - def set_innernamespace(self, innernamespace): self.innernamespace = innernamespace + def set_innernamespace( + self, innernamespace): self.innernamespace = innernamespace + def add_innernamespace(self, value): self.innernamespace.append(value) - def insert_innernamespace(self, index, value): self.innernamespace[index] = value + def insert_innernamespace( + self, index, value): self.innernamespace[index] = value + def get_innerpage(self): return self.innerpage def set_innerpage(self, innerpage): self.innerpage = innerpage def add_innerpage(self, value): self.innerpage.append(value) @@ -374,35 +422,51 @@ def set_innergroup(self, innergroup): self.innergroup = innergroup def add_innergroup(self, value): self.innergroup.append(value) def insert_innergroup(self, index, value): self.innergroup[index] = value def get_templateparamlist(self): return self.templateparamlist - def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist + def set_templateparamlist( + self, templateparamlist): self.templateparamlist = templateparamlist + def get_sectiondef(self): return self.sectiondef def set_sectiondef(self, sectiondef): self.sectiondef = sectiondef def add_sectiondef(self, value): self.sectiondef.append(value) def insert_sectiondef(self, index, value): self.sectiondef[index] = value def get_briefdescription(self): return self.briefdescription - def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription + def set_briefdescription( + self, briefdescription): self.briefdescription = briefdescription + def get_detaileddescription(self): return self.detaileddescription - def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription + def set_detaileddescription( + self, detaileddescription): self.detaileddescription = detaileddescription + def get_inheritancegraph(self): return self.inheritancegraph - def set_inheritancegraph(self, inheritancegraph): self.inheritancegraph = inheritancegraph + def set_inheritancegraph( + self, inheritancegraph): self.inheritancegraph = inheritancegraph + def get_collaborationgraph(self): return self.collaborationgraph - def set_collaborationgraph(self, collaborationgraph): self.collaborationgraph = collaborationgraph + def set_collaborationgraph( + self, collaborationgraph): self.collaborationgraph = collaborationgraph + def get_programlisting(self): return self.programlisting - def set_programlisting(self, programlisting): self.programlisting = programlisting + def set_programlisting( + self, programlisting): self.programlisting = programlisting + def get_location(self): return self.location def set_location(self, location): self.location = location def get_listofallmembers(self): return self.listofallmembers - def set_listofallmembers(self, listofallmembers): self.listofallmembers = listofallmembers + def set_listofallmembers( + self, listofallmembers): self.listofallmembers = listofallmembers + def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='compounddefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='compounddefType') + self.exportAttributes(outfile, level, namespace_, + name_='compounddefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -410,32 +474,41 @@ def export(self, outfile, level, namespace_='', name_='compounddefType', namespa outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='compounddefType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='compounddefType'): if self.compoundname is not None: showIndent(outfile, level) - outfile.write('<%scompoundname>%s\n' % (namespace_, self.format_string(quote_xml(self.compoundname).encode(ExternalEncoding), input_name='compoundname'), namespace_)) + outfile.write('<%scompoundname>%s\n' % (namespace_, self.format_string( + quote_xml(self.compoundname).encode(ExternalEncoding), input_name='compoundname'), namespace_)) if self.title is not None: showIndent(outfile, level) - outfile.write('<%stitle>%s\n' % (namespace_, self.format_string(quote_xml(self.title).encode(ExternalEncoding), input_name='title'), namespace_)) + outfile.write('<%stitle>%s\n' % (namespace_, self.format_string( + quote_xml(self.title).encode(ExternalEncoding), input_name='title'), namespace_)) for basecompoundref_ in self.basecompoundref: - basecompoundref_.export(outfile, level, namespace_, name_='basecompoundref') + basecompoundref_.export( + outfile, level, namespace_, name_='basecompoundref') for derivedcompoundref_ in self.derivedcompoundref: - derivedcompoundref_.export(outfile, level, namespace_, name_='derivedcompoundref') + derivedcompoundref_.export( + outfile, level, namespace_, name_='derivedcompoundref') for includes_ in self.includes: includes_.export(outfile, level, namespace_, name_='includes') for includedby_ in self.includedby: includedby_.export(outfile, level, namespace_, name_='includedby') if self.incdepgraph: - self.incdepgraph.export(outfile, level, namespace_, name_='incdepgraph') + self.incdepgraph.export( + outfile, level, namespace_, name_='incdepgraph') if self.invincdepgraph: - self.invincdepgraph.export(outfile, level, namespace_, name_='invincdepgraph') + self.invincdepgraph.export( + outfile, level, namespace_, name_='invincdepgraph') for innerdir_ in self.innerdir: innerdir_.export(outfile, level, namespace_, name_='innerdir') for innerfile_ in self.innerfile: @@ -443,29 +516,38 @@ def exportChildren(self, outfile, level, namespace_='', name_='compounddefType') for innerclass_ in self.innerclass: innerclass_.export(outfile, level, namespace_, name_='innerclass') for innernamespace_ in self.innernamespace: - innernamespace_.export(outfile, level, namespace_, name_='innernamespace') + innernamespace_.export( + outfile, level, namespace_, name_='innernamespace') for innerpage_ in self.innerpage: innerpage_.export(outfile, level, namespace_, name_='innerpage') for innergroup_ in self.innergroup: innergroup_.export(outfile, level, namespace_, name_='innergroup') if self.templateparamlist: - self.templateparamlist.export(outfile, level, namespace_, name_='templateparamlist') + self.templateparamlist.export( + outfile, level, namespace_, name_='templateparamlist') for sectiondef_ in self.sectiondef: sectiondef_.export(outfile, level, namespace_, name_='sectiondef') if self.briefdescription: - self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') + self.briefdescription.export( + outfile, level, namespace_, name_='briefdescription') if self.detaileddescription: - self.detaileddescription.export(outfile, level, namespace_, name_='detaileddescription') + self.detaileddescription.export( + outfile, level, namespace_, name_='detaileddescription') if self.inheritancegraph: - self.inheritancegraph.export(outfile, level, namespace_, name_='inheritancegraph') + self.inheritancegraph.export( + outfile, level, namespace_, name_='inheritancegraph') if self.collaborationgraph: - self.collaborationgraph.export(outfile, level, namespace_, name_='collaborationgraph') + self.collaborationgraph.export( + outfile, level, namespace_, name_='collaborationgraph') if self.programlisting: - self.programlisting.export(outfile, level, namespace_, name_='programlisting') + self.programlisting.export( + outfile, level, namespace_, name_='programlisting') if self.location: self.location.export(outfile, level, namespace_, name_='location') if self.listofallmembers: - self.listofallmembers.export(outfile, level, namespace_, name_='listofallmembers') + self.listofallmembers.export( + outfile, level, namespace_, name_='listofallmembers') + def hasContent_(self): if ( self.compoundname is not None or @@ -491,15 +573,17 @@ def hasContent_(self): self.programlisting is not None or self.location is not None or self.listofallmembers is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='compounddefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) @@ -510,9 +594,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('compoundname=%s,\n' % quote_python(self.compoundname).encode(ExternalEncoding)) + outfile.write('compoundname=%s,\n' % quote_python( + self.compoundname).encode(ExternalEncoding)) if self.title: showIndent(outfile, level) outfile.write('title=model_.xsd_string(\n') @@ -525,7 +611,8 @@ def exportLiteralChildren(self, outfile, level, name_): for basecompoundref in self.basecompoundref: showIndent(outfile, level) outfile.write('model_.basecompoundref(\n') - basecompoundref.exportLiteral(outfile, level, name_='basecompoundref') + basecompoundref.exportLiteral( + outfile, level, name_='basecompoundref') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -537,7 +624,8 @@ def exportLiteralChildren(self, outfile, level, name_): for derivedcompoundref in self.derivedcompoundref: showIndent(outfile, level) outfile.write('model_.derivedcompoundref(\n') - derivedcompoundref.exportLiteral(outfile, level, name_='derivedcompoundref') + derivedcompoundref.exportLiteral( + outfile, level, name_='derivedcompoundref') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -576,7 +664,8 @@ def exportLiteralChildren(self, outfile, level, name_): if self.invincdepgraph: showIndent(outfile, level) outfile.write('invincdepgraph=model_.graphType(\n') - self.invincdepgraph.exportLiteral(outfile, level, name_='invincdepgraph') + self.invincdepgraph.exportLiteral( + outfile, level, name_='invincdepgraph') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) @@ -621,7 +710,8 @@ def exportLiteralChildren(self, outfile, level, name_): for innernamespace in self.innernamespace: showIndent(outfile, level) outfile.write('model_.innernamespace(\n') - innernamespace.exportLiteral(outfile, level, name_='innernamespace') + innernamespace.exportLiteral( + outfile, level, name_='innernamespace') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -654,7 +744,8 @@ def exportLiteralChildren(self, outfile, level, name_): if self.templateparamlist: showIndent(outfile, level) outfile.write('templateparamlist=model_.templateparamlistType(\n') - self.templateparamlist.exportLiteral(outfile, level, name_='templateparamlist') + self.templateparamlist.exportLiteral( + outfile, level, name_='templateparamlist') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) @@ -672,31 +763,36 @@ def exportLiteralChildren(self, outfile, level, name_): if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') - self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') + self.briefdescription.exportLiteral( + outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') if self.detaileddescription: showIndent(outfile, level) outfile.write('detaileddescription=model_.descriptionType(\n') - self.detaileddescription.exportLiteral(outfile, level, name_='detaileddescription') + self.detaileddescription.exportLiteral( + outfile, level, name_='detaileddescription') showIndent(outfile, level) outfile.write('),\n') if self.inheritancegraph: showIndent(outfile, level) outfile.write('inheritancegraph=model_.graphType(\n') - self.inheritancegraph.exportLiteral(outfile, level, name_='inheritancegraph') + self.inheritancegraph.exportLiteral( + outfile, level, name_='inheritancegraph') showIndent(outfile, level) outfile.write('),\n') if self.collaborationgraph: showIndent(outfile, level) outfile.write('collaborationgraph=model_.graphType(\n') - self.collaborationgraph.exportLiteral(outfile, level, name_='collaborationgraph') + self.collaborationgraph.exportLiteral( + outfile, level, name_='collaborationgraph') showIndent(outfile, level) outfile.write('),\n') if self.programlisting: showIndent(outfile, level) outfile.write('programlisting=model_.listingType(\n') - self.programlisting.exportLiteral(outfile, level, name_='programlisting') + self.programlisting.exportLiteral( + outfile, level, name_='programlisting') showIndent(outfile, level) outfile.write('),\n') if self.location: @@ -708,15 +804,18 @@ def exportLiteralChildren(self, outfile, level, name_): if self.listofallmembers: showIndent(outfile, level) outfile.write('listofallmembers=model_.listofallmembersType(\n') - self.listofallmembers.exportLiteral(outfile, level, name_='listofallmembers') + self.listofallmembers.exportLiteral( + outfile, level, name_='listofallmembers') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value @@ -724,120 +823,121 @@ def buildAttributes(self, attrs): self.prot = attrs.get('prot').value if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'compoundname': + nodeName_ == 'compoundname': compoundname_ = '' for text__content_ in child_.childNodes: compoundname_ += text__content_.nodeValue self.compoundname = compoundname_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': obj_ = docTitleType.factory() obj_.build(child_) self.set_title(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'basecompoundref': + nodeName_ == 'basecompoundref': obj_ = compoundRefType.factory() obj_.build(child_) self.basecompoundref.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'derivedcompoundref': + nodeName_ == 'derivedcompoundref': obj_ = compoundRefType.factory() obj_.build(child_) self.derivedcompoundref.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'includes': + nodeName_ == 'includes': obj_ = incType.factory() obj_.build(child_) self.includes.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'includedby': + nodeName_ == 'includedby': obj_ = incType.factory() obj_.build(child_) self.includedby.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'incdepgraph': + nodeName_ == 'incdepgraph': obj_ = graphType.factory() obj_.build(child_) self.set_incdepgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'invincdepgraph': + nodeName_ == 'invincdepgraph': obj_ = graphType.factory() obj_.build(child_) self.set_invincdepgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innerdir': + nodeName_ == 'innerdir': obj_ = refType.factory() obj_.build(child_) self.innerdir.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innerfile': + nodeName_ == 'innerfile': obj_ = refType.factory() obj_.build(child_) self.innerfile.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innerclass': + nodeName_ == 'innerclass': obj_ = refType.factory() obj_.build(child_) self.innerclass.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innernamespace': + nodeName_ == 'innernamespace': obj_ = refType.factory() obj_.build(child_) self.innernamespace.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innerpage': + nodeName_ == 'innerpage': obj_ = refType.factory() obj_.build(child_) self.innerpage.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innergroup': + nodeName_ == 'innergroup': obj_ = refType.factory() obj_.build(child_) self.innergroup.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'templateparamlist': + nodeName_ == 'templateparamlist': obj_ = templateparamlistType.factory() obj_.build(child_) self.set_templateparamlist(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sectiondef': + nodeName_ == 'sectiondef': obj_ = sectiondefType.factory() obj_.build(child_) self.sectiondef.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'briefdescription': + nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'detaileddescription': + nodeName_ == 'detaileddescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_detaileddescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'inheritancegraph': + nodeName_ == 'inheritancegraph': obj_ = graphType.factory() obj_.build(child_) self.set_inheritancegraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'collaborationgraph': + nodeName_ == 'collaborationgraph': obj_ = graphType.factory() obj_.build(child_) self.set_collaborationgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'programlisting': + nodeName_ == 'programlisting': obj_ = listingType.factory() obj_.build(child_) self.set_programlisting(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'location': + nodeName_ == 'location': obj_ = locationType.factory() obj_.build(child_) self.set_location(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'listofallmembers': + nodeName_ == 'listofallmembers': obj_ = listofallmembersType.factory() obj_.build(child_) self.set_listofallmembers(obj_) @@ -847,11 +947,13 @@ def buildChildren(self, child_, nodeName_): class listofallmembersType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, member=None): if member is None: self.member = [] else: self.member = member + def factory(*args_, **kwargs_): if listofallmembersType.subclass: return listofallmembersType.subclass(*args_, **kwargs_) @@ -862,10 +964,12 @@ def get_member(self): return self.member def set_member(self, member): self.member = member def add_member(self, value): self.member.append(value) def insert_member(self, index, value): self.member[index] = value + def export(self, outfile, level, namespace_='', name_='listofallmembersType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='listofallmembersType') + self.exportAttributes(outfile, level, namespace_, + name_='listofallmembersType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -873,25 +977,31 @@ def export(self, outfile, level, namespace_='', name_='listofallmembersType', na outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='listofallmembersType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='listofallmembersType'): for member_ in self.member: member_.export(outfile, level, namespace_, name_='member') + def hasContent_(self): if ( self.member is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='listofallmembersType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('member=[\n') @@ -905,17 +1015,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'member': + nodeName_ == 'member': obj_ = memberRefType.factory() obj_.build(child_) self.member.append(obj_) @@ -925,6 +1038,7 @@ def buildChildren(self, child_, nodeName_): class memberRefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope=None, name=None): self.virt = virt self.prot = prot @@ -932,6 +1046,7 @@ def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope= self.ambiguityscope = ambiguityscope self.scope = scope self.name = name + def factory(*args_, **kwargs_): if memberRefType.subclass: return memberRefType.subclass(*args_, **kwargs_) @@ -949,11 +1064,15 @@ def set_prot(self, prot): self.prot = prot def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_ambiguityscope(self): return self.ambiguityscope - def set_ambiguityscope(self, ambiguityscope): self.ambiguityscope = ambiguityscope + + def set_ambiguityscope( + self, ambiguityscope): self.ambiguityscope = ambiguityscope + def export(self, outfile, level, namespace_='', name_='memberRefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='memberRefType') + self.exportAttributes(outfile, level, namespace_, + name_='memberRefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -961,35 +1080,44 @@ def export(self, outfile, level, namespace_='', name_='memberRefType', namespace outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='memberRefType'): if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.ambiguityscope is not None: - outfile.write(' ambiguityscope=%s' % (self.format_string(quote_attrib(self.ambiguityscope).encode(ExternalEncoding), input_name='ambiguityscope'), )) + outfile.write(' ambiguityscope=%s' % (self.format_string(quote_attrib( + self.ambiguityscope).encode(ExternalEncoding), input_name='ambiguityscope'), )) + def exportChildren(self, outfile, level, namespace_='', name_='memberRefType'): if self.scope is not None: showIndent(outfile, level) - outfile.write('<%sscope>%s\n' % (namespace_, self.format_string(quote_xml(self.scope).encode(ExternalEncoding), input_name='scope'), namespace_)) + outfile.write('<%sscope>%s\n' % (namespace_, self.format_string( + quote_xml(self.scope).encode(ExternalEncoding), input_name='scope'), namespace_)) if self.name is not None: showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + outfile.write('<%sname>%s\n' % (namespace_, self.format_string( + quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + def hasContent_(self): if ( self.scope is not None or self.name is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='memberRefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.virt is not None: showIndent(outfile, level) @@ -1003,17 +1131,22 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.ambiguityscope is not None: showIndent(outfile, level) outfile.write('ambiguityscope = %s,\n' % (self.ambiguityscope,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('scope=%s,\n' % quote_python(self.scope).encode(ExternalEncoding)) + outfile.write('scope=%s,\n' % quote_python( + self.scope).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) + outfile.write('name=%s,\n' % quote_python( + self.name).encode(ExternalEncoding)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('virt'): self.virt = attrs.get('virt').value @@ -1023,15 +1156,16 @@ def buildAttributes(self, attrs): self.refid = attrs.get('refid').value if attrs.get('ambiguityscope'): self.ambiguityscope = attrs.get('ambiguityscope').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'scope': + nodeName_ == 'scope': scope_ = '' for text__content_ in child_.childNodes: scope_ += text__content_.nodeValue self.scope = scope_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue @@ -1042,8 +1176,10 @@ def buildChildren(self, child_, nodeName_): class scope(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if scope.subclass: return scope.subclass(*args_, **kwargs_) @@ -1052,6 +1188,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='scope', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1063,33 +1200,40 @@ def export(self, outfile, level, namespace_='', name_='scope', namespacedef_='') outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='scope'): pass + def exportChildren(self, outfile, level, namespace_='', name_='scope'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='scope'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1097,21 +1241,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class scope class name(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if name.subclass: return name.subclass(*args_, **kwargs_) @@ -1120,6 +1268,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='name', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1131,33 +1280,40 @@ def export(self, outfile, level, namespace_='', name_='name', namespacedef_=''): outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='name'): pass + def exportChildren(self, outfile, level, namespace_='', name_='name'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='name'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1165,19 +1321,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class name class compoundRefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.virt = virt self.prot = prot @@ -1190,6 +1349,7 @@ def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=No self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if compoundRefType.subclass: return compoundRefType.subclass(*args_, **kwargs_) @@ -1204,40 +1364,48 @@ def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='compoundRefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='compoundRefType') + self.exportAttributes(outfile, level, namespace_, + name_='compoundRefType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='compoundRefType'): if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='compoundRefType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='compoundRefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.virt is not None: showIndent(outfile, level) @@ -1248,9 +1416,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1258,6 +1428,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('virt'): self.virt = attrs.get('virt').value @@ -1265,21 +1436,23 @@ def buildAttributes(self, attrs): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class compoundRefType class reimplementType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid if mixedclass_ is None: @@ -1290,6 +1463,7 @@ def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if reimplementType.subclass: return reimplementType.subclass(*args_, **kwargs_) @@ -1300,43 +1474,53 @@ def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='reimplementType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='reimplementType') + self.exportAttributes(outfile, level, namespace_, + name_='reimplementType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='reimplementType'): if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='reimplementType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='reimplementType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1344,24 +1528,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class reimplementType class incType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.local = local self.refid = refid @@ -1373,6 +1560,7 @@ def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, conten self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if incType.subclass: return incType.subclass(*args_, **kwargs_) @@ -1385,6 +1573,7 @@ def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='incType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1392,31 +1581,37 @@ def export(self, outfile, level, namespace_='', name_='incType', namespacedef_=' outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='incType'): if self.local is not None: outfile.write(' local=%s' % (quote_attrib(self.local), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='incType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='incType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.local is not None: showIndent(outfile, level) @@ -1424,9 +1619,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1434,26 +1631,29 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('local'): self.local = attrs.get('local').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class incType class refType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.prot = prot self.refid = refid @@ -1465,6 +1665,7 @@ def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if refType.subclass: return refType.subclass(*args_, **kwargs_) @@ -1477,6 +1678,7 @@ def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='refType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1484,31 +1686,37 @@ def export(self, outfile, level, namespace_='', name_='refType', namespacedef_=' outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='refType'): if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='refType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='refType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.prot is not None: showIndent(outfile, level) @@ -1516,9 +1724,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1526,26 +1736,29 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class refType class refTextType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid self.kindref = kindref @@ -1558,6 +1771,7 @@ def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedcl self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if refTextType.subclass: return refTextType.subclass(*args_, **kwargs_) @@ -1572,6 +1786,7 @@ def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='refTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1579,33 +1794,40 @@ def export(self, outfile, level, namespace_='', name_='refTextType', namespacede outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='refTextType'): if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.kindref is not None: outfile.write(' kindref=%s' % (quote_attrib(self.kindref), )) if self.external is not None: - outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) + outfile.write(' external=%s' % (self.format_string(quote_attrib( + self.external).encode(ExternalEncoding), input_name='external'), )) + def exportChildren(self, outfile, level, namespace_='', name_='refTextType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='refTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) @@ -1616,9 +1838,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1626,6 +1850,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value @@ -1633,21 +1858,23 @@ def buildAttributes(self, attrs): self.kindref = attrs.get('kindref').value if attrs.get('external'): self.external = attrs.get('external').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class refTextType class sectiondefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, header=None, description=None, memberdef=None): self.kind = kind self.header = header @@ -1656,6 +1883,7 @@ def __init__(self, kind=None, header=None, description=None, memberdef=None): self.memberdef = [] else: self.memberdef = memberdef + def factory(*args_, **kwargs_): if sectiondefType.subclass: return sectiondefType.subclass(*args_, **kwargs_) @@ -1672,10 +1900,12 @@ def add_memberdef(self, value): self.memberdef.append(value) def insert_memberdef(self, index, value): self.memberdef[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind + def export(self, outfile, level, namespace_='', name_='sectiondefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='sectiondefType') + self.exportAttributes(outfile, level, namespace_, + name_='sectiondefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -1683,38 +1913,47 @@ def export(self, outfile, level, namespace_='', name_='sectiondefType', namespac outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='sectiondefType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) + def exportChildren(self, outfile, level, namespace_='', name_='sectiondefType'): if self.header is not None: showIndent(outfile, level) - outfile.write('<%sheader>%s\n' % (namespace_, self.format_string(quote_xml(self.header).encode(ExternalEncoding), input_name='header'), namespace_)) + outfile.write('<%sheader>%s\n' % (namespace_, self.format_string( + quote_xml(self.header).encode(ExternalEncoding), input_name='header'), namespace_)) if self.description: - self.description.export(outfile, level, namespace_, name_='description') + self.description.export( + outfile, level, namespace_, name_='description') for memberdef_ in self.memberdef: memberdef_.export(outfile, level, namespace_, name_='memberdef') + def hasContent_(self): if ( self.header is not None or self.description is not None or self.memberdef is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='sectiondefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('header=%s,\n' % quote_python(self.header).encode(ExternalEncoding)) + outfile.write('header=%s,\n' % quote_python( + self.header).encode(ExternalEncoding)) if self.description: showIndent(outfile, level) outfile.write('description=model_.descriptionType(\n') @@ -1733,29 +1972,32 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'header': + nodeName_ == 'header': header_ = '' for text__content_ in child_.childNodes: header_ += text__content_.nodeValue self.header = header_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'description': + nodeName_ == 'description': obj_ = descriptionType.factory() obj_.build(child_) self.set_description(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'memberdef': + nodeName_ == 'memberdef': obj_ = memberdefType.factory() obj_.build(child_) self.memberdef.append(obj_) @@ -1765,6 +2007,7 @@ def buildChildren(self, child_, nodeName_): class memberdefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, initonly=None, kind=None, volatile=None, const=None, raisexx=None, virt=None, readable=None, prot=None, explicit=None, new=None, final=None, writable=None, add=None, static=None, remove=None, sealed=None, mutable=None, gettable=None, inline=None, settable=None, id=None, templateparamlist=None, type_=None, definition=None, argsstring=None, name=None, read=None, write=None, bitfield=None, reimplements=None, reimplementedby=None, param=None, enumvalue=None, initializer=None, exceptions=None, briefdescription=None, detaileddescription=None, inbodydescription=None, location=None, references=None, referencedby=None): self.initonly = initonly self.kind = kind @@ -1825,6 +2068,7 @@ def __init__(self, initonly=None, kind=None, volatile=None, const=None, raisexx= self.referencedby = [] else: self.referencedby = referencedby + def factory(*args_, **kwargs_): if memberdefType.subclass: return memberdefType.subclass(*args_, **kwargs_) @@ -1832,7 +2076,9 @@ def factory(*args_, **kwargs_): return memberdefType(*args_, **kwargs_) factory = staticmethod(factory) def get_templateparamlist(self): return self.templateparamlist - def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist + def set_templateparamlist( + self, templateparamlist): self.templateparamlist = templateparamlist + def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_definition(self): return self.definition @@ -1850,11 +2096,17 @@ def set_bitfield(self, bitfield): self.bitfield = bitfield def get_reimplements(self): return self.reimplements def set_reimplements(self, reimplements): self.reimplements = reimplements def add_reimplements(self, value): self.reimplements.append(value) - def insert_reimplements(self, index, value): self.reimplements[index] = value + def insert_reimplements( + self, index, value): self.reimplements[index] = value + def get_reimplementedby(self): return self.reimplementedby - def set_reimplementedby(self, reimplementedby): self.reimplementedby = reimplementedby + def set_reimplementedby( + self, reimplementedby): self.reimplementedby = reimplementedby + def add_reimplementedby(self, value): self.reimplementedby.append(value) - def insert_reimplementedby(self, index, value): self.reimplementedby[index] = value + def insert_reimplementedby( + self, index, value): self.reimplementedby[index] = value + def get_param(self): return self.param def set_param(self, param): self.param = param def add_param(self, value): self.param.append(value) @@ -1868,11 +2120,17 @@ def set_initializer(self, initializer): self.initializer = initializer def get_exceptions(self): return self.exceptions def set_exceptions(self, exceptions): self.exceptions = exceptions def get_briefdescription(self): return self.briefdescription - def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription + def set_briefdescription( + self, briefdescription): self.briefdescription = briefdescription + def get_detaileddescription(self): return self.detaileddescription - def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription + def set_detaileddescription( + self, detaileddescription): self.detaileddescription = detaileddescription + def get_inbodydescription(self): return self.inbodydescription - def set_inbodydescription(self, inbodydescription): self.inbodydescription = inbodydescription + def set_inbodydescription( + self, inbodydescription): self.inbodydescription = inbodydescription + def get_location(self): return self.location def set_location(self, location): self.location = location def get_references(self): return self.references @@ -1882,7 +2140,9 @@ def insert_references(self, index, value): self.references[index] = value def get_referencedby(self): return self.referencedby def set_referencedby(self, referencedby): self.referencedby = referencedby def add_referencedby(self, value): self.referencedby.append(value) - def insert_referencedby(self, index, value): self.referencedby[index] = value + def insert_referencedby( + self, index, value): self.referencedby[index] = value + def get_initonly(self): return self.initonly def set_initonly(self, initonly): self.initonly = initonly def get_kind(self): return self.kind @@ -1925,10 +2185,12 @@ def get_settable(self): return self.settable def set_settable(self, settable): self.settable = settable def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='memberdefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='memberdefType') + self.exportAttributes(outfile, level, namespace_, + name_='memberdefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -1936,6 +2198,7 @@ def export(self, outfile, level, namespace_='', name_='memberdefType', namespace outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='memberdefType'): if self.initonly is not None: outfile.write(' initonly=%s' % (quote_attrib(self.initonly), )) @@ -1978,54 +2241,73 @@ def exportAttributes(self, outfile, level, namespace_='', name_='memberdefType') if self.settable is not None: outfile.write(' settable=%s' % (quote_attrib(self.settable), )) if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='memberdefType'): if self.templateparamlist: - self.templateparamlist.export(outfile, level, namespace_, name_='templateparamlist') + self.templateparamlist.export( + outfile, level, namespace_, name_='templateparamlist') if self.type_: self.type_.export(outfile, level, namespace_, name_='type') if self.definition is not None: showIndent(outfile, level) - outfile.write('<%sdefinition>%s\n' % (namespace_, self.format_string(quote_xml(self.definition).encode(ExternalEncoding), input_name='definition'), namespace_)) + outfile.write('<%sdefinition>%s\n' % (namespace_, self.format_string( + quote_xml(self.definition).encode(ExternalEncoding), input_name='definition'), namespace_)) if self.argsstring is not None: showIndent(outfile, level) - outfile.write('<%sargsstring>%s\n' % (namespace_, self.format_string(quote_xml(self.argsstring).encode(ExternalEncoding), input_name='argsstring'), namespace_)) + outfile.write('<%sargsstring>%s\n' % (namespace_, self.format_string( + quote_xml(self.argsstring).encode(ExternalEncoding), input_name='argsstring'), namespace_)) if self.name is not None: showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + outfile.write('<%sname>%s\n' % (namespace_, self.format_string( + quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) if self.read is not None: showIndent(outfile, level) - outfile.write('<%sread>%s\n' % (namespace_, self.format_string(quote_xml(self.read).encode(ExternalEncoding), input_name='read'), namespace_)) + outfile.write('<%sread>%s\n' % (namespace_, self.format_string( + quote_xml(self.read).encode(ExternalEncoding), input_name='read'), namespace_)) if self.write is not None: showIndent(outfile, level) - outfile.write('<%swrite>%s\n' % (namespace_, self.format_string(quote_xml(self.write).encode(ExternalEncoding), input_name='write'), namespace_)) + outfile.write('<%swrite>%s\n' % (namespace_, self.format_string( + quote_xml(self.write).encode(ExternalEncoding), input_name='write'), namespace_)) if self.bitfield is not None: showIndent(outfile, level) - outfile.write('<%sbitfield>%s\n' % (namespace_, self.format_string(quote_xml(self.bitfield).encode(ExternalEncoding), input_name='bitfield'), namespace_)) + outfile.write('<%sbitfield>%s\n' % (namespace_, self.format_string( + quote_xml(self.bitfield).encode(ExternalEncoding), input_name='bitfield'), namespace_)) for reimplements_ in self.reimplements: - reimplements_.export(outfile, level, namespace_, name_='reimplements') + reimplements_.export( + outfile, level, namespace_, name_='reimplements') for reimplementedby_ in self.reimplementedby: - reimplementedby_.export(outfile, level, namespace_, name_='reimplementedby') + reimplementedby_.export( + outfile, level, namespace_, name_='reimplementedby') for param_ in self.param: param_.export(outfile, level, namespace_, name_='param') for enumvalue_ in self.enumvalue: enumvalue_.export(outfile, level, namespace_, name_='enumvalue') if self.initializer: - self.initializer.export(outfile, level, namespace_, name_='initializer') + self.initializer.export( + outfile, level, namespace_, name_='initializer') if self.exceptions: - self.exceptions.export(outfile, level, namespace_, name_='exceptions') + self.exceptions.export( + outfile, level, namespace_, name_='exceptions') if self.briefdescription: - self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') + self.briefdescription.export( + outfile, level, namespace_, name_='briefdescription') if self.detaileddescription: - self.detaileddescription.export(outfile, level, namespace_, name_='detaileddescription') + self.detaileddescription.export( + outfile, level, namespace_, name_='detaileddescription') if self.inbodydescription: - self.inbodydescription.export(outfile, level, namespace_, name_='inbodydescription') + self.inbodydescription.export( + outfile, level, namespace_, name_='inbodydescription') if self.location: - self.location.export(outfile, level, namespace_, name_='location', ) + self.location.export( + outfile, level, namespace_, name_='location', ) for references_ in self.references: references_.export(outfile, level, namespace_, name_='references') for referencedby_ in self.referencedby: - referencedby_.export(outfile, level, namespace_, name_='referencedby') + referencedby_.export( + outfile, level, namespace_, name_='referencedby') + def hasContent_(self): if ( self.templateparamlist is not None or @@ -2048,15 +2330,17 @@ def hasContent_(self): self.location is not None or self.references is not None or self.referencedby is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='memberdefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.initonly is not None: showIndent(outfile, level) @@ -2121,11 +2405,13 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): if self.templateparamlist: showIndent(outfile, level) outfile.write('templateparamlist=model_.templateparamlistType(\n') - self.templateparamlist.exportLiteral(outfile, level, name_='templateparamlist') + self.templateparamlist.exportLiteral( + outfile, level, name_='templateparamlist') showIndent(outfile, level) outfile.write('),\n') if self.type_: @@ -2135,17 +2421,23 @@ def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) - outfile.write('definition=%s,\n' % quote_python(self.definition).encode(ExternalEncoding)) + outfile.write('definition=%s,\n' % quote_python( + self.definition).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('argsstring=%s,\n' % quote_python(self.argsstring).encode(ExternalEncoding)) + outfile.write('argsstring=%s,\n' % quote_python( + self.argsstring).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) + outfile.write('name=%s,\n' % quote_python( + self.name).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('read=%s,\n' % quote_python(self.read).encode(ExternalEncoding)) + outfile.write('read=%s,\n' % quote_python( + self.read).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('write=%s,\n' % quote_python(self.write).encode(ExternalEncoding)) + outfile.write('write=%s,\n' % quote_python( + self.write).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('bitfield=%s,\n' % quote_python(self.bitfield).encode(ExternalEncoding)) + outfile.write('bitfield=%s,\n' % quote_python( + self.bitfield).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('reimplements=[\n') level += 1 @@ -2164,7 +2456,8 @@ def exportLiteralChildren(self, outfile, level, name_): for reimplementedby in self.reimplementedby: showIndent(outfile, level) outfile.write('model_.reimplementedby(\n') - reimplementedby.exportLiteral(outfile, level, name_='reimplementedby') + reimplementedby.exportLiteral( + outfile, level, name_='reimplementedby') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -2209,19 +2502,22 @@ def exportLiteralChildren(self, outfile, level, name_): if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') - self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') + self.briefdescription.exportLiteral( + outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') if self.detaileddescription: showIndent(outfile, level) outfile.write('detaileddescription=model_.descriptionType(\n') - self.detaileddescription.exportLiteral(outfile, level, name_='detaileddescription') + self.detaileddescription.exportLiteral( + outfile, level, name_='detaileddescription') showIndent(outfile, level) outfile.write('),\n') if self.inbodydescription: showIndent(outfile, level) outfile.write('inbodydescription=model_.descriptionType(\n') - self.inbodydescription.exportLiteral(outfile, level, name_='inbodydescription') + self.inbodydescription.exportLiteral( + outfile, level, name_='inbodydescription') showIndent(outfile, level) outfile.write('),\n') if self.location: @@ -2254,12 +2550,14 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('initonly'): self.initonly = attrs.get('initonly').value @@ -2303,110 +2601,111 @@ def buildAttributes(self, attrs): self.settable = attrs.get('settable').value if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'templateparamlist': + nodeName_ == 'templateparamlist': obj_ = templateparamlistType.factory() obj_.build(child_) self.set_templateparamlist(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'type': + nodeName_ == 'type': obj_ = linkedTextType.factory() obj_.build(child_) self.set_type(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'definition': + nodeName_ == 'definition': definition_ = '' for text__content_ in child_.childNodes: definition_ += text__content_.nodeValue self.definition = definition_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'argsstring': + nodeName_ == 'argsstring': argsstring_ = '' for text__content_ in child_.childNodes: argsstring_ += text__content_.nodeValue self.argsstring = argsstring_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue self.name = name_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'read': + nodeName_ == 'read': read_ = '' for text__content_ in child_.childNodes: read_ += text__content_.nodeValue self.read = read_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'write': + nodeName_ == 'write': write_ = '' for text__content_ in child_.childNodes: write_ += text__content_.nodeValue self.write = write_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'bitfield': + nodeName_ == 'bitfield': bitfield_ = '' for text__content_ in child_.childNodes: bitfield_ += text__content_.nodeValue self.bitfield = bitfield_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'reimplements': + nodeName_ == 'reimplements': obj_ = reimplementType.factory() obj_.build(child_) self.reimplements.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'reimplementedby': + nodeName_ == 'reimplementedby': obj_ = reimplementType.factory() obj_.build(child_) self.reimplementedby.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'param': + nodeName_ == 'param': obj_ = paramType.factory() obj_.build(child_) self.param.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'enumvalue': + nodeName_ == 'enumvalue': obj_ = enumvalueType.factory() obj_.build(child_) self.enumvalue.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'initializer': + nodeName_ == 'initializer': obj_ = linkedTextType.factory() obj_.build(child_) self.set_initializer(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'exceptions': + nodeName_ == 'exceptions': obj_ = linkedTextType.factory() obj_.build(child_) self.set_exceptions(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'briefdescription': + nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'detaileddescription': + nodeName_ == 'detaileddescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_detaileddescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'inbodydescription': + nodeName_ == 'inbodydescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_inbodydescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'location': + nodeName_ == 'location': obj_ = locationType.factory() obj_.build(child_) self.set_location(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'references': + nodeName_ == 'references': obj_ = referenceType.factory() obj_.build(child_) self.references.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'referencedby': + nodeName_ == 'referencedby': obj_ = referenceType.factory() obj_.build(child_) self.referencedby.append(obj_) @@ -2416,8 +2715,10 @@ def buildChildren(self, child_, nodeName_): class definition(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if definition.subclass: return definition.subclass(*args_, **kwargs_) @@ -2426,6 +2727,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='definition', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2437,33 +2739,40 @@ def export(self, outfile, level, namespace_='', name_='definition', namespacedef outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='definition'): pass + def exportChildren(self, outfile, level, namespace_='', name_='definition'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='definition'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2471,21 +2780,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class definition class argsstring(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if argsstring.subclass: return argsstring.subclass(*args_, **kwargs_) @@ -2494,6 +2807,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='argsstring', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2505,33 +2819,40 @@ def export(self, outfile, level, namespace_='', name_='argsstring', namespacedef outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='argsstring'): pass + def exportChildren(self, outfile, level, namespace_='', name_='argsstring'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='argsstring'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2539,21 +2860,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class argsstring class read(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if read.subclass: return read.subclass(*args_, **kwargs_) @@ -2562,6 +2887,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='read', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2573,33 +2899,40 @@ def export(self, outfile, level, namespace_='', name_='read', namespacedef_=''): outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='read'): pass + def exportChildren(self, outfile, level, namespace_='', name_='read'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='read'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2607,21 +2940,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class read class write(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if write.subclass: return write.subclass(*args_, **kwargs_) @@ -2630,6 +2967,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='write', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2641,33 +2979,40 @@ def export(self, outfile, level, namespace_='', name_='write', namespacedef_='') outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='write'): pass + def exportChildren(self, outfile, level, namespace_='', name_='write'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='write'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2675,21 +3020,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class write class bitfield(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if bitfield.subclass: return bitfield.subclass(*args_, **kwargs_) @@ -2698,6 +3047,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='bitfield', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2709,33 +3059,40 @@ def export(self, outfile, level, namespace_='', name_='bitfield', namespacedef_= outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='bitfield'): pass + def exportChildren(self, outfile, level, namespace_='', name_='bitfield'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='bitfield'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2743,19 +3100,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class bitfield class descriptionType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, title=None, para=None, sect1=None, internal=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -2765,6 +3125,7 @@ def __init__(self, title=None, para=None, sect1=None, internal=None, mixedclass_ self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if descriptionType.subclass: return descriptionType.subclass(*args_, **kwargs_) @@ -2783,35 +3144,43 @@ def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal + def export(self, outfile, level, namespace_='', name_='descriptionType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='descriptionType') + self.exportAttributes(outfile, level, namespace_, + name_='descriptionType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='descriptionType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='descriptionType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect1 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='descriptionType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -2837,46 +3206,49 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect1': + nodeName_ == 'sect1': childobj_ = docSect1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect1', childobj_) + MixedContainer.TypeNone, 'sect1', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class descriptionType @@ -2884,6 +3256,7 @@ def buildChildren(self, child_, nodeName_): class enumvalueType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, prot=None, id=None, name=None, initializer=None, briefdescription=None, detaileddescription=None, mixedclass_=None, content_=None): self.prot = prot self.id = id @@ -2895,6 +3268,7 @@ def __init__(self, prot=None, id=None, name=None, initializer=None, briefdescrip self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if enumvalueType.subclass: return enumvalueType.subclass(*args_, **kwargs_) @@ -2906,43 +3280,55 @@ def set_name(self, name): self.name = name def get_initializer(self): return self.initializer def set_initializer(self, initializer): self.initializer = initializer def get_briefdescription(self): return self.briefdescription - def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription + def set_briefdescription( + self, briefdescription): self.briefdescription = briefdescription + def get_detaileddescription(self): return self.detaileddescription - def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription + def set_detaileddescription( + self, detaileddescription): self.detaileddescription = detaileddescription + def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='enumvalueType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='enumvalueType') + self.exportAttributes(outfile, level, namespace_, + name_='enumvalueType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='enumvalueType'): if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='enumvalueType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.name is not None or self.initializer is not None or self.briefdescription is not None or self.detaileddescription is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='enumvalueType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.prot is not None: showIndent(outfile, level) @@ -2950,6 +3336,7 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -2975,51 +3362,54 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': value_ = [] for text_ in child_.childNodes: value_.append(text_.nodeValue) valuestr_ = ''.join(value_) obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'name', valuestr_) + MixedContainer.TypeString, 'name', valuestr_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'initializer': + nodeName_ == 'initializer': childobj_ = linkedTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'initializer', childobj_) + MixedContainer.TypeNone, 'initializer', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'briefdescription': + nodeName_ == 'briefdescription': childobj_ = descriptionType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'briefdescription', childobj_) + MixedContainer.TypeNone, 'briefdescription', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'detaileddescription': + nodeName_ == 'detaileddescription': childobj_ = descriptionType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'detaileddescription', childobj_) + MixedContainer.TypeNone, 'detaileddescription', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class enumvalueType @@ -3027,11 +3417,13 @@ def buildChildren(self, child_, nodeName_): class templateparamlistType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, param=None): if param is None: self.param = [] else: self.param = param + def factory(*args_, **kwargs_): if templateparamlistType.subclass: return templateparamlistType.subclass(*args_, **kwargs_) @@ -3042,10 +3434,12 @@ def get_param(self): return self.param def set_param(self, param): self.param = param def add_param(self, value): self.param.append(value) def insert_param(self, index, value): self.param[index] = value + def export(self, outfile, level, namespace_='', name_='templateparamlistType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='templateparamlistType') + self.exportAttributes(outfile, level, namespace_, + name_='templateparamlistType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -3053,25 +3447,31 @@ def export(self, outfile, level, namespace_='', name_='templateparamlistType', n outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='templateparamlistType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='templateparamlistType'): for param_ in self.param: param_.export(outfile, level, namespace_, name_='param') + def hasContent_(self): if ( self.param is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='templateparamlistType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('param=[\n') @@ -3085,17 +3485,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'param': + nodeName_ == 'param': obj_ = paramType.factory() obj_.build(child_) self.param.append(obj_) @@ -3105,6 +3508,7 @@ def buildChildren(self, child_, nodeName_): class paramType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, type_=None, declname=None, defname=None, array=None, defval=None, briefdescription=None): self.type_ = type_ self.declname = declname @@ -3112,6 +3516,7 @@ def __init__(self, type_=None, declname=None, defname=None, array=None, defval=N self.array = array self.defval = defval self.briefdescription = briefdescription + def factory(*args_, **kwargs_): if paramType.subclass: return paramType.subclass(*args_, **kwargs_) @@ -3129,7 +3534,10 @@ def set_array(self, array): self.array = array def get_defval(self): return self.defval def set_defval(self, defval): self.defval = defval def get_briefdescription(self): return self.briefdescription - def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription + + def set_briefdescription( + self, briefdescription): self.briefdescription = briefdescription + def export(self, outfile, level, namespace_='', name_='paramType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3141,24 +3549,31 @@ def export(self, outfile, level, namespace_='', name_='paramType', namespacedef_ outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='paramType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='paramType'): if self.type_: self.type_.export(outfile, level, namespace_, name_='type') if self.declname is not None: showIndent(outfile, level) - outfile.write('<%sdeclname>%s\n' % (namespace_, self.format_string(quote_xml(self.declname).encode(ExternalEncoding), input_name='declname'), namespace_)) + outfile.write('<%sdeclname>%s\n' % (namespace_, self.format_string( + quote_xml(self.declname).encode(ExternalEncoding), input_name='declname'), namespace_)) if self.defname is not None: showIndent(outfile, level) - outfile.write('<%sdefname>%s\n' % (namespace_, self.format_string(quote_xml(self.defname).encode(ExternalEncoding), input_name='defname'), namespace_)) + outfile.write('<%sdefname>%s\n' % (namespace_, self.format_string( + quote_xml(self.defname).encode(ExternalEncoding), input_name='defname'), namespace_)) if self.array is not None: showIndent(outfile, level) - outfile.write('<%sarray>%s\n' % (namespace_, self.format_string(quote_xml(self.array).encode(ExternalEncoding), input_name='array'), namespace_)) + outfile.write('<%sarray>%s\n' % (namespace_, self.format_string( + quote_xml(self.array).encode(ExternalEncoding), input_name='array'), namespace_)) if self.defval: self.defval.export(outfile, level, namespace_, name_='defval') if self.briefdescription: - self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') + self.briefdescription.export( + outfile, level, namespace_, name_='briefdescription') + def hasContent_(self): if ( self.type_ is not None or @@ -3167,17 +3582,20 @@ def hasContent_(self): self.array is not None or self.defval is not None or self.briefdescription is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='paramType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): if self.type_: showIndent(outfile, level) @@ -3186,11 +3604,14 @@ def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) - outfile.write('declname=%s,\n' % quote_python(self.declname).encode(ExternalEncoding)) + outfile.write('declname=%s,\n' % quote_python( + self.declname).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('defname=%s,\n' % quote_python(self.defname).encode(ExternalEncoding)) + outfile.write('defname=%s,\n' % quote_python( + self.defname).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('array=%s,\n' % quote_python(self.array).encode(ExternalEncoding)) + outfile.write('array=%s,\n' % quote_python( + self.array).encode(ExternalEncoding)) if self.defval: showIndent(outfile, level) outfile.write('defval=model_.linkedTextType(\n') @@ -3200,48 +3621,52 @@ def exportLiteralChildren(self, outfile, level, name_): if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') - self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') + self.briefdescription.exportLiteral( + outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'type': + nodeName_ == 'type': obj_ = linkedTextType.factory() obj_.build(child_) self.set_type(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'declname': + nodeName_ == 'declname': declname_ = '' for text__content_ in child_.childNodes: declname_ += text__content_.nodeValue self.declname = declname_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'defname': + nodeName_ == 'defname': defname_ = '' for text__content_ in child_.childNodes: defname_ += text__content_.nodeValue self.defname = defname_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'array': + nodeName_ == 'array': array_ = '' for text__content_ in child_.childNodes: array_ += text__content_.nodeValue self.array = array_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'defval': + nodeName_ == 'defval': obj_ = linkedTextType.factory() obj_.build(child_) self.set_defval(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'briefdescription': + nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) @@ -3251,8 +3676,10 @@ def buildChildren(self, child_, nodeName_): class declname(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if declname.subclass: return declname.subclass(*args_, **kwargs_) @@ -3261,6 +3688,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='declname', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3272,33 +3700,40 @@ def export(self, outfile, level, namespace_='', name_='declname', namespacedef_= outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='declname'): pass + def exportChildren(self, outfile, level, namespace_='', name_='declname'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='declname'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3306,21 +3741,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class declname class defname(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if defname.subclass: return defname.subclass(*args_, **kwargs_) @@ -3329,6 +3768,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='defname', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3340,33 +3780,40 @@ def export(self, outfile, level, namespace_='', name_='defname', namespacedef_=' outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='defname'): pass + def exportChildren(self, outfile, level, namespace_='', name_='defname'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='defname'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3374,21 +3821,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class defname class array(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if array.subclass: return array.subclass(*args_, **kwargs_) @@ -3397,6 +3848,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='array', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3408,33 +3860,40 @@ def export(self, outfile, level, namespace_='', name_='array', namespacedef_='') outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='array'): pass + def exportChildren(self, outfile, level, namespace_='', name_='array'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='array'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3442,19 +3901,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class array class linkedTextType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, ref=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -3464,6 +3926,7 @@ def __init__(self, ref=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if linkedTextType.subclass: return linkedTextType.subclass(*args_, **kwargs_) @@ -3474,32 +3937,40 @@ def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def add_ref(self, value): self.ref.append(value) def insert_ref(self, index, value): self.ref[index] = value + def export(self, outfile, level, namespace_='', name_='linkedTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='linkedTextType') + self.exportAttributes(outfile, level, namespace_, + name_='linkedTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='linkedTextType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='linkedTextType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.ref is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='linkedTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -3507,25 +3978,28 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'ref': + nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'ref', childobj_) + MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class linkedTextType @@ -3533,11 +4007,13 @@ def buildChildren(self, child_, nodeName_): class graphType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, node=None): if node is None: self.node = [] else: self.node = node + def factory(*args_, **kwargs_): if graphType.subclass: return graphType.subclass(*args_, **kwargs_) @@ -3548,6 +4024,7 @@ def get_node(self): return self.node def set_node(self, node): self.node = node def add_node(self, value): self.node.append(value) def insert_node(self, index, value): self.node[index] = value + def export(self, outfile, level, namespace_='', name_='graphType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3559,25 +4036,31 @@ def export(self, outfile, level, namespace_='', name_='graphType', namespacedef_ outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='graphType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='graphType'): for node_ in self.node: node_.export(outfile, level, namespace_, name_='node') + def hasContent_(self): if ( self.node is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='graphType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('node=[\n') @@ -3591,17 +4074,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'node': + nodeName_ == 'node': obj_ = nodeType.factory() obj_.build(child_) self.node.append(obj_) @@ -3611,6 +4097,7 @@ def buildChildren(self, child_, nodeName_): class nodeType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, label=None, link=None, childnode=None): self.id = id self.label = label @@ -3619,6 +4106,7 @@ def __init__(self, id=None, label=None, link=None, childnode=None): self.childnode = [] else: self.childnode = childnode + def factory(*args_, **kwargs_): if nodeType.subclass: return nodeType.subclass(*args_, **kwargs_) @@ -3635,6 +4123,7 @@ def add_childnode(self, value): self.childnode.append(value) def insert_childnode(self, index, value): self.childnode[index] = value def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='nodeType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3646,38 +4135,47 @@ def export(self, outfile, level, namespace_='', name_='nodeType', namespacedef_= outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='nodeType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='nodeType'): if self.label is not None: showIndent(outfile, level) - outfile.write('<%slabel>%s\n' % (namespace_, self.format_string(quote_xml(self.label).encode(ExternalEncoding), input_name='label'), namespace_)) + outfile.write('<%slabel>%s\n' % (namespace_, self.format_string( + quote_xml(self.label).encode(ExternalEncoding), input_name='label'), namespace_)) if self.link: self.link.export(outfile, level, namespace_, name_='link') for childnode_ in self.childnode: childnode_.export(outfile, level, namespace_, name_='childnode') + def hasContent_(self): if ( self.label is not None or self.link is not None or self.childnode is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='nodeType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('label=%s,\n' % quote_python(self.label).encode(ExternalEncoding)) + outfile.write('label=%s,\n' % quote_python( + self.label).encode(ExternalEncoding)) if self.link: showIndent(outfile, level) outfile.write('link=model_.linkType(\n') @@ -3696,29 +4194,32 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'label': + nodeName_ == 'label': label_ = '' for text__content_ in child_.childNodes: label_ += text__content_.nodeValue self.label = label_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'link': + nodeName_ == 'link': obj_ = linkType.factory() obj_.build(child_) self.set_link(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'childnode': + nodeName_ == 'childnode': obj_ = childnodeType.factory() obj_.build(child_) self.childnode.append(obj_) @@ -3728,8 +4229,10 @@ def buildChildren(self, child_, nodeName_): class label(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if label.subclass: return label.subclass(*args_, **kwargs_) @@ -3738,6 +4241,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='label', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3749,33 +4253,40 @@ def export(self, outfile, level, namespace_='', name_='label', namespacedef_='') outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='label'): pass + def exportChildren(self, outfile, level, namespace_='', name_='label'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='label'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3783,19 +4294,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class label class childnodeType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, relation=None, refid=None, edgelabel=None): self.relation = relation self.refid = refid @@ -3803,6 +4317,7 @@ def __init__(self, relation=None, refid=None, edgelabel=None): self.edgelabel = [] else: self.edgelabel = edgelabel + def factory(*args_, **kwargs_): if childnodeType.subclass: return childnodeType.subclass(*args_, **kwargs_) @@ -3817,10 +4332,12 @@ def get_relation(self): return self.relation def set_relation(self, relation): self.relation = relation def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid + def export(self, outfile, level, namespace_='', name_='childnodeType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='childnodeType') + self.exportAttributes(outfile, level, namespace_, + name_='childnodeType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -3828,27 +4345,34 @@ def export(self, outfile, level, namespace_='', name_='childnodeType', namespace outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='childnodeType'): if self.relation is not None: outfile.write(' relation=%s' % (quote_attrib(self.relation), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='childnodeType'): for edgelabel_ in self.edgelabel: showIndent(outfile, level) - outfile.write('<%sedgelabel>%s\n' % (namespace_, self.format_string(quote_xml(edgelabel_).encode(ExternalEncoding), input_name='edgelabel'), namespace_)) + outfile.write('<%sedgelabel>%s\n' % (namespace_, self.format_string( + quote_xml(edgelabel_).encode(ExternalEncoding), input_name='edgelabel'), namespace_)) + def hasContent_(self): if ( self.edgelabel is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='childnodeType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.relation is not None: showIndent(outfile, level) @@ -3856,30 +4380,35 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('edgelabel=[\n') level += 1 for edgelabel in self.edgelabel: showIndent(outfile, level) - outfile.write('%s,\n' % quote_python(edgelabel).encode(ExternalEncoding)) + outfile.write('%s,\n' % quote_python( + edgelabel).encode(ExternalEncoding)) level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('relation'): self.relation = attrs.get('relation').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'edgelabel': + nodeName_ == 'edgelabel': edgelabel_ = '' for text__content_ in child_.childNodes: edgelabel_ += text__content_.nodeValue @@ -3890,8 +4419,10 @@ def buildChildren(self, child_, nodeName_): class edgelabel(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if edgelabel.subclass: return edgelabel.subclass(*args_, **kwargs_) @@ -3900,6 +4431,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='edgelabel', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3911,33 +4443,40 @@ def export(self, outfile, level, namespace_='', name_='edgelabel', namespacedef_ outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='edgelabel'): pass + def exportChildren(self, outfile, level, namespace_='', name_='edgelabel'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='edgelabel'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3945,23 +4484,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class edgelabel class linkType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, refid=None, external=None, valueOf_=''): self.refid = refid self.external = external self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if linkType.subclass: return linkType.subclass(*args_, **kwargs_) @@ -3974,6 +4517,7 @@ def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='linkType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3985,31 +4529,38 @@ def export(self, outfile, level, namespace_='', name_='linkType', namespacedef_= outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='linkType'): if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.external is not None: - outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) + outfile.write(' external=%s' % (self.format_string(quote_attrib( + self.external).encode(ExternalEncoding), input_name='external'), )) + def exportChildren(self, outfile, level, namespace_='', name_='linkType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='linkType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) @@ -4017,9 +4568,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -4027,27 +4580,31 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('external'): self.external = attrs.get('external').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class linkType class listingType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, codeline=None): if codeline is None: self.codeline = [] else: self.codeline = codeline + def factory(*args_, **kwargs_): if listingType.subclass: return listingType.subclass(*args_, **kwargs_) @@ -4058,6 +4615,7 @@ def get_codeline(self): return self.codeline def set_codeline(self, codeline): self.codeline = codeline def add_codeline(self, value): self.codeline.append(value) def insert_codeline(self, index, value): self.codeline[index] = value + def export(self, outfile, level, namespace_='', name_='listingType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4069,25 +4627,31 @@ def export(self, outfile, level, namespace_='', name_='listingType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='listingType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='listingType'): for codeline_ in self.codeline: codeline_.export(outfile, level, namespace_, name_='codeline') + def hasContent_(self): if ( self.codeline is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='listingType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('codeline=[\n') @@ -4101,17 +4665,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'codeline': + nodeName_ == 'codeline': obj_ = codelineType.factory() obj_.build(child_) self.codeline.append(obj_) @@ -4121,6 +4688,7 @@ def buildChildren(self, child_, nodeName_): class codelineType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None): self.external = external self.lineno = lineno @@ -4130,6 +4698,7 @@ def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlig self.highlight = [] else: self.highlight = highlight + def factory(*args_, **kwargs_): if codelineType.subclass: return codelineType.subclass(*args_, **kwargs_) @@ -4148,6 +4717,7 @@ def get_refkind(self): return self.refkind def set_refkind(self, refkind): self.refkind = refkind def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid + def export(self, outfile, level, namespace_='', name_='codelineType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4159,30 +4729,37 @@ def export(self, outfile, level, namespace_='', name_='codelineType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='codelineType'): if self.external is not None: outfile.write(' external=%s' % (quote_attrib(self.external), )) if self.lineno is not None: - outfile.write(' lineno="%s"' % self.format_integer(self.lineno, input_name='lineno')) + outfile.write(' lineno="%s"' % self.format_integer( + self.lineno, input_name='lineno')) if self.refkind is not None: outfile.write(' refkind=%s' % (quote_attrib(self.refkind), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='codelineType'): for highlight_ in self.highlight: highlight_.export(outfile, level, namespace_, name_='highlight') + def hasContent_(self): if ( self.highlight is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='codelineType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) @@ -4196,6 +4773,7 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('highlight=[\n') @@ -4209,12 +4787,14 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('external'): self.external = attrs.get('external').value @@ -4227,9 +4807,10 @@ def buildAttributes(self, attrs): self.refkind = attrs.get('refkind').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'highlight': + nodeName_ == 'highlight': obj_ = highlightType.factory() obj_.build(child_) self.highlight.append(obj_) @@ -4239,6 +4820,7 @@ def buildChildren(self, child_, nodeName_): class highlightType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, classxx=None, sp=None, ref=None, mixedclass_=None, content_=None): self.classxx = classxx if mixedclass_ is None: @@ -4249,6 +4831,7 @@ def __init__(self, classxx=None, sp=None, ref=None, mixedclass_=None, content_=N self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if highlightType.subclass: return highlightType.subclass(*args_, **kwargs_) @@ -4265,36 +4848,44 @@ def add_ref(self, value): self.ref.append(value) def insert_ref(self, index, value): self.ref[index] = value def get_class(self): return self.classxx def set_class(self, classxx): self.classxx = classxx + def export(self, outfile, level, namespace_='', name_='highlightType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='highlightType') + self.exportAttributes(outfile, level, namespace_, + name_='highlightType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='highlightType'): if self.classxx is not None: outfile.write(' class=%s' % (quote_attrib(self.classxx), )) + def exportChildren(self, outfile, level, namespace_='', name_='highlightType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.sp is not None or self.ref is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='highlightType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.classxx is not None: showIndent(outfile, level) outfile.write('classxx = "%s",\n' % (self.classxx,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -4308,35 +4899,38 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('class'): self.classxx = attrs.get('class').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sp': + nodeName_ == 'sp': value_ = [] for text_ in child_.childNodes: value_.append(text_.nodeValue) valuestr_ = ''.join(value_) obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'sp', valuestr_) + MixedContainer.TypeString, 'sp', valuestr_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'ref': + nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'ref', childobj_) + MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class highlightType @@ -4344,8 +4938,10 @@ def buildChildren(self, child_, nodeName_): class sp(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if sp.subclass: return sp.subclass(*args_, **kwargs_) @@ -4354,6 +4950,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='sp', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4365,33 +4962,40 @@ def export(self, outfile, level, namespace_='', name_='sp', namespacedef_=''): outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='sp'): pass + def exportChildren(self, outfile, level, namespace_='', name_='sp'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='sp'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -4399,19 +5003,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class sp class referenceType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, endline=None, startline=None, refid=None, compoundref=None, valueOf_='', mixedclass_=None, content_=None): self.endline = endline self.startline = startline @@ -4425,6 +5032,7 @@ def __init__(self, endline=None, startline=None, refid=None, compoundref=None, v self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if referenceType.subclass: return referenceType.subclass(*args_, **kwargs_) @@ -4441,42 +5049,53 @@ def get_compoundref(self): return self.compoundref def set_compoundref(self, compoundref): self.compoundref = compoundref def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='referenceType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='referenceType') + self.exportAttributes(outfile, level, namespace_, + name_='referenceType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='referenceType'): if self.endline is not None: - outfile.write(' endline="%s"' % self.format_integer(self.endline, input_name='endline')) + outfile.write(' endline="%s"' % self.format_integer( + self.endline, input_name='endline')) if self.startline is not None: - outfile.write(' startline="%s"' % self.format_integer(self.startline, input_name='startline')) + outfile.write(' startline="%s"' % self.format_integer( + self.startline, input_name='startline')) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.compoundref is not None: - outfile.write(' compoundref=%s' % (self.format_string(quote_attrib(self.compoundref).encode(ExternalEncoding), input_name='compoundref'), )) + outfile.write(' compoundref=%s' % (self.format_string(quote_attrib( + self.compoundref).encode(ExternalEncoding), input_name='compoundref'), )) + def exportChildren(self, outfile, level, namespace_='', name_='referenceType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='referenceType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.endline is not None: showIndent(outfile, level) @@ -4490,9 +5109,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.compoundref is not None: showIndent(outfile, level) outfile.write('compoundref = %s,\n' % (self.compoundref,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -4500,6 +5121,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('endline'): try: @@ -4515,21 +5137,23 @@ def buildAttributes(self, attrs): self.refid = attrs.get('refid').value if attrs.get('compoundref'): self.compoundref = attrs.get('compoundref').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class referenceType class locationType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file=None, valueOf_=''): self.bodystart = bodystart self.line = line @@ -4537,6 +5161,7 @@ def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file= self.bodyfile = bodyfile self.file = file self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if locationType.subclass: return locationType.subclass(*args_, **kwargs_) @@ -4555,6 +5180,7 @@ def get_file(self): return self.file def set_file(self, file): self.file = file def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='locationType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4566,37 +5192,47 @@ def export(self, outfile, level, namespace_='', name_='locationType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='locationType'): if self.bodystart is not None: - outfile.write(' bodystart="%s"' % self.format_integer(self.bodystart, input_name='bodystart')) + outfile.write(' bodystart="%s"' % self.format_integer( + self.bodystart, input_name='bodystart')) if self.line is not None: - outfile.write(' line="%s"' % self.format_integer(self.line, input_name='line')) + outfile.write(' line="%s"' % self.format_integer( + self.line, input_name='line')) if self.bodyend is not None: - outfile.write(' bodyend="%s"' % self.format_integer(self.bodyend, input_name='bodyend')) + outfile.write(' bodyend="%s"' % self.format_integer( + self.bodyend, input_name='bodyend')) if self.bodyfile is not None: - outfile.write(' bodyfile=%s' % (self.format_string(quote_attrib(self.bodyfile).encode(ExternalEncoding), input_name='bodyfile'), )) + outfile.write(' bodyfile=%s' % (self.format_string(quote_attrib( + self.bodyfile).encode(ExternalEncoding), input_name='bodyfile'), )) if self.file is not None: - outfile.write(' file=%s' % (self.format_string(quote_attrib(self.file).encode(ExternalEncoding), input_name='file'), )) + outfile.write(' file=%s' % (self.format_string(quote_attrib( + self.file).encode(ExternalEncoding), input_name='file'), )) + def exportChildren(self, outfile, level, namespace_='', name_='locationType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='locationType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.bodystart is not None: showIndent(outfile, level) @@ -4613,9 +5249,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.file is not None: showIndent(outfile, level) outfile.write('file = %s,\n' % (self.file,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -4623,6 +5261,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('bodystart'): try: @@ -4643,17 +5282,19 @@ def buildAttributes(self, attrs): self.bodyfile = attrs.get('bodyfile').value if attrs.get('file'): self.file = attrs.get('file').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class locationType class docSect1Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, title=None, para=None, sect2=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -4664,6 +5305,7 @@ def __init__(self, id=None, title=None, para=None, sect2=None, internal=None, mi self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docSect1Type.subclass: return docSect1Type.subclass(*args_, **kwargs_) @@ -4684,6 +5326,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docSect1Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4691,31 +5334,38 @@ def export(self, outfile, level, namespace_='', name_='docSect1Type', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docSect1Type'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSect1Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect2 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSect1Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -4741,47 +5391,50 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect2': + nodeName_ == 'sect2': childobj_ = docSect2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect2', childobj_) + MixedContainer.TypeNone, 'sect2', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalS1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect1Type @@ -4789,6 +5442,7 @@ def buildChildren(self, child_, nodeName_): class docSect2Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, title=None, para=None, sect3=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -4799,6 +5453,7 @@ def __init__(self, id=None, title=None, para=None, sect3=None, internal=None, mi self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docSect2Type.subclass: return docSect2Type.subclass(*args_, **kwargs_) @@ -4819,6 +5474,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docSect2Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4826,31 +5482,38 @@ def export(self, outfile, level, namespace_='', name_='docSect2Type', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docSect2Type'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSect2Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect3 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSect2Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -4876,47 +5539,50 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect3': + nodeName_ == 'sect3': childobj_ = docSect3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect3', childobj_) + MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalS2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect2Type @@ -4924,6 +5590,7 @@ def buildChildren(self, child_, nodeName_): class docSect3Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, title=None, para=None, sect4=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -4934,6 +5601,7 @@ def __init__(self, id=None, title=None, para=None, sect4=None, internal=None, mi self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docSect3Type.subclass: return docSect3Type.subclass(*args_, **kwargs_) @@ -4954,6 +5622,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docSect3Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4961,31 +5630,38 @@ def export(self, outfile, level, namespace_='', name_='docSect3Type', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docSect3Type'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSect3Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect4 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSect3Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5011,47 +5687,50 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect4': + nodeName_ == 'sect4': childobj_ = docSect4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect4', childobj_) + MixedContainer.TypeNone, 'sect4', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalS3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect3Type @@ -5059,6 +5738,7 @@ def buildChildren(self, child_, nodeName_): class docSect4Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, title=None, para=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -5069,6 +5749,7 @@ def __init__(self, id=None, title=None, para=None, internal=None, mixedclass_=No self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docSect4Type.subclass: return docSect4Type.subclass(*args_, **kwargs_) @@ -5085,6 +5766,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docSect4Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -5092,30 +5774,37 @@ def export(self, outfile, level, namespace_='', name_='docSect4Type', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docSect4Type'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSect4Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSect4Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5135,40 +5824,43 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalS4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect4Type @@ -5176,6 +5868,7 @@ def buildChildren(self, child_, nodeName_): class docInternalType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5185,6 +5878,7 @@ def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalType.subclass: return docInternalType.subclass(*args_, **kwargs_) @@ -5199,33 +5893,41 @@ def get_sect1(self): return self.sect1 def set_sect1(self, sect1): self.sect1 = sect1 def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalType') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None or self.sect1 is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5239,32 +5941,35 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect1': + nodeName_ == 'sect1': childobj_ = docSect1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect1', childobj_) + MixedContainer.TypeNone, 'sect1', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalType @@ -5272,6 +5977,7 @@ def buildChildren(self, child_, nodeName_): class docInternalS1Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5281,6 +5987,7 @@ def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalS1Type.subclass: return docInternalS1Type.subclass(*args_, **kwargs_) @@ -5295,33 +6002,41 @@ def get_sect2(self): return self.sect2 def set_sect2(self, sect2): self.sect2 = sect2 def add_sect2(self, value): self.sect2.append(value) def insert_sect2(self, index, value): self.sect2[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalS1Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalS1Type') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalS1Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS1Type'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalS1Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None or self.sect2 is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalS1Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5335,32 +6050,35 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect2': + nodeName_ == 'sect2': childobj_ = docSect2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect2', childobj_) + MixedContainer.TypeNone, 'sect2', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS1Type @@ -5368,6 +6086,7 @@ def buildChildren(self, child_, nodeName_): class docInternalS2Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5377,6 +6096,7 @@ def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalS2Type.subclass: return docInternalS2Type.subclass(*args_, **kwargs_) @@ -5391,33 +6111,41 @@ def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalS2Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalS2Type') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalS2Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS2Type'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalS2Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None or self.sect3 is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalS2Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5431,32 +6159,35 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect3': + nodeName_ == 'sect3': childobj_ = docSect3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect3', childobj_) + MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS2Type @@ -5464,6 +6195,7 @@ def buildChildren(self, child_, nodeName_): class docInternalS3Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5473,6 +6205,7 @@ def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalS3Type.subclass: return docInternalS3Type.subclass(*args_, **kwargs_) @@ -5487,33 +6220,41 @@ def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalS3Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalS3Type') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalS3Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS3Type'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalS3Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None or self.sect3 is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalS3Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5527,32 +6268,35 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect3': + nodeName_ == 'sect3': childobj_ = docSect4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect3', childobj_) + MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS3Type @@ -5560,6 +6304,7 @@ def buildChildren(self, child_, nodeName_): class docInternalS4Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5569,6 +6314,7 @@ def __init__(self, para=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalS4Type.subclass: return docInternalS4Type.subclass(*args_, **kwargs_) @@ -5579,32 +6325,40 @@ def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalS4Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalS4Type') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalS4Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS4Type'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalS4Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalS4Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5612,25 +6366,28 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS4Type @@ -5638,6 +6395,7 @@ def buildChildren(self, child_, nodeName_): class docTitleType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5647,6 +6405,7 @@ def __init__(self, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docTitleType.subclass: return docTitleType.subclass(*args_, **kwargs_) @@ -5655,6 +6414,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docTitleType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -5662,33 +6422,40 @@ def export(self, outfile, level, namespace_='', name_='docTitleType', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docTitleType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docTitleType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docTitleType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -5696,23 +6463,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docTitleType class docParaType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5722,6 +6492,7 @@ def __init__(self, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docParaType.subclass: return docParaType.subclass(*args_, **kwargs_) @@ -5730,6 +6501,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docParaType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -5737,33 +6509,40 @@ def export(self, outfile, level, namespace_='', name_='docParaType', namespacede outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docParaType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docParaType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParaType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -5771,23 +6550,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docParaType class docMarkupType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5797,6 +6579,7 @@ def __init__(self, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docMarkupType.subclass: return docMarkupType.subclass(*args_, **kwargs_) @@ -5805,40 +6588,49 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docMarkupType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docMarkupType') + self.exportAttributes(outfile, level, namespace_, + name_='docMarkupType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docMarkupType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docMarkupType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docMarkupType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -5846,23 +6638,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docMarkupType class docURLLink(GeneratedsSuper): subclass = None superclass = None + def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): self.url = url if mixedclass_ is None: @@ -5873,6 +6668,7 @@ def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docURLLink.subclass: return docURLLink.subclass(*args_, **kwargs_) @@ -5883,6 +6679,7 @@ def get_url(self): return self.url def set_url(self, url): self.url = url def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docURLLink', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -5890,36 +6687,44 @@ def export(self, outfile, level, namespace_='', name_='docURLLink', namespacedef outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docURLLink'): if self.url is not None: - outfile.write(' url=%s' % (self.format_string(quote_attrib(self.url).encode(ExternalEncoding), input_name='url'), )) + outfile.write(' url=%s' % (self.format_string(quote_attrib( + self.url).encode(ExternalEncoding), input_name='url'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docURLLink'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docURLLink'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.url is not None: showIndent(outfile, level) outfile.write('url = %s,\n' % (self.url,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -5927,24 +6732,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('url'): self.url = attrs.get('url').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docURLLink class docAnchorType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -5955,6 +6763,7 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docAnchorType.subclass: return docAnchorType.subclass(*args_, **kwargs_) @@ -5965,43 +6774,53 @@ def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docAnchorType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docAnchorType') + self.exportAttributes(outfile, level, namespace_, + name_='docAnchorType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docAnchorType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docAnchorType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docAnchorType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -6009,24 +6828,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docAnchorType class docFormulaType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -6037,6 +6859,7 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docFormulaType.subclass: return docFormulaType.subclass(*args_, **kwargs_) @@ -6047,43 +6870,53 @@ def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docFormulaType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docFormulaType') + self.exportAttributes(outfile, level, namespace_, + name_='docFormulaType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docFormulaType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docFormulaType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docFormulaType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -6091,27 +6924,31 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docFormulaType class docIndexEntryType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, primaryie=None, secondaryie=None): self.primaryie = primaryie self.secondaryie = secondaryie + def factory(*args_, **kwargs_): if docIndexEntryType.subclass: return docIndexEntryType.subclass(*args_, **kwargs_) @@ -6122,10 +6959,12 @@ def get_primaryie(self): return self.primaryie def set_primaryie(self, primaryie): self.primaryie = primaryie def get_secondaryie(self): return self.secondaryie def set_secondaryie(self, secondaryie): self.secondaryie = secondaryie + def export(self, outfile, level, namespace_='', name_='docIndexEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docIndexEntryType') + self.exportAttributes(outfile, level, namespace_, + name_='docIndexEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6133,52 +6972,65 @@ def export(self, outfile, level, namespace_='', name_='docIndexEntryType', names outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docIndexEntryType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docIndexEntryType'): if self.primaryie is not None: showIndent(outfile, level) - outfile.write('<%sprimaryie>%s\n' % (namespace_, self.format_string(quote_xml(self.primaryie).encode(ExternalEncoding), input_name='primaryie'), namespace_)) + outfile.write('<%sprimaryie>%s\n' % (namespace_, self.format_string( + quote_xml(self.primaryie).encode(ExternalEncoding), input_name='primaryie'), namespace_)) if self.secondaryie is not None: showIndent(outfile, level) - outfile.write('<%ssecondaryie>%s\n' % (namespace_, self.format_string(quote_xml(self.secondaryie).encode(ExternalEncoding), input_name='secondaryie'), namespace_)) + outfile.write('<%ssecondaryie>%s\n' % (namespace_, self.format_string( + quote_xml(self.secondaryie).encode(ExternalEncoding), input_name='secondaryie'), namespace_)) + def hasContent_(self): if ( self.primaryie is not None or self.secondaryie is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docIndexEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('primaryie=%s,\n' % quote_python(self.primaryie).encode(ExternalEncoding)) + outfile.write('primaryie=%s,\n' % quote_python( + self.primaryie).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('secondaryie=%s,\n' % quote_python(self.secondaryie).encode(ExternalEncoding)) + outfile.write('secondaryie=%s,\n' % quote_python( + self.secondaryie).encode(ExternalEncoding)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'primaryie': + nodeName_ == 'primaryie': primaryie_ = '' for text__content_ in child_.childNodes: primaryie_ += text__content_.nodeValue self.primaryie = primaryie_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'secondaryie': + nodeName_ == 'secondaryie': secondaryie_ = '' for text__content_ in child_.childNodes: secondaryie_ += text__content_.nodeValue @@ -6189,11 +7041,13 @@ def buildChildren(self, child_, nodeName_): class docListType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, listitem=None): if listitem is None: self.listitem = [] else: self.listitem = listitem + def factory(*args_, **kwargs_): if docListType.subclass: return docListType.subclass(*args_, **kwargs_) @@ -6204,6 +7058,7 @@ def get_listitem(self): return self.listitem def set_listitem(self, listitem): self.listitem = listitem def add_listitem(self, value): self.listitem.append(value) def insert_listitem(self, index, value): self.listitem[index] = value + def export(self, outfile, level, namespace_='', name_='docListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -6215,25 +7070,31 @@ def export(self, outfile, level, namespace_='', name_='docListType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docListType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docListType'): for listitem_ in self.listitem: listitem_.export(outfile, level, namespace_, name_='listitem') + def hasContent_(self): if ( self.listitem is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('listitem=[\n') @@ -6247,17 +7108,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'listitem': + nodeName_ == 'listitem': obj_ = docListItemType.factory() obj_.build(child_) self.listitem.append(obj_) @@ -6267,11 +7131,13 @@ def buildChildren(self, child_, nodeName_): class docListItemType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None): if para is None: self.para = [] else: self.para = para + def factory(*args_, **kwargs_): if docListItemType.subclass: return docListItemType.subclass(*args_, **kwargs_) @@ -6282,10 +7148,12 @@ def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value + def export(self, outfile, level, namespace_='', name_='docListItemType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docListItemType') + self.exportAttributes(outfile, level, namespace_, + name_='docListItemType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6293,25 +7161,31 @@ def export(self, outfile, level, namespace_='', name_='docListItemType', namespa outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docListItemType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docListItemType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') + def hasContent_(self): if ( self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docListItemType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') @@ -6325,17 +7199,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) @@ -6345,6 +7222,7 @@ def buildChildren(self, child_, nodeName_): class docSimpleSectType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, title=None, para=None): self.kind = kind self.title = title @@ -6352,6 +7230,7 @@ def __init__(self, kind=None, title=None, para=None): self.para = [] else: self.para = para + def factory(*args_, **kwargs_): if docSimpleSectType.subclass: return docSimpleSectType.subclass(*args_, **kwargs_) @@ -6366,10 +7245,12 @@ def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind + def export(self, outfile, level, namespace_='', name_='docSimpleSectType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docSimpleSectType') + self.exportAttributes(outfile, level, namespace_, + name_='docSimpleSectType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6377,31 +7258,37 @@ def export(self, outfile, level, namespace_='', name_='docSimpleSectType', names outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docSimpleSectType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSimpleSectType'): if self.title: self.title.export(outfile, level, namespace_, name_='title') for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') + def hasContent_(self): if ( self.title is not None or self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSimpleSectType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) + def exportLiteralChildren(self, outfile, level, name_): if self.title: showIndent(outfile, level) @@ -6421,23 +7308,26 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': obj_ = docTitleType.factory() obj_.build(child_) self.set_title(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) @@ -6447,8 +7337,10 @@ def buildChildren(self, child_, nodeName_): class docVarListEntryType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, term=None): self.term = term + def factory(*args_, **kwargs_): if docVarListEntryType.subclass: return docVarListEntryType.subclass(*args_, **kwargs_) @@ -6457,10 +7349,12 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def get_term(self): return self.term def set_term(self, term): self.term = term + def export(self, outfile, level, namespace_='', name_='docVarListEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docVarListEntryType') + self.exportAttributes(outfile, level, namespace_, + name_='docVarListEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6468,25 +7362,31 @@ def export(self, outfile, level, namespace_='', name_='docVarListEntryType', nam outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docVarListEntryType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docVarListEntryType'): if self.term: self.term.export(outfile, level, namespace_, name_='term', ) + def hasContent_(self): if ( self.term is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docVarListEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): if self.term: showIndent(outfile, level) @@ -6494,17 +7394,20 @@ def exportLiteralChildren(self, outfile, level, name_): self.term.exportLiteral(outfile, level, name_='term') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'term': + nodeName_ == 'term': obj_ = docTitleType.factory() obj_.build(child_) self.set_term(obj_) @@ -6514,8 +7417,10 @@ def buildChildren(self, child_, nodeName_): class docVariableListType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if docVariableListType.subclass: return docVariableListType.subclass(*args_, **kwargs_) @@ -6524,10 +7429,12 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docVariableListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docVariableListType') + self.exportAttributes(outfile, level, namespace_, + name_='docVariableListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6535,33 +7442,40 @@ def export(self, outfile, level, namespace_='', name_='docVariableListType', nam outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docVariableListType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docVariableListType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docVariableListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -6569,19 +7483,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docVariableListType class docRefTextType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid self.kindref = kindref @@ -6594,6 +7511,7 @@ def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedcl self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docRefTextType.subclass: return docRefTextType.subclass(*args_, **kwargs_) @@ -6608,40 +7526,49 @@ def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docRefTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docRefTextType') + self.exportAttributes(outfile, level, namespace_, + name_='docRefTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docRefTextType'): if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.kindref is not None: outfile.write(' kindref=%s' % (quote_attrib(self.kindref), )) if self.external is not None: - outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) + outfile.write(' external=%s' % (self.format_string(quote_attrib( + self.external).encode(ExternalEncoding), input_name='external'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docRefTextType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docRefTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) @@ -6652,9 +7579,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -6662,6 +7591,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value @@ -6669,21 +7599,23 @@ def buildAttributes(self, attrs): self.kindref = attrs.get('kindref').value if attrs.get('external'): self.external = attrs.get('external').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docRefTextType class docTableType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, rows=None, cols=None, row=None, caption=None): self.rows = rows self.cols = cols @@ -6692,6 +7624,7 @@ def __init__(self, rows=None, cols=None, row=None, caption=None): else: self.row = row self.caption = caption + def factory(*args_, **kwargs_): if docTableType.subclass: return docTableType.subclass(*args_, **kwargs_) @@ -6708,6 +7641,7 @@ def get_rows(self): return self.rows def set_rows(self, rows): self.rows = rows def get_cols(self): return self.cols def set_cols(self, cols): self.cols = cols + def export(self, outfile, level, namespace_='', name_='docTableType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -6719,29 +7653,36 @@ def export(self, outfile, level, namespace_='', name_='docTableType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docTableType'): if self.rows is not None: - outfile.write(' rows="%s"' % self.format_integer(self.rows, input_name='rows')) + outfile.write(' rows="%s"' % self.format_integer( + self.rows, input_name='rows')) if self.cols is not None: - outfile.write(' cols="%s"' % self.format_integer(self.cols, input_name='cols')) + outfile.write(' cols="%s"' % self.format_integer( + self.cols, input_name='cols')) + def exportChildren(self, outfile, level, namespace_='', name_='docTableType'): for row_ in self.row: row_.export(outfile, level, namespace_, name_='row') if self.caption: self.caption.export(outfile, level, namespace_, name_='caption') + def hasContent_(self): if ( self.row is not None or self.caption is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docTableType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.rows is not None: showIndent(outfile, level) @@ -6749,6 +7690,7 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.cols is not None: showIndent(outfile, level) outfile.write('cols = %s,\n' % (self.cols,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('row=[\n') @@ -6768,12 +7710,14 @@ def exportLiteralChildren(self, outfile, level, name_): self.caption.exportLiteral(outfile, level, name_='caption') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('rows'): try: @@ -6785,14 +7729,15 @@ def buildAttributes(self, attrs): self.cols = int(attrs.get('cols').value) except ValueError as exp: raise ValueError('Bad integer attribute (cols): %s' % exp) + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'row': + nodeName_ == 'row': obj_ = docRowType.factory() obj_.build(child_) self.row.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'caption': + nodeName_ == 'caption': obj_ = docCaptionType.factory() obj_.build(child_) self.set_caption(obj_) @@ -6802,11 +7747,13 @@ def buildChildren(self, child_, nodeName_): class docRowType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, entry=None): if entry is None: self.entry = [] else: self.entry = entry + def factory(*args_, **kwargs_): if docRowType.subclass: return docRowType.subclass(*args_, **kwargs_) @@ -6817,6 +7764,7 @@ def get_entry(self): return self.entry def set_entry(self, entry): self.entry = entry def add_entry(self, value): self.entry.append(value) def insert_entry(self, index, value): self.entry[index] = value + def export(self, outfile, level, namespace_='', name_='docRowType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -6828,25 +7776,31 @@ def export(self, outfile, level, namespace_='', name_='docRowType', namespacedef outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docRowType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docRowType'): for entry_ in self.entry: entry_.export(outfile, level, namespace_, name_='entry') + def hasContent_(self): if ( self.entry is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docRowType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('entry=[\n') @@ -6860,17 +7814,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'entry': + nodeName_ == 'entry': obj_ = docEntryType.factory() obj_.build(child_) self.entry.append(obj_) @@ -6880,12 +7837,14 @@ def buildChildren(self, child_, nodeName_): class docEntryType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, thead=None, para=None): self.thead = thead if para is None: self.para = [] else: self.para = para + def factory(*args_, **kwargs_): if docEntryType.subclass: return docEntryType.subclass(*args_, **kwargs_) @@ -6898,6 +7857,7 @@ def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_thead(self): return self.thead def set_thead(self, thead): self.thead = thead + def export(self, outfile, level, namespace_='', name_='docEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -6909,28 +7869,34 @@ def export(self, outfile, level, namespace_='', name_='docEntryType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docEntryType'): if self.thead is not None: outfile.write(' thead=%s' % (quote_attrib(self.thead), )) + def exportChildren(self, outfile, level, namespace_='', name_='docEntryType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') + def hasContent_(self): if ( self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.thead is not None: showIndent(outfile, level) outfile.write('thead = "%s",\n' % (self.thead,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') @@ -6944,18 +7910,21 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('thead'): self.thead = attrs.get('thead').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) @@ -6965,6 +7934,7 @@ def buildChildren(self, child_, nodeName_): class docCaptionType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -6974,6 +7944,7 @@ def __init__(self, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docCaptionType.subclass: return docCaptionType.subclass(*args_, **kwargs_) @@ -6982,40 +7953,49 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docCaptionType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docCaptionType') + self.exportAttributes(outfile, level, namespace_, + name_='docCaptionType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docCaptionType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docCaptionType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docCaptionType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7023,23 +8003,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docCaptionType class docHeadingType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): self.level = level if mixedclass_ is None: @@ -7050,6 +8033,7 @@ def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docHeadingType.subclass: return docHeadingType.subclass(*args_, **kwargs_) @@ -7060,43 +8044,53 @@ def get_level(self): return self.level def set_level(self, level): self.level = level def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docHeadingType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docHeadingType') + self.exportAttributes(outfile, level, namespace_, + name_='docHeadingType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docHeadingType'): if self.level is not None: - outfile.write(' level="%s"' % self.format_integer(self.level, input_name='level')) + outfile.write(' level="%s"' % self.format_integer( + self.level, input_name='level')) + def exportChildren(self, outfile, level, namespace_='', name_='docHeadingType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docHeadingType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.level is not None: showIndent(outfile, level) outfile.write('level = %s,\n' % (self.level,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7104,27 +8098,30 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('level'): try: self.level = int(attrs.get('level').value) except ValueError as exp: raise ValueError('Bad integer attribute (level): %s' % exp) + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docHeadingType class docImageType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', mixedclass_=None, content_=None): self.width = width self.type_ = type_ @@ -7138,6 +8135,7 @@ def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docImageType.subclass: return docImageType.subclass(*args_, **kwargs_) @@ -7154,6 +8152,7 @@ def get_height(self): return self.height def set_height(self, height): self.height = height def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docImageType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -7161,35 +8160,43 @@ def export(self, outfile, level, namespace_='', name_='docImageType', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docImageType'): if self.width is not None: - outfile.write(' width=%s' % (self.format_string(quote_attrib(self.width).encode(ExternalEncoding), input_name='width'), )) + outfile.write(' width=%s' % (self.format_string(quote_attrib( + self.width).encode(ExternalEncoding), input_name='width'), )) if self.type_ is not None: outfile.write(' type=%s' % (quote_attrib(self.type_), )) if self.name is not None: - outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) + outfile.write(' name=%s' % (self.format_string(quote_attrib( + self.name).encode(ExternalEncoding), input_name='name'), )) if self.height is not None: - outfile.write(' height=%s' % (self.format_string(quote_attrib(self.height).encode(ExternalEncoding), input_name='height'), )) + outfile.write(' height=%s' % (self.format_string(quote_attrib( + self.height).encode(ExternalEncoding), input_name='height'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docImageType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docImageType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.width is not None: showIndent(outfile, level) @@ -7203,9 +8210,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.height is not None: showIndent(outfile, level) outfile.write('height = %s,\n' % (self.height,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7213,6 +8222,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('width'): self.width = attrs.get('width').value @@ -7222,21 +8232,23 @@ def buildAttributes(self, attrs): self.name = attrs.get('name').value if attrs.get('height'): self.height = attrs.get('height').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docImageType class docDotFileType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): self.name = name if mixedclass_ is None: @@ -7247,6 +8259,7 @@ def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docDotFileType.subclass: return docDotFileType.subclass(*args_, **kwargs_) @@ -7257,43 +8270,53 @@ def get_name(self): return self.name def set_name(self, name): self.name = name def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docDotFileType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docDotFileType') + self.exportAttributes(outfile, level, namespace_, + name_='docDotFileType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docDotFileType'): if self.name is not None: - outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) + outfile.write(' name=%s' % (self.format_string(quote_attrib( + self.name).encode(ExternalEncoding), input_name='name'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docDotFileType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docDotFileType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.name is not None: showIndent(outfile, level) outfile.write('name = %s,\n' % (self.name,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7301,24 +8324,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('name'): self.name = attrs.get('name').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docDotFileType class docTocItemType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -7329,6 +8355,7 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docTocItemType.subclass: return docTocItemType.subclass(*args_, **kwargs_) @@ -7339,43 +8366,53 @@ def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docTocItemType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docTocItemType') + self.exportAttributes(outfile, level, namespace_, + name_='docTocItemType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docTocItemType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docTocItemType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docTocItemType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7383,29 +8420,33 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docTocItemType class docTocListType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, tocitem=None): if tocitem is None: self.tocitem = [] else: self.tocitem = tocitem + def factory(*args_, **kwargs_): if docTocListType.subclass: return docTocListType.subclass(*args_, **kwargs_) @@ -7416,10 +8457,12 @@ def get_tocitem(self): return self.tocitem def set_tocitem(self, tocitem): self.tocitem = tocitem def add_tocitem(self, value): self.tocitem.append(value) def insert_tocitem(self, index, value): self.tocitem[index] = value + def export(self, outfile, level, namespace_='', name_='docTocListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docTocListType') + self.exportAttributes(outfile, level, namespace_, + name_='docTocListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7427,25 +8470,31 @@ def export(self, outfile, level, namespace_='', name_='docTocListType', namespac outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docTocListType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docTocListType'): for tocitem_ in self.tocitem: tocitem_.export(outfile, level, namespace_, name_='tocitem') + def hasContent_(self): if ( self.tocitem is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docTocListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('tocitem=[\n') @@ -7459,17 +8508,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'tocitem': + nodeName_ == 'tocitem': obj_ = docTocItemType.factory() obj_.build(child_) self.tocitem.append(obj_) @@ -7479,12 +8531,14 @@ def buildChildren(self, child_, nodeName_): class docLanguageType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, langid=None, para=None): self.langid = langid if para is None: self.para = [] else: self.para = para + def factory(*args_, **kwargs_): if docLanguageType.subclass: return docLanguageType.subclass(*args_, **kwargs_) @@ -7497,10 +8551,12 @@ def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_langid(self): return self.langid def set_langid(self, langid): self.langid = langid + def export(self, outfile, level, namespace_='', name_='docLanguageType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docLanguageType') + self.exportAttributes(outfile, level, namespace_, + name_='docLanguageType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7508,28 +8564,35 @@ def export(self, outfile, level, namespace_='', name_='docLanguageType', namespa outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docLanguageType'): if self.langid is not None: - outfile.write(' langid=%s' % (self.format_string(quote_attrib(self.langid).encode(ExternalEncoding), input_name='langid'), )) + outfile.write(' langid=%s' % (self.format_string(quote_attrib( + self.langid).encode(ExternalEncoding), input_name='langid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docLanguageType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') + def hasContent_(self): if ( self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docLanguageType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.langid is not None: showIndent(outfile, level) outfile.write('langid = %s,\n' % (self.langid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') @@ -7543,18 +8606,21 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('langid'): self.langid = attrs.get('langid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) @@ -7564,12 +8630,14 @@ def buildChildren(self, child_, nodeName_): class docParamListType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, parameteritem=None): self.kind = kind if parameteritem is None: self.parameteritem = [] else: self.parameteritem = parameteritem + def factory(*args_, **kwargs_): if docParamListType.subclass: return docParamListType.subclass(*args_, **kwargs_) @@ -7577,15 +8645,21 @@ def factory(*args_, **kwargs_): return docParamListType(*args_, **kwargs_) factory = staticmethod(factory) def get_parameteritem(self): return self.parameteritem - def set_parameteritem(self, parameteritem): self.parameteritem = parameteritem + def set_parameteritem( + self, parameteritem): self.parameteritem = parameteritem + def add_parameteritem(self, value): self.parameteritem.append(value) - def insert_parameteritem(self, index, value): self.parameteritem[index] = value + def insert_parameteritem( + self, index, value): self.parameteritem[index] = value + def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind + def export(self, outfile, level, namespace_='', name_='docParamListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docParamListType') + self.exportAttributes(outfile, level, namespace_, + name_='docParamListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7593,28 +8667,35 @@ def export(self, outfile, level, namespace_='', name_='docParamListType', namesp outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docParamListType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) + def exportChildren(self, outfile, level, namespace_='', name_='docParamListType'): for parameteritem_ in self.parameteritem: - parameteritem_.export(outfile, level, namespace_, name_='parameteritem') + parameteritem_.export( + outfile, level, namespace_, name_='parameteritem') + def hasContent_(self): if ( self.parameteritem is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParamListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parameteritem=[\n') @@ -7628,18 +8709,21 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'parameteritem': + nodeName_ == 'parameteritem': obj_ = docParamListItem.factory() obj_.build(child_) self.parameteritem.append(obj_) @@ -7649,12 +8733,14 @@ def buildChildren(self, child_, nodeName_): class docParamListItem(GeneratedsSuper): subclass = None superclass = None + def __init__(self, parameternamelist=None, parameterdescription=None): if parameternamelist is None: self.parameternamelist = [] else: self.parameternamelist = parameternamelist self.parameterdescription = parameterdescription + def factory(*args_, **kwargs_): if docParamListItem.subclass: return docParamListItem.subclass(*args_, **kwargs_) @@ -7662,15 +8748,25 @@ def factory(*args_, **kwargs_): return docParamListItem(*args_, **kwargs_) factory = staticmethod(factory) def get_parameternamelist(self): return self.parameternamelist - def set_parameternamelist(self, parameternamelist): self.parameternamelist = parameternamelist - def add_parameternamelist(self, value): self.parameternamelist.append(value) - def insert_parameternamelist(self, index, value): self.parameternamelist[index] = value + + def set_parameternamelist( + self, parameternamelist): self.parameternamelist = parameternamelist + + def add_parameternamelist( + self, value): self.parameternamelist.append(value) + def insert_parameternamelist( + self, index, value): self.parameternamelist[index] = value + def get_parameterdescription(self): return self.parameterdescription - def set_parameterdescription(self, parameterdescription): self.parameterdescription = parameterdescription + + def set_parameterdescription( + self, parameterdescription): self.parameterdescription = parameterdescription + def export(self, outfile, level, namespace_='', name_='docParamListItem', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docParamListItem') + self.exportAttributes(outfile, level, namespace_, + name_='docParamListItem') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7678,28 +8774,36 @@ def export(self, outfile, level, namespace_='', name_='docParamListItem', namesp outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docParamListItem'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docParamListItem'): for parameternamelist_ in self.parameternamelist: - parameternamelist_.export(outfile, level, namespace_, name_='parameternamelist') + parameternamelist_.export( + outfile, level, namespace_, name_='parameternamelist') if self.parameterdescription: - self.parameterdescription.export(outfile, level, namespace_, name_='parameterdescription', ) + self.parameterdescription.export( + outfile, level, namespace_, name_='parameterdescription', ) + def hasContent_(self): if ( self.parameternamelist is not None or self.parameterdescription is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParamListItem'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parameternamelist=[\n') @@ -7707,7 +8811,8 @@ def exportLiteralChildren(self, outfile, level, name_): for parameternamelist in self.parameternamelist: showIndent(outfile, level) outfile.write('model_.parameternamelist(\n') - parameternamelist.exportLiteral(outfile, level, name_='parameternamelist') + parameternamelist.exportLiteral( + outfile, level, name_='parameternamelist') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -7716,25 +8821,29 @@ def exportLiteralChildren(self, outfile, level, name_): if self.parameterdescription: showIndent(outfile, level) outfile.write('parameterdescription=model_.descriptionType(\n') - self.parameterdescription.exportLiteral(outfile, level, name_='parameterdescription') + self.parameterdescription.exportLiteral( + outfile, level, name_='parameterdescription') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'parameternamelist': + nodeName_ == 'parameternamelist': obj_ = docParamNameList.factory() obj_.build(child_) self.parameternamelist.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'parameterdescription': + nodeName_ == 'parameterdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_parameterdescription(obj_) @@ -7744,11 +8853,13 @@ def buildChildren(self, child_, nodeName_): class docParamNameList(GeneratedsSuper): subclass = None superclass = None + def __init__(self, parametername=None): if parametername is None: self.parametername = [] else: self.parametername = parametername + def factory(*args_, **kwargs_): if docParamNameList.subclass: return docParamNameList.subclass(*args_, **kwargs_) @@ -7756,13 +8867,19 @@ def factory(*args_, **kwargs_): return docParamNameList(*args_, **kwargs_) factory = staticmethod(factory) def get_parametername(self): return self.parametername - def set_parametername(self, parametername): self.parametername = parametername + def set_parametername( + self, parametername): self.parametername = parametername + def add_parametername(self, value): self.parametername.append(value) - def insert_parametername(self, index, value): self.parametername[index] = value + + def insert_parametername( + self, index, value): self.parametername[index] = value + def export(self, outfile, level, namespace_='', name_='docParamNameList', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docParamNameList') + self.exportAttributes(outfile, level, namespace_, + name_='docParamNameList') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7770,25 +8887,32 @@ def export(self, outfile, level, namespace_='', name_='docParamNameList', namesp outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docParamNameList'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docParamNameList'): for parametername_ in self.parametername: - parametername_.export(outfile, level, namespace_, name_='parametername') + parametername_.export( + outfile, level, namespace_, name_='parametername') + def hasContent_(self): if ( self.parametername is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParamNameList'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parametername=[\n') @@ -7802,17 +8926,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'parametername': + nodeName_ == 'parametername': obj_ = docParamName.factory() obj_.build(child_) self.parametername.append(obj_) @@ -7822,6 +8949,7 @@ def buildChildren(self, child_, nodeName_): class docParamName(GeneratedsSuper): subclass = None superclass = None + def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): self.direction = direction if mixedclass_ is None: @@ -7832,6 +8960,7 @@ def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docParamName.subclass: return docParamName.subclass(*args_, **kwargs_) @@ -7842,6 +8971,7 @@ def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def get_direction(self): return self.direction def set_direction(self, direction): self.direction = direction + def export(self, outfile, level, namespace_='', name_='docParamName', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -7849,28 +8979,34 @@ def export(self, outfile, level, namespace_='', name_='docParamName', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docParamName'): if self.direction is not None: outfile.write(' direction=%s' % (quote_attrib(self.direction), )) + def exportChildren(self, outfile, level, namespace_='', name_='docParamName'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.ref is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParamName'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.direction is not None: showIndent(outfile, level) outfile.write('direction = "%s",\n' % (self.direction,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -7878,26 +9014,29 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('direction'): self.direction = attrs.get('direction').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'ref': + nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'ref', childobj_) + MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docParamName @@ -7905,6 +9044,7 @@ def buildChildren(self, child_, nodeName_): class docXRefSectType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, xreftitle=None, xrefdescription=None): self.id = id if xreftitle is None: @@ -7912,6 +9052,7 @@ def __init__(self, id=None, xreftitle=None, xrefdescription=None): else: self.xreftitle = xreftitle self.xrefdescription = xrefdescription + def factory(*args_, **kwargs_): if docXRefSectType.subclass: return docXRefSectType.subclass(*args_, **kwargs_) @@ -7923,13 +9064,17 @@ def set_xreftitle(self, xreftitle): self.xreftitle = xreftitle def add_xreftitle(self, value): self.xreftitle.append(value) def insert_xreftitle(self, index, value): self.xreftitle[index] = value def get_xrefdescription(self): return self.xrefdescription - def set_xrefdescription(self, xrefdescription): self.xrefdescription = xrefdescription + def set_xrefdescription( + self, xrefdescription): self.xrefdescription = xrefdescription + def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docXRefSectType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docXRefSectType') + self.exportAttributes(outfile, level, namespace_, + name_='docXRefSectType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7937,66 +9082,80 @@ def export(self, outfile, level, namespace_='', name_='docXRefSectType', namespa outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docXRefSectType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docXRefSectType'): for xreftitle_ in self.xreftitle: showIndent(outfile, level) - outfile.write('<%sxreftitle>%s\n' % (namespace_, self.format_string(quote_xml(xreftitle_).encode(ExternalEncoding), input_name='xreftitle'), namespace_)) + outfile.write('<%sxreftitle>%s\n' % (namespace_, self.format_string( + quote_xml(xreftitle_).encode(ExternalEncoding), input_name='xreftitle'), namespace_)) if self.xrefdescription: - self.xrefdescription.export(outfile, level, namespace_, name_='xrefdescription', ) + self.xrefdescription.export( + outfile, level, namespace_, name_='xrefdescription', ) + def hasContent_(self): if ( self.xreftitle is not None or self.xrefdescription is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docXRefSectType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('xreftitle=[\n') level += 1 for xreftitle in self.xreftitle: showIndent(outfile, level) - outfile.write('%s,\n' % quote_python(xreftitle).encode(ExternalEncoding)) + outfile.write('%s,\n' % quote_python( + xreftitle).encode(ExternalEncoding)) level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.xrefdescription: showIndent(outfile, level) outfile.write('xrefdescription=model_.descriptionType(\n') - self.xrefdescription.exportLiteral(outfile, level, name_='xrefdescription') + self.xrefdescription.exportLiteral( + outfile, level, name_='xrefdescription') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'xreftitle': + nodeName_ == 'xreftitle': xreftitle_ = '' for text__content_ in child_.childNodes: xreftitle_ += text__content_.nodeValue self.xreftitle.append(xreftitle_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'xrefdescription': + nodeName_ == 'xrefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_xrefdescription(obj_) @@ -8006,6 +9165,7 @@ def buildChildren(self, child_, nodeName_): class docCopyType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, link=None, para=None, sect1=None, internal=None): self.link = link if para is None: @@ -8017,6 +9177,7 @@ def __init__(self, link=None, para=None, sect1=None, internal=None): else: self.sect1 = sect1 self.internal = internal + def factory(*args_, **kwargs_): if docCopyType.subclass: return docCopyType.subclass(*args_, **kwargs_) @@ -8035,6 +9196,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_link(self): return self.link def set_link(self, link): self.link = link + def export(self, outfile, level, namespace_='', name_='docCopyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -8046,9 +9208,12 @@ def export(self, outfile, level, namespace_='', name_='docCopyType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docCopyType'): if self.link is not None: - outfile.write(' link=%s' % (self.format_string(quote_attrib(self.link).encode(ExternalEncoding), input_name='link'), )) + outfile.write(' link=%s' % (self.format_string(quote_attrib( + self.link).encode(ExternalEncoding), input_name='link'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docCopyType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') @@ -8056,24 +9221,28 @@ def exportChildren(self, outfile, level, namespace_='', name_='docCopyType'): sect1_.export(outfile, level, namespace_, name_='sect1') if self.internal: self.internal.export(outfile, level, namespace_, name_='internal') + def hasContent_(self): if ( self.para is not None or self.sect1 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docCopyType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.link is not None: showIndent(outfile, level) outfile.write('link = %s,\n' % (self.link,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') @@ -8105,28 +9274,31 @@ def exportLiteralChildren(self, outfile, level, name_): self.internal.exportLiteral(outfile, level, name_='internal') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('link'): self.link = attrs.get('link').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect1': + nodeName_ == 'sect1': obj_ = docSect1Type.factory() obj_.build(child_) self.sect1.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': obj_ = docInternalType.factory() obj_.build(child_) self.set_internal(obj_) @@ -8136,9 +9308,11 @@ def buildChildren(self, child_, nodeName_): class docCharType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, char=None, valueOf_=''): self.char = char self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if docCharType.subclass: return docCharType.subclass(*args_, **kwargs_) @@ -8149,6 +9323,7 @@ def get_char(self): return self.char def set_char(self, char): self.char = char def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docCharType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -8160,36 +9335,43 @@ def export(self, outfile, level, namespace_='', name_='docCharType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docCharType'): if self.char is not None: outfile.write(' char=%s' % (quote_attrib(self.char), )) + def exportChildren(self, outfile, level, namespace_='', name_='docCharType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docCharType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.char is not None: showIndent(outfile, level) outfile.write('char = "%s",\n' % (self.char,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -8197,22 +9379,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('char'): self.char = attrs.get('char').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docCharType class docEmptyType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if docEmptyType.subclass: return docEmptyType.subclass(*args_, **kwargs_) @@ -8221,6 +9407,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docEmptyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -8232,33 +9419,40 @@ def export(self, outfile, level, namespace_='', name_='docEmptyType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docEmptyType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docEmptyType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docEmptyType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -8266,13 +9460,15 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docEmptyType @@ -8282,6 +9478,7 @@ def buildChildren(self, child_, nodeName_): -s Use the SAX parser, not the minidom parser. """ + def usage(): print(USAGE_TEXT) sys.exit(1) @@ -8296,7 +9493,7 @@ def parse(inFileName): doc = None sys.stdout.write('\n') rootObj.export(sys.stdout, 0, name_="doxygen", - namespacedef_='') + namespacedef_='') return rootObj @@ -8309,7 +9506,7 @@ def parseString(inString): doc = None sys.stdout.write('\n') rootObj.export(sys.stdout, 0, name_="doxygen", - namespacedef_='') + namespacedef_='') return rootObj @@ -8338,4 +9535,4 @@ def main(): if __name__ == '__main__': main() #import pdb - #pdb.run('main()') + # pdb.run('main()') diff --git a/docs/doxygen/doxyxml/generated/index.py b/docs/doxygen/doxyxml/generated/index.py index c58407dbfef..7ffbdf191ac 100644 --- a/docs/doxygen/doxyxml/generated/index.py +++ b/docs/doxygen/doxyxml/generated/index.py @@ -12,6 +12,7 @@ from . import indexsuper as supermod + class DoxygenTypeSub(supermod.DoxygenType): def __init__(self, version=None, compound=None): supermod.DoxygenType.__init__(self, version, compound) @@ -32,6 +33,7 @@ def find_compounds_and_members(self, details): return results + supermod.DoxygenType.subclass = DoxygenTypeSub # end class DoxygenTypeSub @@ -53,6 +55,7 @@ def find_members(self, details): return results + supermod.CompoundType.subclass = CompoundTypeSub # end class CompoundTypeSub @@ -62,6 +65,7 @@ class MemberTypeSub(supermod.MemberType): def __init__(self, kind=None, refid=None, name=''): supermod.MemberType.__init__(self, kind, refid, name) + supermod.MemberType.subclass = MemberTypeSub # end class MemberTypeSub @@ -74,4 +78,3 @@ def parse(inFilename): rootObj.build(rootNode) return rootObj - diff --git a/docs/doxygen/doxyxml/generated/indexsuper.py b/docs/doxygen/doxyxml/generated/indexsuper.py index cc2c1124182..b30e062ae7d 100644 --- a/docs/doxygen/doxyxml/generated/indexsuper.py +++ b/docs/doxygen/doxyxml/generated/indexsuper.py @@ -24,12 +24,16 @@ class GeneratedsSuper(object): def format_string(self, input_data, input_name=''): return input_data + def format_integer(self, input_data, input_name=''): return '%d' % input_data + def format_float(self, input_data, input_name=''): return '%f' % input_data + def format_double(self, input_data, input_name=''): return '%e' % input_data + def format_boolean(self, input_data, input_name=''): return '%s' % input_data @@ -41,9 +45,9 @@ def format_boolean(self, input_data, input_name=''): ## from IPython.Shell import IPShellEmbed ## args = '' -## ipshell = IPShellEmbed(args, +# ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') +# exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: @@ -59,10 +63,12 @@ def format_boolean(self, input_data, input_name=''): # Support/utility functions. # + def showIndent(outfile, level): for idx in range(level): outfile.write(' ') + def quote_xml(inStr): s1 = (isinstance(inStr, str) and inStr or '%s' % inStr) @@ -71,6 +77,7 @@ def quote_xml(inStr): s1 = s1.replace('>', '>') return s1 + def quote_attrib(inStr): s1 = (isinstance(inStr, str) and inStr or '%s' % inStr) @@ -86,6 +93,7 @@ def quote_attrib(inStr): s1 = '"%s"' % s1 return s1 + def quote_python(inStr): s1 = inStr if s1.find("'") == -1: @@ -117,26 +125,33 @@ class MixedContainer(object): TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 + def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value + def getCategory(self): return self.category + def getContenttype(self, content_type): return self.content_type + def getValue(self): return self.value + def getName(self): return self.name + def export(self, outfile, level, name, namespace): if self.category == MixedContainer.CategoryText: outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex - self.value.export(outfile, level, namespace,name) + self.value.export(outfile, level, namespace, name) + def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: outfile.write('<%s>%s' % (self.name, self.value, self.name)) @@ -148,19 +163,20 @@ def exportSimple(self, outfile, level, name): outfile.write('<%s>%f' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: outfile.write('<%s>%g' % (self.name, self.value, self.name)) + def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) + outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % + (self.category, self.content_type, self.name, self.value)) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) + outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % + (self.category, self.content_type, self.name, self.value)) else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s",\n' % \ - (self.category, self.content_type, self.name,)) + outfile.write('MixedContainer(%d, %d, "%s",\n' % + (self.category, self.content_type, self.name,)) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) outfile.write(')\n') @@ -171,6 +187,7 @@ def __init__(self, name='', data_type='', container=0): self.name = name self.data_type = data_type self.container = container + def set_name(self, name): self.name = name def get_name(self): return self.name def set_data_type(self, data_type): self.data_type = data_type @@ -186,12 +203,14 @@ def get_container(self): return self.container class DoxygenType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, version=None, compound=None): self.version = version if compound is None: self.compound = [] else: self.compound = compound + def factory(*args_, **kwargs_): if DoxygenType.subclass: return DoxygenType.subclass(*args_, **kwargs_) @@ -204,6 +223,7 @@ def add_compound(self, value): self.compound.append(value) def insert_compound(self, index, value): self.compound[index] = value def get_version(self): return self.version def set_version(self, version): self.version = version + def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -215,27 +235,34 @@ def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='DoxygenType'): - outfile.write(' version=%s' % (self.format_string(quote_attrib(self.version).encode(ExternalEncoding), input_name='version'), )) + outfile.write(' version=%s' % (self.format_string(quote_attrib( + self.version).encode(ExternalEncoding), input_name='version'), )) + def exportChildren(self, outfile, level, namespace_='', name_='DoxygenType'): for compound_ in self.compound: compound_.export(outfile, level, namespace_, name_='compound') + def hasContent_(self): if ( self.compound is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='DoxygenType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.version is not None: showIndent(outfile, level) outfile.write('version = %s,\n' % (self.version,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('compound=[\n') @@ -249,18 +276,21 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('version'): self.version = attrs.get('version').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'compound': + nodeName_ == 'compound': obj_ = CompoundType.factory() obj_.build(child_) self.compound.append(obj_) @@ -270,6 +300,7 @@ def buildChildren(self, child_, nodeName_): class CompoundType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, refid=None, name=None, member=None): self.kind = kind self.refid = refid @@ -278,6 +309,7 @@ def __init__(self, kind=None, refid=None, name=None, member=None): self.member = [] else: self.member = member + def factory(*args_, **kwargs_): if CompoundType.subclass: return CompoundType.subclass(*args_, **kwargs_) @@ -294,6 +326,7 @@ def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid + def export(self, outfile, level, namespace_='', name_='CompoundType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -305,28 +338,35 @@ def export(self, outfile, level, namespace_='', name_='CompoundType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='CompoundType'): outfile.write(' kind=%s' % (quote_attrib(self.kind), )) - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='CompoundType'): if self.name is not None: showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + outfile.write('<%sname>%s\n' % (namespace_, self.format_string( + quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) for member_ in self.member: member_.export(outfile, level, namespace_, name_='member') + def hasContent_(self): if ( self.name is not None or self.member is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='CompoundType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) @@ -334,9 +374,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) + outfile.write('name=%s,\n' % quote_python( + self.name).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('member=[\n') level += 1 @@ -349,26 +391,29 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue self.name = name_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'member': + nodeName_ == 'member': obj_ = MemberType.factory() obj_.build(child_) self.member.append(obj_) @@ -378,10 +423,12 @@ def buildChildren(self, child_, nodeName_): class MemberType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, refid=None, name=None): self.kind = kind self.refid = refid self.name = name + def factory(*args_, **kwargs_): if MemberType.subclass: return MemberType.subclass(*args_, **kwargs_) @@ -394,6 +441,7 @@ def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid + def export(self, outfile, level, namespace_='', name_='MemberType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -405,25 +453,32 @@ def export(self, outfile, level, namespace_='', name_='MemberType', namespacedef outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='MemberType'): outfile.write(' kind=%s' % (quote_attrib(self.kind), )) - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='MemberType'): if self.name is not None: showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + outfile.write('<%sname>%s\n' % (namespace_, self.format_string( + quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + def hasContent_(self): if ( self.name is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='MemberType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) @@ -431,23 +486,28 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) + outfile.write('name=%s,\n' % quote_python( + self.name).encode(ExternalEncoding)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue @@ -461,6 +521,7 @@ def buildChildren(self, child_, nodeName_): -s Use the SAX parser, not the minidom parser. """ + def usage(): print(USAGE_TEXT) sys.exit(1) @@ -475,7 +536,7 @@ def parse(inFileName): doc = None sys.stdout.write('\n') rootObj.export(sys.stdout, 0, name_="doxygenindex", - namespacedef_='') + namespacedef_='') return rootObj @@ -488,7 +549,7 @@ def parseString(inString): doc = None sys.stdout.write('\n') rootObj.export(sys.stdout, 0, name_="doxygenindex", - namespacedef_='') + namespacedef_='') return rootObj @@ -514,9 +575,7 @@ def main(): usage() - - if __name__ == '__main__': main() #import pdb - #pdb.run('main()') + # pdb.run('main()') diff --git a/docs/doxygen/doxyxml/text.py b/docs/doxygen/doxyxml/text.py index dc3d390a7db..36d678e5c1c 100644 --- a/docs/doxygen/doxyxml/text.py +++ b/docs/doxygen/doxyxml/text.py @@ -10,6 +10,7 @@ Utilities for extracting text from generated classes. """ + def is_string(txt): if isinstance(txt, str): return True @@ -20,11 +21,13 @@ def is_string(txt): pass return False + def description(obj): if obj is None: return None return description_bit(obj).strip() + def description_bit(obj): if hasattr(obj, 'content'): contents = [description_bit(item) for item in obj.content] @@ -37,7 +40,8 @@ def description_bit(obj): elif is_string(obj): return obj else: - raise Exception('Expecting a string or something with content, content_ or value attribute') + raise Exception( + 'Expecting a string or something with content, content_ or value attribute') # If this bit is a paragraph then add one some line breaks. if hasattr(obj, 'name') and obj.name == 'para': result += "\n\n" diff --git a/docs/doxygen/other/doxypy.py b/docs/doxygen/other/doxypy.py index b5007190118..28b166440f3 100644 --- a/docs/doxygen/other/doxypy.py +++ b/docs/doxygen/other/doxypy.py @@ -9,7 +9,7 @@ """ __doc__ = __blurb__ + \ -""" + """ In order to make Doxygen preprocess files through doxypy, simply add the following lines to your Doxyfile: FILTER_SOURCE_FILES = YES @@ -45,6 +45,7 @@ from argparse import ArgumentParser + class FSM(object): """Implements a finite state machine. @@ -87,85 +88,115 @@ def makeTransition(self, input): self.current_input = input self.current_transition = transition if args.debug: - print("# FSM: executing (%s -> %s) for line '%s'" % (from_state, to_state, input), file=sys.stderr) + print("# FSM: executing (%s -> %s) for line '%s'" % + (from_state, to_state, input), file=sys.stderr) callback(match) return + class Doxypy(object): def __init__(self): string_prefixes = "[uU]?[rR]?" - self.start_single_comment_re = re.compile(r"^\s*%s(''')" % string_prefixes) + self.start_single_comment_re = re.compile( + r"^\s*%s(''')" % string_prefixes) self.end_single_comment_re = re.compile(r"(''')\s*$") - self.start_double_comment_re = re.compile(r'^\s*%s(""")' % string_prefixes) + self.start_double_comment_re = re.compile( + r'^\s*%s(""")' % string_prefixes) self.end_double_comment_re = re.compile(r'(""")\s*$') - self.single_comment_re = re.compile(r"^\s*%s(''').*(''')\s*$" % string_prefixes) - self.double_comment_re = re.compile(r'^\s*%s(""").*(""")\s*$' % string_prefixes) + self.single_comment_re = re.compile( + r"^\s*%s(''').*(''')\s*$" % string_prefixes) + self.double_comment_re = re.compile( + r'^\s*%s(""").*(""")\s*$' % string_prefixes) self.defclass_re = re.compile(r"^(\s*)(def .+:|class .+:)") self.empty_re = re.compile(r"^\s*$") self.hashline_re = re.compile(r"^\s*#.*$") self.importline_re = re.compile(r"^\s*(import |from .+ import)") - self.multiline_defclass_start_re = re.compile(r"^(\s*)(def|class)(\s.*)?$") + self.multiline_defclass_start_re = re.compile( + r"^(\s*)(def|class)(\s.*)?$") self.multiline_defclass_end_re = re.compile(r":\s*$") - ## Transition list format + # Transition list format # ["FROM", "TO", condition, action] transitions = [ - ### FILEHEAD + # FILEHEAD # single line comments - ["FILEHEAD", "FILEHEAD", self.single_comment_re.search, self.appendCommentLine], - ["FILEHEAD", "FILEHEAD", self.double_comment_re.search, self.appendCommentLine], + ["FILEHEAD", "FILEHEAD", self.single_comment_re.search, + self.appendCommentLine], + ["FILEHEAD", "FILEHEAD", self.double_comment_re.search, + self.appendCommentLine], # multiline comments - ["FILEHEAD", "FILEHEAD_COMMENT_SINGLE", self.start_single_comment_re.search, self.appendCommentLine], - ["FILEHEAD_COMMENT_SINGLE", "FILEHEAD", self.end_single_comment_re.search, self.appendCommentLine], - ["FILEHEAD_COMMENT_SINGLE", "FILEHEAD_COMMENT_SINGLE", self.catchall, self.appendCommentLine], - ["FILEHEAD", "FILEHEAD_COMMENT_DOUBLE", self.start_double_comment_re.search, self.appendCommentLine], - ["FILEHEAD_COMMENT_DOUBLE", "FILEHEAD", self.end_double_comment_re.search, self.appendCommentLine], - ["FILEHEAD_COMMENT_DOUBLE", "FILEHEAD_COMMENT_DOUBLE", self.catchall, self.appendCommentLine], + ["FILEHEAD", "FILEHEAD_COMMENT_SINGLE", + self.start_single_comment_re.search, self.appendCommentLine], + ["FILEHEAD_COMMENT_SINGLE", "FILEHEAD", + self.end_single_comment_re.search, self.appendCommentLine], + ["FILEHEAD_COMMENT_SINGLE", "FILEHEAD_COMMENT_SINGLE", + self.catchall, self.appendCommentLine], + ["FILEHEAD", "FILEHEAD_COMMENT_DOUBLE", + self.start_double_comment_re.search, self.appendCommentLine], + ["FILEHEAD_COMMENT_DOUBLE", "FILEHEAD", + self.end_double_comment_re.search, self.appendCommentLine], + ["FILEHEAD_COMMENT_DOUBLE", "FILEHEAD_COMMENT_DOUBLE", + self.catchall, self.appendCommentLine], # other lines ["FILEHEAD", "FILEHEAD", self.empty_re.search, self.appendFileheadLine], ["FILEHEAD", "FILEHEAD", self.hashline_re.search, self.appendFileheadLine], - ["FILEHEAD", "FILEHEAD", self.importline_re.search, self.appendFileheadLine], + ["FILEHEAD", "FILEHEAD", self.importline_re.search, + self.appendFileheadLine], ["FILEHEAD", "DEFCLASS", self.defclass_re.search, self.resetCommentSearch], - ["FILEHEAD", "DEFCLASS_MULTI", self.multiline_defclass_start_re.search, self.resetCommentSearch], + ["FILEHEAD", "DEFCLASS_MULTI", + self.multiline_defclass_start_re.search, self.resetCommentSearch], ["FILEHEAD", "DEFCLASS_BODY", self.catchall, self.appendFileheadLine], - ### DEFCLASS + # DEFCLASS # single line comments - ["DEFCLASS", "DEFCLASS_BODY", self.single_comment_re.search, self.appendCommentLine], - ["DEFCLASS", "DEFCLASS_BODY", self.double_comment_re.search, self.appendCommentLine], + ["DEFCLASS", "DEFCLASS_BODY", + self.single_comment_re.search, self.appendCommentLine], + ["DEFCLASS", "DEFCLASS_BODY", + self.double_comment_re.search, self.appendCommentLine], # multiline comments - ["DEFCLASS", "COMMENT_SINGLE", self.start_single_comment_re.search, self.appendCommentLine], - ["COMMENT_SINGLE", "DEFCLASS_BODY", self.end_single_comment_re.search, self.appendCommentLine], - ["COMMENT_SINGLE", "COMMENT_SINGLE", self.catchall, self.appendCommentLine], - ["DEFCLASS", "COMMENT_DOUBLE", self.start_double_comment_re.search, self.appendCommentLine], - ["COMMENT_DOUBLE", "DEFCLASS_BODY", self.end_double_comment_re.search, self.appendCommentLine], - ["COMMENT_DOUBLE", "COMMENT_DOUBLE", self.catchall, self.appendCommentLine], + ["DEFCLASS", "COMMENT_SINGLE", + self.start_single_comment_re.search, self.appendCommentLine], + ["COMMENT_SINGLE", "DEFCLASS_BODY", + self.end_single_comment_re.search, self.appendCommentLine], + ["COMMENT_SINGLE", "COMMENT_SINGLE", + self.catchall, self.appendCommentLine], + ["DEFCLASS", "COMMENT_DOUBLE", + self.start_double_comment_re.search, self.appendCommentLine], + ["COMMENT_DOUBLE", "DEFCLASS_BODY", + self.end_double_comment_re.search, self.appendCommentLine], + ["COMMENT_DOUBLE", "COMMENT_DOUBLE", + self.catchall, self.appendCommentLine], # other lines ["DEFCLASS", "DEFCLASS", self.empty_re.search, self.appendDefclassLine], ["DEFCLASS", "DEFCLASS", self.defclass_re.search, self.resetCommentSearch], - ["DEFCLASS", "DEFCLASS_MULTI", self.multiline_defclass_start_re.search, self.resetCommentSearch], + ["DEFCLASS", "DEFCLASS_MULTI", + self.multiline_defclass_start_re.search, self.resetCommentSearch], ["DEFCLASS", "DEFCLASS_BODY", self.catchall, self.stopCommentSearch], - ### DEFCLASS_BODY + # DEFCLASS_BODY - ["DEFCLASS_BODY", "DEFCLASS", self.defclass_re.search, self.startCommentSearch], - ["DEFCLASS_BODY", "DEFCLASS_MULTI", self.multiline_defclass_start_re.search, self.startCommentSearch], + ["DEFCLASS_BODY", "DEFCLASS", + self.defclass_re.search, self.startCommentSearch], + ["DEFCLASS_BODY", "DEFCLASS_MULTI", + self.multiline_defclass_start_re.search, self.startCommentSearch], ["DEFCLASS_BODY", "DEFCLASS_BODY", self.catchall, self.appendNormalLine], - ### DEFCLASS_MULTI - ["DEFCLASS_MULTI", "DEFCLASS", self.multiline_defclass_end_re.search, self.appendDefclassLine], - ["DEFCLASS_MULTI", "DEFCLASS_MULTI", self.catchall, self.appendDefclassLine], + # DEFCLASS_MULTI + ["DEFCLASS_MULTI", "DEFCLASS", + self.multiline_defclass_end_re.search, self.appendDefclassLine], + ["DEFCLASS_MULTI", "DEFCLASS_MULTI", + self.catchall, self.appendDefclassLine], ] self.fsm = FSM("FILEHEAD", transitions) @@ -182,8 +213,9 @@ def __closeComment(self): if args.autobrief: if len(self.comment) == 1 \ - or (len(self.comment) > 2 and self.comment[1].strip() == ''): - self.comment[0] = self.__docstringSummaryToBrief(self.comment[0]) + or (len(self.comment) > 2 and self.comment[1].strip() == ''): + self.comment[0] = self.__docstringSummaryToBrief( + self.comment[0]) if self.comment: block = self.makeCommentBlock() @@ -281,11 +313,12 @@ def appendCommentLine(self, match): # single line comment if (from_state == "DEFCLASS" and to_state == "DEFCLASS_BODY") \ - or (from_state == "FILEHEAD" and to_state == "FILEHEAD"): + or (from_state == "FILEHEAD" and to_state == "FILEHEAD"): # remove comment delimiter from begin and end of the line activeCommentDelim = match.group(1) line = self.fsm.current_input - self.comment.append(line[line.find(activeCommentDelim)+len(activeCommentDelim):line.rfind(activeCommentDelim)]) + self.comment.append(line[line.find( + activeCommentDelim) + len(activeCommentDelim):line.rfind(activeCommentDelim)]) if (to_state == "DEFCLASS_BODY"): self.__closeComment() @@ -295,7 +328,8 @@ def appendCommentLine(self, match): # remove comment delimiter from begin of the line activeCommentDelim = match.group(1) line = self.fsm.current_input - self.comment.append(line[line.find(activeCommentDelim)+len(activeCommentDelim):]) + self.comment.append( + line[line.find(activeCommentDelim) + len(activeCommentDelim):]) # multiline end elif to_state == "DEFCLASS_BODY" or to_state == "FILEHEAD": # remove comment delimiter from end of the line @@ -379,23 +413,25 @@ def parseLine(self, line): self.fsm.makeTransition(line) self.__flushBuffer() + def argParse(): """Parses commandline args.""" parser = ArgumentParser(prog=__applicationName__) parser.add_argument("--version", action="version", - version="%(prog)s " + __version__ - ) + version="%(prog)s " + __version__ + ) parser.add_argument("--autobrief", action="store_true", - help="use the docstring summary line as \\brief description" - ) + help="use the docstring summary line as \\brief description" + ) parser.add_argument("--debug", action="store_true", - help="enable debug output on stderr" - ) + help="enable debug output on stderr" + ) parser.add_argument("filename", metavar="FILENAME") return parser.parse_args() + def main(): """Starts the parser on the file given by the filename as the first argument on the commandline. @@ -405,5 +441,6 @@ def main(): fsm = Doxypy() fsm.parseFile(args.filename) + if __name__ == "__main__": main() diff --git a/docs/doxygen/update_pydoc.py b/docs/doxygen/update_pydoc.py index ccf982ac9bd..b65e168ae53 100644 --- a/docs/doxygen/update_pydoc.py +++ b/docs/doxygen/update_pydoc.py @@ -16,16 +16,23 @@ """ -import os, sys, time, glob, re, json +import os +import sys +import time +import glob +import re +import json from argparse import ArgumentParser from doxyxml import DoxyIndex, DoxyClass, DoxyFriend, DoxyFunction, DoxyFile from doxyxml import DoxyOther, base + def py_name(name): bits = name.split('_') return '_'.join(bits[1:]) + def make_name(name): bits = name.split('_') return bits[0] + '_make_' + '_'.join(bits[1:]) @@ -50,6 +57,7 @@ def includes(cls, item): is_a_block = di.has_member(friendname, DoxyFunction) return is_a_block + class Block2(object): """ Checks if doxyxml produced objects correspond to a new style @@ -63,7 +71,8 @@ def includes(cls, item): # Check for a parsing error. if item.error(): return False - is_a_block2 = item.has_member('make', DoxyFunction) and item.has_member('sptr', DoxyOther) + is_a_block2 = item.has_member( + 'make', DoxyFunction) and item.has_member('sptr', DoxyOther) return is_a_block2 @@ -94,6 +103,7 @@ def combine_descriptions(obj): description.append(dd) return utoascii('\n\n'.join(description)).strip() + def format_params(parameteritems): output = ['Args:'] template = ' {0} : {1}' @@ -101,7 +111,10 @@ def format_params(parameteritems): output.append(template.format(pi.name, pi.description)) return '\n'.join(output) + entry_templ = '%feature("docstring") {name} "{docstring}"' + + def make_entry(obj, name=None, templ="{description}", description=None, params=[]): """ Create a docstring key/value pair, where the key is the object name. @@ -114,9 +127,9 @@ def make_entry(obj, name=None, templ="{description}", description=None, params=[ used as the description instead of extracting it from obj. """ if name is None: - name=obj.name() - if hasattr(obj,'_parse_data') and hasattr(obj._parse_data,'definition'): - name=obj._parse_data.definition.split(' ')[-1] + name = obj.name() + if hasattr(obj, '_parse_data') and hasattr(obj._parse_data, 'definition'): + name = obj._parse_data.definition.split(' ')[-1] if "operator " in name: return '' if description is None: @@ -174,9 +187,10 @@ def make_block_entry(di, block): output = {} output.update(make_class_entry(block, description=super_description)) output.update(make_entry(make_func, description=super_description, - params=block.params)) + params=block.params)) return output + def make_block2_entry(di, block): """ Create class and function docstrings of a new style gnuradio block @@ -186,19 +200,21 @@ def make_block2_entry(di, block): class_description = combine_descriptions(block) make_func = block.get_member('make', DoxyFunction) make_description = combine_descriptions(make_func) - description = class_description + "\n\nConstructor Specific Documentation:\n\n" + make_description + description = class_description + \ + "\n\nConstructor Specific Documentation:\n\n" + make_description # Associate the combined description with the class and # the make function. output = {} output.update(make_class_entry( - block, description=description, - ignored_methods=['make'], params=make_func.params)) + block, description=description, + ignored_methods=['make'], params=make_func.params)) makename = block.name() + '::make' output.update(make_entry( - make_func, name=makename, description=description, - params=make_func.params)) + make_func, name=makename, description=description, + params=make_func.params)) return output + def get_docstrings_dict(di, custom_output=None): output = {} @@ -218,19 +234,21 @@ def get_docstrings_dict(di, custom_output=None): make_funcs.add(make_func.name()) output.update(make_block_entry(di, block)) except block.ParsingError: - sys.stderr.write('Parsing error for block {0}\n'.format(block.name())) + sys.stderr.write( + 'Parsing error for block {0}\n'.format(block.name())) raise for block in blocks2: try: make_func = block.get_member('make', DoxyFunction) - make_func_name = block.name() +'::make' + make_func_name = block.name() + '::make' # Don't want to risk writing to output twice. if make_func_name not in make_funcs: make_funcs.add(make_func_name) output.update(make_block2_entry(di, block)) except block.ParsingError: - sys.stderr.write('Parsing error for block {0}\n'.format(block.name())) + sys.stderr.write( + 'Parsing error for block {0}\n'.format(block.name())) raise # Create docstrings for functions @@ -241,7 +259,8 @@ def get_docstrings_dict(di, custom_output=None): try: output.update(make_entry(f)) except f.ParsingError: - sys.stderr.write('Parsing error for function {0}\n'.format(f.name())) + sys.stderr.write( + 'Parsing error for function {0}\n'.format(f.name())) # Create docstrings for classes block_names = [block.name() for block in blocks] @@ -259,60 +278,69 @@ def get_docstrings_dict(di, custom_output=None): return output + def sub_docstring_in_pydoc_h(pydoc_files, docstrings_dict, output_dir, filter_str=None): if filter_str: - docstrings_dict = {k: v for k, v in docstrings_dict.items() if k.startswith(filter_str)} + docstrings_dict = { + k: v for k, v in docstrings_dict.items() if k.startswith(filter_str)} + + with open(os.path.join(output_dir, 'docstring_status'), 'w') as status_file: - with open(os.path.join(output_dir,'docstring_status'),'w') as status_file: - for pydoc_file in pydoc_files: if filter_str: - filter_str2 = "::".join((filter_str,os.path.split(pydoc_file)[-1].split('_pydoc_template.h')[0])) - docstrings_dict2 = {k: v for k, v in docstrings_dict.items() if k.startswith(filter_str2)} + filter_str2 = "::".join((filter_str, os.path.split( + pydoc_file)[-1].split('_pydoc_template.h')[0])) + docstrings_dict2 = { + k: v for k, v in docstrings_dict.items() if k.startswith(filter_str2)} else: docstrings_dict2 = docstrings_dict - - - file_in = open(pydoc_file,'r').read() - for key, value in docstrings_dict2.items(): - file_in_tmp = file_in + file_in = open(pydoc_file, 'r').read() + for key, value in docstrings_dict2.items(): + file_in_tmp = file_in try: doc_key = key.split("::") # if 'gr' in doc_key: - # doc_key.remove('gr') + # doc_key.remove('gr') doc_key = '_'.join(doc_key) - regexp = r'(__doc_{} =\sR\"doc\()[^)]*(\)doc\")'.format(doc_key) + regexp = r'(__doc_{} =\sR\"doc\()[^)]*(\)doc\")'.format( + doc_key) regexp = re.compile(regexp, re.MULTILINE) - - (file_in, nsubs) = regexp.subn(r'\1'+value+r'\2', file_in, count=1) + + (file_in, nsubs) = regexp.subn( + r'\1' + value + r'\2', file_in, count=1) if nsubs == 1: status_file.write("PASS: " + pydoc_file + "\n") except KeyboardInterrupt: raise KeyboardInterrupt - except: # be permissive, TODO log, but just leave the docstring blank + except: # be permissive, TODO log, but just leave the docstring blank status_file.write("FAIL: " + pydoc_file + "\n") file_in = file_in_tmp - output_pathname = os.path.join(output_dir, os.path.basename(pydoc_file).replace('_template.h','.h')) - with open(output_pathname,'w') as file_out: + output_pathname = os.path.join(output_dir, os.path.basename( + pydoc_file).replace('_template.h', '.h')) + with open(output_pathname, 'w') as file_out: file_out.write(file_in) + def copy_docstring_templates(pydoc_files, output_dir): - with open(os.path.join(output_dir,'docstring_status'),'w') as status_file: + with open(os.path.join(output_dir, 'docstring_status'), 'w') as status_file: for pydoc_file in pydoc_files: - file_in = open(pydoc_file,'r').read() - output_pathname = os.path.join(output_dir, os.path.basename(pydoc_file).replace('_template.h','.h')) - with open(output_pathname,'w') as file_out: + file_in = open(pydoc_file, 'r').read() + output_pathname = os.path.join(output_dir, os.path.basename( + pydoc_file).replace('_template.h', '.h')) + with open(output_pathname, 'w') as file_out: file_out.write(file_in) status_file.write("DONE") + def argParse(): """Parses commandline args.""" - desc='Scrape the doxygen generated xml for docstrings to insert into python bindings' + desc = 'Scrape the doxygen generated xml for docstrings to insert into python bindings' parser = ArgumentParser(description=desc) - - parser.add_argument("function", help="Operation to perform on docstrings", choices=["scrape","sub","copy"]) + + parser.add_argument("function", help="Operation to perform on docstrings", choices=[ + "scrape", "sub", "copy"]) parser.add_argument("--xml_path") parser.add_argument("--bindings_dir") @@ -322,6 +350,7 @@ def argParse(): return parser.parse_args() + if __name__ == "__main__": # Parse command line options and set up doxyxml. args = argParse() @@ -333,10 +362,11 @@ def argParse(): elif args.function.lower() == 'sub': with open(args.json_path, 'r') as fp: docstrings_dict = json.load(fp) - pydoc_files = glob.glob(os.path.join(args.bindings_dir,'*_pydoc_template.h')) - sub_docstring_in_pydoc_h(pydoc_files, docstrings_dict, args.output_dir, args.filter) + pydoc_files = glob.glob(os.path.join( + args.bindings_dir, '*_pydoc_template.h')) + sub_docstring_in_pydoc_h( + pydoc_files, docstrings_dict, args.output_dir, args.filter) elif args.function.lower() == 'copy': - pydoc_files = glob.glob(os.path.join(args.bindings_dir,'*_pydoc_template.h')) + pydoc_files = glob.glob(os.path.join( + args.bindings_dir, '*_pydoc_template.h')) copy_docstring_templates(pydoc_files, args.output_dir) - - diff --git a/docs/usage-manual/export-usage-manual.py b/docs/usage-manual/export-usage-manual.py index 02d3fb620a5..153f5f5fea7 100644 --- a/docs/usage-manual/export-usage-manual.py +++ b/docs/usage-manual/export-usage-manual.py @@ -36,7 +36,7 @@ # hit Export submit_button = driver.find_element_by_xpath("//*[@value='Export']") - submit_button.click() + submit_button.click() # get HTML of new page raw_html = driver.page_source @@ -45,7 +45,8 @@ # save text to file h = HTMLParser.HTMLParser() - cropped_html_text = h.unescape(cropped_html) # makes it so stuff like > shows up as a greater than sign + # makes it so stuff like > shows up as a greater than sign + cropped_html_text = h.unescape(cropped_html) text_file = open("(exported from wiki) " + page_name + ".txt", "w") text_file.write(cropped_html_text) text_file.close() diff --git a/gnuradio-runtime/CMakeLists.txt b/gnuradio-runtime/CMakeLists.txt index 83705cd83c6..a81a5c14272 100644 --- a/gnuradio-runtime/CMakeLists.txt +++ b/gnuradio-runtime/CMakeLists.txt @@ -19,6 +19,11 @@ find_package(MPLIB REQUIRED) include(${CMAKE_CURRENT_SOURCE_DIR}/ConfigChecks.cmake) GR_CHECK_LINUX_SCHED_AVAIL() +######################################################################## +# Find spdlog +######################################################################## +find_package(spdlog CONFIG) + ######################################################################## # Register component ######################################################################## @@ -27,7 +32,7 @@ GR_REGISTER_COMPONENT("gnuradio-runtime" ENABLE_GNURADIO_RUNTIME Boost_FOUND PYTHONINTERP_FOUND MPLIB_FOUND - LOG4CPP_FOUND + spdlog_FOUND pybind11_FOUND ) @@ -70,6 +75,7 @@ if(ENABLE_COMMON_PCH) PUBLIC $<$:$> ) + target_link_libraries(common-precompiled-headers PUBLIC spdlog::spdlog) endif() ######################################################################## diff --git a/gnuradio-runtime/apps/evaluation_random_numbers.py b/gnuradio-runtime/apps/evaluation_random_numbers.py index 614a568d61f..0d00554c3dd 100644 --- a/gnuradio-runtime/apps/evaluation_random_numbers.py +++ b/gnuradio-runtime/apps/evaluation_random_numbers.py @@ -26,9 +26,9 @@ rayleigh_num_bins = 31 laplace_num_bins = 31 -rndm = gr.random() # instance of gnuradio random class (gr::random) +rndm = gr.random() # instance of gnuradio random class (gr::random) -print('All histograms contain',num_tests,'realisations.') +print('All histograms contain', num_tests, 'realisations.') #*** GENERATE DATA ***# @@ -45,83 +45,97 @@ #*** HISTOGRAM DATA AND CALCULATE EXPECTED COUNTS ***# -uniform_bins = np.linspace(0,1,uniform_num_bins) -gauss_bins = np.linspace(-8,8,gauss_num_bins) -laplace_bins = np.linspace(-8,8,laplace_num_bins) -rayleigh_bins = np.linspace(0,10,rayleigh_num_bins) +uniform_bins = np.linspace(0, 1, uniform_num_bins) +gauss_bins = np.linspace(-8, 8, gauss_num_bins) +laplace_bins = np.linspace(-8, 8, laplace_num_bins) +rayleigh_bins = np.linspace(0, 10, rayleigh_num_bins) -uniform_hist = np.histogram(uniform_values,uniform_bins) -gauss_hist = np.histogram(gauss_values,gauss_bins) -rayleigh_hist = np.histogram(rayleigh_values,rayleigh_bins) -laplace_hist = np.histogram(laplace_values,laplace_bins) +uniform_hist = np.histogram(uniform_values, uniform_bins) +gauss_hist = np.histogram(gauss_values, gauss_bins) +rayleigh_hist = np.histogram(rayleigh_values, rayleigh_bins) +laplace_hist = np.histogram(laplace_values, laplace_bins) -uniform_expected = np.zeros(uniform_num_bins-1) -gauss_expected = np.zeros(gauss_num_bins-1) -rayleigh_expected = np.zeros(rayleigh_num_bins-1) -laplace_expected = np.zeros(laplace_num_bins-1) +uniform_expected = np.zeros(uniform_num_bins - 1) +gauss_expected = np.zeros(gauss_num_bins - 1) +rayleigh_expected = np.zeros(rayleigh_num_bins - 1) +laplace_expected = np.zeros(laplace_num_bins - 1) for k in range(len(uniform_hist[0])): - uniform_expected[k] = num_tests / float(uniform_num_bins-1) + uniform_expected[k] = num_tests / float(uniform_num_bins - 1) for k in range(len(gauss_hist[0])): - gauss_expected[k] = float(norm.cdf(gauss_hist[1][k+1])-norm.cdf(gauss_hist[1][k]))*num_tests + gauss_expected[k] = float( + norm.cdf(gauss_hist[1][k + 1]) - norm.cdf(gauss_hist[1][k])) * num_tests for k in range(len(rayleigh_hist[0])): - rayleigh_expected[k] = float(rayleigh.cdf(rayleigh_hist[1][k+1])-rayleigh.cdf(rayleigh_hist[1][k]))*num_tests + rayleigh_expected[k] = float(rayleigh.cdf( + rayleigh_hist[1][k + 1]) - rayleigh.cdf(rayleigh_hist[1][k])) * num_tests for k in range(len(laplace_hist[0])): - laplace_expected[k] = float(laplace.cdf(laplace_hist[1][k+1])-laplace.cdf(laplace_hist[1][k]))*num_tests + laplace_expected[k] = float(laplace.cdf( + laplace_hist[1][k + 1]) - laplace.cdf(laplace_hist[1][k])) * num_tests #*** PLOT HISTOGRAMS AND EXPECTATIONS TAKEN FROM SCIPY ***# -uniform_bins_center = uniform_bins[0:-1]+(uniform_bins[1]-uniform_bins[0]) / 2.0 -gauss_bins_center = gauss_bins[0:-1]+(gauss_bins[1]-gauss_bins[0]) / 2.0 -rayleigh_bins_center = rayleigh_bins[0:-1]+(rayleigh_bins[1]-rayleigh_bins[0]) / 2.0 -laplace_bins_center = laplace_bins[0:-1]+(laplace_bins[1]-laplace_bins[0]) / 2.0 +uniform_bins_center = uniform_bins[0:-1] + \ + (uniform_bins[1] - uniform_bins[0]) / 2.0 +gauss_bins_center = gauss_bins[0:-1] + (gauss_bins[1] - gauss_bins[0]) / 2.0 +rayleigh_bins_center = rayleigh_bins[0:-1] + \ + (rayleigh_bins[1] - rayleigh_bins[0]) / 2.0 +laplace_bins_center = laplace_bins[0:-1] + \ + (laplace_bins[1] - laplace_bins[0]) / 2.0 plt.figure(1) -plt.subplot(2,1,1) -plt.plot(uniform_bins_center,uniform_hist[0],'s--',uniform_bins_center,uniform_expected,'o:') +plt.subplot(2, 1, 1) +plt.plot(uniform_bins_center, + uniform_hist[0], 's--', uniform_bins_center, uniform_expected, 'o:') plt.xlabel('Bins'), plt.ylabel('Count'), plt.title('Uniform: Distribution') -plt.legend(['histogram gr::random','calculation scipy'],loc=1) +plt.legend(['histogram gr::random', 'calculation scipy'], loc=1) -plt.subplot(2,1,2) -plt.plot(uniform_bins_center,uniform_hist[0] / uniform_expected,'rs--') -plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title('Uniform: Relative deviation to scipy') +plt.subplot(2, 1, 2) +plt.plot(uniform_bins_center, uniform_hist[0] / uniform_expected, 'rs--') +plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title( + 'Uniform: Relative deviation to scipy') plt.figure(2) -plt.subplot(2,1,1) -plt.plot(gauss_bins_center,gauss_hist[0],'s--',gauss_bins_center,gauss_expected,'o:') +plt.subplot(2, 1, 1) +plt.plot(gauss_bins_center, gauss_hist[0], 's--', + gauss_bins_center, gauss_expected, 'o:') plt.xlabel('Bins'), plt.ylabel('Count'), plt.title('Gauss: Distribution') -plt.legend(['histogram gr::random','calculation scipy'],loc=1) +plt.legend(['histogram gr::random', 'calculation scipy'], loc=1) -plt.subplot(2,1,2) -plt.plot(gauss_bins_center,gauss_hist[0] / gauss_expected,'rs--') -plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title('Gauss: Relative deviation to scipy') +plt.subplot(2, 1, 2) +plt.plot(gauss_bins_center, gauss_hist[0] / gauss_expected, 'rs--') +plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title( + 'Gauss: Relative deviation to scipy') plt.figure(3) -plt.subplot(2,1,1) -plt.plot(rayleigh_bins_center,rayleigh_hist[0],'s--',rayleigh_bins_center,rayleigh_expected,'o:') +plt.subplot(2, 1, 1) +plt.plot(rayleigh_bins_center, + rayleigh_hist[0], 's--', rayleigh_bins_center, rayleigh_expected, 'o:') plt.xlabel('Bins'), plt.ylabel('Count'), plt.title('Rayleigh: Distribution') -plt.legend(['histogram gr::random','calculation scipy'],loc=1) +plt.legend(['histogram gr::random', 'calculation scipy'], loc=1) -plt.subplot(2,1,2) -plt.plot(rayleigh_bins_center,rayleigh_hist[0] / rayleigh_expected,'rs--') -plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title('Rayleigh: Relative deviation to scipy') +plt.subplot(2, 1, 2) +plt.plot(rayleigh_bins_center, rayleigh_hist[0] / rayleigh_expected, 'rs--') +plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title( + 'Rayleigh: Relative deviation to scipy') plt.figure(4) -plt.subplot(2,1,1) -plt.plot(laplace_bins_center,laplace_hist[0],'s--',laplace_bins_center,laplace_expected,'o:') +plt.subplot(2, 1, 1) +plt.plot(laplace_bins_center, + laplace_hist[0], 's--', laplace_bins_center, laplace_expected, 'o:') plt.xlabel('Bins'), plt.ylabel('Count'), plt.title('Laplace: Distribution') -plt.legend(['histogram gr::random','calculation scipy'],loc=1) +plt.legend(['histogram gr::random', 'calculation scipy'], loc=1) -plt.subplot(2,1,2) -plt.plot(laplace_bins_center,laplace_hist[0] / laplace_expected,'rs--') -plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title('Laplace: Relative deviation to scipy') +plt.subplot(2, 1, 2) +plt.plot(laplace_bins_center, laplace_hist[0] / laplace_expected, 'rs--') +plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title( + 'Laplace: Relative deviation to scipy') plt.show() diff --git a/gnuradio-runtime/apps/gnuradio-config-info.cc b/gnuradio-runtime/apps/gnuradio-config-info.cc index f2dd563edbe..f4dc7762904 100644 --- a/gnuradio-runtime/apps/gnuradio-config-info.cc +++ b/gnuradio-runtime/apps/gnuradio-config-info.cc @@ -21,12 +21,11 @@ #include namespace po = boost::program_options; -using boost::format; int main(int argc, char** argv) { po::options_description desc( - (format("Program options: %1% [options]") % argv[0]).str()); + (boost::format("Program options: %1% [options]") % argv[0]).str()); po::variables_map vm; // clang-format off diff --git a/gnuradio-runtime/examples/mp-sched/affinity_set.py b/gnuradio-runtime/examples/mp-sched/affinity_set.py index 4516b96f540..530742ef227 100644 --- a/gnuradio-runtime/examples/mp-sched/affinity_set.py +++ b/gnuradio-runtime/examples/mp-sched/affinity_set.py @@ -13,6 +13,7 @@ from argparse import ArgumentParser import sys + class affinity_set(gr.top_block): def __init__(self): @@ -27,19 +28,23 @@ def __init__(self): # Blocks ################################################## vec_len = 1 - self.blocks_throttle_0 = blocks.throttle(gr.sizeof_gr_complex*vec_len, samp_rate) - self.blocks_null_source_0 = blocks.null_source(gr.sizeof_gr_complex*vec_len) - self.blocks_null_sink_0 = blocks.null_sink(gr.sizeof_gr_complex*vec_len) - self.filter_filt_0 = filter.fir_filter_ccc(1, 40000*[0.2+0.3j,]) - self.filter_filt_1 = filter.fir_filter_ccc(1, 40000*[0.2+0.3j,]) + self.blocks_throttle_0 = blocks.throttle( + gr.sizeof_gr_complex * vec_len, samp_rate) + self.blocks_null_source_0 = blocks.null_source( + gr.sizeof_gr_complex * vec_len) + self.blocks_null_sink_0 = blocks.null_sink( + gr.sizeof_gr_complex * vec_len) + self.filter_filt_0 = filter.fir_filter_ccc(1, 40000 * [0.2 + 0.3j, ]) + self.filter_filt_1 = filter.fir_filter_ccc(1, 40000 * [0.2 + 0.3j, ]) - self.filter_filt_0.set_processor_affinity([0,]) - self.filter_filt_1.set_processor_affinity([0,1]) + self.filter_filt_0.set_processor_affinity([0, ]) + self.filter_filt_1.set_processor_affinity([0, 1]) ################################################## # Connections ################################################## - self.connect((self.blocks_null_source_0, 0), (self.blocks_throttle_0, 0)) + self.connect((self.blocks_null_source_0, 0), + (self.blocks_throttle_0, 0)) self.connect((self.blocks_throttle_0, 0), (self.filter_filt_0, 0)) self.connect((self.filter_filt_0, 0), (self.filter_filt_1, 0)) self.connect((self.filter_filt_1, 0), (self.blocks_null_sink_0, 0)) @@ -50,6 +55,7 @@ def get_samp_rate(self): def set_samp_rate(self, samp_rate): self.samp_rate = samp_rate + if __name__ == '__main__': parser = ArgumentParser() args = parser.parse_args() @@ -69,4 +75,4 @@ def set_samp_rate(self, samp_rate): except ValueError: print("Invalid number") else: - tb.filter_filt_0.set_processor_affinity([n,]) + tb.filter_filt_0.set_processor_affinity([n, ]) diff --git a/gnuradio-runtime/examples/mp-sched/plot_flops.py b/gnuradio-runtime/examples/mp-sched/plot_flops.py index 918197f9f4c..5b58e1ddcfb 100644 --- a/gnuradio-runtime/examples/mp-sched/plot_flops.py +++ b/gnuradio-runtime/examples/mp-sched/plot_flops.py @@ -47,9 +47,11 @@ def parse_file(input_filename, output): def handle_file(input_filename): - cmd_file = tempfile.NamedTemporaryFile(mode='w+', prefix='pf', suffix='.cmd') + cmd_file = tempfile.NamedTemporaryFile( + mode='w+', prefix='pf', suffix='.cmd') cmd_file_name = cmd_file.name - data_file = tempfile.NamedTemporaryFile(mode='w+', prefix='pf', suffix='.dat') + data_file = tempfile.NamedTemporaryFile( + mode='w+', prefix='pf', suffix='.dat') data_file_name = data_file.name desc = parse_file(input_filename, data_file) if len(desc) > 0: @@ -68,8 +70,8 @@ def handle_file(input_filename): os.system("gnuplot " + cmd_file_name + " -") - #sys.stdout.write(open(cmd_file_name,'r').read()) - #sys.stdout.write(open(data_file_name,'r').read()) + # sys.stdout.write(open(cmd_file_name,'r').read()) + # sys.stdout.write(open(data_file_name,'r').read()) def main(): diff --git a/gnuradio-runtime/examples/mp-sched/run_synthetic.py b/gnuradio-runtime/examples/mp-sched/run_synthetic.py index 35e7f1820dd..db8378efe02 100644 --- a/gnuradio-runtime/examples/mp-sched/run_synthetic.py +++ b/gnuradio-runtime/examples/mp-sched/run_synthetic.py @@ -38,18 +38,20 @@ def write_shell_script(f, data_filename, description, ncores, gflops, max_pipes_ # We'd like each run of synthetic to take ~10 seconds desired_time_per_run = 10 est_gflops_avail = min(nstages * npipes, ncores) * gflops - nsamples = (est_gflops_avail * desired_time_per_run) / (512.0 * nstages * npipes) + nsamples = (est_gflops_avail * desired_time_per_run) / \ + (512.0 * nstages * npipes) nsamples = int(nsamples * 1e9) - cmd = "./synthetic.py -m -s %d -p %d -N %d\n" % (nstages, npipes, nsamples) + cmd = "./synthetic.py -m -s %d -p %d -N %d\n" % ( + nstages, npipes, nsamples) f.write(cmd) f.write('if test $? -ge 128; then exit 128; fi\n') - f.write(") 2>&1 | grep --line-buffered -v '^>>>' | tee %s\n" % (data_filename,)) + f.write(") 2>&1 | grep --line-buffered -v '^>>>' | tee %s\n" % + (data_filename,)) f.flush() - def main(): description = """%prog gathers multiprocessor scaling data using the ./synthetic.py benchmark. All combinations of npipes and nstages between 1 and --max-pipes-and-stages are tried. @@ -61,14 +63,15 @@ def main(): """ parser = ArgumentParser(description=description) parser.add_argument("-d", "--description", metavar="DESC", - help="machine description, e.g., \"Dual quad-core Xeon 3 GHz\"") + help="machine description, e.g., \"Dual quad-core Xeon 3 GHz\"") parser.add_argument("-n", "--ncores", type=int, default=1, - help="number of processor cores [default=%(default)s]") + help="number of processor cores [default=%(default)s]") parser.add_argument("-g", "--gflops", metavar="GFLOPS", type=float, default=3.0, - help="estimated GFLOPS per core [default=%(default)s]") + help="estimated GFLOPS per core [default=%(default)s]") parser.add_argument("-m", "--max-pipes-and-stages", metavar="MAX", type=int, default=16, - help="maximum number of pipes and stages to use [default=%(default)s]") - parser.add_argument("output_file_name", metavar="FILE", help="output file name") + help="maximum number of pipes and stages to use [default=%(default)s]") + parser.add_argument("output_file_name", metavar="FILE", + help="output file name") args = parser.parse_args() shell = os.popen("/bin/sh", "w") @@ -80,6 +83,6 @@ def main(): args.gflops, args.max_pipes_and_stages) + if __name__ == '__main__': main() - diff --git a/gnuradio-runtime/examples/mp-sched/synthetic.py b/gnuradio-runtime/examples/mp-sched/synthetic.py index 4d6f3b9a222..cff6fd970d3 100644 --- a/gnuradio-runtime/examples/mp-sched/synthetic.py +++ b/gnuradio-runtime/examples/mp-sched/synthetic.py @@ -24,7 +24,7 @@ def __init__(self, nstages, ntaps=256): gr.hier_block2.__init__(self, "pipeline", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(0, 0, 0)) - taps = ntaps*[1.0 / ntaps] + taps = ntaps * [1.0 / ntaps] upstream = self for i in range(nstages): op = filter.fir_filter_fff(1, taps) @@ -41,14 +41,14 @@ def __init__(self): default_nsamples = 10e6 parser = ArgumentParser() parser.add_argument("-p", "--npipelines", type=intx, default=1, - metavar="NPIPES", help="the number of pipelines to create (default=%(default)s)") + metavar="NPIPES", help="the number of pipelines to create (default=%(default)s)") parser.add_argument("-s", "--nstages", type=intx, default=1, metavar="NSTAGES", - help="the number of stages in each pipeline (default=%(default)s)") + help="the number of stages in each pipeline (default=%(default)s)") parser.add_argument("-N", "--nsamples", type=eng_float, default=default_nsamples, - help=("the number of samples to run through the graph (default=%s)" % - (eng_notation.num_to_str(default_nsamples)))) + help=("the number of samples to run through the graph (default=%s)" % + (eng_notation.num_to_str(default_nsamples)))) parser.add_argument("-m", "--machine-readable", action="store_true", default=False, - help="enable machine readable output") + help="enable machine readable output") args = parser.parse_args() @@ -74,23 +74,24 @@ def time_it(tb): start = os.times() tb.run() stop = os.times() - delta = list(map((lambda a, b: a-b), stop, start)) + delta = list(map((lambda a, b: a - b), stop, start)) user, sys, childrens_user, childrens_sys, real = delta total_user = user + childrens_user - total_sys = sys + childrens_sys + total_sys = sys + childrens_sys if tb.machine_readable: print("%3d %3d %.3e %7.3f %7.3f %7.3f %7.3f %.6e %.3e" % ( - tb.npipes, tb.nstages, tb.nsamples, real, total_user, total_sys, (total_user+total_sys) / real, tb.flop, tb.flop / real)) + tb.npipes, tb.nstages, tb.nsamples, real, total_user, total_sys, (total_user + total_sys) / real, tb.flop, tb.flop / real)) else: - print("npipes %7d" % (tb.npipes,)) - print("nstages %7d" % (tb.nstages,)) - print("nsamples %s" % (eng_notation.num_to_str(tb.nsamples),)) + print("npipes %7d" % (tb.npipes,)) + print("nstages %7d" % (tb.nstages,)) + print("nsamples %s" % (eng_notation.num_to_str(tb.nsamples),)) print("real %7.3f" % (real,)) print("user %7.3f" % (total_user,)) print("sys %7.3f" % (total_sys,)) print("(user+sys)/real %7.3f" % ((total_user + total_sys) / real,)) - print("pseudo_flop %s" % (eng_notation.num_to_str(tb.flop),)) - print("pseudo_flop/real %s" % (eng_notation.num_to_str(tb.flop / real),)) + print("pseudo_flop %s" % (eng_notation.num_to_str(tb.flop),)) + print("pseudo_flop/real %s" % + (eng_notation.num_to_str(tb.flop / real),)) if __name__ == "__main__": @@ -99,7 +100,3 @@ def time_it(tb): time_it(tb) except KeyboardInterrupt: raise SystemExit(128) - - - - diff --git a/gnuradio-runtime/examples/mp-sched/wfm_rcv_pll_to_wav.py b/gnuradio-runtime/examples/mp-sched/wfm_rcv_pll_to_wav.py index f78404a66a8..d2fa94b8add 100644 --- a/gnuradio-runtime/examples/mp-sched/wfm_rcv_pll_to_wav.py +++ b/gnuradio-runtime/examples/mp-sched/wfm_rcv_pll_to_wav.py @@ -17,14 +17,15 @@ import sys import math + class wfm_rx_block (gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = ArgumentParser(description="Decode WFM signal into WAV file.") parser.add_argument("-V", "--volume", type=eng_float, - help="Volume (dB) <%r, %r> (default is midpoint)" % \ - self.volume_range()[:2]) + help="Volume (dB) <%r, %r> (default is midpoint)" % + self.volume_range()[:2]) parser.add_argument("input_file", help="Input file (complex samples)") parser.add_argument("output_file", help="Output WAV file") @@ -34,7 +35,8 @@ def __init__(self): # build graph - self.src = blocks.file_source(gr.sizeof_gr_complex, args.input_file, False) + self.src = blocks.file_source( + gr.sizeof_gr_complex, args.input_file, False) adc_rate = 64e6 # 64 MS/s usrp_decim = 200 @@ -44,19 +46,17 @@ def __init__(self): audio_decimation = 10 audio_rate = demod_rate / audio_decimation # 32 kHz - - chan_filt_coeffs = filter.optfir.low_pass (1, # gain - usrp_rate, # sampling rate - 80e3, # passband cutoff - 115e3, # stopband cutoff - 0.1, # passband ripple - 60) # stopband attenuation - #print len(chan_filt_coeffs) - chan_filt = filter.fir_filter_ccf (chanfilt_decim, chan_filt_coeffs) - + chan_filt_coeffs = filter.optfir.low_pass(1, # gain + usrp_rate, # sampling rate + 80e3, # passband cutoff + 115e3, # stopband cutoff + 0.1, # passband ripple + 60) # stopband attenuation + # print len(chan_filt_coeffs) + chan_filt = filter.fir_filter_ccf(chanfilt_decim, chan_filt_coeffs) #self.guts = analog.wfm_rcv (demod_rate, audio_decimation) - self.guts = analog.wfm_rcv_pll (demod_rate, audio_decimation) + self.guts = analog.wfm_rcv_pll(demod_rate, audio_decimation) # FIXME rework {add,multiply}_const_* to handle multiple streams self.volume_control_l = blocks.multiply_const_ff(self.vol) @@ -67,24 +67,24 @@ def __init__(self): sink = blocks.wavfile_sink(args.output_file, 2, int(audio_rate), blocks.FORMAT_WAV, blocks.FORMAT_PCM_16) else: - sink = audio.sink (int (audio_rate), - args.audio_output, - False) # ok_to_block + sink = audio.sink(int(audio_rate), + args.audio_output, + False) # ok_to_block # now wire it all together - self.connect (self.src, chan_filt, self.guts) - self.connect ((self.guts, 0), self.volume_control_l, (sink, 0)) - self.connect ((self.guts, 1), self.volume_control_r, (sink, 1)) + self.connect(self.src, chan_filt, self.guts) + self.connect((self.guts, 0), self.volume_control_l, (sink, 0)) + self.connect((self.guts, 1), self.volume_control_r, (sink, 1)) if args.volume is None: g = self.volume_range() - args.volume = float(g[0]+g[1]) / 2 + args.volume = float(g[0] + g[1]) / 2 # set initial values self.set_vol(args.volume) - def set_vol (self, vol): + def set_vol(self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) self.volume_control_l.set_k(10**(self.vol / 10)) diff --git a/gnuradio-runtime/examples/network/audio_sink.py b/gnuradio-runtime/examples/network/audio_sink.py index 68cc2ae95d2..d38b30d34cf 100644 --- a/gnuradio-runtime/examples/network/audio_sink.py +++ b/gnuradio-runtime/examples/network/audio_sink.py @@ -16,9 +16,11 @@ try: from gnuradio import audio except ImportError: - sys.stderr.write("Failed to import gnuradio.audio. Make sure gr-audio component is installed.\n") + sys.stderr.write( + "Failed to import gnuradio.audio. Make sure gr-audio component is installed.\n") sys.exit(1) + class audio_sink(gr.top_block): def __init__(self, host, port, pkt_size, sample_rate, eof): gr.top_block.__init__(self, "audio_sink") @@ -26,18 +28,19 @@ def __init__(self, host, port, pkt_size, sample_rate, eof): dst = audio.sink(sample_rate) self.connect(src, dst) + if __name__ == '__main__': parser = ArgumentParser() parser.add_argument("--host", default="0.0.0.0", - help="local host name (domain name or IP address)") + help="local host name (domain name or IP address)") parser.add_argument("--port", type=int, default=65500, - help="port value to listen to for connection") + help="port value to listen to for connection") parser.add_argument("--packet-size", type=int, default=1472, - help="packet size.") + help="packet size.") parser.add_argument("-r", "--sample-rate", type=int, default=32000, - help="audio signal sample rate [default=%(default)r]") + help="audio signal sample rate [default=%(default)r]") parser.add_argument("--no-eof", action="store_true", default=False, - help="don't send EOF on disconnect") + help="don't send EOF on disconnect") args = parser.parse_args() # Create an instance of a hierarchical block top_block = audio_sink(args.host, args.port, @@ -50,4 +53,3 @@ def __init__(self, host, port, pkt_size, sample_rate, eof): except KeyboardInterrupt: # Ctrl-C exits pass - diff --git a/gnuradio-runtime/examples/network/audio_source.py b/gnuradio-runtime/examples/network/audio_source.py index 70430025f27..6cffc3aedf9 100644 --- a/gnuradio-runtime/examples/network/audio_source.py +++ b/gnuradio-runtime/examples/network/audio_source.py @@ -16,28 +16,32 @@ try: from gnuradio import audio except ImportError: - sys.stderr.write("Failed to import gnuradio.audio. Make sure gr-audio component is installed.\n") + sys.stderr.write( + "Failed to import gnuradio.audio. Make sure gr-audio component is installed.\n") sys.exit(1) + class audio_source(gr.top_block): def __init__(self, host, port, pkt_size, sample_rate, eof): gr.top_block.__init__(self, "audio_source") self.audio = audio.source(sample_rate) - self.sink = blocks.udp_sink(gr.sizeof_float, host, port, pkt_size, eof=eof) + self.sink = blocks.udp_sink( + gr.sizeof_float, host, port, pkt_size, eof=eof) self.connect(self.audio, self.sink) + if __name__ == '__main__': parser = ArgumentParser() parser.add_argument("--host", default="127.0.0.1", - help="Remote host name (domain name or IP address") + help="Remote host name (domain name or IP address") parser.add_argument("--port", type=int, default=65500, - help="port number to connect to") + help="port number to connect to") parser.add_argument("--packet-size", type=int, default=1472, - help="packet size.") - parser.add_argument("-r", "--sample-rate", type=int, default=32000 , - help="audio signal sample rate [default=%(default)r]") + help="packet size.") + parser.add_argument("-r", "--sample-rate", type=int, default=32000, + help="audio signal sample rate [default=%(default)r]") parser.add_argument("--no-eof", action="store_true", default=False, - help="don't send EOF on disconnect") + help="don't send EOF on disconnect") args = parser.parse_args() # Create an instance of a hierarchical block top_block = audio_source(args.host, args.port, @@ -50,4 +54,3 @@ def __init__(self, host, port, pkt_size, sample_rate, eof): except KeyboardInterrupt: # Ctrl-C exits pass - diff --git a/gnuradio-runtime/examples/network/dial_tone_sink.py b/gnuradio-runtime/examples/network/dial_tone_sink.py index 8fff674d235..d0702a5539f 100644 --- a/gnuradio-runtime/examples/network/dial_tone_sink.py +++ b/gnuradio-runtime/examples/network/dial_tone_sink.py @@ -12,6 +12,7 @@ from gnuradio import blocks from argparse import ArgumentParser + class dial_tone_sink(gr.top_block): def __init__(self, host, port, pkt_size, sample_rate, eof): gr.top_block.__init__(self, "dial_tone_sink") @@ -19,18 +20,19 @@ def __init__(self, host, port, pkt_size, sample_rate, eof): sink = audio.sink(sample_rate) self.connect(udp, sink) + if __name__ == '__main__': parser = ArgumentParser() parser.add_argument("--host", default="0.0.0.0", - help="local host name (domain name or IP address)") + help="local host name (domain name or IP address)") parser.add_argument("--port", type=int, default=65500, - help="port value to listen to for connection") + help="port value to listen to for connection") parser.add_argument("--packet-size", type=int, default=1472, - help="packet size.") + help="packet size.") parser.add_argument("-r", "--sample-rate", type=int, default=8000, - help="audio signal sample rate [default=%(default)r]") + help="audio signal sample rate [default=%(default)r]") parser.add_argument("--no-eof", action="store_true", default=False, - help="don't send EOF on disconnect") + help="don't send EOF on disconnect") args = parser.parse_args() # Create an instance of a hierarchical block top_block = dial_tone_sink(args.host, args.port, @@ -43,4 +45,3 @@ def __init__(self, host, port, pkt_size, sample_rate, eof): except KeyboardInterrupt: # Ctrl-C exits pass - diff --git a/gnuradio-runtime/examples/network/dial_tone_source.py b/gnuradio-runtime/examples/network/dial_tone_source.py index 16e5fa34a83..abddf0f96ec 100644 --- a/gnuradio-runtime/examples/network/dial_tone_source.py +++ b/gnuradio-runtime/examples/network/dial_tone_source.py @@ -22,13 +22,16 @@ except ImportError: sys.stderr.write("This example requires gr-blocks.\n") + class dial_tone_source(gr.top_block): def __init__(self, host, port, pkt_size, sample_rate, eof): gr.top_block.__init__(self, "dial_tone_source") amplitude = 0.3 - src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, amplitude) - src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, amplitude) + src0 = analog.sig_source_f( + sample_rate, analog.GR_SIN_WAVE, 350, amplitude) + src1 = analog.sig_source_f( + sample_rate, analog.GR_SIN_WAVE, 440, amplitude) add = blocks.add_ff() # Throttle needed here to account for the other side's audio card sampling rate @@ -38,18 +41,19 @@ def __init__(self, host, port, pkt_size, sample_rate, eof): self.connect(src1, (add, 1)) self.connect(add, thr, sink) + if __name__ == '__main__': parser = ArgumentParser() parser.add_argument("--host", default="127.0.0.1", - help="Remote host name (domain name or IP address") + help="Remote host name (domain name or IP address") parser.add_argument("--port", type=int, default=65500, - help="port number to connect to") + help="port number to connect to") parser.add_argument("--packet-size", type=int, default=1472, - help="packet size.") + help="packet size.") parser.add_argument("-r", "--sample-rate", type=int, default=8000, - help="audio signal sample rate [default=%(default)r]") + help="audio signal sample rate [default=%(default)r]") parser.add_argument("--no-eof", action="store_true", default=False, - help="don't send EOF on disconnect") + help="don't send EOF on disconnect") args = parser.parse_args() # Create an instance of a hierarchical block top_block = dial_tone_source(args.host, args.port, diff --git a/gnuradio-runtime/examples/network/vector_sink.py b/gnuradio-runtime/examples/network/vector_sink.py index 619303d7ecd..06d0519b85b 100644 --- a/gnuradio-runtime/examples/network/vector_sink.py +++ b/gnuradio-runtime/examples/network/vector_sink.py @@ -13,6 +13,7 @@ from gnuradio.eng_arg import eng_float, intx from argparse import ArgumentParser + class vector_sink(gr.top_block): def __init__(self, host, port, pkt_size, eof): gr.top_block.__init__(self, "vector_sink") @@ -21,16 +22,17 @@ def __init__(self, host, port, pkt_size, eof): sink = blocks.file_sink(gr.sizeof_float, "received.dat") self.connect(udp, sink) + if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("-H", "--host", default="0.0.0.0", - help="local host name (domain name or IP address)") + help="local host name (domain name or IP address)") parser.add_argument("-p", "--port", type=int, default=65500, - help="port value to listen to for connection") + help="port value to listen to for connection") parser.add_argument("-s", "--packet-size", type=int, default=1471, - help="packet size.") + help="packet size.") parser.add_argument("--no-eof", action="store_true", default=False, - help="don't send EOF on disconnect") + help="don't send EOF on disconnect") args = parser.parse_args() # Create an instance of a hierarchical block top_block = vector_sink(args.host, args.port, @@ -43,4 +45,3 @@ def __init__(self, host, port, pkt_size, eof): except KeyboardInterrupt: # Ctrl-C exits pass - diff --git a/gnuradio-runtime/examples/network/vector_source.py b/gnuradio-runtime/examples/network/vector_source.py index 0a43b4978b9..7ab6a66df16 100644 --- a/gnuradio-runtime/examples/network/vector_source.py +++ b/gnuradio-runtime/examples/network/vector_source.py @@ -12,24 +12,26 @@ from gnuradio import blocks from argparse import ArgumentParser + class vector_source(gr.top_block): def __init__(self, host, port, pkt_size, eof): gr.top_block.__init__(self, "vector_source") - data = [i*0.01 for i in range(1000)] + data = [i * 0.01 for i in range(1000)] vec = blocks.vector_source_f(data, True) udp = blocks.udp_sink(gr.sizeof_float, host, port, pkt_size, eof=eof) self.connect(vec, udp) + if __name__ == '__main__': parser = ArgumentParser() parser.add_argument("--host", default="127.0.0.1", - help="Remote host name (domain name or IP address") + help="Remote host name (domain name or IP address") parser.add_argument("--port", type=int, default=65500, - help="port number to connect to") + help="port number to connect to") parser.add_argument("--packet-size", type=int, default=1471, - help="packet size.") + help="packet size.") parser.add_argument("--no-eof", action="store_true", default=False, - help="don't send EOF on disconnect") + help="don't send EOF on disconnect") args = parser.parse_args() # Create an instance of a hierarchical block top_block = vector_source(args.host, args.port, args.packet_size, @@ -41,4 +43,3 @@ def __init__(self, host, port, pkt_size, eof): except KeyboardInterrupt: # Ctrl-C exits pass - diff --git a/gnuradio-runtime/include/gnuradio/basic_block.h b/gnuradio-runtime/include/gnuradio/basic_block.h index 3816e8ab98b..ba8c903d169 100644 --- a/gnuradio-runtime/include/gnuradio/basic_block.h +++ b/gnuradio-runtime/include/gnuradio/basic_block.h @@ -399,7 +399,7 @@ class GR_RUNTIME_API basic_block : public msg_accepter, virtual std::vector processor_affinity() = 0; - virtual void set_log_level(std::string level) = 0; + virtual void set_log_level(const std::string& level) = 0; virtual std::string log_level() = 0; }; diff --git a/gnuradio-runtime/include/gnuradio/block.h b/gnuradio-runtime/include/gnuradio/block.h index 882a0466a8b..8b486cc398f 100644 --- a/gnuradio-runtime/include/gnuradio/block.h +++ b/gnuradio-runtime/include/gnuradio/block.h @@ -674,7 +674,7 @@ class GR_RUNTIME_API block : public basic_block * \brief Checks if this block is already exporting perf. counters * to ControlPort. */ - bool is_pc_rpc_set() { return d_pc_rpc_set; } + bool is_pc_rpc_set() const { return d_pc_rpc_set; } /*! * \brief If the block calls this in its constructor, it's @@ -744,7 +744,7 @@ class GR_RUNTIME_API block : public basic_block * \li fatal * \li emerg */ - void set_log_level(std::string level) override; + void set_log_level(const std::string& level) override; /*! * \brief Get the logger's output level diff --git a/gnuradio-runtime/include/gnuradio/hier_block2.h b/gnuradio-runtime/include/gnuradio/hier_block2.h index f79f4ef01f8..ca709fa81ac 100644 --- a/gnuradio-runtime/include/gnuradio/hier_block2.h +++ b/gnuradio-runtime/include/gnuradio/hier_block2.h @@ -289,7 +289,7 @@ class GR_RUNTIME_API hier_block2 : public basic_block * \li fatal * \li emerg */ - void set_log_level(std::string level) override; + void set_log_level(const std::string& level) override; /*! * \brief Get the logger's output level diff --git a/gnuradio-runtime/include/gnuradio/logger.h b/gnuradio-runtime/include/gnuradio/logger.h index e9409c93a3c..68dbf0ad339 100644 --- a/gnuradio-runtime/include/gnuradio/logger.h +++ b/gnuradio-runtime/include/gnuradio/logger.h @@ -1,6 +1,7 @@ /* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. + * Copyright 2021 Marcus Müller * * This file is part of GNU Radio * @@ -13,28 +14,60 @@ /*! * \ingroup logging - * \brief GNU Radio logging wrapper for log4cpp library (C++ port of log4j) + * \brief GNU Radio logging wrapper * */ -#ifdef _MSC_VER -typedef int mode_t; -#else -#include -#endif - // Since this file is included in *all* gr::blocks, please make sure this list of includes // keeps as short as possible; if anything is needed only by the implementation in // buffer.cc, then only include it there #include -#include -#include -#include -#include +#include +#include +#include #include +#ifndef SPDLOG_FMT_EXTERNAL +#define SPDLOG_FMT_EXTERNAL +#endif +#include + +#include + +#include namespace gr { +using log_level = spdlog::level::level_enum; + +class GR_RUNTIME_API logging +{ +public: + logging(logging const&) = delete; // delete copy ctor, this is a singleton class + void operator=(logging const&) = delete; // can't assign to singleton class + static logging& singleton(); //! \brief get the singleton + + //! \brief get the default logging level + inline log_level default_level() const { return _default_level; } + + //! \brief get the debug logging level + inline log_level debug_level() const { return _debug_level; } + spdlog::sink_ptr default_backend() const; + //! \brief adds a logging sink + void add_default_sink(const spdlog::sink_ptr& sink); + //! \brief adds a debugging sink + void add_debug_sink(const spdlog::sink_ptr& sink); + //! \brief add a default-constructed console sink to the default logger + void add_default_console_sink(); + //! \brief add a default-constructed console sink to the debugging logger + void add_debug_console_sink(); + + static constexpr const char* default_pattern = "%n :%l: %v"; + +private: + logging(); + const log_level _default_level, _debug_level; + std::shared_ptr _default_backend, _debug_backend; +}; /*! * \brief GR_LOG macros @@ -52,564 +85,6 @@ namespace gr { * LOG_FATAL * LOG_EMERG */ -typedef log4cpp::Category* logger_ptr; - -} /* namespace gr */ - -/* Macros for Programmatic Configuration */ -#define GR_LOG_DECLARE_LOGPTR(logger) gr::logger_ptr logger - -#define GR_LOG_ASSIGN_LOGPTR(logger, name) logger = gr::logger_get_logger(name) - -#define GR_LOG_ASSIGN_CONFIGURED_LOGPTR(logger, name) \ - logger = gr::logger_get_configured_logger(name) - -#define GR_CONFIG_LOGGER(config) gr::logger_config::load_config(config) - -#define GR_CONFIG_AND_WATCH_LOGGER(config, period) \ - gr::logger_config::load_config(config, period) - -#define GR_LOG_GETLOGGER(logger, name) gr::logger_ptr logger = gr::logger_get_logger(name) - -#define GR_LOG_GET_CONFIGURED_LOGGER(logger, name) \ - gr::logger_ptr logger = gr::logger_get_configured_logger(name) - -#define GR_SET_LEVEL(name, level) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - gr::logger_set_level(logger, level); \ - } - -#define GR_LOG_SET_LEVEL(logger, level) gr::logger_set_level(logger, level) - -#define GR_GET_LEVEL(name, level) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - gr::logger_get_level(logger, level); \ - } - -#define GR_LOG_GET_LEVEL(logger, level) gr::logger_get_level(logger, level) - -#define GR_ADD_CONSOLE_APPENDER(name, target, pattern) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - gr::logger_add_console_appender(logger, target, pattern); \ - } - -#define GR_LOG_ADD_CONSOLE_APPENDER(logger, target, pattern) \ - { \ - gr::logger_add_console_appender(logger, target, pattern); \ - } - -#define GR_SET_CONSOLE_APPENDER(name, target, pattern) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - gr::logger_set_console_appender(logger, target, pattern); \ - } - -#define GR_LOG_SET_CONSOLE_APPENDER(logger, target, pattern) \ - { \ - gr::logger_set_console_appender(logger, target, pattern); \ - } - -#define GR_ADD_FILE_APPENDER(name, filename, append, pattern) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - gr::logger_add_file_appender(logger, filename, append, pattern); \ - } - -#define GR_LOG_ADD_FILE_APPENDER(logger, filename, append, pattern) \ - { \ - gr::logger_add_file_appender(logger, filename, append, pattern); \ - } - -#define GR_SET_FILE_APPENDER(name, filename, append, pattern) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - gr::logger_set_file_appender(logger, filename, append, pattern); \ - } - -#define GR_LOG_SET_FILE_APPENDER(logger, filename, append, pattern) \ - { \ - gr::logger_set_file_appender(logger, filename, append, pattern); \ - } - -#define GR_ADD_ROLLINGFILE_APPENDER( \ - name, filename, filesize, bkup_index, append, mode, pattern) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - gr::logger_add_rollingfile_appender( \ - logger, filename, filesize, bkup_index, append, mode, pattern); \ - } - -#define GR_LOG_ADD_ROLLINGFILE_APPENDER( \ - logger, filename, filesize, bkup_index, append, mode, pattern) \ - { \ - gr::logger_add_rollingfile_appender( \ - logger, filename, filesize, bkup_index, append, mode, pattern); \ - } - -#define GR_GET_LOGGER_NAMES(names) \ - { \ - names = gr::logger_get_logger_names(); \ - } - -#define GR_RESET_CONFIGURATION() gr::logger_config::reset_config(); - -/* Logger name referenced macros */ -#define GR_DEBUG(name, msg) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::DEBUG << (msg) << log4cpp::eol; \ - } - -#define GR_INFO(name, msg) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::INFO << (msg) << log4cpp::eol; \ - } - -#define GR_NOTICE(name, msg) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::NOTICE << (msg); \ - } - -#define GR_WARN(name, msg) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::WARN << (msg) << log4cpp::eol; \ - } - -#define GR_ERROR(name, msg) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::ERROR << (msg) << log4cpp::eol; \ - } - -#define GR_CRIT(name, msg) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::CRIT << (msg) << log4cpp::eol; \ - } - -#define GR_ALERT(name, msg) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::ALERT << (msg) << log4cpp::eol; \ - } - -#define GR_FATAL(name, msg) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::FATAL << (msg) << log4cpp::eol; \ - } - -#define GR_EMERG(name, msg) \ - { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::EMERG << (msg) << log4cpp::eol; \ - } - -#define GR_ERRORIF(name, cond, msg) \ - { \ - if ((cond)) { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::ERROR << (msg) << log4cpp::eol; \ - } \ - } - -#define GR_ASSERT(name, cond, msg) \ - { \ - if (!(cond)) { \ - gr::logger_ptr logger = gr::logger_get_logger(name); \ - *logger << log4cpp::Priority::EMERG << (msg) << log4cpp::eol; \ - } \ - assert(0); \ - } - -/* LoggerPtr Referenced Macros */ -#define GR_LOG_DEBUG(logger, msg) \ - { \ - *logger << log4cpp::Priority::DEBUG << (msg) << log4cpp::eol; \ - } - -#define GR_LOG_INFO(logger, msg) \ - { \ - *logger << log4cpp::Priority::INFO << (msg) << log4cpp::eol; \ - } - -#define GR_LOG_NOTICE(logger, msg) \ - { \ - *logger << log4cpp::Priority::NOTICE << (msg) << log4cpp::eol; \ - } - -#define GR_LOG_WARN(logger, msg) \ - { \ - *logger << log4cpp::Priority::WARN << (msg) << log4cpp::eol; \ - } - -#define GR_LOG_ERROR(logger, msg) \ - { \ - *logger << log4cpp::Priority::ERROR << (msg) << log4cpp::eol; \ - } - -#define GR_LOG_CRIT(logger, msg) \ - { \ - *logger << log4cpp::Priority::CRIT << (msg) << log4cpp::eol; \ - } - -#define GR_LOG_ALERT(logger, msg) \ - { \ - *logger << log4cpp::Priority::ALERT << (msg) << log4cpp::eol; \ - } - -#define GR_LOG_FATAL(logger, msg) \ - { \ - *logger << log4cpp::Priority::FATAL << (msg) << log4cpp::eol; \ - } - -#define GR_LOG_EMERG(logger, msg) \ - { \ - *logger << log4cpp::Priority::EMERG << (msg) << log4cpp::eol; \ - } - -#define GR_LOG_ERRORIF(logger, cond, msg) \ - { \ - if ((cond)) { \ - *logger << log4cpp::Priority::ERROR << (msg) << log4cpp::eol; \ - } \ - } - -#define GR_LOG_ASSERT(logger, cond, msg) \ - { \ - if (!(cond)) { \ - *logger << log4cpp::Priority::EMERG << (msg) << log4cpp::eol; \ - assert(0); \ - } \ - } - -namespace gr { - -/*! - * \brief Class to control configuration of logger. - * This is a singleton that can launch a thread to watch a config file for changes - * \ingroup logging - */ -class GR_RUNTIME_API logger_config -{ -private: - /*! \brief filename of logger config file */ - std::string filename; - /*! \brief Period (seconds) over which watcher thread checks config file for changes - */ - unsigned int watch_period; - /*! \brief watch thread for config file changes */ - std::unique_ptr watch_thread; - - /*! \brief Watcher thread method - * /param filename Name of configuration file - * /param watch_period Seconds between checks for changes in config file - */ - static void watch_file(std::string filename, unsigned int watch_period); - - static bool logger_configured; - - logger_config() /*: - rpc_get_filename("logger_config", "filename", &logger_config::get_filename4rpc, - pmt::mp(""), pmt::mp(""), pmt::mp(""), - "", "filename", RPC_PRIVLVL_MIN, - DISPTIME | DISPOPTSTRIP), - rpc_get_watchperiod("logger_config", "watch_period", - &logger_config::get_watchperiod4rpc, pmt::mp(0), pmt::mp(32768), pmt::mp(0), - "", "watch_period", RPC_PRIVLVL_MIN, - DISPTIME | DISPOPTSTRIP), - rpc_get_config("logger_config", "config", &logger_config::get_config4rpc, - pmt::mp(""), pmt::mp(""), pmt::mp(""), - "", "filename", RPC_PRIVLVL_MIN, - DISPTIME | DISPOPTSTRIP), - rpc_set_config("logger_config","config", &logger_config::set_config4rpc, - pmt::mp(""), pmt::mp(""), pmt::mp(""), - "", "filename", RPC_PRIVLVL_MIN, - DISPTIME | DISPOPTSTRIP) - */ - { - } //!< Constructor - - /* - rpcbasic_register_get rpc_get_filename; - rpcbasic_register_get rpc_get_watchperiod; - rpcbasic_register_get rpc_get_config; - rpcbasic_register_set rpc_set_config; - */ - - logger_config(logger_config const&); //!< Copy constructor - void operator=(logger_config const&); //!< Assignment Operator - - std::string get_filename4rpc() { return filename; } - int get_watchperiod4rpc() { return watch_period; }; - - std::string get_config4rpc() { return filename; } - - void set_config4rpc(std::string set) { printf("Set string was:%s\n", set.c_str()); } - - /*! \brief Instance getter for singleton. Only used by class. */ - static logger_config& get_instance(void); - -public: - /*! \brief destructor stops watch thread before exits */ - ~logger_config() { stop_watch(); } - /*! \brief Getter for config filename */ - static std::string get_filename(); - /*! \brief Getter for watch period */ - static unsigned int get_watch_period(); - /*! \brief Method to load configuration - * /param filename Name of configuration file - * /param watch_period Seconds between checks for changes in config file - */ - static void load_config(std::string filename, unsigned int watch_period = 0); - /*! \brief Method to stop watcher thread */ - static void stop_watch(); - /*! \brief method to reset logger configuration */ - static void reset_config(void); -}; - -/*! - * \brief Retrieve a pointer to a logger by name - * - * Retrieves a logger pointer - * \p name. - * - * \param name Name of the logger for which a pointer is requested - */ -GR_RUNTIME_API logger_ptr logger_get_logger(std::string name); - -/*! - * \brief Retrieve a pointer to a fully configured logger by name - * - * Retrieves a logger pointer. - * This method differs from logger_get_logger in that it configures the logger to - * reflect the current gnuradio configuration, including log level and log output file. - * - * \p name. - * - * \param name Name of the logger for which a pointer is requested - */ -GR_RUNTIME_API logger_ptr logger_get_configured_logger(const std::string& name); - -/*! - * \brief Load logger's configuration file. - * - * Initialize the GNU Radio logger by loading the configuration file - * \p config_filename. - * - * \param config_filename The configuration file. Set to "" for the - * basic logger that outputs to the console. - */ -GR_RUNTIME_API bool logger_load_config(const std::string& config_filename = ""); - -/*! - * \brief Reset logger's configuration file. - * - * Remove all appenders from loggers - */ -GR_RUNTIME_API void logger_reset_config(void); - -/*! - * \brief Set the logger's output level. - * - * Sets the level of the logger. This takes a string that is - * translated to the standard levels and can be (case insensitive): - * - * \li off , notset - * \li debug - * \li info - * \li notice - * \li warn - * \li error - * \li crit - * \li alert - * \li fatal - * \li emerg - * - * \param logger the logger to set the level of. - * \param level string to set the level to. - */ -GR_RUNTIME_API void logger_set_level(logger_ptr logger, const std::string& level); - -/*! - * \brief Set the logger's output level. - * - * Sets the level of the logger. This takes the actual Log4cpp::Priority - * data type, which can be: - * - * \li log4cpp::Priority::NOTSET - * \li log4cpp::Priority::DEBUG - * \li log4cpp::Priority::INFO - * \li log4cpp::Priority::NOTICE - * \li log4cpp::Priority::WARN - * \li log4cpp::Priority::ERROR - * \li log4cpp::Priority::CRIT - * \li log4cpp::Priority::ALERT - * \li log4cpp::Priority::FATAL - * \li log4cpp::Priority::EMERG - * - * \param logger the logger to set the level of. - * \param level new logger level of type Log4cpp::Priority - */ -GR_RUNTIME_API void logger_set_level(logger_ptr logger, log4cpp::Priority::Value level); - -/*! - * \brief Get the logger's output level. - * - * Gets the level of the logger. This returns a string that - * corresponds to the standard levels and can be (case insensitive): - * - * \li notset - * \li debug - * \li info - * \li notice - * \li warn - * \li error - * \li crit - * \li alert - * \li fatal - * \li emerg - * - * \param logger the logger to get the level of. - * \param level string to get the level into. - */ -GR_RUNTIME_API void logger_get_level(logger_ptr logger, std::string& level); - -/*! - * \brief Get the logger's output level. - * - * Gets the level of the logger. This returns the actual Log4cpp::Level - * data type, which can be: - * - * \li log4cpp::Priority::NOTSET - * \li log4cpp::Priority::DEBUG - * \li log4cpp::Priority::INFO - * \li log4cpp::Priority::NOTICE - * \li log4cpp::Priority::WARN - * \li log4cpp::Priority::ERROR - * \li log4cpp::Priority::CRIT - * \li log4cpp::Priority::ALERT - * \li log4cpp::Priority::FATAL - * \li log4cpp::Priority::EMERG - * - * \param logger the logger to get the level of. - * \param level of the logger. - */ -GR_RUNTIME_API void logger_get_level(logger_ptr logger, log4cpp::Priority::Value& level); - -/*! - * \brief Add console appender to a given logger - * - * Add console appender to a given logger - * - * \param logger Logger to which appender will be added - * \param appender Name of appender to add to logger - */ -GR_RUNTIME_API void logger_add_appender(logger_ptr logger, std::string appender); - -/*! - * \brief Sets a console appender to a given logger. Deletes any - * existing appenders and adds a new one. To add an additional - * appender, use logger_add_appender. - * - * \param logger Logger to which appender will be added - * \param appender Name of appender to add to logger - */ -GR_RUNTIME_API void logger_set_appender(logger_ptr logger, std::string appender); - -/*! - * \brief Add console appender to a given logger - * - * Add console appender to a given logger - * - * \param logger Logger to which appender will be added - * \param target Std target to write 'cout' or 'cerr' (default is cout) - * \param pattern Formatting pattern for log messages - */ -GR_RUNTIME_API void -logger_add_console_appender(logger_ptr logger, std::string target, std::string pattern); - -/*! - * \brief Sets a new console appender to a given logger after - * removing all others. Use logger_add_console_appender to add - * another. - * - * \param logger Logger to which appender will be added - * \param target Std target to write 'cout' or 'cerr' (default is cout) - * \param pattern Formatting pattern for log messages - */ -GR_RUNTIME_API void -logger_set_console_appender(logger_ptr logger, std::string target, std::string pattern); - -/*! - * \brief Add file appender to a given logger - * - * Add file appender to a given logger - * - * \param logger Logger to which appender will be added - * \param filename File to which log will be written - * \param append Overwrite or append to log file - * \param pattern Formatting pattern for log messages - */ -GR_RUNTIME_API void logger_add_file_appender(logger_ptr logger, - std::string filename, - bool append, - std::string pattern); - -/*! - * \brief Set a file appender to a given logger. To add another file - * appender, use logger_add_file_appender. - * - * \param logger Logger to which appender will be added - * \param filename File to which log will be written - * \param append Overwrite or append to log file - * \param pattern Formatting pattern for log messages - */ -GR_RUNTIME_API void logger_set_file_appender(logger_ptr logger, - std::string filename, - bool append, - std::string pattern); - -/*! - * \brief Add rolling file appender to a given logger - * - * Add rolling file appender to a given logger - * - * \param logger Logger to which appender will be added - * \param filename File to which log will be written - * \param filesize Sizez of files to write - * \param bkup_index Number of files to write - * \param append Overwrite or append to log file - * \param mode Permissions to set on log file - * \param pattern Formatting pattern for log messages - */ -GR_RUNTIME_API void logger_add_rollingfile_appender(logger_ptr logger, - std::string filename, - size_t filesize, - int bkup_index, - bool append, - mode_t mode, - std::string pattern); - -/*! - * \brief Add rolling file appender to a given logger - * - * Add rolling file appender to a given logger - * - * \return vector of string names of loggers - */ -GR_RUNTIME_API std::vector logger_get_logger_names(void); - -} /* namespace gr */ - -// If Logger disable do nothing -namespace gr { /********************* Start Classes and Methods for Python ******************/ /*! @@ -622,126 +97,108 @@ namespace gr { class GR_RUNTIME_API logger { private: - /*! \brief logger pointer to logger associated wiith this wrapper class */ - GR_LOG_DECLARE_LOGPTR(d_logger); + /*! \brief pointer to logger associated with this wrapper class */ + std::string _name; + using underlying_logger_ptr = std::shared_ptr; public: /*! * \brief constructor Provide name of logger to associate with this class * \param logger_name Name of logger associated with class */ - logger(std::string logger_name) { GR_LOG_ASSIGN_LOGPTR(d_logger, logger_name); }; + logger(const std::string& logger_name); /*! \brief Destructor */ - ~logger() { ; } + // FIXME implement or = default + ~logger() = default; + + underlying_logger_ptr d_logger; // Wrappers for logging macros /*! \brief inline function, wrapper to set the logger level */ - void set_level(std::string level) { GR_LOG_SET_LEVEL(d_logger, level); } + void set_level(const std::string& level); + void set_level(const log_level level); /*! \brief inline function, wrapper to get the logger level */ - void get_level(std::string& level) { GR_LOG_GET_LEVEL(d_logger, level); } - - /*! \brief inline function, wrapper for LOG4CPP_DEBUG for DEBUG message */ - void debug(std::string msg) { GR_LOG_DEBUG(d_logger, msg); }; - - /*! \brief inline function, wrapper for LOG4CPP_INFO for INFO message */ - void info(std::string msg) { GR_LOG_INFO(d_logger, msg); } - - /*! \brief inline function, wrapper for NOTICE message */ - void notice(std::string msg) { GR_LOG_NOTICE(d_logger, msg); } + void get_level(std::string& level) const; + const std::string get_string_level() const; + log_level get_level() const; - /*! \brief inline function, wrapper for LOG4CPP_WARN for WARN message */ - void warn(std::string msg) { GR_LOG_WARN(d_logger, msg); } + const std::string& name() const; + void set_name(const std::string& name); - /*! \brief inline function, wrapper for LOG4CPP_ERROR for ERROR message */ - void error(std::string msg) { GR_LOG_ERROR(d_logger, msg); } - - /*! \brief inline function, wrapper for NOTICE message */ - void crit(std::string msg) { GR_LOG_CRIT(d_logger, msg); } - - /*! \brief inline function, wrapper for ALERT message */ - void alert(std::string msg) { GR_LOG_ALERT(d_logger, msg); } + /*! \brief inline function, wrapper for TRACE message */ + template + inline void trace(const spdlog::string_view_t& msg, const Args&... args) + { + d_logger->trace(msg, args...); + } - /*! \brief inline function, wrapper for FATAL message */ - void fatal(std::string msg) { GR_LOG_FATAL(d_logger, msg); } + /*! \brief inline function, wrapper for DEBUG message */ + template + inline void debug(const spdlog::string_view_t& msg, const Args&... args) + { + d_logger->debug(msg, args...); + } - /*! \brief inline function, wrapper for EMERG message */ - void emerg(std::string msg) { GR_LOG_EMERG(d_logger, msg); } + /*! \brief inline function, wrapper for INFO message */ + template + inline void info(const spdlog::string_view_t& msg, const Args&... args) + { + d_logger->info(msg, args...); + } - /*! \brief inline function, wrapper for LOG4CPP_ASSERT for conditional ERROR message - */ - void errorIF(bool cond, std::string msg) { GR_LOG_ERRORIF(d_logger, cond, msg); } + /*! \brief inline function, wrapper for INFO message, DEPRECATED */ + template + inline void notice(const spdlog::string_view_t& msg, const Args&... args) + { + d_logger->info(msg, args...); + } - /*! \brief inline function, wrapper for LOG4CPP_ASSERT for conditional ERROR message - */ - void log_assert(bool cond, std::string msg) { GR_LOG_ASSERT(d_logger, cond, msg); } + /*! \brief inline function, wrapper for WARN message */ + template + inline void warn(const spdlog::string_view_t& msg, const Args&... args) + { + d_logger->warn(msg, args...); + } - /*! \brief inline function, Method to add console appender to logger */ - void add_console_appender(std::string target, std::string pattern) + /*! \brief inline function, wrapper for ERROR message */ + template + inline void error(const spdlog::string_view_t& msg, const Args&... args) { - GR_LOG_ADD_CONSOLE_APPENDER(d_logger, target, pattern); + d_logger->error(msg, args...); } - /*! \brief inline function, Method to set a console appender to logger */ - void set_console_appender(std::string target, std::string pattern) + /*! \brief inline function, wrapper for CRITICAL message */ + template + inline void crit(const spdlog::string_view_t& msg, const Args&... args) { - GR_LOG_SET_CONSOLE_APPENDER(d_logger, target, pattern); + d_logger->critical(msg, args...); } - /*! \brief inline function, Method to add file appender to logger */ - void add_file_appender(std::string filename, bool append, std::string pattern) + /*! \brief inline function, wrapper for CRITICAL message, DEPRECATED */ + template + inline void alert(const spdlog::string_view_t& msg, const Args&... args) { - GR_LOG_ADD_FILE_APPENDER(d_logger, filename, append, pattern); + d_logger->critical(msg, args...); } - /*! \brief inline function, Method to set a file appender to logger */ - void set_file_appender(std::string filename, bool append, std::string pattern) + /*! \brief inline function, wrapper for CRITICAL message, DEPRECATED */ + template + inline void fatal(const spdlog::string_view_t& msg, const Args&... args) { - GR_LOG_SET_FILE_APPENDER(d_logger, filename, append, pattern); + d_logger->critical(msg, args...); } - /*! \brief inline function, Method to add rolling file appender to logger */ - void add_rollingfile_appender(std::string filename, - size_t filesize, - int bkup_index, - bool append, - mode_t mode, - std::string pattern) + /*! \brief inline function, wrapper for CRITICAL message, DEPRECATED */ + template + inline void emerg(const spdlog::string_view_t& msg, const Args&... args) { - GR_LOG_ADD_ROLLINGFILE_APPENDER( - d_logger, filename, filesize, bkup_index, append, mode, pattern); + d_logger->critical(msg, args...); } }; +using logger_ptr = std::shared_ptr; -} /* namespace gr */ - -/**************** Start Configuration Class and Methods for Python ************/ -/*! - * \brief Function to call configuration macro from python. - * Note: Configuration is only updated if filename or watch_period has changed. - * \param config_filename Name of configuration file - * \param watch_period Seconds to wait between checking for changes in conf file. - * Watch_period defaults to 0 in which case the file is not watched for changes - */ -GR_RUNTIME_API void gr_logger_config(const std::string config_filename, - unsigned int watch_period = 0); - -/*! - * \brief Function to return logger names to python - * \return Vector of name strings - * - */ -GR_RUNTIME_API std::vector gr_logger_get_logger_names(void); - -/*! - * \brief Function to reset logger configuration from python - * - */ -GR_RUNTIME_API void gr_logger_reset_config(void); - - -namespace gr { /*! * Function to use the GR prefs files to get and setup the two * default loggers defined there. The loggers are unique to the @@ -751,11 +208,73 @@ namespace gr { * automatically in gr::block. */ GR_RUNTIME_API bool -configure_default_loggers(gr::logger_ptr& l, gr::logger_ptr& d, const std::string name); - -GR_RUNTIME_API bool update_logger_alias(const std::string& name, - const std::string& alias); +configure_default_loggers(gr::logger_ptr& l, gr::logger_ptr& d, const std::string& name); } /* namespace gr */ +// global logging shorthands + +#define GR_LOG_TRACE(log, msg) \ + { \ + log->d_logger->trace(msg); \ + } + +#define GR_LOG_DEBUG(log, msg) \ + { \ + log->d_logger->debug(msg); \ + } + +#define GR_LOG_INFO(log, msg) \ + { \ + log->d_logger->info(msg); \ + } + +#define GR_LOG_NOTICE(log, msg) \ + { \ + log->d_logger->info(msg); \ + } + + +#define GR_LOG_WARN(log, msg) \ + { \ + log->d_logger->warn(msg); \ + } + +#define GR_LOG_ERROR(log, msg) \ + { \ + log->d_logger->error(msg); \ + } + +#define GR_LOG_CRIT(log, msg) \ + { \ + log->d_logger->critical(msg); \ + } + +#define GR_LOG_ALERT(log, msg) \ + { \ + log->d_logger->critical(msg); \ + } + +#define GR_LOG_FATAL(log, msg) \ + { \ + log->d_logger->critical(msg); \ + } + +#define GR_LOG_EMERG(log, msg) \ + { \ + log->d_logger->critical(msg); \ + } + +// Helper class to allow passing of boost::format to fmt +template <> +struct fmt::formatter : formatter { + // parse is inherited from formatter. + template + auto format(const boost::format& bfmt, FormatContext& ctx) + -> decltype(formatter::format(bfmt.str(), ctx)) + { + return formatter::format(bfmt.str(), ctx); + } +}; + #endif /* INCLUDED_GR_LOGGER_H */ diff --git a/gnuradio-runtime/include/gnuradio/thread/thread_group.h b/gnuradio-runtime/include/gnuradio/thread/thread_group.h index 425858636f5..9895068373b 100644 --- a/gnuradio-runtime/include/gnuradio/thread/thread_group.h +++ b/gnuradio-runtime/include/gnuradio/thread/thread_group.h @@ -17,6 +17,7 @@ #include #include +#include #include #include #include diff --git a/gnuradio-runtime/include/gnuradio/thrift_application_base.h b/gnuradio-runtime/include/gnuradio/thrift_application_base.h index c8bb8ed3f50..996c769c8c8 100644 --- a/gnuradio-runtime/include/gnuradio/thrift_application_base.h +++ b/gnuradio-runtime/include/gnuradio/thrift_application_base.h @@ -214,9 +214,8 @@ void thrift_application_base::start_application() } if (!app_started) { - GR_WARN("thrift_application_base", - "thrift_application_base::start_application(), " - "timeout waiting to port number might have failed?"); + gr::logger log("thrift_application_base"); + log.warn("start_application(): timeout waiting"); } p_impl->d_application_initialized = true; diff --git a/gnuradio-runtime/include/pmt/pmt.h b/gnuradio-runtime/include/pmt/pmt.h index 7afdb922885..b55cc57d9f7 100644 --- a/gnuradio-runtime/include/pmt/pmt.h +++ b/gnuradio-runtime/include/pmt/pmt.h @@ -12,8 +12,8 @@ #define INCLUDED_PMT_H #include +#include #include -#include #include #include #include @@ -664,9 +664,10 @@ PMT_API pmt_t dict_values(pmt_t dict); /* * ------------------------------------------------------------------------ - * Any (wraps std::any -- can be used to wrap pretty much anything) + * Any (wraps boost::any -- can be used to wrap pretty much anything) * * Cannot be serialized or used across process boundaries. + * See http://www.boost.org/doc/html/any.html * ------------------------------------------------------------------------ */ @@ -674,13 +675,13 @@ PMT_API pmt_t dict_values(pmt_t dict); PMT_API bool is_any(pmt_t obj); //! make an any -PMT_API pmt_t make_any(const std::any& any); +PMT_API pmt_t make_any(const boost::any& any); -//! Return underlying std::any -PMT_API std::any any_ref(pmt_t obj); +//! Return underlying boost::any +PMT_API boost::any any_ref(pmt_t obj); //! Store \p any in \p obj -PMT_API void any_set(pmt_t obj, const std::any& any); +PMT_API void any_set(pmt_t obj, const boost::any& any); /* diff --git a/gnuradio-runtime/lib/CMakeLists.txt b/gnuradio-runtime/lib/CMakeLists.txt index f91900f5ccb..2d8a81ab10b 100644 --- a/gnuradio-runtime/lib/CMakeLists.txt +++ b/gnuradio-runtime/lib/CMakeLists.txt @@ -86,7 +86,6 @@ add_library(gnuradio-runtime sys_paths.cc tagged_stream_block.cc terminate_handler.cc - test.cc top_block.cc top_block_impl.cc tpb_detail.cc @@ -131,7 +130,7 @@ target_link_libraries(gnuradio-runtime PUBLIC Boost::system Boost::regex Boost::thread - Log4Cpp::log4cpp + spdlog::spdlog MPLib::mplib # INTERFACE/PRIVATE split so users of the library can choose how to link to Python # (importantly, extension modules can avoid linking against Python and resolve diff --git a/gnuradio-runtime/lib/basic_block.cc b/gnuradio-runtime/lib/basic_block.cc index 988b3995725..08ae0791727 100644 --- a/gnuradio-runtime/lib/basic_block.cc +++ b/gnuradio-runtime/lib/basic_block.cc @@ -8,6 +8,7 @@ * */ +#include #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -36,9 +37,12 @@ basic_block::basic_block(const std::string& name, d_symbol_name(global_block_registry.register_symbolic_name(this)), d_color(WHITE), d_rpc_set(false), + d_logger(std::make_shared(name)), + d_debug_logger(std::make_shared(name + " (debug)")), d_message_subscribers(pmt::make_dict()) { - configure_default_loggers(d_logger, d_debug_logger, d_symbol_name); + d_logger->set_level(logging::singleton().default_level()); + d_debug_logger->set_level(logging::singleton().debug_level()); s_ncurrently_allocated++; } @@ -62,7 +66,8 @@ void basic_block::set_block_alias(std::string name) // set the block's alias d_symbol_alias = name; - update_logger_alias(symbol_name(), d_symbol_alias); + d_logger->set_name(name); + d_debug_logger->set_name(name + " (debug)"); } // ** Message passing interface ** diff --git a/gnuradio-runtime/lib/block.cc b/gnuradio-runtime/lib/block.cc index f2970cd6675..8965a9eaeaf 100644 --- a/gnuradio-runtime/lib/block.cc +++ b/gnuradio-runtime/lib/block.cc @@ -762,12 +762,12 @@ void block::system_handler(pmt::pmt_t msg) } } -void block::set_log_level(std::string level) { logger_set_level(d_logger, level); } +void block::set_log_level(const std::string& level) { d_logger->set_level(level); } std::string block::log_level() { std::string level; - logger_get_level(d_logger, level); + d_logger->get_level(level); return level; } diff --git a/gnuradio-runtime/lib/block_registry.cc b/gnuradio-runtime/lib/block_registry.cc index 9ba79c924a3..a32c0e68016 100644 --- a/gnuradio-runtime/lib/block_registry.cc +++ b/gnuradio-runtime/lib/block_registry.cc @@ -13,7 +13,6 @@ #include #include #include -#include gr::block_registry global_block_registry; @@ -97,7 +96,7 @@ basic_block_sptr block_registry::block_lookup(pmt::pmt_t symbol) if (pmt::eq(ref, pmt::PMT_NIL)) { throw std::runtime_error("block lookup failed! block not found!"); } - basic_block* blk = std::any_cast(pmt::any_ref(ref)); + basic_block* blk = boost::any_cast(pmt::any_ref(ref)); return blk->shared_from_this(); } diff --git a/gnuradio-runtime/lib/hier_block2.cc b/gnuradio-runtime/lib/hier_block2.cc index 70fc446225c..3cd18af3bb4 100644 --- a/gnuradio-runtime/lib/hier_block2.cc +++ b/gnuradio-runtime/lib/hier_block2.cc @@ -140,7 +140,10 @@ std::vector hier_block2::processor_affinity() return d_detail->processor_affinity(); } -void hier_block2::set_log_level(std::string level) { d_detail->set_log_level(level); } +void hier_block2::set_log_level(const std::string& level) +{ + d_detail->set_log_level(level); +} std::string hier_block2::log_level() { return d_detail->log_level(); } diff --git a/gnuradio-runtime/lib/hier_block2_detail.cc b/gnuradio-runtime/lib/hier_block2_detail.cc index 282ec793327..8776328a27b 100644 --- a/gnuradio-runtime/lib/hier_block2_detail.cc +++ b/gnuradio-runtime/lib/hier_block2_detail.cc @@ -912,7 +912,7 @@ std::vector hier_block2_detail::processor_affinity() return tmp[0]->processor_affinity(); } -void hier_block2_detail::set_log_level(std::string level) +void hier_block2_detail::set_log_level(const std::string& level) { basic_block_vector_t tmp = d_fg->calc_used_blocks(); for (basic_block_viter_t p = tmp.begin(); p != tmp.end(); p++) { diff --git a/gnuradio-runtime/lib/hier_block2_detail.h b/gnuradio-runtime/lib/hier_block2_detail.h index 15a45e00919..527c832d687 100644 --- a/gnuradio-runtime/lib/hier_block2_detail.h +++ b/gnuradio-runtime/lib/hier_block2_detail.h @@ -49,7 +49,7 @@ class GR_RUNTIME_API hier_block2_detail : boost::noncopyable void unset_processor_affinity(); std::vector processor_affinity(); - void set_log_level(std::string level); + void set_log_level(const std::string& level); std::string log_level(); // Track output buffer min/max settings diff --git a/gnuradio-runtime/lib/logger.cc b/gnuradio-runtime/lib/logger.cc index 4721571119c..64219d6a8ec 100644 --- a/gnuradio-runtime/lib/logger.cc +++ b/gnuradio-runtime/lib/logger.cc @@ -1,6 +1,7 @@ /* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. + * Copyright 2021 Marcus Müller * * This file is part of GNU Radio * @@ -8,410 +9,143 @@ * */ -/******************************************************************************* - * Author: Mark Plett - * Description: - * The gr_log module wraps the log4cpp library for logging in gnuradio. - *******************************************************************************/ - +#include #ifdef HAVE_CONFIG_H #include "config.h" #endif #include - #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -#include -#include -#include #include -#include namespace gr { - -bool logger_config::logger_configured(false); - -/************************ BEGIN LOG4CPP HELPERS ***********************/ -/* Logger config class. This is a singleton that controls how - * log4cpp is configured If watch_period>0 a thread is started to - * watch the config file for changes. - */ - -// Getters of logger_config -logger_config& logger_config::get_instance(void) -{ - static logger_config instance; - return instance; -} - -std::string logger_config::get_filename() -{ - logger_config& in = get_instance(); - return in.filename; -} - -unsigned int logger_config::get_watch_period() -{ - logger_config& in = get_instance(); - return in.watch_period; -} - -// Method to watch config file for changes -void logger_config::watch_file(std::string filename, unsigned int watch_period) -{ - auto last_write = std::filesystem::last_write_time(filename); - while (true) { - try { - auto current_time = std::filesystem::last_write_time(filename); - if (current_time > last_write) { - // std::cout<<"GNURadio Reloading logger - // configuration:"<get_string("LOG", "log_level", "off"))), + _debug_level(spdlog::level::from_str( + prefs::singleton()->get_string("LOG", "debug_level", "off"))), + _default_backend(std::make_shared()), + _debug_backend(std::make_shared()) +{ + _default_backend->set_level(_default_level); + _debug_backend->set_level(_debug_level); + + + auto debug_console_sink = std::make_shared(); + _debug_backend->add_sink(debug_console_sink); + + const auto pref = prefs::singleton(); + const auto default_file = pref->get_string("LOG", "log_file", ""); + + if (default_file == "stderr") { + auto console_sink = std::make_shared(); + _default_backend->add_sink(console_sink); + } else if ((!default_file.empty()) && default_file != "stdout") { + auto file_sink = + std::make_shared(default_file, true); + _default_backend->add_sink(file_sink); } -} - -// Method to load the configuration. It only loads if the filename -// or watch has changed -void logger_config::load_config(std::string filename, unsigned int watch_period) -{ - logger_config& instance = get_instance(); - // Only reconfigure if filename or watch has changed - if (!logger_configured) { - instance.filename = filename; - instance.watch_period = watch_period; - // Stop any file watching thread - if (instance.watch_thread) - stop_watch(); - // Load configuration - // std::cout<<"GNURadio Loading logger - // configuration:"< 0) { - instance.watch_thread = std::make_unique( - watch_file, instance.filename, instance.watch_period); - } - } -} - -// Method to stop the watcher thread -void logger_config::stop_watch() -{ - logger_config& instance = get_instance(); - if (instance.watch_thread) { - instance.watch_thread->interrupt(); - instance.watch_thread->join(); - instance.watch_thread.reset(); - } -} - -// Method to reset logger configuration -void logger_config::reset_config(void) -{ - logger_config& instance = get_instance(); - stop_watch(); - std::vector* loggers = log4cpp::Category::getCurrentCategories(); - std::vector::iterator logger = loggers->begin(); - // We can't destroy categories but we can neuter them by removing all appenders. - for (; logger != loggers->end(); logger++) { - (*logger)->removeAllAppenders(); - } - instance.filename = std::string(""); - instance.watch_period = 0; - logger_configured = false; -} - -/***************** Functions to call log4cpp methods *************************/ - -logger_ptr logger_get_logger(std::string name) -{ - if (log4cpp::Category::exists(name)) { - logger_ptr logger = &log4cpp::Category::getInstance(name); - return logger; - } else { - logger_ptr logger = &log4cpp::Category::getInstance(name); - logger->setPriority(log4cpp::Priority::NOTSET); - return logger; - } -} - -logger_ptr logger_get_configured_logger(const std::string& name) -{ - if (log4cpp::Category::exists(name)) - return &log4cpp::Category::getInstance(name); - - prefs* p = prefs::singleton(); - std::string config_file = p->get_string("LOG", "log_config", ""); - std::string log_level = p->get_string("LOG", "log_level", "off"); - std::string log_file = p->get_string("LOG", "log_file", ""); - GR_LOG_GETLOGGER(LOG, "gr_log." + name); - GR_LOG_SET_LEVEL(LOG, log_level); - - if (!log_file.empty()) { - if (log_file == "stdout") { - GR_LOG_SET_CONSOLE_APPENDER(LOG, "stdout", "gr::log :%p: %c{1} - %m%n"); - } else if (log_file == "stderr") { - GR_LOG_SET_CONSOLE_APPENDER(LOG, "stderr", "gr::log :%p: %c{1} - %m%n"); - } else { - GR_LOG_SET_FILE_APPENDER(LOG, log_file, true, "%r :%p: %c{1} - %m%n"); - } + if (default_file == "stdout") { + auto console_sink = std::make_shared(); + _default_backend->add_sink(console_sink); } - return LOG; } -bool logger_load_config(const std::string& config_filename) -{ - if (!config_filename.empty()) { - try { - log4cpp::PropertyConfigurator::configure(config_filename); - return true; - } catch (log4cpp::ConfigureFailure& e) { - std::cerr << "Logger config failed :" << e.what() << std::endl; - } - } - return false; -} -void logger_set_level(logger_ptr logger, const std::string& level) +logging& logging::singleton() { - std::string nocase = level; - std::transform(level.begin(), level.end(), nocase.begin(), ::tolower); - - if (nocase == "off" || nocase == "notset") - logger_set_level(logger, log4cpp::Priority::NOTSET); - else if (nocase == "all" || nocase == "debug") - logger_set_level(logger, log4cpp::Priority::DEBUG); - else if (nocase == "info") - logger_set_level(logger, log4cpp::Priority::INFO); - else if (nocase == "notice") - logger_set_level(logger, log4cpp::Priority::NOTICE); - else if (nocase == "warn") - logger_set_level(logger, log4cpp::Priority::WARN); - else if (nocase == "error") - logger_set_level(logger, log4cpp::Priority::ERROR); - else if (nocase == "crit") - logger_set_level(logger, log4cpp::Priority::CRIT); - else if (nocase == "alert") - logger_set_level(logger, log4cpp::Priority::ALERT); - else if (nocase == "fatal") - logger_set_level(logger, log4cpp::Priority::FATAL); - else if (nocase == "emerg") - logger_set_level(logger, log4cpp::Priority::EMERG); - else - throw std::runtime_error("logger_set_level: Bad level type."); + static logging the_only_one; + return the_only_one; } -void logger_set_level(logger_ptr logger, log4cpp::Priority::Value level) +spdlog::sink_ptr logging::default_backend() const { return _default_backend; } +void logging::add_default_sink(const spdlog::sink_ptr& sink) { - logger->setPriority(level); -} - -void logger_get_level(logger_ptr logger, std::string& level) + _default_backend->add_sink(sink); +}; +void logging::add_debug_sink(const spdlog::sink_ptr& sink) { - log4cpp::Priority::Value levelPtr = logger->getPriority(); - if (levelPtr == log4cpp::Priority::NOTSET) - level = "notset"; - if (levelPtr == log4cpp::Priority::DEBUG) - level = "debug"; - if (levelPtr == log4cpp::Priority::INFO) - level = "info"; - if (levelPtr == log4cpp::Priority::NOTICE) - level = "notice"; - if (levelPtr == log4cpp::Priority::WARN) - level = "warn"; - if (levelPtr == log4cpp::Priority::ERROR) - level = "error"; - if (levelPtr == log4cpp::Priority::CRIT) - level = "crit"; - if (levelPtr == log4cpp::Priority::ALERT) - level = "alert"; - if (levelPtr == log4cpp::Priority::FATAL) - level = "fatal"; - if (levelPtr == log4cpp::Priority::EMERG) - level = "emerg"; -} + _debug_backend->add_sink(sink); +}; -void logger_get_level(logger_ptr logger, log4cpp::Priority::Value level) +void logging::add_default_console_sink() { - level = logger->getPriority(); + add_default_sink(std::make_shared()); } -void logger_add_console_appender(logger_ptr logger, - std::string target, - std::string pattern) +void logging::add_debug_console_sink() { - log4cpp::PatternLayout* layout = new log4cpp::PatternLayout(); - log4cpp::Appender* app; - if (target == "stdout") - app = new log4cpp::OstreamAppender("ConsoleAppender::", &std::cout); - else - app = new log4cpp::OstreamAppender("ConsoleAppender::", &std::cerr); - - layout->setConversionPattern(pattern); - app->setLayout(layout); - logger->setAppender(app); + add_debug_sink(std::make_shared()); } -void logger_set_console_appender(logger_ptr logger, - std::string target, - std::string pattern) +logger::logger(const std::string& logger_name) + : _name(logger_name), + d_logger( + std::make_shared(_name, logging::singleton().default_backend())) { - logger->removeAllAppenders(); - logger_add_console_appender(logger, target, pattern); + d_logger->set_level(logging::singleton().default_level()); + // gr::log :%p: %c{1} - %m%n + // :level: block alias - message + d_logger->set_pattern(logging::default_pattern); } -void logger_add_file_appender(logger_ptr logger, - std::string filename, - bool append, - std::string pattern) -{ - log4cpp::PatternLayout* layout = new log4cpp::PatternLayout(); - log4cpp::Appender* app = - new log4cpp::FileAppender("FileAppender::" + filename, filename, append); - layout->setConversionPattern(pattern); - app->setLayout(layout); - logger->setAppender(app); -} +log_level logger::get_level() const { return d_logger->level(); } -void logger_set_file_appender(logger_ptr logger, - std::string filename, - bool append, - std::string pattern) +const std::string logger::get_string_level() const { - logger->removeAllAppenders(); - logger_add_file_appender(logger, filename, append, pattern); + const auto view = spdlog::level::to_string_view(d_logger->level()); + return std::string(view.begin(), view.end()); } -void logger_add_rollingfile_appender(logger_ptr logger, - std::string filename, - size_t filesize, - int bkup_index, - bool append, - mode_t mode, - std::string pattern) -{ - log4cpp::PatternLayout* layout = new log4cpp::PatternLayout(); - log4cpp::Appender* app = new log4cpp::RollingFileAppender( - "RollFileAppender::" + filename, filename, filesize, bkup_index, append, mode); - layout->setConversionPattern(pattern); - app->setLayout(layout); - logger->setAppender(app); -} +void logger::get_level(std::string& level) const { level = get_string_level(); } +void logger::set_level(const log_level level) { d_logger->set_level(level); } -std::vector logger_get_logger_names(void) +void logger::set_level(const std::string& level) { - std::vector names; - std::vector* loggers = log4cpp::Category::getCurrentCategories(); - std::vector::iterator logger = loggers->begin(); - - for (; logger != loggers->end(); logger++) { - names.push_back((*logger)->getName()); + auto parsed_level = spdlog::level::from_str(level); + if (parsed_level == spdlog::level::off) { + if (level == "notice") { + parsed_level = spdlog::level::info; + } else if (level == "warn") { + // older versions of spdlog don't convert this themselves + parsed_level = spdlog::level::warn; + } else if (level == "crit" || level == "alert" || level == "fatal" || + level == "emerg") { + parsed_level = spdlog::level::critical; + } } - return names; + d_logger->set_level(parsed_level); } -} /* namespace gr */ - -/****** Start Methods to provide Python the capabilities of the macros ********/ -void gr_logger_config(const std::string config_filename, unsigned int watch_period) +const std::string& logger::name() const { return _name; } +void logger::set_name(const std::string& name) { - GR_CONFIG_AND_WATCH_LOGGER(config_filename, watch_period); + _name = name; + d_logger->set_pattern(logging::default_pattern); } -std::vector gr_logger_get_logger_names(void) -{ - std::vector names; - GR_GET_LOGGER_NAMES(names); - return names; -} - -void gr_logger_reset_config(void) { GR_RESET_CONFIGURATION(); } - -// Remaining capability provided by gr::logger class in gnuradio/logger.h - -namespace gr { - bool configure_default_loggers(gr::logger_ptr& l, gr::logger_ptr& d, - const std::string name) + const std::string& name) { - prefs* p = prefs::singleton(); - std::string config_file = p->get_string("LOG", "log_config", ""); - std::string log_level = p->get_string("LOG", "log_level", "off"); - std::string log_file = p->get_string("LOG", "log_file", ""); - std::string debug_level = p->get_string("LOG", "debug_level", "off"); - std::string debug_file = p->get_string("LOG", "debug_file", ""); - - GR_CONFIG_LOGGER(config_file); - - GR_LOG_GETLOGGER(LOG, "gr_log." + name); - GR_LOG_SET_LEVEL(LOG, log_level); - - if (!log_file.empty()) { - if (log_file == "stdout") { - GR_LOG_SET_CONSOLE_APPENDER(LOG, "stdout", "gr::log :%p: %c{1} - %m%n"); - } else if (log_file == "stderr") { - GR_LOG_SET_CONSOLE_APPENDER(LOG, "stderr", "gr::log :%p: %c{1} - %m%n"); - } else { - GR_LOG_SET_FILE_APPENDER(LOG, log_file, true, "%r :%p: %c{1} - %m%n"); - } + if (l == nullptr) { + l = std::make_shared(name); } - l = LOG; - - GR_LOG_GETLOGGER(DLOG, "gr_log_debug." + name); - GR_LOG_SET_LEVEL(DLOG, debug_level); - if (!debug_file.empty()) { - if (debug_file == "stdout") { - GR_LOG_SET_CONSOLE_APPENDER(DLOG, "stdout", "gr::debug :%p: %c{1} - %m%n"); - } else if (debug_file == "stderr") { - GR_LOG_SET_CONSOLE_APPENDER(DLOG, "stderr", "gr::debug :%p: %c{1} - %m%n"); - } else { - GR_LOG_SET_FILE_APPENDER(DLOG, debug_file, true, "%r :%p: %c{1} - %m%n"); - } - } - d = DLOG; - return true; -} - -bool update_logger_alias(const std::string& name, const std::string& alias) -{ - prefs* p = prefs::singleton(); - std::string log_file = p->get_string("LOG", "log_file", ""); - std::string debug_file = p->get_string("LOG", "debug_file", ""); - - GR_LOG_GETLOGGER(LOG, "gr_log." + name); - if (!log_file.empty()) { - if (log_file == "stdout") { - boost::format str("gr::log :%%p: %1% - %%m%%n"); - GR_LOG_SET_CONSOLE_APPENDER(LOG, "stdout", boost::str(str % alias)); - } else if (log_file == "stderr") { - boost::format str("gr::log :%%p: %1% - %%m%%n"); - GR_LOG_SET_CONSOLE_APPENDER(LOG, "stderr", boost::str(str % alias)); - } else { - boost::format str("%%r :%%p: %1% - %%m%%n"); - GR_LOG_SET_FILE_APPENDER(LOG, log_file, true, boost::str(str % alias)); - } + if (d == nullptr) { + d = std::make_shared(name); } + l->set_level(logging::singleton().default_level()); + d->set_level(logging::singleton().debug_level()); + l->set_name(name); + d->set_name(name); return true; } diff --git a/gnuradio-runtime/lib/math/gen_sine_table.py b/gnuradio-runtime/lib/math/gen_sine_table.py index ae31b6b81a2..b45cb52e7e2 100644 --- a/gnuradio-runtime/lib/math/gen_sine_table.py +++ b/gnuradio-runtime/lib/math/gen_sine_table.py @@ -11,33 +11,36 @@ import math import sys -def gen_approx_table (f, nentries, min_x, max_x): + +def gen_approx_table(f, nentries, min_x, max_x): """return a list of nentries containing tuples of the form: (m, c). min_x and max_x specify the domain of the table. """ r = [] - incx = float (max_x - min_x) / nentries - for i in range (nentries): + incx = float(max_x - min_x) / nentries + for i in range(nentries): a = (i * incx) + min_x b = ((i + 1) * incx) + min_x - m = (f(b)-f(a)) / (b-a) + m = (f(b) - f(a)) / (b - a) c = f(a) - r.append ((m, c)) + r.append((m, c)) return r -def scaled_sine (x): - return math.sin (x * math.pi / 2**31) -def gen_sine_table (): +def scaled_sine(x): + return math.sin(x * math.pi / 2**31) + + +def gen_sine_table(): nbits = 10 nentries = 2**nbits # min_x = -2**31 # max_x = 2**31-1 min_x = 0 - max_x = 2**32-1 - t = gen_approx_table (scaled_sine, nentries, min_x, max_x) + max_x = 2**32 - 1 + t = gen_approx_table(scaled_sine, nentries, min_x, max_x) # sys.stdout.write ('static const int WORDBITS = 32;\n') # sys.stdout.write ('static const int NBITS = %d;\n' % (nbits,)) @@ -45,9 +48,10 @@ def gen_sine_table (): # sys.stdout.write ('static const double sine_table[%d][2] = {\n'% (nentries,)) for e in t: - sys.stdout.write (' { %22.15e, %22.15e },\n' % (e[0], e[1])) + sys.stdout.write(' { %22.15e, %22.15e },\n' % (e[0], e[1])) # sys.stdout.write ('};\n') + if __name__ == '__main__': - gen_sine_table () + gen_sine_table() diff --git a/gnuradio-runtime/lib/pmt/CMakeLists.txt b/gnuradio-runtime/lib/pmt/CMakeLists.txt index a45869d218d..76d7ddeca5b 100644 --- a/gnuradio-runtime/lib/pmt/CMakeLists.txt +++ b/gnuradio-runtime/lib/pmt/CMakeLists.txt @@ -16,7 +16,7 @@ add_library(gnuradio-pmt target_link_libraries(gnuradio-pmt Boost::boost Boost::thread - Log4Cpp::log4cpp + spdlog::spdlog Volk::volk ) diff --git a/gnuradio-runtime/lib/pmt/pmt.cc b/gnuradio-runtime/lib/pmt/pmt.cc index 043b9eb6a67..d4ada683f97 100644 --- a/gnuradio-runtime/lib/pmt/pmt.cc +++ b/gnuradio-runtime/lib/pmt/pmt.cc @@ -16,7 +16,6 @@ #include #include #include -#include #include #include #include @@ -742,20 +741,20 @@ pmt_t dict_values(pmt_t dict) // Any //////////////////////////////////////////////////////////////////////////// -pmt_any::pmt_any(const std::any& any) : d_any(any) {} +pmt_any::pmt_any(const boost::any& any) : d_any(any) {} bool is_any(pmt_t obj) { return obj->is_any(); } -pmt_t make_any(const std::any& any) { return pmt_t(new pmt_any(any)); } +pmt_t make_any(const boost::any& any) { return pmt_t(new pmt_any(any)); } -std::any any_ref(pmt_t obj) +boost::any any_ref(pmt_t obj) { if (!obj->is_any()) throw wrong_type("pmt_any_ref", obj); return _any(obj)->ref(); } -void any_set(pmt_t obj, const std::any& any) +void any_set(pmt_t obj, const boost::any& any) { if (!obj->is_any()) throw wrong_type("pmt_any_set", obj); @@ -771,8 +770,8 @@ bool is_msg_accepter(const pmt_t& obj) if (!is_any(obj)) return false; - std::any r = any_ref(obj); - return std::any_cast(&r) != 0; + boost::any r = any_ref(obj); + return boost::any_cast(&r) != 0; } //! make a msg_accepter @@ -782,8 +781,8 @@ pmt_t make_msg_accepter(gr::messages::msg_accepter_sptr ma) { return make_any(ma gr::messages::msg_accepter_sptr msg_accepter_ref(const pmt_t& obj) { try { - return std::any_cast(any_ref(obj)); - } catch (std::bad_any_cast& e) { + return boost::any_cast(any_ref(obj)); + } catch (boost::bad_any_cast& e) { throw wrong_type("pmt_msg_accepter_ref", obj); } } diff --git a/gnuradio-runtime/lib/pmt/pmt_int.h b/gnuradio-runtime/lib/pmt/pmt_int.h index 1c4b149a49e..7aadefe4d73 100644 --- a/gnuradio-runtime/lib/pmt/pmt_int.h +++ b/gnuradio-runtime/lib/pmt/pmt_int.h @@ -11,7 +11,7 @@ #define INCLUDED_PMT_INT_H #include -#include +#include /* * EVERYTHING IN THIS FILE IS PRIVATE TO THE IMPLEMENTATION! @@ -170,15 +170,15 @@ class pmt_tuple : public pmt_base class pmt_any : public pmt_base { - std::any d_any; + boost::any d_any; public: - pmt_any(const std::any& any); + pmt_any(const boost::any& any); //~pmt_any(); bool is_any() const override { return true; } - const std::any& ref() const { return d_any; } - void set(const std::any& any) { d_any = any; } + const boost::any& ref() const { return d_any; } + void set(const boost::any& any) { d_any = any; } }; diff --git a/gnuradio-runtime/lib/pmt/qa_pmt_prims.cc b/gnuradio-runtime/lib/pmt/qa_pmt_prims.cc index 7219f6f0999..f74dd2f7f9f 100644 --- a/gnuradio-runtime/lib/pmt/qa_pmt_prims.cc +++ b/gnuradio-runtime/lib/pmt/qa_pmt_prims.cc @@ -12,7 +12,6 @@ #include //reason: suppress warnings #include #include -#include #include #include @@ -456,9 +455,9 @@ std::ostream& operator<<(std::ostream& os, const foo obj) BOOST_AUTO_TEST_CASE(test_any) { - std::any a0; - std::any a1; - std::any a2; + boost::any a0; + boost::any a1; + boost::any a2; a0 = std::string("Hello!"); a1 = 42; @@ -469,11 +468,11 @@ BOOST_AUTO_TEST_CASE(test_any) pmt::pmt_t p2 = pmt::make_any(a2); BOOST_CHECK_EQUAL(std::string("Hello!"), - std::any_cast(pmt::any_ref(p0))); + boost::any_cast(pmt::any_ref(p0))); - BOOST_CHECK_EQUAL(42, std::any_cast(pmt::any_ref(p1))); + BOOST_CHECK_EQUAL(42, boost::any_cast(pmt::any_ref(p1))); - BOOST_CHECK_EQUAL(foo(3.250, 21), std::any_cast(pmt::any_ref(p2))); + BOOST_CHECK_EQUAL(foo(3.250, 21), boost::any_cast(pmt::any_ref(p2))); } // ------------------------------------------------------------------------ @@ -492,7 +491,7 @@ BOOST_AUTO_TEST_CASE(test_msg_accepter) { pmt::pmt_t sym = pmt::mp("my-symbol"); - std::any a0; + boost::any a0; a0 = std::string("Hello!"); pmt::pmt_t p0 = pmt::make_any(a0); diff --git a/gnuradio-runtime/lib/qa_logger.cc b/gnuradio-runtime/lib/qa_logger.cc index 597e21e77ac..99a412dc7cd 100644 --- a/gnuradio-runtime/lib/qa_logger.cc +++ b/gnuradio-runtime/lib/qa_logger.cc @@ -19,21 +19,18 @@ #include #include +#include BOOST_AUTO_TEST_CASE(t1) { -#ifdef ENABLE_GR_LOG // This doesn't really test anything, more just // making sure nothing's gone horribly wrong. - - GR_LOG_GETLOGGER(LOG, "main"); - GR_ADD_CONSOLE_APPENDER("main", "cout", "%d{%H:%M:%S} : %m%n"); - GR_LOG_NOTICE(LOG, "test from c++ NOTICE"); - GR_LOG_DEBUG(LOG, "test from c++ DEBUG"); - GR_LOG_INFO(LOG, "test from c++ INFO"); - GR_LOG_WARN(LOG, "test from c++ WARN"); - GR_LOG_ERROR(LOG, "test from c++ ERROR"); - GR_LOG_FATAL(LOG, "test from c++ FATAL"); + auto log = std::make_shared("main"); + GR_LOG_NOTICE(log, "test from c++ NOTICE"); + GR_LOG_DEBUG(log, "test from c++ DEBUG"); + GR_LOG_INFO(log, "test from c++ INFO"); + GR_LOG_WARN(log, "test from c++ WARN"); + GR_LOG_ERROR(log, "test from c++ ERROR"); + GR_LOG_FATAL(log, "test from c++ FATAL"); BOOST_CHECK(true); -#endif } diff --git a/gnuradio-runtime/lib/test.cc b/gnuradio-runtime/lib/test.cc deleted file mode 100644 index 297d1066ff2..00000000000 --- a/gnuradio-runtime/lib/test.cc +++ /dev/null @@ -1,186 +0,0 @@ -/* -*- c++ -*- */ -/* - * Copyright 2006,2008,2010,2013 Free Software Foundation, Inc. - * - * This file is part of GNU Radio - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "test.h" -#include -#include -#include - -namespace gr { - -test_sptr make_test(const std::string& name, - int min_inputs, - int max_inputs, - unsigned int sizeof_input_item, - int min_outputs, - int max_outputs, - unsigned int sizeof_output_item, - unsigned int history, - unsigned int output_multiple, - double relative_rate, - bool fixed_rate, - consume_type_t cons_type, - produce_type_t prod_type) -{ - return gnuradio::make_block_sptr(name, - min_inputs, - max_inputs, - sizeof_input_item, - min_outputs, - max_outputs, - sizeof_output_item, - history, - output_multiple, - relative_rate, - fixed_rate, - cons_type, - prod_type); -} - -test::test(const std::string& name, - int min_inputs, - int max_inputs, - unsigned int sizeof_input_item, - int min_outputs, - int max_outputs, - unsigned int sizeof_output_item, - unsigned int history, - unsigned int output_multiple, - double relative_rate, - bool fixed_rate, - consume_type_t cons_type, - produce_type_t prod_type) - : block(name, - io_signature::make(min_inputs, max_inputs, sizeof_input_item), - io_signature::make(min_outputs, max_outputs, sizeof_output_item)), - d_sizeof_input_item(sizeof_input_item), - d_sizeof_output_item(sizeof_output_item), - d_check_topology(true), - d_consume_type(cons_type), - d_min_consume(0), - d_max_consume(0), - d_produce_type(prod_type), - d_min_produce(0), - d_max_produce(0) -{ - set_history(history); - set_output_multiple(output_multiple); - set_relative_rate(relative_rate); - set_fixed_rate(fixed_rate); -} - -int test::general_work(int noutput_items, - gr_vector_int& ninput_items, - gr_vector_const_void_star& input_items, - gr_vector_void_star& output_items) -{ - // touch all inputs and outputs to detect segfaults - unsigned ninputs = input_items.size(); - unsigned noutputs = output_items.size(); - for (unsigned i = 0; i < ninputs; i++) { - char* in = (char*)input_items[i]; - if (ninput_items[i] < (int)(noutput_items + history())) { - std::ostringstream msg; - msg << "ninput_items[" << i << "] < noutput_items+history()" - << "ninput_items[" << i << "] = " << ninput_items[i] - << "noutput_items+history() = " << (noutput_items + history()) - << "noutput_items = " << noutput_items << "history() = " << history(); - GR_LOG_ERROR(d_logger, msg.str()); - throw std::runtime_error("test"); - } else { - for (int j = 0; j < ninput_items[i]; j++) { - // Touch every available input_item - // We use a class variable to avoid the compiler to optimize this away - for (unsigned int k = 0; k < d_sizeof_input_item; k++) - d_temp = in[j * d_sizeof_input_item + k]; - } - switch (d_consume_type) { - case CONSUME_NOUTPUT_ITEMS: - consume(i, noutput_items); - break; - case CONSUME_NOUTPUT_ITEMS_LIMIT_MAX: - consume(i, std::min(noutput_items, d_max_consume)); - break; - case CONSUME_NOUTPUT_ITEMS_LIMIT_MIN: - consume( - i, std::min(std::max(noutput_items, d_min_consume), ninput_items[i])); - break; - case CONSUME_ALL_AVAILABLE: - consume(i, ninput_items[i]); - break; - case CONSUME_ALL_AVAILABLE_LIMIT_MAX: - consume(i, std::min(ninput_items[i], d_max_consume)); - break; - /* //This could result in segfault, uncomment if you want to test - this case CONSUME_ALL_AVAILABLE_LIMIT_MIN: - consume(i,std::max(ninput_items[i],d_max_consume)); - break;*/ - case CONSUME_ZERO: - consume(i, 0); - break; - case CONSUME_ONE: - consume(i, 1); - break; - case CONSUME_MINUS_ONE: - consume(i, -1); - break; - default: - consume(i, noutput_items); - } - } - } - for (unsigned i = 0; i < noutputs; i++) { - char* out = (char*)output_items[i]; - { - for (int j = 0; j < noutput_items; j++) { - // Touch every available output_item - for (unsigned int k = 0; k < d_sizeof_output_item; k++) - out[j * d_sizeof_input_item + k] = 0; - } - } - } - // Now copy input to output until max ninputs or max noutputs is reached - int common_nports = std::min(ninputs, noutputs); - if (d_sizeof_output_item == d_sizeof_input_item) - for (int i = 0; i < common_nports; i++) { - memcpy(output_items[i], input_items[i], noutput_items * d_sizeof_input_item); - } - int noutput_items_produced = 0; - switch (d_produce_type) { - case PRODUCE_NOUTPUT_ITEMS: - noutput_items_produced = noutput_items; - break; - case PRODUCE_NOUTPUT_ITEMS_LIMIT_MAX: - noutput_items_produced = std::min(noutput_items, d_max_produce); - break; - /* //This could result in segfault, uncomment if you want to test this - case PRODUCE_NOUTPUT_ITEMS_LIMIT_MIN: - noutput_items_produced=std::max(noutput_items,d_min_produce); - break;*/ - case PRODUCE_ZERO: - noutput_items_produced = 0; - break; - case PRODUCE_ONE: - noutput_items_produced = 1; - break; - case PRODUCE_MINUS_ONE: - noutput_items_produced = -1; - break; - default: - noutput_items_produced = noutput_items; - } - return noutput_items_produced; -} - -} /* namespace gr */ diff --git a/gnuradio-runtime/lib/test.h b/gnuradio-runtime/lib/test.h deleted file mode 100644 index 7c9842ad4a6..00000000000 --- a/gnuradio-runtime/lib/test.h +++ /dev/null @@ -1,214 +0,0 @@ -/* -*- c++ -*- */ -/* - * Copyright 2006,2013 Free Software Foundation, Inc. - * - * This file is part of GNU Radio - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#ifndef INCLUDED_GR_TEST_H -#define INCLUDED_GR_TEST_H - -#include "test_types.h" -#include -#include -#include - -namespace gr { - -class test; -typedef std::shared_ptr test_sptr; - -// public constructor -GR_RUNTIME_API test_sptr make_test(const std::string& name = std::string("test"), - int min_inputs = 1, - int max_inputs = 1, - unsigned int sizeof_input_item = 1, - int min_outputs = 1, - int max_outputs = 1, - unsigned int sizeof_output_item = 1, - unsigned int history = 1, - unsigned int output_multiple = 1, - double relative_rate = 1.0, - bool fixed_rate = true, - consume_type_t cons_type = CONSUME_NOUTPUT_ITEMS, - produce_type_t prod_type = PRODUCE_NOUTPUT_ITEMS); - -/*! - * \brief Test class for testing runtime system (setting up buffers and such.) - * \ingroup misc - * - * This block does not do any useful actual data processing. It - * just exposes setting all standard block parameters using the - * constructor or public methods. - * - * This block can be useful when testing the runtime system. - * You can force this block to have a large history, decimation - * factor and/or large output_multiple. - * The runtime system should detect this and create large enough buffers - * all through the signal chain. - */ -class GR_RUNTIME_API test : public block -{ -public: - ~test() override {} - - int general_work(int noutput_items, - gr_vector_int& ninput_items, - gr_vector_const_void_star& input_items, - gr_vector_void_star& output_items) override; - - // ---------------------------------------------------------------- - // override these to define your behavior - // ---------------------------------------------------------------- - - /*! - * \brief Estimate input requirements given output request - * - * \param noutput_items number of output items to produce - * \param ninput_items_required number of input items required on each input stream - * - * Given a request to product \p noutput_items, estimate the - * number of data items required on each input stream. The - * estimate doesn't have to be exact, but should be close. - */ - void forecast(int noutput_items, gr_vector_int& ninput_items_required) override - { - unsigned ninputs = ninput_items_required.size(); - for (unsigned i = 0; i < ninputs; i++) - ninput_items_required[i] = - (int)((double)noutput_items / relative_rate()) + (int)history(); - } - - /*! - * \brief Force check topology to return true or false. - * - * \param check_topology value to return when check_topology is - * called (true or false) default check_topology returns true - */ - void set_check_topology(bool check_topology) { d_check_topology = check_topology; } - - /*! - * \brief Confirm that ninputs and noutputs is an acceptable combination. - * - * \param ninputs number of input streams connected - * \param noutputs number of output streams connected - * - * \returns true if this is a valid configuration for this block. - * - * This function is called by the runtime system whenever the - * topology changes. Most classes do not need to override this. - * This check is in addition to the constraints specified by the - * input and output gr::io_signatures. - */ - bool check_topology(int ninputs, int noutputs) override { return d_check_topology; } - - // ---------------------------------------------------------------- - /* - * The following two methods provide special case info to the - * scheduler in the event that a block has a fixed input to output - * ratio. gr::sync_block, gr::sync_decimator and - * gr::sync_interpolator override these. If you're fixed rate, - * subclass one of those. - */ - /*! - * \brief Given ninput samples, return number of output samples - * that will be produced. N.B. this is only defined if fixed_rate - * returns true. Generally speaking, you don't need to override - * this. - */ - int fixed_rate_ninput_to_noutput(int ninput) override - { - return (int)((double)ninput / relative_rate()); - } - - /*! - * \brief Given noutput samples, return number of input samples - * required to produce noutput. N.B. this is only defined if - * fixed_rate returns true. - */ - int fixed_rate_noutput_to_ninput(int noutput) override - { - return (int)((double)noutput * relative_rate()); - } - - /*! - * \brief Set if fixed rate should return true. - * N.B. This is normally a private method but we make it available here as public. - */ - void set_fixed_rate_public(bool fixed_rate) { set_fixed_rate(fixed_rate); } - - /*! - * \brief Set the consume pattern. - * - * \param cons_type which consume pattern to use - */ - void set_consume_type(consume_type_t cons_type) { d_consume_type = cons_type; } - - /*! - * \brief Set the consume limit. - * - * \param limit min or maximum items to consume (depending on - * consume_type) - */ - void set_consume_limit(unsigned int limit) - { - d_min_consume = limit; - d_max_consume = limit; - } - - /*! - * \brief Set the produce pattern. - * - * \param prod_type which produce pattern to use - */ - void set_produce_type(produce_type_t prod_type) { d_produce_type = prod_type; } - - /*! - * \brief Set the produce limit. - * - * \param limit min or maximum items to produce (depending on - * produce_type) - */ - void set_produce_limit(unsigned int limit) - { - d_min_produce = limit; - d_max_produce = limit; - } - - // ---------------------------------------------------------------------------- - -protected: - unsigned int d_sizeof_input_item; - unsigned int d_sizeof_output_item; - bool d_check_topology; - char d_temp; - consume_type_t d_consume_type; - int d_min_consume; - int d_max_consume; - produce_type_t d_produce_type; - int d_min_produce; - int d_max_produce; - test(const std::string& name, - int min_inputs, - int max_inputs, - unsigned int sizeof_input_item, - int min_outputs, - int max_outputs, - unsigned int sizeof_output_item, - unsigned int history, - unsigned int output_multiple, - double relative_rate, - bool fixed_rate, - consume_type_t cons_type, - produce_type_t prod_type); - - template - friend std::shared_ptr gnuradio::make_block_sptr(Args&&... args); -}; - -} /* namespace gr */ - -#endif /* INCLUDED_TEST_H */ diff --git a/gnuradio-runtime/lib/test_types.h b/gnuradio-runtime/lib/test_types.h deleted file mode 100644 index 7b25284d246..00000000000 --- a/gnuradio-runtime/lib/test_types.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -*- c++ -*- */ -/* - * Copyright 2006,2013 Free Software Foundation, Inc. - * - * This file is part of GNU Radio - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#ifndef INCLUDED_GR_TEST_TYPES_H -#define INCLUDED_GR_TEST_TYPES_H - -namespace gr { - -typedef enum { - CONSUME_NOUTPUT_ITEMS = 0, - CONSUME_NOUTPUT_ITEMS_LIMIT_MAX = 1, - CONSUME_NOUTPUT_ITEMS_LIMIT_MIN = 2, - CONSUME_ALL_AVAILABLE = 3, - CONSUME_ALL_AVAILABLE_LIMIT_MAX = 4, - /*CONSUME_ALL_AVAILABLE_LIMIT_MIN=5,*/ - CONSUME_ZERO = 6, - CONSUME_ONE = 7, - CONSUME_MINUS_ONE = 8 -} consume_type_t; - -typedef enum { - PRODUCE_NOUTPUT_ITEMS = 0, - PRODUCE_NOUTPUT_ITEMS_LIMIT_MAX = 1, - /*PRODUCE_NOUTPUT_ITEMS_LIMIT_MIN=2,*/ - PRODUCE_ZERO = 6, - PRODUCE_ONE = 7, - PRODUCE_MINUS_ONE = 8 -} produce_type_t; - -} /* namespace gr */ - -#endif /* INCLUDED_GR_TEST_TYPES_H */ diff --git a/gnuradio-runtime/lib/tpb_thread_body.cc b/gnuradio-runtime/lib/tpb_thread_body.cc index d6e76379524..abf722dec21 100644 --- a/gnuradio-runtime/lib/tpb_thread_body.cc +++ b/gnuradio-runtime/lib/tpb_thread_body.cc @@ -49,23 +49,9 @@ tpb_thread_body::tpb_thread_body(block_sptr block, prefs* p = prefs::singleton(); size_t max_nmsgs = static_cast(p->get_long("DEFAULT", "max_messages", 100)); -// Setup the logger for the scheduler -#undef LOG - std::string config_file = p->get_string("LOG", "log_config", ""); - std::string log_level = p->get_string("LOG", "log_level", "off"); - std::string log_file = p->get_string("LOG", "log_file", ""); - GR_LOG_GETLOGGER(LOG, "gr_log.tpb_thread_body"); - GR_LOG_SET_LEVEL(LOG, log_level); - GR_CONFIG_LOGGER(config_file); - if (!log_file.empty()) { - if (log_file == "stdout") { - GR_LOG_SET_CONSOLE_APPENDER(LOG, "stdout", "gr::log :%p: %c{1} - %m%n"); - } else if (log_file == "stderr") { - GR_LOG_SET_CONSOLE_APPENDER(LOG, "stderr", "gr::log :%p: %c{1} - %m%n"); - } else { - GR_LOG_SET_FILE_APPENDER(LOG, log_file, true, "%r :%p: %c{1} - %m%n"); - } - } + // Set up logging + auto logger = gr::logger("tpb_thread_body"); + // Set thread affinity if it was set before fg was started. if (!block->processor_affinity().empty()) { @@ -99,8 +85,8 @@ tpb_thread_body::tpb_thread_body(block_sptr block, // If we don't have a handler but are building up messages, // prune the queue from the front to keep memory in check. if (block->nmsgs(i.first) > max_nmsgs) { - GR_LOG_WARN( - LOG, "asynchronous message buffer overflowing, dropping message"); + logger.warn( + "asynchronous message buffer overflowing, dropping message"); msg = block->delete_head_nowait(i.first); } } diff --git a/gnuradio-runtime/python/gnuradio/__init__.py b/gnuradio-runtime/python/gnuradio/__init__.py index 8b9e89c177e..85b47c9fc6b 100644 --- a/gnuradio-runtime/python/gnuradio/__init__.py +++ b/gnuradio-runtime/python/gnuradio/__init__.py @@ -17,18 +17,20 @@ # https://docs.python.org/3/whatsnew/3.8.html#bpo-36085-whatsnew if os.name == 'nt' and hasattr(os, 'add_dll_directory'): root_dir = __file__ - for i in range(5): #limit search depth + for i in range(5): # limit search depth root_dir = os.path.dirname(root_dir) bin_dir = os.path.join(root_dir, 'bin') if os.path.exists(bin_dir): - try: os.add_dll_directory(bin_dir) + try: + os.add_dll_directory(bin_dir) except Exception as ex: - print('add_dll_directory(%s): %s'%(bin_dir, ex)) + print('add_dll_directory(%s): %s' % (bin_dir, ex)) break # Check if the gnuradio package is installed or whether we're attempting to import it from # the build directory. -path_ending = os.path.join('gnuradio-runtime', 'python', 'gnuradio', '__init__.py') +path_ending = os.path.join( + 'gnuradio-runtime', 'python', 'gnuradio', '__init__.py') path = os.path.abspath(__file__) if path.endswith('.pyc'): path = path[:-1] diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/GNURadioControlPortClient.py b/gnuradio-runtime/python/gnuradio/ctrlport/GNURadioControlPortClient.py index e1fbf973376..a57759b3d1c 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/GNURadioControlPortClient.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/GNURadioControlPortClient.py @@ -32,6 +32,7 @@ """ + class GNURadioControlPortClient(object): """ Constructor for creating a ControlPort connection to a specified host / port @@ -62,6 +63,7 @@ class GNURadioControlPortClient(object): such as QtGui.QApplication.exec_ """ + def __init__(self, host=None, port=None, rpcmethod='thrift', callback=None, blockingcallback=None): self.client = None diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/GrDataPlotter.py b/gnuradio-runtime/python/gnuradio/ctrlport/GrDataPlotter.py index f363393c368..ae3857d2f9b 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/GrDataPlotter.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/GrDataPlotter.py @@ -13,7 +13,9 @@ from gnuradio import blocks from gnuradio import filter, fft from gnuradio.ctrlport.GNURadio import ControlPort -import sys, time, struct +import sys +import time +import struct try: from gnuradio import qtgui @@ -23,6 +25,7 @@ print("Error: Program requires PyQt5 and gr-qtgui.") sys.exit(1) + class GrDataPlotParent(gr.top_block, Qt.QWidget): # Setup signals plotupdated = QtCore.pyqtSignal(Qt.QWidget) @@ -34,7 +37,7 @@ def __init__(self, name, rate, pmin=None, pmax=None): self._name = name self._npts = 500 self._rate = rate - self.knobnames = [name,] + self.knobnames = [name, ] self.layout = Qt.QVBoxLayout() self.setLayout(self.layout) @@ -52,10 +55,10 @@ def _setup(self, nconnections): self.disconnect(self.thr, (self.snk, 0)) self.disconnect(self.src[0], self.thr) for n in range(1, self._ncons): - self.disconnect(self.src[n], (self.snk,n)) + self.disconnect(self.src[n], (self.snk, n)) self._ncons = nconnections - self._data_len = self._ncons*[0,] + self._data_len = self._ncons * [0, ] self.thr = blocks.throttle(self._datasize, self._rate) self.snk = self.get_qtsink() @@ -67,13 +70,13 @@ def _setup(self, nconnections): for n in range(self._ncons): self.set_line_label(n, self.knobnames[n]) - self._last_data.append(int(self._npts)*[0,]) + self._last_data.append(int(self._npts) * [0, ]) self.src.append(self.get_vecsource()) if(n == 0): self.connect(self.src[n], self.thr) else: - self.connect(self.src[n], (self.snk,n)) + self.connect(self.src[n], (self.snk, n)) self.py_window = sip.wrapinstance(self.snk.qwidget(), Qt.QWidget) @@ -122,7 +125,7 @@ def data_to_complex(self, data): if(self._iscomplex): data_r = data[0::2] data_i = data[1::2] - data = [complex(r,i) for r,i in zip(data_r, data_i)] + data = [complex(r, i) for r, i in zip(data_r, data_i)] return data def update(self, data): @@ -136,10 +139,11 @@ def update(self, data): if(self._data_len[n] < npts): self._last_data[n] = self._last_data[n][0:npts] else: - self._last_data[n] = self._last_data[n][self._data_len[n]-npts:self._data_len[n]] + self._last_data[n] = self._last_data[n][self._data_len[n] - + npts:self._data_len[n]] self._data_len[n] = npts else: - self._last_data[n] += (npts - self._npts)*[0,] + self._last_data[n] += (npts - self._npts) * [0, ] self._npts = npts self.snk.reset() @@ -152,12 +156,13 @@ def update(self, data): self.src[n].set_data(data[n]) self._last_data[n] = data[n][-self._npts:] else: - newdata = self._last_data[n][-(self._npts-len(data)):] + newdata = self._last_data[n][-( + self._npts - len(data)):] newdata += data[n] self.src[n].set_data(newdata) self._last_data[n] = newdata - else: # single value update + else: # single value update if(self._iscomplex): data[n] = complex(data[n][0], data[n][1]) if(self._data_len[n] < self._npts): @@ -170,12 +175,11 @@ def update(self, data): else: for n in range(self._ncons): if(type(data[n]) != list): - data[n] = [data[n],] + data[n] = [data[n], ] data[n] = self.data_to_complex(data[n]) self.src[n].set_data(data[n]) - class GrDataPlotterC(GrDataPlotParent): def __init__(self, name, rate, pmin=None, pmax=None, stripchart=False): GrDataPlotParent.__init__(self, name, rate, pmin, pmax) @@ -203,8 +207,8 @@ def get_npts(self): return self._npts def set_line_label(self, n, name): - self.snk.set_line_label(2*n+0, "Re{" + self.knobnames[n] + "}") - self.snk.set_line_label(2*n+1, "Im{" + self.knobnames[n] + "}") + self.snk.set_line_label(2 * n + 0, "Re{" + self.knobnames[n] + "}") + self.snk.set_line_label(2 * n + 1, "Im{" + self.knobnames[n] + "}") class GrDataPlotterF(GrDataPlotParent): @@ -366,6 +370,7 @@ def get_npts(self): def set_line_label(self, n, name): self.snk.set_line_label(n, self.knobnames[n]) + class GrTimeRasterB(GrDataPlotParent): def __init__(self, name, rate, pmin=None, pmax=None): GrDataPlotParent.__init__(self, name, rate, pmin, pmax) @@ -404,7 +409,7 @@ def __init__(self, uid, parent, x, y, xsize, ysize, self.uid = uid self.treeWidget = Qt.QTreeWidget(parent) self.treeWidget.setColumnCount(len(headers)) - self.treeWidget.setGeometry(x,y,xsize,ysize) + self.treeWidget.setGeometry(x, y, xsize, ysize) self.treeWidget.setHeaderLabels(headers) self.treeWidget.resizeColumnToContents(0) @@ -432,19 +437,19 @@ def updateItems(self, knobs, knobprops): descr = str(knobprops[itemKey].description) if(type(v) == ControlPort.complex): - v = v.re + v.im*1j + v = v.re + v.im * 1j # If it's a byte stream, Python thinks it's a string. # Unpack and convert to floats for plotting. # Ignore the edge list knob if it's being exported elif(type(v) == str and itemKey.find('probe2_b') == 0): - v = struct.unpack(len(v)*'b', v) + v = struct.unpack(len(v) * 'b', v) # Convert the final value to a string for displaying v = str(v) if (item.text(1) != v or item.text(2) != units or - item.text(3) != descr): + item.text(3) != descr): item.setText(1, v) item.setText(2, units) @@ -458,20 +463,21 @@ def updateItems(self, knobs, knobprops): if k not in foundKeys: v = knobs[k].value if(type(v) == ControlPort.complex): - v = v.re + v.im*1j + v = v.re + v.im * 1j # If it's a byte stream, Python thinks it's a string. # Unpack and convert to floats for plotting. # Ignore the edge list knob if it's being exported elif(type(v) == str and k.find('probe2_b') == 0): - v = struct.unpack(len(v)*'b', v) + v = struct.unpack(len(v) * 'b', v) item = Qt.QTreeWidgetItem([k, str(v), - knobprops[k].units, knobprops[k].description]) + knobprops[k].units, knobprops[k].description]) self.treeWidget.addTopLevelItem(item) # Remove items currently in tree that are not in the knob list. for itemKey in deleteKeys: - qtwiList = self.treeWidget.findItems(itemKey, Qt.Qt.MatchFixedString) + qtwiList = self.treeWidget.findItems( + itemKey, Qt.Qt.MatchFixedString) if (len(qtwiList) > 1): raise Exception('More than one item with key %s in tree' % itemKey) diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnection.py b/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnection.py index cfc8ce07343..fa15a1e7df2 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnection.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnection.py @@ -18,8 +18,8 @@ RPCMethods = {'thrift': 'Apache Thrift', - #'ice': 'Zeroc ICE' - } + # 'ice': 'Zeroc ICE' + } """ @@ -62,14 +62,17 @@ def setKnobs({}): Given a dictionary of ControlPort property host: hostname of the connection """ + class RPCConnection(object): def __init__(self, method, port, host=None): (self.method, self.port) = (method, port) - if host is None: self.host = '127.0.0.1' - else: self.host = host + if host is None: + self.host = '127.0.0.1' + else: + self.host = host def __str__(self): - return "%s connection on %s:%s"%(self.getName(), self.getHost(), self.getPort()) + return "%s connection on %s:%s" % (self.getName(), self.getHost(), self.getPort()) def getName(self): return RPCMethods[self.method] @@ -89,13 +92,13 @@ def properties(self, *args): def getKnobs(self, *args): raise NotImplementedError() - def getRe(self,*args): + def getRe(self, *args): raise NotImplementedError() - def postMessage(self,*args): + def postMessage(self, *args): raise NotImplementedError() - def setKnobs(self,*args): + def setKnobs(self, *args): raise NotImplementedError() def shutdown(self): diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnectionThrift.py b/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnectionThrift.py index dd9044a36c1..7a87ea57395 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnectionThrift.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnectionThrift.py @@ -18,6 +18,7 @@ import pmt import sys + class ThriftRadioClient(object): def __init__(self, host, port): self.tsocket = TSocket.TSocket(host, port) @@ -39,6 +40,7 @@ def __del__(self): def getRadio(self): return self.radio + """ RPC Client interface for the Apache Thrift middle-ware RPC transport. @@ -47,6 +49,7 @@ def getRadio(self): host: hostname of the connection """ + class RPCConnectionThrift(RPCConnection.RPCConnection): class Knob(object): def __init__(self, key, value=None, ktype=0): @@ -73,43 +76,44 @@ def __init__(self, host=None, port=None): else: port = int(port) - super(RPCConnectionThrift, self).__init__(method='thrift', port=port, host=host) + super(RPCConnectionThrift, self).__init__( + method='thrift', port=port, host=host) self.newConnection(host, port) self.unpack_dict = { - self.BaseTypes.BOOL: lambda k,b: self.Knob(k, b.value.a_bool, self.BaseTypes.BOOL), - self.BaseTypes.BYTE: lambda k,b: self.Knob(k, b.value.a_byte, self.BaseTypes.BYTE), - self.BaseTypes.SHORT: lambda k,b: self.Knob(k, b.value.a_short, self.BaseTypes.SHORT), - self.BaseTypes.INT: lambda k,b: self.Knob(k, b.value.a_int, self.BaseTypes.INT), - self.BaseTypes.LONG: lambda k,b: self.Knob(k, b.value.a_long, self.BaseTypes.LONG), - self.BaseTypes.DOUBLE: lambda k,b: self.Knob(k, b.value.a_double, self.BaseTypes.DOUBLE), - self.BaseTypes.STRING: lambda k,b: self.Knob(k, b.value.a_string, self.BaseTypes.STRING), - self.BaseTypes.COMPLEX: lambda k,b: self.Knob(k, b.value.a_complex, self.BaseTypes.COMPLEX), - self.BaseTypes.F32VECTOR: lambda k,b: self.Knob(k, b.value.a_f32vector, self.BaseTypes.F32VECTOR), - self.BaseTypes.F64VECTOR: lambda k,b: self.Knob(k, b.value.a_f64vector, self.BaseTypes.F64VECTOR), - self.BaseTypes.S64VECTOR: lambda k,b: self.Knob(k, b.value.a_s64vector, self.BaseTypes.S64VECTOR), - self.BaseTypes.S32VECTOR: lambda k,b: self.Knob(k, b.value.a_s32vector, self.BaseTypes.S32VECTOR), - self.BaseTypes.S16VECTOR: lambda k,b: self.Knob(k, b.value.a_s16vector, self.BaseTypes.S16VECTOR), - self.BaseTypes.S8VECTOR: lambda k,b: self.Knob(k, b.value.a_s8vector, self.BaseTypes.S8VECTOR), - self.BaseTypes.C32VECTOR: lambda k,b: self.Knob(k, b.value.a_c32vector, self.BaseTypes.C32VECTOR), + self.BaseTypes.BOOL: lambda k, b: self.Knob(k, b.value.a_bool, self.BaseTypes.BOOL), + self.BaseTypes.BYTE: lambda k, b: self.Knob(k, b.value.a_byte, self.BaseTypes.BYTE), + self.BaseTypes.SHORT: lambda k, b: self.Knob(k, b.value.a_short, self.BaseTypes.SHORT), + self.BaseTypes.INT: lambda k, b: self.Knob(k, b.value.a_int, self.BaseTypes.INT), + self.BaseTypes.LONG: lambda k, b: self.Knob(k, b.value.a_long, self.BaseTypes.LONG), + self.BaseTypes.DOUBLE: lambda k, b: self.Knob(k, b.value.a_double, self.BaseTypes.DOUBLE), + self.BaseTypes.STRING: lambda k, b: self.Knob(k, b.value.a_string, self.BaseTypes.STRING), + self.BaseTypes.COMPLEX: lambda k, b: self.Knob(k, b.value.a_complex, self.BaseTypes.COMPLEX), + self.BaseTypes.F32VECTOR: lambda k, b: self.Knob(k, b.value.a_f32vector, self.BaseTypes.F32VECTOR), + self.BaseTypes.F64VECTOR: lambda k, b: self.Knob(k, b.value.a_f64vector, self.BaseTypes.F64VECTOR), + self.BaseTypes.S64VECTOR: lambda k, b: self.Knob(k, b.value.a_s64vector, self.BaseTypes.S64VECTOR), + self.BaseTypes.S32VECTOR: lambda k, b: self.Knob(k, b.value.a_s32vector, self.BaseTypes.S32VECTOR), + self.BaseTypes.S16VECTOR: lambda k, b: self.Knob(k, b.value.a_s16vector, self.BaseTypes.S16VECTOR), + self.BaseTypes.S8VECTOR: lambda k, b: self.Knob(k, b.value.a_s8vector, self.BaseTypes.S8VECTOR), + self.BaseTypes.C32VECTOR: lambda k, b: self.Knob(k, b.value.a_c32vector, self.BaseTypes.C32VECTOR), } self.pack_dict = { - self.BaseTypes.BOOL: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_bool = k.value)), - self.BaseTypes.BYTE: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_byte = k.value)), - self.BaseTypes.SHORT: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_short = k.value)), - self.BaseTypes.INT: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_int = k.value)), - self.BaseTypes.LONG: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_long = k.value)), - self.BaseTypes.DOUBLE: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_double = k.value)), - self.BaseTypes.STRING: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_string = k.value)), - self.BaseTypes.COMPLEX: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_complex = k.value)), - self.BaseTypes.F32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_f32vector = k.value)), - self.BaseTypes.F64VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_f64vector = k.value)), - self.BaseTypes.S64VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s64vector = k.value)), - self.BaseTypes.S32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s32vector = k.value)), - self.BaseTypes.S16VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s16vector = k.value)), - self.BaseTypes.S8VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s8vector = k.value)), - self.BaseTypes.C32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_c32vector = k.value)), + self.BaseTypes.BOOL: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_bool=k.value)), + self.BaseTypes.BYTE: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_byte=k.value)), + self.BaseTypes.SHORT: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_short=k.value)), + self.BaseTypes.INT: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_int=k.value)), + self.BaseTypes.LONG: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_long=k.value)), + self.BaseTypes.DOUBLE: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_double=k.value)), + self.BaseTypes.STRING: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_string=k.value)), + self.BaseTypes.COMPLEX: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_complex=k.value)), + self.BaseTypes.F32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_f32vector=k.value)), + self.BaseTypes.F64VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_f64vector=k.value)), + self.BaseTypes.S64VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s64vector=k.value)), + self.BaseTypes.S32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s32vector=k.value)), + self.BaseTypes.S16VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s16vector=k.value)), + self.BaseTypes.S8VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_s8vector=k.value)), + self.BaseTypes.C32VECTOR: lambda k: ttypes.Knob(type=k.ktype, value=ttypes.KnobBase(a_c32vector=k.value)), } def __str__(self): @@ -122,7 +126,8 @@ def unpackKnob(self, key, knob): if(f): return f(key, knob) else: - sys.stderr.write("unpackKnobs: Incorrect Knob type: {0}\n".format(knob.type)) + sys.stderr.write( + "unpackKnobs: Incorrect Knob type: {0}\n".format(knob.type)) raise exceptions.ValueError def packKnob(self, knob): @@ -130,7 +135,8 @@ def packKnob(self, knob): if(f): return f(knob) else: - sys.stderr.write("packKnobs: Incorrect Knob type: {0}\n".format(knob.type)) + sys.stderr.write( + "packKnobs: Incorrect Knob type: {0}\n".format(knob.type)) raise exceptions.ValueError def newConnection(self, host=None, port=None): @@ -142,7 +148,8 @@ def properties(self, *args): #print("key:", key, "value:", knobprop, "type:", knobprop.type) knobprops[key].min = self.unpackKnob(key, knobprop.min) knobprops[key].max = self.unpackKnob(key, knobprop.max) - knobprops[key].defaultvalue = self.unpackKnob(key, knobprop.defaultvalue) + knobprops[key].defaultvalue = self.unpackKnob( + key, knobprop.defaultvalue) return knobprops def getKnobs(self, *args): @@ -166,7 +173,7 @@ def getKnobsRaw(self, *args): result[key] = knob return result - def getRe(self,*args): + def getRe(self, *args): result = {} for key, knob in list(self.thriftclient.radio.getRe(*args).items()): result[key] = self.unpackKnob(key, knob) @@ -186,7 +193,8 @@ def setKnobs(self, *args): result[k.key] = self.packKnob(k) self.thriftclient.radio.setKnobs(result) else: - sys.stderr.write("setKnobs: Invalid type; must be dict, list, or tuple\n") + sys.stderr.write( + "setKnobs: Invalid type; must be dict, list, or tuple\n") def shutdown(self): self.thriftclient.radio.shutdown() @@ -204,8 +212,10 @@ def postMessage(self, blk_alias, port, msg): serialized. The msg is already a PMT and so just serialized. ''' self.thriftclient.radio.postMessage(pmt.serialize_str(pmt.intern(blk_alias)), - pmt.serialize_str(pmt.intern(port)), + pmt.serialize_str( + pmt.intern(port)), pmt.serialize_str(msg)) + def printProperties(self, props): info = "" info += "Item:\t\t{0}\n".format(props.description) diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/gr-ctrlport-monitor b/gnuradio-runtime/python/gnuradio/ctrlport/gr-ctrlport-monitor index 01b6a84d3f5..c8c4771e457 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/gr-ctrlport-monitor +++ b/gnuradio-runtime/python/gnuradio/ctrlport/gr-ctrlport-monitor @@ -11,12 +11,16 @@ from PyQt5 import QtCore, Qt from argparse import ArgumentParser -import os, sys, time, struct +import os +import sys +import time +import struct from gnuradio import gr, ctrlport from gnuradio.ctrlport.GrDataPlotter import * from gnuradio.ctrlport.GNURadioControlPortClient import GNURadioControlPortClient + class RateDialog(Qt.QDialog): def __init__(self, delay, parent=None): super(RateDialog, self).__init__(parent) @@ -24,19 +28,23 @@ class RateDialog(Qt.QDialog): self.setWindowTitle("Update Delay (ms)") self.delay = Qt.QLineEdit(self) self.delay.setText(str(delay)) - self.buttonBox = Qt.QDialogButtonBox(Qt.QDialogButtonBox.Ok | Qt.QDialogButtonBox.Cancel) + self.buttonBox = Qt.QDialogButtonBox( + Qt.QDialogButtonBox.Ok | Qt.QDialogButtonBox.Cancel) self.gridLayout.addWidget(self.delay) self.gridLayout.addWidget(self.buttonBox) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) + def accept(self): self.done(1) + def reject(self): self.done(0) + class MAINWindow(Qt.QMainWindow): def minimumSizeHint(self): - return Qt.QSize(800,600) + return Qt.QSize(800, 600) def __init__(self, radioclient): @@ -65,7 +73,7 @@ class MAINWindow(Qt.QMainWindow): self.setUnifiedTitleAndToolBarOnMac(True) self.newCon(radioclient) - icon = Qt.QIcon(ctrlport.__path__[0] + "/icon.png" ) + icon = Qt.QIcon(ctrlport.__path__[0] + "/icon.png") self.setWindowIcon(icon) # Locally turn off ControlPort export from GR. This prevents @@ -74,14 +82,14 @@ class MAINWindow(Qt.QMainWindow): # been specified). os.environ['GR_CONF_CONTROLPORT_ON'] = 'False' - def setUpdateRate(self,nur): + def setUpdateRate(self, nur): self.updateRate = int(nur) for c in self.conns: c.updateRate = self.updateRate c.timer.setInterval(self.updateRate) def newCon(self, radioclient=None): - child = MForm(radioclient, len(self.conns), parent = self) + child = MForm(radioclient, len(self.conns), parent=self) if(child.radioclient is not None): child.setWindowTitle(str(child.radioclient)) self.mdiArea.addSubWindow(child) @@ -95,7 +103,7 @@ class MAINWindow(Qt.QMainWindow): props = radio.properties([key]) - pmin,pmax = get_minmax(props[key]) + pmin, pmax = get_minmax(props[key]) # Use display option mask of item to set up available plot # types and default options. @@ -166,8 +174,8 @@ class MAINWindow(Qt.QMainWindow): knobprop = self.knobprops[uid][tag] strr = str(tree.radioclient) - title = strr #title = "{0}:{1}".format(r[3], r[5]) - pmin,pmax = get_minmax(knobprop) + title = strr # title = "{0}:{1}".format(r[3], r[5]) + pmin, pmax = get_minmax(knobprop) disp = knobprop.display if(disp & gr.DISPTIME): @@ -217,7 +225,8 @@ class MAINWindow(Qt.QMainWindow): self.mdiArea.addSubWindow(plot) plot.setWindowTitle("{0}: {1}".format(title, plot.name())) - plot.qwidget().destroyed.connect(lambda obj=None, plot=plot: self.destroyPlot(plot=plot)), + plot.qwidget().destroyed.connect(lambda obj=None, + plot=plot: self.destroyPlot(plot=plot)), # when the plot is updated via drag-and-drop, we need to be # notified of the new qwidget that's created so we can @@ -232,8 +241,8 @@ class MAINWindow(Qt.QMainWindow): for i, plots in enumerate(self.plots): for p in plots: if(p == q): - #plots.remove(p) - #plots.append(q) + # plots.remove(p) + # plots.append(q) q.qwidget().destroyed.connect(lambda obj=None, plot=p: self.destroyPlot(plot=plot)) break @@ -290,7 +299,7 @@ class MAINWindow(Qt.QMainWindow): # If it's a byte stream, Python thinks it's a string. # Unpack and convert to floats for plotting. if(type(d) == str and n.find('probe2_b') == 0): - d = struct.unpack(len(d)*'b', d) + d = struct.unpack(len(d) * 'b', d) d = [float(di) for di in d] data.append(d) @@ -303,59 +312,58 @@ class MAINWindow(Qt.QMainWindow): if window: self.mdiArea.setActiveSubWindow(window) - def createActions(self): self.newConAct = Qt.QAction("&New Connection", - self, shortcut=Qt.QKeySequence.New, - statusTip="Create a new file", triggered=lambda x: self.newCon(None)) + self, shortcut=Qt.QKeySequence.New, + statusTip="Create a new file", triggered=lambda x: self.newCon(None)) self.exitAct = Qt.QAction("E&xit", self, shortcut="Ctrl+Q", - statusTip="Exit the application", - triggered=Qt.qApp.closeAllWindows) + statusTip="Exit the application", + triggered=Qt.qApp.closeAllWindows) self.closeAct = Qt.QAction("Cl&ose", self, shortcut="Ctrl+F4", - statusTip="Close the active window", - triggered=self.mdiArea.closeActiveSubWindow) + statusTip="Close the active window", + triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = Qt.QAction("Close &All", self, - statusTip="Close all the windows", - triggered=self.mdiArea.closeAllSubWindows) + statusTip="Close all the windows", + triggered=self.mdiArea.closeAllSubWindows) self.urAct = Qt.QAction("Update Rate", self, shortcut="F5", - statusTip="Change Update Rate", - triggered=self.updateRateShow) + statusTip="Change Update Rate", + triggered=self.updateRateShow) qks = Qt.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_T) self.tileAct = Qt.QAction("&Tile", self, - statusTip="Tile the windows", - triggered=self.mdiArea.tileSubWindows, - shortcut=qks) + statusTip="Tile the windows", + triggered=self.mdiArea.tileSubWindows, + shortcut=qks) qks = Qt.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_C) self.cascadeAct = Qt.QAction("&Cascade", self, - statusTip="Cascade the windows", shortcut=qks, - triggered=self.mdiArea.cascadeSubWindows) + statusTip="Cascade the windows", shortcut=qks, + triggered=self.mdiArea.cascadeSubWindows) self.nextAct = Qt.QAction("Ne&xt", self, - shortcut=Qt.QKeySequence.NextChild, - statusTip="Move the focus to the next window", - triggered=self.mdiArea.activateNextSubWindow) + shortcut=Qt.QKeySequence.NextChild, + statusTip="Move the focus to the next window", + triggered=self.mdiArea.activateNextSubWindow) self.previousAct = Qt.QAction("Pre&vious", self, - shortcut=Qt.QKeySequence.PreviousChild, - statusTip="Move the focus to the previous window", - triggered=self.mdiArea.activatePreviousSubWindow) + shortcut=Qt.QKeySequence.PreviousChild, + statusTip="Move the focus to the previous window", + triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = Qt.QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = Qt.QAction("&About", self, - statusTip="Show the application's About box", - triggered=self.about) + statusTip="Show the application's About box", + triggered=self.about) self.aboutQtAct = Qt.QAction("About &Qt", self, - statusTip="Show the Qt library's About box", - triggered=Qt.qApp.aboutQt) + statusTip="Show the Qt library's About box", + triggered=Qt.qApp.aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") @@ -395,7 +403,6 @@ class MAINWindow(Qt.QMainWindow): def createStatusBar(self): self.statusBar().showMessage("Ready") - def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: @@ -426,7 +433,7 @@ class MAINWindow(Qt.QMainWindow): def about(self): about_info = \ -'''Copyright 2012 Free Software Foundation, Inc.\n + '''Copyright 2012 Free Software Foundation, Inc.\n This program is part of GNU Radio.\n GNU Radio is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.\n GNU Radio is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n @@ -441,13 +448,13 @@ class ConInfoDialog(Qt.QDialog): self.gridLayout = Qt.QGridLayout(self) - self.host = Qt.QLineEdit(self) self.port = Qt.QLineEdit(self) self.host.setText("localhost") self.port.setText("43243") - self.buttonBox = Qt.QDialogButtonBox(Qt.QDialogButtonBox.Ok | Qt.QDialogButtonBox.Cancel) + self.buttonBox = Qt.QDialogButtonBox( + Qt.QDialogButtonBox.Ok | Qt.QDialogButtonBox.Cancel) self.gridLayout.addWidget(self.host) self.gridLayout.addWidget(self.port) @@ -456,7 +463,6 @@ class ConInfoDialog(Qt.QDialog): self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) - def accept(self): self.done(1) @@ -471,7 +477,7 @@ class UpdaterWindow(Qt.QDialog): self.key = key self.radio = radio - self.resize(300,200) + self.resize(300, 200) self.layout = Qt.QVBoxLayout() self.props = radio.properties([key])[key] @@ -487,7 +493,6 @@ class UpdaterWindow(Qt.QDialog): except: has_set = False - if(has_set is False): self.cancelButton = Qt.QPushButton("Ok") self.cancelButton.clicked.connect(self.reject) @@ -496,7 +501,7 @@ class UpdaterWindow(Qt.QDialog): self.buttonlayout.addWidget(self.cancelButton) self.layout.addLayout(self.buttonlayout) - else: # we have a set function + else: # we have a set function self.textInput = Qt.QLineEdit() self.layout.addWidget(self.textInput) @@ -507,7 +512,7 @@ class UpdaterWindow(Qt.QDialog): rv = radio.getKnobs([key]) val = rv[key].value if(type(val) == ControlPort.complex): - val = val.re + val.im*1j + val = val.re + val.im * 1j self.textInput.setText(str(val)) self.sv = rv[key] @@ -516,15 +521,18 @@ class UpdaterWindow(Qt.QDialog): self.setButton.clicked.connect(self._set) self.cancelButton.clicked.connect(self.reject) - self.is_num = ((type(self.sv.value)==float) or (type(self.sv.value)==int)) + self.is_num = ((type(self.sv.value) == float) or + (type(self.sv.value) == int)) if(self.is_num): self.sliderlayout = Qt.QHBoxLayout() self.slider = Qt.QSlider(QtCore.Qt.Horizontal) - self.sliderlayout.addWidget(Qt.QLabel(str(self.props.min.value))) + self.sliderlayout.addWidget( + Qt.QLabel(str(self.props.min.value))) self.sliderlayout.addWidget(self.slider) - self.sliderlayout.addWidget(Qt.QLabel(str(self.props.max.value))) + self.sliderlayout.addWidget( + Qt.QLabel(str(self.props.max.value))) self.steps = 10000 self.valspan = self.props.max.value - self.props.min.value @@ -548,10 +556,12 @@ class UpdaterWindow(Qt.QDialog): self.setLayout(self.layout) def _set_slider_value(self, val): - self.slider.setValue(self.steps*(val-self.props.min.value)/self.valspan) + self.slider.setValue( + self.steps * (val - self.props.min.value) / self.valspan) def _slide(self): - val = self.props.min.value + (self.slider.value()/float(self.steps)*self.valspan) + val = self.props.min.value + \ + (self.slider.value() / float(self.steps) * self.valspan) self.textInput.setText(str(val)) def _apply(self): @@ -568,7 +578,8 @@ class UpdaterWindow(Qt.QDialog): val.re = t.real val.im = t.imag else: - sys.stderr.write("set type not supported! ({0})\n".format(type(self.sv.value))) + sys.stderr.write( + "set type not supported! ({0})\n".format(type(self.sv.value))) return self.sv.value = val @@ -589,11 +600,13 @@ class MForm(Qt.QWidget): st = time.time() knobs = self.radioclient.getKnobs([]) ft = time.time() - latency = ft-st - self.parent.statusBar().showMessage("Current GNU Radio Control Port Query Latency: %f ms"%(latency*1000)) + latency = ft - st + self.parent.statusBar().showMessage( + "Current GNU Radio Control Port Query Latency: %f ms" % (latency * 1000)) except Exception as e: - sys.stderr.write("ctrlport-monitor: lost connection ({0}).\n".format(e)) + sys.stderr.write( + "ctrlport-monitor: lost connection ({0}).\n".format(e)) if(type(self.parent) is MAINWindow): # Find window of connection remove = [] @@ -623,13 +636,12 @@ class MForm(Qt.QWidget): tableitems = knobs.keys() - #UPDATE TABLE: + # UPDATE TABLE: self.table.updateItems(knobs, self.knobprops) - #UPDATE PLOTS + # UPDATE PLOTS self.parent.update(knobs, self.uid) - def __init__(self, radioclient, uid=0, updateRate=2000, parent=None): super(MForm, self).__init__() @@ -642,7 +654,8 @@ class MForm(Qt.QWidget): port = str(askinfo.port.text()) try: - self.radioclient = GNURadioControlPortClient(host, port, 'thrift').client + self.radioclient = GNURadioControlPortClient( + host, port, 'thrift').client print("Connected to %s:%s" % (host, port)) except: print("Cannot connect to %s:%s" % (host, port)) @@ -659,17 +672,19 @@ class MForm(Qt.QWidget): self.knobprops = self.radioclient.properties([]) self.parent.knobprops.append(self.knobprops) - self.resize(775,500) + self.resize(775, 500) self.timer = QtCore.QTimer() self.constupdatediv = 0 self.tableupdatediv = 0 - plotsize=250 + plotsize = 250 # make table self.table = GrDataPlotterValueTable(uid, self, 0, 0, 400, 200) - sizePolicy = Qt.QSizePolicy(Qt.QSizePolicy.Preferred, Qt.QSizePolicy.Preferred) + sizePolicy = Qt.QSizePolicy( + Qt.QSizePolicy.Preferred, Qt.QSizePolicy.Preferred) self.table.treeWidget.setSizePolicy(sizePolicy) - self.table.treeWidget.setEditTriggers(Qt.QAbstractItemView.EditKeyPressed) + self.table.treeWidget.setEditTriggers( + Qt.QAbstractItemView.EditKeyPressed) self.table.treeWidget.setSortingEnabled(True) self.table.treeWidget.setDragEnabled(True) @@ -721,24 +736,27 @@ def get_minmax(p): if pmin == []: pmin = None else: - pmin = 1.1*float(pmin) + pmin = 1.1 * float(pmin) if pmax == []: pmax = None else: - pmax = 1.1*float(pmax) + pmax = 1.1 * float(pmax) return pmin, pmax + class MyApp(object): def __init__(self, args): parser = ArgumentParser(description="GNU Radio Control Port Monitor") - parser.add_argument("host", nargs="?", default="localhost", help="host name or IP") + parser.add_argument("host", nargs="?", + default="localhost", help="host name or IP") parser.add_argument("port", help="port") args = parser.parse_args() try: - GNURadioControlPortClient(args.host, args.port, 'thrift', self.run, Qt.QApplication(sys.argv).exec_) + GNURadioControlPortClient( + args.host, args.port, 'thrift', self.run, Qt.QApplication(sys.argv).exec_) except: print("ControlPort failed to connect. Check the config of your endpoint.") print("\t[ControlPort] on = True") @@ -749,4 +767,5 @@ class MyApp(object): def run(self, client): MAINWindow(client).show() + MyApp(sys.argv) diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitorx b/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitorx index 3c807755db6..cd704888bbf 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitorx +++ b/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitorx @@ -10,8 +10,13 @@ from argparse import ArgumentParser -import sys, time, re, signal -import random,math,operator +import sys +import time +import re +import signal +import random +import math +import operator from gnuradio.ctrlport.GNURadioControlPortClient import GNURadioControlPortClient @@ -29,11 +34,10 @@ try: print(sys.argv[0], "could not load QTAgg backend.") sys.exit(1) - from matplotlib.figure import Figure except ImportError: print(sys.argv[0], "requires networkx and matplotlib.", - "Please check that they are installed and try again.") + "Please check that they are installed and try again.") sys.exit(1) from PyQt5 import QtCore, Qt @@ -44,9 +48,10 @@ from gnuradio.ctrlport.GrDataPlotter import * from networkx.drawing.nx_agraph import graphviz_layout + class MAINWindow(Qt.QMainWindow): def minimumSizeHint(self): - return Qt.QSize(800,600) + return Qt.QSize(800, 600) def __init__(self, radioclient): @@ -74,7 +79,7 @@ class MAINWindow(Qt.QMainWindow): self.newCon(radioclient) - icon = Qt.QIcon(ctrlport.__path__[0] + "/icon.png" ) + icon = Qt.QIcon(ctrlport.__path__[0] + "/icon.png") self.setWindowIcon(icon) def newSubWindow(self, window, title): @@ -96,55 +101,54 @@ class MAINWindow(Qt.QMainWindow): if window: self.mdiArea.setActiveSubWindow(window) - def createActions(self): self.newConAct = Qt.QAction("&New Connection", - self, shortcut=Qt.QKeySequence.New, - statusTip="Create a new file", triggered=lambda x: self.newCon(None)) + self, shortcut=Qt.QKeySequence.New, + statusTip="Create a new file", triggered=lambda x: self.newCon(None)) self.exitAct = Qt.QAction("E&xit", self, shortcut="Ctrl+Q", - statusTip="Exit the application", - triggered=Qt.qApp.closeAllWindows) + statusTip="Exit the application", + triggered=Qt.qApp.closeAllWindows) self.closeAct = Qt.QAction("Cl&ose", self, shortcut="Ctrl+F4", - statusTip="Close the active window", - triggered=self.mdiArea.closeActiveSubWindow) + statusTip="Close the active window", + triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = Qt.QAction("Close &All", self, - statusTip="Close all the windows", - triggered=self.mdiArea.closeAllSubWindows) + statusTip="Close all the windows", + triggered=self.mdiArea.closeAllSubWindows) qks = Qt.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_T) self.tileAct = Qt.QAction("&Tile", self, - statusTip="Tile the windows", - triggered=self.mdiArea.tileSubWindows, - shortcut=qks) + statusTip="Tile the windows", + triggered=self.mdiArea.tileSubWindows, + shortcut=qks) qks = Qt.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_C) self.cascadeAct = Qt.QAction("&Cascade", self, - statusTip="Cascade the windows", shortcut=qks, - triggered=self.mdiArea.cascadeSubWindows) + statusTip="Cascade the windows", shortcut=qks, + triggered=self.mdiArea.cascadeSubWindows) self.nextAct = Qt.QAction("Ne&xt", self, - shortcut=Qt.QKeySequence.NextChild, - statusTip="Move the focus to the next window", - triggered=self.mdiArea.activateNextSubWindow) + shortcut=Qt.QKeySequence.NextChild, + statusTip="Move the focus to the next window", + triggered=self.mdiArea.activateNextSubWindow) self.previousAct = Qt.QAction("Pre&vious", self, - shortcut=Qt.QKeySequence.PreviousChild, - statusTip="Move the focus to the previous window", - triggered=self.mdiArea.activatePreviousSubWindow) + shortcut=Qt.QKeySequence.PreviousChild, + statusTip="Move the focus to the previous window", + triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = Qt.QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = Qt.QAction("&About", self, - statusTip="Show the application's About box", - triggered=self.about) + statusTip="Show the application's About box", + triggered=self.about) self.aboutQtAct = Qt.QAction("About &Qt", self, - statusTip="Show the Qt library's About box", - triggered=Qt.qApp.aboutQt) + statusTip="Show the Qt library's About box", + triggered=Qt.qApp.aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") @@ -173,7 +177,6 @@ class MAINWindow(Qt.QMainWindow): def createStatusBar(self): self.statusBar().showMessage("Ready") - def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: @@ -204,7 +207,7 @@ class MAINWindow(Qt.QMainWindow): def about(self): about_info = \ -'''Copyright 2012 Free Software Foundation, Inc.\n + '''Copyright 2012 Free Software Foundation, Inc.\n This program is part of GNU Radio.\n GNU Radio is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.\n GNU Radio is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n @@ -219,14 +222,13 @@ class ConInfoDialog(Qt.QDialog): self.gridLayout = Qt.QGridLayout(self) - self.host = Qt.QLineEdit(self) self.port = Qt.QLineEdit(self) self.host.setText("localhost") self.port.setText("43243") self.buttonBox = Qt.QDialogButtonBox(Qt.QDialogButtonBox.Ok | - Qt.QDialogButtonBox.Cancel) + Qt.QDialogButtonBox.Cancel) self.gridLayout.addWidget(self.host) self.gridLayout.addWidget(self.port) @@ -235,7 +237,6 @@ class ConInfoDialog(Qt.QDialog): self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) - def accept(self): self.done(1) @@ -288,21 +289,22 @@ class DataTable(Qt.QWidget): self.perfTable = Qt.QTableWidget() self.perfTable.setColumnCount(2) self.perfTable.verticalHeader().hide() - self.perfTable.setHorizontalHeaderLabels( ["Block Name", "Percent Runtime"] ) + self.perfTable.setHorizontalHeaderLabels( + ["Block Name", "Percent Runtime"]) self.perfTable.horizontalHeader().setStretchLastSection(True) self.perfTable.setSortingEnabled(True) nodes = self.G.nodes(data=True) # set up plot - self.f = plt.figure(figsize=(10,8), dpi=90) + self.f = plt.figure(figsize=(10, 8), dpi=90) self.sp = self.f.add_subplot(111) - self.sp.autoscale_view(True,True,True) + self.sp.autoscale_view(True, True, True) self.sp.set_autoscale_on(True) # set up tabs self.tabber = Qt.QTabWidget() self.layout.addWidget(self.tabber) - self.tabber.addTab(self.perfTable,"Table View") + self.tabber.addTab(self.perfTable, "Table View") self.tabber.addTab(self.f.canvas, "Graph View") # set up timer @@ -312,19 +314,21 @@ class DataTable(Qt.QWidget): for i, node in enumerate(nodes): self.perfTable.setItem(i, 0, - Qt.QTableWidgetItem(node[0])) + Qt.QTableWidgetItem(node[0])) - def table_update(self,data): + def table_update(self, data): for k in data.keys(): weight = data[k] - existing = self.perfTable.findItems(str(k),QtCore.Qt.MatchFixedString) + existing = self.perfTable.findItems( + str(k), QtCore.Qt.MatchFixedString) if(len(existing) == 0): i = self.perfTable.rowCount() - self.perfTable.setRowCount( i+1) - self.perfTable.setItem( i,0, Qt.QTableWidgetItem(str(k))) - self.perfTable.setItem( i,1, Qt.QTableWidgetItem(str(weight))) + self.perfTable.setRowCount(i + 1) + self.perfTable.setItem(i, 0, Qt.QTableWidgetItem(str(k))) + self.perfTable.setItem(i, 1, Qt.QTableWidgetItem(str(weight))) else: - self.perfTable.setItem( self.perfTable.row(existing[0]),1, Qt.QTableWidgetItem(str(weight))) + self.perfTable.setItem(self.perfTable.row( + existing[0]), 1, Qt.QTableWidgetItem(str(weight))) def stat_changed(self, index): self._statistic = str(self.stattype.currentText()) @@ -332,22 +336,25 @@ class DataTable(Qt.QWidget): def checksort_changed(self, state): self._sort = state > 0 + class DataTableBuffers(DataTable): def __init__(self, radioclient, G): super(DataTableBuffers, self).__init__(radioclient, G) - self.perfTable.setHorizontalHeaderLabels( ["Block Name", "Percent Buffer Full"] ) + self.perfTable.setHorizontalHeaderLabels( + ["Block Name", "Percent Buffer Full"]) def update(self): nodes = self.G.nodes() # get buffer fullness for all blocks - kl = list(map(lambda x: "%s::%soutput %% full" % \ - (x, self._statistics_table[self._statistic]), - nodes)) + kl = list(map(lambda x: "%s::%soutput %% full" % + (x, self._statistics_table[self._statistic]), + nodes)) try: buf_knobs = self.radioclient.getKnobs(kl) except Exception as e: - sys.stderr.write("gr-perf-monitorx: lost connection ({0}).\n".format(e)) + sys.stderr.write( + "gr-perf-monitorx: lost connection ({0}).\n".format(e)) self.parentWidget().mdiArea().removeSubWindow(self.parentWidget()) self.close() return @@ -361,8 +368,8 @@ class DataTableBuffers(DataTable): for blk in buffer_fullness: bdata = buffer_fullness[blk] if bdata: - for port in range(0,len(bdata)): - blockport_fullness["%s:%d"%(blk,port)] = bdata[port] + for port in range(0, len(bdata)): + blockport_fullness["%s:%d" % (blk, port)] = bdata[port] if(self.perfTable.isVisible()): self.table_update(blockport_fullness) @@ -371,48 +378,54 @@ class DataTableBuffers(DataTable): if(self._sort): sorted_fullness = sorted(blockport_fullness.items(), key=operator.itemgetter(1)) - self._keymap = list(map(operator.itemgetter(0), sorted_fullness)) + self._keymap = list( + map(operator.itemgetter(0), sorted_fullness)) else: if self._keymap: - sorted_fullness = len(self._keymap)*['',] + sorted_fullness = len(self._keymap) * ['', ] for b in blockport_fullness: - sorted_fullness[self._keymap.index(b)] = (b, blockport_fullness[b]) + sorted_fullness[self._keymap.index(b)] = ( + b, blockport_fullness[b]) else: sorted_fullness = blockport_fullness.items() if(not self.disp): - self.disp = self.sp.bar(range(0,len(sorted_fullness)), - list(map(lambda x: x[1], sorted_fullness)), + self.disp = self.sp.bar(range(0, len(sorted_fullness)), + list( + map(lambda x: x[1], sorted_fullness)), alpha=0.5, align='edge') self.sp.set_ylabel("% Buffers Full") - self.sp.set_xticks(list(map(lambda x: x+0.5, range(0,len(sorted_fullness))))) + self.sp.set_xticks( + list(map(lambda x: x + 0.5, range(0, len(sorted_fullness))))) self.sp.set_xticklabels(list(map(lambda x: " " + x, map(lambda x: x[0], sorted_fullness))), rotation="vertical", verticalalignment="bottom") else: self.sp.set_xticklabels(list(map(lambda x: " " + x, map(lambda x: x[0], sorted_fullness))), rotation="vertical", verticalalignment="bottom") - for r,w in zip(self.disp, sorted_fullness): + for r, w in zip(self.disp, sorted_fullness): r.set_height(w[1]) self.f.canvas.draw() + class DataTableRuntimes(DataTable): def __init__(self, radioclient, G): - super(DataTableRuntimes, self).__init__( radioclient, G) + super(DataTableRuntimes, self).__init__(radioclient, G) def update(self): nodes = self.G.nodes() # get work time for all blocks - kl = list(map(lambda x: "%s::%swork time" % \ - (x, self._statistics_table[self._statistic]), - nodes)) + kl = list(map(lambda x: "%s::%swork time" % + (x, self._statistics_table[self._statistic]), + nodes)) try: wrk_knobs = self.radioclient.getKnobs(kl) except Exception as e: - sys.stderr.write("gr-perf-monitorx: lost connection ({0}).\n".format(e)) + sys.stderr.write( + "gr-perf-monitorx: lost connection ({0}).\n".format(e)) self.parentWidget().mdiArea().removeSubWindow(self.parentWidget()) self.close() return @@ -423,7 +436,7 @@ class DataTableRuntimes(DataTable): total_work = 1 work_times = dict(zip( map(lambda x: x.split("::")[0], wrk_knobs.keys()), - map(lambda x: 1e-10 + x.value/total_work, wrk_knobs.values()))) + map(lambda x: 1e-10 + x.value / total_work, wrk_knobs.values()))) # update table view if(self.perfTable.isVisible()): @@ -431,32 +444,35 @@ class DataTableRuntimes(DataTable): else: if(self._sort): - sorted_work = sorted(work_times.items(), key=operator.itemgetter(1)) + sorted_work = sorted(work_times.items(), + key=operator.itemgetter(1)) self._keymap = list(map(operator.itemgetter(0), sorted_work)) else: if self._keymap: - sorted_work = len(list(self._keymap))*['',] + sorted_work = len(list(self._keymap)) * ['', ] for b in work_times: sorted_work[self._keymap.index(b)] = (b, work_times[b]) else: sorted_work = work_times.items() if(not self.disp): - self.disp = self.sp.bar(range(0,len(sorted_work)), + self.disp = self.sp.bar(range(0, len(sorted_work)), list(map(lambda x: x[1], sorted_work)), alpha=0.5, align='edge') self.sp.set_ylabel("% Runtime") - self.sp.set_xticks(list(map(lambda x: x+0.5, range(0,len(sorted_work))))) + self.sp.set_xticks( + list(map(lambda x: x + 0.5, range(0, len(sorted_work))))) self.sp.set_xticklabels(list(map(lambda x: " " + x[0], sorted_work)), - rotation="vertical", verticalalignment="bottom" ) + rotation="vertical", verticalalignment="bottom") else: self.sp.set_xticklabels(list(map(lambda x: " " + x[0], sorted_work)), - rotation="vertical", verticalalignment="bottom" ) - for r,w in zip(self.disp, sorted_work): + rotation="vertical", verticalalignment="bottom") + for r, w in zip(self.disp, sorted_work): r.set_height(w[1]) self.f.canvas.draw() + class MForm(Qt.QWidget): def update(self): try: @@ -470,7 +486,8 @@ class MForm(Qt.QWidget): kl1 = self.radioclient.getKnobs([self.clockKey]) self.clockKey = list(kl1.keys())[0] self.currClock = kl1[self.clockKey].value - self.clockSelIdx = list(self.clocks.values()).index(self.currClock) + self.clockSelIdx = list( + self.clocks.values()).index(self.currClock) self.clockSel.setCurrentIndex(self.clockSelIdx) self.prevent_clock_change = False except Exception as e: @@ -481,9 +498,9 @@ class MForm(Qt.QWidget): nodes_msg = self.G_msg.nodes() # get current buffer depths of all output buffers - kl = list(map(lambda x: "%s::%soutput %% full" % \ - (x, self._statistics_table[self._statistic]), - nodes_stream)) + kl = list(map(lambda x: "%s::%soutput %% full" % + (x, self._statistics_table[self._statistic]), + nodes_stream)) st = time.time() buf_knobs = self.radioclient.getKnobs(kl) @@ -495,9 +512,9 @@ class MForm(Qt.QWidget): map(lambda x: x.value, buf_knobs.values()))) # get work time for all blocks - kl = list(map(lambda x: "%s::%swork time" % \ - (x, self._statistics_table[self._statistic]), - nodes_stream)) + kl = list(map(lambda x: "%s::%swork time" % + (x, self._statistics_table[self._statistic]), + nodes_stream)) st = time.time() wrk_knobs = self.radioclient.getKnobs(kl) td2 = time.time() - st @@ -507,18 +524,18 @@ class MForm(Qt.QWidget): if(total_work == 0): total_work = 1 work_times = dict(zip( - map(lambda x: x.split("::")[0], wrk_knobs.keys()), - map(lambda x: x.value/total_work, wrk_knobs.values()))) + map(lambda x: x.split("::")[0], wrk_knobs.keys()), + map(lambda x: x.value / total_work, wrk_knobs.values()))) work_times_padded = dict(zip( - self.G.nodes(), - [0.1]*len(self.G.nodes()))) + self.G.nodes(), + [0.1] * len(self.G.nodes()))) work_times_padded.update(work_times) for n in nodes_stream: # ne is the list of edges away from this node! - ne = self.G.edges([n],True) - #for e in ne: # iterate over edges from this block - for e in ne: # iterate over edges from this block + ne = self.G.edges([n], True) + # for e in ne: # iterate over edges from this block + for e in ne: # iterate over edges from this block # get the right output buffer/port weight for each edge sourceport = e[2]["sourceport"] if(e[2]["type"] == "stream"): @@ -526,8 +543,8 @@ class MForm(Qt.QWidget): e[2]["weight"] = newweight for n in nodes_msg: - ne = self.G.edges([n],True) - for e in ne: # iterate over edges from this block + ne = self.G.edges([n], True) + for e in ne: # iterate over edges from this block sourceport = e[2]["sourceport"] if(e[2]["type"] == "msg"): newweight = 0.01 @@ -535,8 +552,10 @@ class MForm(Qt.QWidget): # set updated weights #self.node_weights = map(lambda x: 20+2000*work_times[x], nodes_stream) - self.node_weights = list(map(lambda x: 20+2000*work_times_padded[x], self.G.nodes())) - self.edge_weights = list(map(lambda x: 100.0*x[2]["weight"], self.G.edges(data=True))) + self.node_weights = list( + map(lambda x: 20 + 2000 * work_times_padded[x], self.G.nodes())) + self.edge_weights = list( + map(lambda x: 100.0 * x[2]["weight"], self.G.edges(data=True))) # draw graph updates if(self.do_update): @@ -545,11 +564,12 @@ class MForm(Qt.QWidget): self.updateGraph() latency = td1 + td2 - self.parent.statusBar().showMessage("Current GNU Radio Control Port Query Latency: %f ms"%\ - (latency*1000)) + self.parent.statusBar().showMessage("Current GNU Radio Control Port Query Latency: %f ms" % + (latency * 1000)) except Exception as e: - sys.stderr.write("gr-perf-monitorx: lost connection ({0}).\n".format(e)) + sys.stderr.write( + "gr-perf-monitorx: lost connection ({0}).\n".format(e)) if(type(self.parent) is MAINWindow): # Find window of connection for p in self.parent.mdiArea.subWindowList(): @@ -562,15 +582,17 @@ class MForm(Qt.QWidget): return def rtt(self): - self.parent.newSubWindow(DataTableRuntimes(self.radioclient, self.G_stream), "Runtime Table") + self.parent.newSubWindow(DataTableRuntimes( + self.radioclient, self.G_stream), "Runtime Table") def bpt(self): - self.parent.newSubWindow(DataTableBuffers(self.radioclient, self.G_stream), "Buffers Table") + self.parent.newSubWindow(DataTableBuffers( + self.radioclient, self.G_stream), "Buffers Table") def resetPCs(self): knobs = [] for b in self.blocks_list: - knobs += [self.radioclient.Knob(b + "::reset_perf_counters"),] + knobs += [self.radioclient.Knob(b + "::reset_perf_counters"), ] k = self.radioclient.setKnobs(knobs) def toggleFlowgraph(self): @@ -614,13 +636,13 @@ class MForm(Qt.QWidget): host = str(askinfo.host.text()) port = str(askinfo.port.text()) try: - self.radioclient = GNURadioControlPortClient(host, port, 'thrift').client + self.radioclient = GNURadioControlPortClient( + host, port, 'thrift').client print("Connected to %s:%s" % (host, port)) except: print("Error connecting to %s:%s" % (host, port)) else: self.radioclient = radioclient - if self.radioclient is None: return @@ -635,27 +657,27 @@ class MForm(Qt.QWidget): self.layoutTop.addLayout(self.layout) self.rttAct = Qt.QAction("Runtime Table", - self, statusTip="Runtime Table", triggered=self.rtt) + self, statusTip="Runtime Table", triggered=self.rtt) self.rttBut = Qt.QToolButton() self.rttBut.setDefaultAction(self.rttAct) self.ctlBox.addWidget(self.rttBut) self.bptAct = Qt.QAction("Buffer Table", - self, statusTip="Buffer Table", triggered=self.bpt) + self, statusTip="Buffer Table", triggered=self.bpt) self.bptBut = Qt.QToolButton() self.bptBut.setDefaultAction(self.bptAct) self.ctlBox.addWidget(self.bptBut) self.resetPCsAct = Qt.QAction("Reset", self, - statusTip="Reset all Performance Counters", - triggered=self.resetPCs) + statusTip="Reset all Performance Counters", + triggered=self.resetPCs) self.resetPCsBut = Qt.QToolButton() self.resetPCsBut.setDefaultAction(self.resetPCsAct) self.ctlBox.addWidget(self.resetPCsBut) self.pauseFGAct = Qt.QAction("Pause", self, - statusTip="Pause the Flowgraph", - triggered=self.toggleFlowgraph) + statusTip="Pause the Flowgraph", + triggered=self.toggleFlowgraph) self.pauseFGAct.setCheckable(True) self.pauseFGBut = Qt.QToolButton() self.pauseFGBut.setDefaultAction(self.pauseFGAct) @@ -663,7 +685,7 @@ class MForm(Qt.QWidget): self.prevent_clock_change = True self.clockKey = None - self.clocks = {"MONOTONIC":1, "THREAD":3} + self.clocks = {"MONOTONIC": 1, "THREAD": 3} self.clockSel = Qt.QComboBox(self) list(map(lambda x: self.clockSel.addItem(x), self.clocks.keys())) self.ctlBox.addWidget(self.clockSel) @@ -691,15 +713,14 @@ class MForm(Qt.QWidget): self.timer = QtCore.QTimer() self.constupdatediv = 0 self.tableupdatediv = 0 - plotsize=250 - + plotsize = 250 # Set up the graph of blocks - input_name = lambda x: x+"::avg input % full" - output_name = lambda x: x+"::avg output % full" - wtime_name = lambda x: x+"::avg work time" - nout_name = lambda x: x+"::avg noutput_items" - nprod_name = lambda x: x+"::avg nproduced" + def input_name(x): return x + "::avg input % full" + def output_name(x): return x + "::avg output % full" + def wtime_name(x): return x + "::avg work time" + def nout_name(x): return x + "::avg noutput_items" + def nprod_name(x): return x + "::avg nproduced" tmplist = [] knobs = self.radio.getKnobs([]) @@ -719,11 +740,10 @@ class MForm(Qt.QWidget): if(input_name(blockname) in knobs): tmplist.append(blockname) - if not edgelist: - sys.stderr.write("Could not find list of edges from flowgraph. " + \ - "Make sure the option 'edges_list' is enabled " + \ - "in the ControlPort configuration.\n\n") + sys.stderr.write("Could not find list of edges from flowgraph. " + + "Make sure the option 'edges_list' is enabled " + + "in the ControlPort configuration.\n\n") sys.exit(1) self.blocks_list = tmplist @@ -736,12 +756,14 @@ class MForm(Qt.QWidget): # add stream connections for e in edges: _e = e.split("->") - edgepairs_stream.append( (_e[0].split(":")[0], _e[1].split(":")[0], {"type":"stream", "sourceport":int(_e[0].split(":")[1])}) ) + edgepairs_stream.append((_e[0].split(":")[0], _e[1].split( + ":")[0], {"type": "stream", "sourceport": int(_e[0].split(":")[1])})) # add msg connections for e in msgedges: _e = e.split("->") - edgepairs_msg.append( (_e[0].split(":")[0], _e[1].split(":")[0], {"type":"msg", "sourceport":_e[0].split(":")[1]}) ) + edgepairs_msg.append((_e[0].split(":")[0], _e[1].split(":")[0], { + "type": "msg", "sourceport": _e[0].split(":")[1]})) self.G = nx.MultiDiGraph() self.G_stream = nx.MultiDiGraph() @@ -755,14 +777,14 @@ class MForm(Qt.QWidget): n_edges = self.G.edges(data=True) for e in n_edges: - e[2]["weight"] = 5+random.random()*10 + e[2]["weight"] = 5 + random.random() * 10 self.G = nx.MultiDiGraph() self.G.add_edges_from(n_edges) - self.f = plt.figure(figsize=(10,8), dpi=90) + self.f = plt.figure(figsize=(10, 8), dpi=90) self.sp = self.f.add_subplot(111) - self.sp.autoscale_view(True,True,True) + self.sp.autoscale_view(True, True, True) self.sp.set_autoscale_on(True) self.layout.addWidget(self.f.canvas) @@ -799,26 +821,26 @@ class MForm(Qt.QWidget): thrsh = 100 if(x is not None and y is not None): - nearby = list(map(lambda z: math.sqrt( math.pow(x-z[0],2) + math.pow(y-z[1],2)), self.pos.values())) + nearby = list(map(lambda z: math.sqrt( + math.pow(x - z[0], 2) + math.pow(y - z[1], 2)), self.pos.values())) i = nearby.index(min(nearby)) if(abs(list(self.pos.values())[i][0] - x) < thrsh and - abs(list(self.pos.values())[i][1]-y) < thrsh): + abs(list(self.pos.values())[i][1] - y) < thrsh): self._current_block = list(self.pos.keys())[i] - #print "MOVING BLOCK: ", self._current_block - #print "CUR POS: ", self.pos.values()[i] + # print "MOVING BLOCK: ", self._current_block + # print "CUR POS: ", self.pos.values()[i] self._grabbed = True def mouse_move(self, event): if self._grabbed: x, y = event.xdata, event.ydata if(x is not None and y is not None): - self.pos[self._current_block] = (x,y) + self.pos[self._current_block] = (x, y) self.updateGraph() def button_release(self, event): self._grabbed = False - def openMenu(self, pos): index = self.table.treeWidget.selectedIndexes() item = self.table.treeWidget.itemFromIndex(index[0]) @@ -835,13 +857,14 @@ class MForm(Qt.QWidget): nx.draw(self.G, self.pos, edge_color=self.edge_weights, node_color='#A0CBE2', - width=list(map(lambda x: 3+math.log(x+1e-20), self.edge_weights)), + width=list( + map(lambda x: 3 + math.log(x + 1e-20), self.edge_weights)), node_shape="s", node_size=self.node_weights, edge_cmap=plt.cm.Reds, ax=self.sp, arrows=False - ) + ) nx.draw_networkx_labels(self.G, self.pos, font_size=12) @@ -859,7 +882,8 @@ class MForm(Qt.QWidget): nx.draw_networkx_edges(self.G, self.pos, edge_color=self.edge_weights, - width=list(map(lambda x: 3+math.log(x+1e-20), self.edge_weights)), + width=list( + map(lambda x: 3 + math.log(x + 1e-20), self.edge_weights)), edge_cmap=plt.cm.Reds, ax=self.sp, arrows=False) @@ -874,7 +898,8 @@ class MyApp(object): def __init__(self, args): parser = ArgumentParser(description="GNU Radio Performance Monitor") - parser.add_argument("host", nargs="?", default="localhost", help="host name or IP") + parser.add_argument("host", nargs="?", + default="localhost", help="host name or IP") parser.add_argument("port", help="port") args = parser.parse_args() @@ -882,7 +907,8 @@ class MyApp(object): signal.signal(signal.SIGTERM, signal.SIG_DFL) try: - GNURadioControlPortClient(args.host, args.port, 'thrift', self.run, Qt.QApplication(sys.argv).exec_) + GNURadioControlPortClient( + args.host, args.port, 'thrift', self.run, Qt.QApplication(sys.argv).exec_) except: print("ControlPort failed to connect. Check the config of your endpoint.") print("\t[ControlPort] on = True") @@ -894,4 +920,5 @@ class MyApp(object): def run(self, client): MAINWindow(client).show() + MyApp(sys.argv) diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/monitor.py b/gnuradio-runtime/python/gnuradio/ctrlport/monitor.py index 1310d9a28b1..58af1340047 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/monitor.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/monitor.py @@ -9,29 +9,38 @@ # -import sys, subprocess, re, signal, time, atexit, os +import sys +import subprocess +import re +import signal +import time +import atexit +import os from gnuradio import gr + class monitor(object): - def __init__(self,tool="gr-ctrlport-monitor"): + def __init__(self, tool="gr-ctrlport-monitor"): print("ControlPort Monitor running.") self.started = False self.tool = tool atexit.register(self.shutdown) # setup export prefs - gr.prefs().singleton().set_bool("ControlPort","on",True) - gr.prefs().singleton().set_bool("PerfCounters","on",True) - gr.prefs().singleton().set_bool("PerfCounters","export",True) + gr.prefs().singleton().set_bool("ControlPort", "on", True) + gr.prefs().singleton().set_bool("PerfCounters", "on", True) + gr.prefs().singleton().set_bool("PerfCounters", "export", True) if(tool == "gr-perf-monitorx"): - gr.prefs().singleton().set_bool("ControlPort","edges_list",True) + gr.prefs().singleton().set_bool("ControlPort", "edges_list", True) def start(self): try: - print("monitor::endpoints() = %s" % (gr.rpcmanager_get().endpoints())) + print("monitor::endpoints() = %s" % + (gr.rpcmanager_get().endpoints())) ep = gr.rpcmanager_get().endpoints()[0] - cmd = [self.tool, re.search(r"-h (\S+|\d+\.\d+\.\d+\.\d+)", ep).group(1), re.search(r"-p (\d+)", ep).group(1)] - print("running: %s"%(str(cmd))) + cmd = [self.tool, re.search( + r"-h (\S+|\d+\.\d+\.\d+\.\d+)", ep).group(1), re.search(r"-p (\d+)", ep).group(1)] + print("running: %s" % (str(cmd))) self.proc = subprocess.Popen(cmd) self.started = True except: diff --git a/gnuradio-runtime/python/gnuradio/eng_arg.py b/gnuradio-runtime/python/gnuradio/eng_arg.py index cefc16e2227..a86ad946071 100644 --- a/gnuradio-runtime/python/gnuradio/eng_arg.py +++ b/gnuradio-runtime/python/gnuradio/eng_arg.py @@ -14,6 +14,7 @@ import argparse from gnuradio import eng_notation + def intx(string): """ Generic integer type, will interpret string as string literal. @@ -26,6 +27,7 @@ def intx(string): "Invalid integer value: {}".format(string) ) + def eng_float(string): """ Takes a string, returns a float. Accepts engineering notation. @@ -38,4 +40,3 @@ def eng_float(string): raise argparse.ArgumentTypeError( "Invalid engineering notation value: {}".format(string) ) - diff --git a/gnuradio-runtime/python/gnuradio/eng_notation.py b/gnuradio-runtime/python/gnuradio/eng_notation.py index adf6e9572cf..c4c95e3cc93 100644 --- a/gnuradio-runtime/python/gnuradio/eng_notation.py +++ b/gnuradio-runtime/python/gnuradio/eng_notation.py @@ -24,7 +24,8 @@ scale_factor['f'] = 1e-15 scale_factor['a'] = 1e-18 -def num_to_str (n, precision=6): + +def num_to_str(n, precision=6): '''Convert a number to a string in engineering notation. E.g., 5e-9 -> 5n''' m = abs(n) format_spec = '%.' + repr(int(precision)) + 'g' @@ -50,7 +51,7 @@ def num_to_str (n, precision=6): return '%s' % float(format_spec % (n)) -def str_to_num (value): +def str_to_num(value): '''Convert a string in engineering notation to a number. E.g., '15m' -> 15e-3''' try: if not isinstance(value, str): @@ -58,8 +59,8 @@ def str_to_num (value): scale = 1.0 suffix = value[-1] if suffix in scale_factor: - return float (value[0:-1]) * scale_factor[suffix] - return float (value) + return float(value[0:-1]) * scale_factor[suffix] + return float(value) except (TypeError, KeyError, ValueError): - raise ValueError ( + raise ValueError( "Invalid engineering notation value: %r" % (value,)) diff --git a/gnuradio-runtime/python/gnuradio/eng_option.py b/gnuradio-runtime/python/gnuradio/eng_option.py index 5e7043ecd9c..5e4cdf2544b 100644 --- a/gnuradio-runtime/python/gnuradio/eng_option.py +++ b/gnuradio-runtime/python/gnuradio/eng_option.py @@ -13,23 +13,25 @@ from optparse import Option, OptionValueError from . import eng_notation -def check_eng_float (option, opt, value): + +def check_eng_float(option, opt, value): try: return eng_notation.str_to_num(value) except (ValueError, TypeError): - raise OptionValueError ( + raise OptionValueError( "option %s: invalid engineering notation value: %r" % (opt, value)) -def check_intx (option, opt, value): + +def check_intx(option, opt, value): try: - return int (value, 0) + return int(value, 0) except (ValueError, TypeError): - raise OptionValueError ( + raise OptionValueError( "option %s: invalid integer value: %r" % (opt, value)) + class eng_option (Option): TYPES = Option.TYPES + ("eng_float", "intx", "subdev") - TYPE_CHECKER = copy (Option.TYPE_CHECKER) + TYPE_CHECKER = copy(Option.TYPE_CHECKER) TYPE_CHECKER["eng_float"] = check_eng_float TYPE_CHECKER["intx"] = check_intx - diff --git a/gnuradio-runtime/python/gnuradio/gr/CMakeLists.txt b/gnuradio-runtime/python/gnuradio/gr/CMakeLists.txt index eccdcf7367a..f4898a5b2cc 100644 --- a/gnuradio-runtime/python/gnuradio/gr/CMakeLists.txt +++ b/gnuradio-runtime/python/gnuradio/gr/CMakeLists.txt @@ -28,7 +28,6 @@ if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS - ${CMAKE_BINARY_DIR}/gruel/src/python ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) diff --git a/gnuradio-runtime/python/gnuradio/gr/__init__.py b/gnuradio-runtime/python/gnuradio/gr/__init__.py index 5103bf97a74..49142c65fc5 100644 --- a/gnuradio-runtime/python/gnuradio/gr/__init__.py +++ b/gnuradio-runtime/python/gnuradio/gr/__init__.py @@ -1,5 +1,6 @@ # # Copyright 2003-2012, 2018 Free Software Foundation, Inc. +# Copyright 2021 Marcus Müller # # This file is part of GNU Radio # @@ -19,7 +20,7 @@ # If gnuradio is installed then the pybind output will be in this directory. # Otherwise it will reside in bindings/. -import os, sys +import os try: from .gr_python import * @@ -39,19 +40,7 @@ log = gr.logger("log") log.set_level(prefs().get_string("LOG", "log_level", "notset")) -log_file = gr.prefs().get_string("LOG", "log_file", ""); -if(log_file == "stderr" or log_file == "stdout"): - log.add_console_appender(log_file, "gr::log %d :%p: %m%n") -else: - log.add_file_appender(log_file, True, "%r :%p: %c{1} - %m%n") - log_debug = gr.logger("log_debug") -log_debug.set_level(prefs().get_string("LOG", "debug_level", "notset")) -log_debug_file = gr.prefs().get_string("LOG", "debug_file", ""); -if(log_debug_file == "stderr" or log_file == "stdout"): - log_debug.add_console_appender(log_debug_file, "gr::log %d :%p: %m%n") -else: - log_debug.add_file_appender(log_debug_file, True, "%r :%p: %c{1} - %m%n") io_signaturev = io_signature.makev io_signature3 = io_signature.make3 diff --git a/gnuradio-runtime/python/gnuradio/gr/bindings/basic_block_python.cc b/gnuradio-runtime/python/gnuradio/gr/bindings/basic_block_python.cc index 933d651fa75..c0dba52176f 100644 --- a/gnuradio-runtime/python/gnuradio/gr/bindings/basic_block_python.cc +++ b/gnuradio-runtime/python/gnuradio/gr/bindings/basic_block_python.cc @@ -14,7 +14,7 @@ /* BINDTOOL_GEN_AUTOMATIC(0) */ /* BINDTOOL_USE_PYGCCXML(0) */ /* BINDTOOL_HEADER_FILE(basic_block.h) */ -/* BINDTOOL_HEADER_FILE_HASH(5c1d5b8a3666a2e0e7a6fafae07afa29) */ +/* BINDTOOL_HEADER_FILE_HASH(53f812404aa54083e64261ba5b5cf26c) */ /***********************************************************************************/ #include diff --git a/gnuradio-runtime/python/gnuradio/gr/bindings/block_python.cc b/gnuradio-runtime/python/gnuradio/gr/bindings/block_python.cc index 4a602c8970c..6f70235496a 100644 --- a/gnuradio-runtime/python/gnuradio/gr/bindings/block_python.cc +++ b/gnuradio-runtime/python/gnuradio/gr/bindings/block_python.cc @@ -14,7 +14,7 @@ /* BINDTOOL_GEN_AUTOMATIC(0) */ /* BINDTOOL_USE_PYGCCXML(0) */ /* BINDTOOL_HEADER_FILE(block.h) */ -/* BINDTOOL_HEADER_FILE_HASH(1c265259ee70fb7b389cc57a9334a1f1) */ +/* BINDTOOL_HEADER_FILE_HASH(ee5f3ad6384686a28dce290f2da34ceb) */ /***********************************************************************************/ #include diff --git a/gnuradio-runtime/python/gnuradio/gr/bindings/docstrings/logger_pydoc_template.h b/gnuradio-runtime/python/gnuradio/gr/bindings/docstrings/logger_pydoc_template.h index 84d2e5e9cf6..a52071098f7 100644 --- a/gnuradio-runtime/python/gnuradio/gr/bindings/docstrings/logger_pydoc_template.h +++ b/gnuradio-runtime/python/gnuradio/gr/bindings/docstrings/logger_pydoc_template.h @@ -16,132 +16,26 @@ static const char* __doc_gr_logger = R"doc()doc"; - - -static const char* __doc_gr_logger_logger_0 = R"doc()doc"; - - -static const char* __doc_gr_logger_logger_1 = R"doc()doc"; - - +static const char* __doc_gr_logger_logger = R"doc()doc"; static const char* __doc_gr_logger_set_level = R"doc()doc"; - - static const char* __doc_gr_logger_get_level = R"doc()doc"; - - +static const char* __doc_gr_logger_get_string_level = R"doc()doc"; +static const char* __doc_gr_logger_trace = R"doc()doc"; static const char* __doc_gr_logger_debug = R"doc()doc"; - - static const char* __doc_gr_logger_info = R"doc()doc"; - - static const char* __doc_gr_logger_notice = R"doc()doc"; - - static const char* __doc_gr_logger_warn = R"doc()doc"; - - static const char* __doc_gr_logger_error = R"doc()doc"; - - static const char* __doc_gr_logger_crit = R"doc()doc"; - - static const char* __doc_gr_logger_alert = R"doc()doc"; - - static const char* __doc_gr_logger_fatal = R"doc()doc"; - - static const char* __doc_gr_logger_emerg = R"doc()doc"; - -static const char* __doc_gr_logger_errorIF = R"doc()doc"; - - -static const char* __doc_gr_logger_log_assert = R"doc()doc"; - - -static const char* __doc_gr_logger_add_console_appender = R"doc()doc"; - - -static const char* __doc_gr_logger_set_console_appender = R"doc()doc"; - - -static const char* __doc_gr_logger_add_file_appender = R"doc()doc"; - - -static const char* __doc_gr_logger_set_file_appender = R"doc()doc"; - - -static const char* __doc_gr_logger_add_rollingfile_appender = R"doc()doc"; - - -static const char* __doc_gr_logger_config = R"doc()doc"; - - -static const char* __doc_gr_logger_config_get_filename = R"doc()doc"; - - -static const char* __doc_gr_logger_config_get_watch_period = R"doc()doc"; - - -static const char* __doc_gr_logger_config_load_config = R"doc()doc"; - - -static const char* __doc_gr_logger_config_stop_watch = R"doc()doc"; - - -static const char* __doc_gr_logger_config_reset_config = R"doc()doc"; - - -static const char* __doc_gr_configure_default_loggers = R"doc()doc"; - - -static const char* __doc_gr_update_logger_alias = R"doc()doc"; - - -static const char* __doc_gr_logger_get_logger = R"doc()doc"; - - -static const char* __doc_gr_logger_load_config = R"doc()doc"; - - -static const char* __doc_gr_logger_reset_config = R"doc()doc"; - - -static const char* __doc_gr_logger_set_level_0 = R"doc()doc"; - - -static const char* __doc_gr_logger_set_level_1 = R"doc()doc"; - - -static const char* __doc_gr_logger_get_level_0 = R"doc()doc"; - - -static const char* __doc_gr_logger_get_level_1 = R"doc()doc"; - - -static const char* __doc_gr_logger_add_appender = R"doc()doc"; - - -static const char* __doc_gr_logger_set_appender = R"doc()doc"; - - -// static const char *__doc_gr_logger_add_console_appender = R"doc()doc"; - - -// static const char *__doc_gr_logger_set_console_appender = R"doc()doc"; - - -// static const char *__doc_gr_logger_add_file_appender = R"doc()doc"; - - -// static const char *__doc_gr_logger_set_file_appender = R"doc()doc"; - - -// static const char *__doc_gr_logger_add_rollingfile_appender = R"doc()doc"; - - -static const char* __doc_gr_logger_get_logger_names = R"doc()doc"; +static const char* __doc_gr_logging_singleton = R"doc()doc"; +static const char* __doc_gr_logging_default_level = R"doc()doc"; +static const char* __doc_gr_logging_debug_level = R"doc()doc"; +static const char* __doc_gr_logging_add_default_sink = R"doc()doc"; +static const char* __doc_gr_logging_add_debug_sink = R"doc()doc"; +static const char* __doc_gr_logging_add_default_console_sink = R"doc()doc"; +static const char* __doc_gr_logging_add_debug_console_sink = R"doc()doc"; +static const char* __doc_gr_logging_default_pattern = R"doc()doc"; diff --git a/gnuradio-runtime/python/gnuradio/gr/bindings/hier_block2_python.cc b/gnuradio-runtime/python/gnuradio/gr/bindings/hier_block2_python.cc index 2e4bdd3c456..3792fd00101 100644 --- a/gnuradio-runtime/python/gnuradio/gr/bindings/hier_block2_python.cc +++ b/gnuradio-runtime/python/gnuradio/gr/bindings/hier_block2_python.cc @@ -14,7 +14,7 @@ /* BINDTOOL_GEN_AUTOMATIC(0) */ /* BINDTOOL_USE_PYGCCXML(0) */ /* BINDTOOL_HEADER_FILE(hier_block2.h) */ -/* BINDTOOL_HEADER_FILE_HASH(fcc165d448a975a42255efafa8268bfd) */ +/* BINDTOOL_HEADER_FILE_HASH(dbc66ee4c3d5ca364dac05a4557c2545) */ /***********************************************************************************/ #include diff --git a/gnuradio-runtime/python/gnuradio/gr/bindings/logger_python.cc b/gnuradio-runtime/python/gnuradio/gr/bindings/logger_python.cc index cccc60fe30a..f82cfaaebf7 100644 --- a/gnuradio-runtime/python/gnuradio/gr/bindings/logger_python.cc +++ b/gnuradio-runtime/python/gnuradio/gr/bindings/logger_python.cc @@ -1,5 +1,6 @@ /* * Copyright 2020 Free Software Foundation, Inc. + * Copyright 2021 Marcus Müller * * This file is part of GNU Radio * @@ -14,152 +15,127 @@ /* BINDTOOL_GEN_AUTOMATIC(0) */ /* BINDTOOL_USE_PYGCCXML(0) */ /* BINDTOOL_HEADER_FILE(logger.h) */ -/* BINDTOOL_HEADER_FILE_HASH(6d4f118d476b888f79737f835ed27a4d) */ +/* BINDTOOL_HEADER_FILE_HASH(7f3cbb9463e52829b27c58d9dd41b422) */ /***********************************************************************************/ #include #include #include +#include namespace py = pybind11; #include +#include void bind_logger(py::module& m) { - using logger = gr::logger; - using logger_config = gr::logger_config; + py::enum_(m, "level_enum") + // Values directly from spdlog/common.h + .value("trace", spdlog::level::trace) + .value("debug", spdlog::level::debug) + .value("info", spdlog::level::info) + .value("warn", spdlog::level::warn) + .value("err", spdlog::level::err) + .value("critical", spdlog::level::critical) + .value("off", spdlog::level::off); + using logger = gr::logger; - py::class_>(m, "logger") + py::class_>(m, "logger", D(logger)) - .def(py::init(), py::arg("logger_name")) + .def(py::init(), py::arg("logger_name"), D(logger, logger)) .def(py::init(), py::arg("arg0")) - .def("set_level", &logger::set_level, py::arg("level")) - .def("get_level", &logger::get_level, py::arg("level")) - .def("debug", &logger::debug, py::arg("msg")) - .def("info", &logger::info, py::arg("msg")) - .def("notice", &logger::notice, py::arg("msg")) - .def("warn", &logger::warn, py::arg("msg")) - .def("error", &logger::error, py::arg("msg")) - .def("crit", &logger::crit, py::arg("msg")) - .def("alert", &logger::alert, py::arg("msg")) - .def("fatal", &logger::fatal, py::arg("msg")) - .def("emerg", &logger::emerg, py::arg("msg")) - .def("errorIF", &logger::errorIF, py::arg("cond"), py::arg("msg")) - .def("log_assert", &logger::log_assert, py::arg("cond"), py::arg("msg")) - .def("add_console_appender", - &logger::add_console_appender, - py::arg("target"), - py::arg("pattern")) - .def("set_console_appender", - &logger::set_console_appender, - py::arg("target"), - py::arg("pattern")) - .def("add_file_appender", - &logger::add_file_appender, - py::arg("filename"), - py::arg("append"), - py::arg("pattern")) - .def("set_file_appender", - &logger::set_file_appender, - py::arg("filename"), - py::arg("append"), - py::arg("pattern")) - .def("add_rollingfile_appender", - &logger::add_rollingfile_appender, - py::arg("filename"), - py::arg("filesize"), - py::arg("bkup_index"), - py::arg("append"), - py::arg("mode"), - py::arg("pattern")); - - - py::class_>(m, "logger_config") - - - .def_static("get_filename", &logger_config::get_filename) - .def_static("get_watch_period", &logger_config::get_watch_period) - .def_static("load_config", - &logger_config::load_config, - py::arg("filename"), - py::arg("watch_period") = 0) - .def_static("stop_watch", &logger_config::stop_watch) - .def_static("reset_config", &logger_config::reset_config); + .def("set_level", + py::overload_cast(&logger::set_level), + py::arg("level"), + D(logger, set_level)) + .def("set_level", + py::overload_cast(&logger::set_level), + py::arg("level"), + D(logger, set_level)) + .def("get_level", + py::overload_cast(&logger::get_level, py::const_), + py::arg("level"), + D(logger, get_level)) + .def("get_string_level", &logger::get_string_level, D(logger, get_string_level)) + .def( + "trace", + [](logger& log, const std::string& msg) { log.trace(msg); }, + py::arg("msg"), + D(logger, trace)) + .def( + "debug", + [](logger& log, const std::string& msg) { log.debug(msg); }, + py::arg("msg"), + D(logger, debug)) + .def( + "info", + [](logger& log, const std::string& msg) { log.info(msg); }, + py::arg("msg"), + D(logger, info)) + .def( + "notice", + [](logger& log, const std::string& msg) { log.notice(msg); }, + py::arg("msg"), + D(logger, notice)) + .def( + "warn", + [](logger& log, const std::string& msg) { log.warn(msg); }, + py::arg("msg"), + D(logger, warn)) + .def( + "error", + [](logger& log, const std::string& msg) { log.error(msg); }, + py::arg("msg"), + D(logger, error)) + .def( + "crit", + [](logger& log, const std::string& msg) { log.crit(msg); }, + py::arg("msg"), + D(logger, crit)) + .def( + "alert", + [](logger& log, const std::string& msg) { log.alert(msg); }, + py::arg("msg"), + D(logger, alert)) + .def( + "fatal", + [](logger& log, const std::string& msg) { log.fatal(msg); }, + py::arg("msg"), + D(logger, fatal)) + .def( + "emerg", + [](logger& log, const std::string& msg) { log.emerg(msg); }, + py::arg("msg"), + D(logger, emerg)); + using logging = gr::logging; - // m.def("configure_default_loggers",&gr::configure_default_loggers, - // py::arg("l"), - // py::arg("d"), - // py::arg("name") - // ); - m.def("update_logger_alias", - &gr::update_logger_alias, - py::arg("name"), - py::arg("alias")); - m.def("logger_get_logger", &gr::logger_get_logger, py::arg("name")); - m.def("logger_get_configured_logger", - &gr::logger_get_configured_logger, - py::arg("name")); - m.def("logger_load_config", &gr::logger_load_config, py::arg("config_filename") = ""); - m.def("gr_logger_reset_config", &gr_logger_reset_config); - m.def("logger_set_level", - (void (*)(gr::logger_ptr, std::string const&)) & gr::logger_set_level, - py::arg("logger"), - py::arg("level")); - m.def("logger_set_level", - (void (*)(gr::logger_ptr, log4cpp::Priority::Value)) & gr::logger_set_level, - py::arg("logger"), - py::arg("level")); - m.def("logger_get_level", - (void (*)(gr::logger_ptr, std::string&)) & gr::logger_get_level, - py::arg("logger"), - py::arg("level")); - // m.def("logger_get_level",(void (*)(gr::logger_ptr, log4cpp::Priority::Value - // &))&gr::logger_get_level, - // py::arg("logger"), - // py::arg("level") - // ); - // m.def("logger_add_appender",&gr::logger_add_appender, - // py::arg("logger"), - // py::arg("appender") - // ); // Not Implemented - // m.def("logger_set_appender",&gr::logger_set_appender, - // py::arg("logger"), - // py::arg("appender") - // ); // Not Implemented - m.def("logger_add_console_appender", - &gr::logger_add_console_appender, - py::arg("logger"), - py::arg("target"), - py::arg("pattern")); - m.def("logger_set_console_appender", - &gr::logger_set_console_appender, - py::arg("logger"), - py::arg("target"), - py::arg("pattern")); - m.def("logger_add_file_appender", - &gr::logger_add_file_appender, - py::arg("logger"), - py::arg("filename"), - py::arg("append"), - py::arg("pattern")); - m.def("logger_set_file_appender", - &gr::logger_set_file_appender, - py::arg("logger"), - py::arg("filename"), - py::arg("append"), - py::arg("pattern")); - m.def("logger_add_rollingfile_appender", - &gr::logger_add_rollingfile_appender, - py::arg("logger"), - py::arg("filename"), - py::arg("filesize"), - py::arg("bkup_index"), - py::arg("append"), - py::arg("mode"), - py::arg("pattern")); - m.def("logger_get_logger_names", &gr::logger_get_logger_names); + py::class_>(m, "logging") + .def(py::init([]() { + return std::unique_ptr(&logging::singleton()); + }), + D(logging, singleton)) + .def("default_level", &logging::default_level, D(logging, default_level)) + .def("debug_level", &logging::debug_level, D(logging, debug_level)) + .def("add_default_sink", + &logging::add_default_sink, + py::arg("sink"), + D(logging, add_default_sink)) + .def("add_debug_sink", + &logging::add_debug_sink, + py::arg("sink"), + D(logging, add_debug_sink)) + .def("add_default_console_sink", + &logging::add_default_console_sink, + D(logging, add_default_console_sink)) + .def("add_debug_console_sink", + &logging::add_debug_console_sink, + D(logging, add_debug_console_sink)) + .def_property_readonly_static( + "default_pattern", + [](py::object) { return logging::default_pattern; }, + D(logging, default_pattern)); } diff --git a/gnuradio-runtime/python/gnuradio/gr/bindings/thrift_application_base_python.cc b/gnuradio-runtime/python/gnuradio/gr/bindings/thrift_application_base_python.cc index 58042b8f619..b1ba2d2246e 100644 --- a/gnuradio-runtime/python/gnuradio/gr/bindings/thrift_application_base_python.cc +++ b/gnuradio-runtime/python/gnuradio/gr/bindings/thrift_application_base_python.cc @@ -14,7 +14,7 @@ /* BINDTOOL_GEN_AUTOMATIC(0) */ /* BINDTOOL_USE_PYGCCXML(0) */ /* BINDTOOL_HEADER_FILE(thrift_application_base.h) */ -/* BINDTOOL_HEADER_FILE_HASH(194037fee916fc62be225080aa9229fc) */ +/* BINDTOOL_HEADER_FILE_HASH(6d4665cd29822e3b0f6248bf71aad6f8) */ /***********************************************************************************/ #include diff --git a/gnuradio-runtime/python/gnuradio/gr/exceptions.py b/gnuradio-runtime/python/gnuradio/gr/exceptions.py index 5dec4a6301d..eda63b79546 100644 --- a/gnuradio-runtime/python/gnuradio/gr/exceptions.py +++ b/gnuradio-runtime/python/gnuradio/gr/exceptions.py @@ -10,6 +10,7 @@ class NotDAG (Exception): """Not a directed acyclic graph""" pass + class CantHappen (Exception): """Can't happen""" pass diff --git a/gnuradio-runtime/python/gnuradio/gr/gateway.py b/gnuradio-runtime/python/gnuradio/gr/gateway.py index 3be5e64eeb0..7091a0586cf 100644 --- a/gnuradio-runtime/python/gnuradio/gr/gateway.py +++ b/gnuradio-runtime/python/gnuradio/gr/gateway.py @@ -8,7 +8,6 @@ # - import numpy import ctypes @@ -80,7 +79,7 @@ def port_types(self, nports): return () if nports <= ntypes: return self.__types[:nports] - return self.__types + [self.__types[-1]]*(nports-ntypes) + return self.__types + [self.__types[-1]] * (nports - ntypes) def __iter__(self): """ @@ -106,7 +105,7 @@ def __init__(self, name, in_sig, out_sig, block_type): # Normalize the many Python ways of saying 'nothing' to '()' in_sig = in_sig or () out_sig = out_sig or () - + # Backward compatibility: array of type strings -> py_io_signature if type(in_sig) is py_io_signature: self.__in_sig = in_sig @@ -138,17 +137,17 @@ def to_basic_block(self): Makes this block connectable by hier/top block python """ return self.gateway.to_basic_block() - + def fixed_rate_noutput_to_ninput(self, noutput_items): return int((noutput_items * self._decim / self._interp) + self.gateway.history() - 1) def handle_forecast(self, noutput_items, ninputs): """ - This is the handler function for forecast calls from + This is the handler function for forecast calls from block_gateway in c++ across pybind11 wrappers """ return self.forecast(noutput_items, ninputs) - + # return ninput_items_required def forecast(self, noutput_items, ninputs): @@ -156,50 +155,51 @@ def forecast(self, noutput_items, ninputs): forecast is only called from a general block this is the default implementation """ - ninput_items_required = [0]*ninputs + ninput_items_required = [0] * ninputs for i in range(ninputs): - ninput_items_required[i] = noutput_items + self.gateway.history() - 1 + ninput_items_required[i] = noutput_items + \ + self.gateway.history() - 1 return ninput_items_required - def handle_general_work(self, noutput_items, - ninput_items, - input_items, - output_items): + def handle_general_work(self, noutput_items, + ninput_items, + input_items, + output_items): ninputs = len(input_items) noutputs = len(output_items) in_types = self.in_sig().port_types(ninputs) out_types = self.out_sig().port_types(noutputs) - ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p - ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p] + ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ + ctypes.py_object, ctypes.c_char_p] if self._block_type != gr.GW_BLOCK_GENERAL: - ii=[pointer_to_ndarray( - ctypes.pythonapi.PyCapsule_GetPointer(input_items[i],None), + ii = [pointer_to_ndarray( + ctypes.pythonapi.PyCapsule_GetPointer(input_items[i], None), in_types[i], self.fixed_rate_noutput_to_ninput(noutput_items) ) for i in range(ninputs)] else: - ii=[pointer_to_ndarray( - ctypes.pythonapi.PyCapsule_GetPointer(input_items[i],None), + ii = [pointer_to_ndarray( + ctypes.pythonapi.PyCapsule_GetPointer(input_items[i], None), in_types[i], ninput_items[i] ) for i in range(ninputs)] - oo=[pointer_to_ndarray( - ctypes.pythonapi.PyCapsule_GetPointer(output_items[i],None), + oo = [pointer_to_ndarray( + ctypes.pythonapi.PyCapsule_GetPointer(output_items[i], None), out_types[i], noutput_items - ) for i in range(noutputs)] + ) for i in range(noutputs)] if self._block_type != gr.GW_BLOCK_GENERAL: - r = self.work(ii,oo) + r = self.work(ii, oo) self.consume_items(r) else: - r = self.general_work(ii,oo) + r = self.general_work(ii, oo) return r @@ -224,7 +224,8 @@ def out_sig(self): return self.__out_sig def set_msg_handler(self, which_port, handler_function): - self.gateway.set_msg_handler_pybind(which_port, handler_function.__name__) + self.gateway.set_msg_handler_pybind( + which_port, handler_function.__name__) # Save handler object in class so it's not garbage collected self.msg_handlers[which_port] = handler_function @@ -247,11 +248,10 @@ def set_msg_handler(self, which_port, handler_function): # return self.gateway.produce(which_output, how_many_items) - ######################################################################## # Wrappers for the user to inherit from ######################################################################## -class basic_block(gateway_block): +class basic_block(gateway_block): """ Args: name (str): block name @@ -263,6 +263,7 @@ class basic_block(gateway_block): For backward compatibility, a sequence of numpy type names is also accepted as an io signature. """ + def __init__(self, name, in_sig, out_sig): gateway_block.__init__(self, name=name, @@ -271,10 +272,11 @@ def __init__(self, name, in_sig, out_sig): block_type=gr.GW_BLOCK_GENERAL ) - def consume_items(self, nitems ): + def consume_items(self, nitems): pass -class sync_block(gateway_block): + +class sync_block(gateway_block): """ Args: name (str): block name @@ -286,6 +288,7 @@ class sync_block(gateway_block): For backward compatibility, a sequence of numpy type names is also accepted as an io signature. """ + def __init__(self, name, in_sig, out_sig): gateway_block.__init__(self, name=name, @@ -296,7 +299,7 @@ def __init__(self, name, in_sig, out_sig): self._decim = 1 self._interp = 1 - def consume_items(self, nitems ): + def consume_items(self, nitems): if (nitems > 0): self.gateway.consume_each(nitems) @@ -313,6 +316,7 @@ class decim_block(gateway_block): For backward compatibility, a sequence of numpy type names is also accepted as an io signature. """ + def __init__(self, name, in_sig, out_sig, decim): gateway_block.__init__(self, name=name, @@ -325,7 +329,7 @@ def __init__(self, name, in_sig, out_sig, decim): self.gateway.set_relative_rate(self._interp, self._decim) self.gateway.set_output_multiple(self._interp) - def consume_items(self, nitems ): + def consume_items(self, nitems): if (nitems > 0): self.gateway.consume_each(int(nitems * self._decim)) @@ -333,7 +337,6 @@ def forecast(self, noutput_items, ninputs): return [self.fixed_rate_noutput_to_ninput(noutput_items) for ii in range(ninputs)] - class interp_block(gateway_block): """ Args: @@ -346,6 +349,7 @@ class interp_block(gateway_block): For backward compatibility, a sequence of numpy type names is also accepted as an io signature. """ + def __init__(self, name, in_sig, out_sig, interp): gateway_block.__init__(self, name=name, @@ -358,8 +362,7 @@ def __init__(self, name, in_sig, out_sig, interp): self.gateway.set_relative_rate(self._interp, self._decim) self.gateway.set_output_multiple(self._interp) - - def consume_items(self, nitems ): + def consume_items(self, nitems): if (nitems > 0): self.gateway.consume_each(int(nitems / self._interp)) diff --git a/gnuradio-runtime/python/gnuradio/gr/hier_block2.py b/gnuradio-runtime/python/gnuradio/gr/hier_block2.py index cbb6e773928..4d0f428174f 100644 --- a/gnuradio-runtime/python/gnuradio/gr/hier_block2.py +++ b/gnuradio-runtime/python/gnuradio/gr/hier_block2.py @@ -19,12 +19,14 @@ def _multiple_endpoints(func): @functools.wraps(func) def wrapped(self, *points): if not points: - raise ValueError("At least one block required for " + func.__name__) + raise ValueError( + "At least one block required for " + func.__name__) elif len(points) == 1: try: block = points[0].to_basic_block() except AttributeError: - raise ValueError("At least two endpoints required for " + func.__name__) + raise ValueError( + "At least two endpoints required for " + func.__name__) func(self, block) else: try: @@ -75,7 +77,7 @@ def __getattr__(self, name): """ Pass-through member requests to the C++ object. """ - + try: object.__getattribute__(self, "_impl") except AttributeError as exception: @@ -84,7 +86,6 @@ def __getattr__(self, name): "a derived class?".format(object.__getattribute__(self.__class__, "__name__"))) from exception return getattr(self._impl, name) - # FIXME: these should really be implemented # in the original C++ class (gr_hier_block2), then they would all be inherited here diff --git a/gnuradio-runtime/python/gnuradio/gr/packet_utils.py b/gnuradio-runtime/python/gnuradio/gr/packet_utils.py index fd7d4244803..53e053317d5 100644 --- a/gnuradio-runtime/python/gnuradio/gr/packet_utils.py +++ b/gnuradio-runtime/python/gnuradio/gr/packet_utils.py @@ -11,6 +11,7 @@ from gnuradio import gr import pmt + def make_lengthtags(lengths, offsets, tagname='length', vlen=1): tags = [] assert(len(offsets) == len(lengths)) @@ -22,26 +23,31 @@ def make_lengthtags(lengths, offsets, tagname='length', vlen=1): tags.append(tag) return tags + def string_to_vector(string): v = [] for s in string: v.append(ord(s)) return v + def strings_to_vectors(strings, tsb_tag_key): vs = [string_to_vector(string) for string in strings] return packets_to_vectors(vs, tsb_tag_key) + def vector_to_string(v): s = [] for d in v: s.append(chr(d)) return ''.join(s) + def vectors_to_strings(data, tags, tsb_tag_key): packets = vectors_to_packets(data, tags, tsb_tag_key) return [vector_to_string(packet) for packet in packets] + def count_bursts(data, tags, tsb_tag_key, vlen=1): lengthtags = [t for t in tags if pmt.symbol_to_string(t.key) == tsb_tag_key] @@ -51,7 +57,7 @@ def count_bursts(data, tags, tsb_tag_key, vlen=1): raise ValueError( "More than one tags with key {0} with the same offset={1}." .format(tsb_tag_key, tag.offset)) - lengths[tag.offset] = pmt.to_long(tag.value)*vlen + lengths[tag.offset] = pmt.to_long(tag.value) * vlen in_burst = False in_packet = False packet_length = None @@ -60,7 +66,8 @@ def count_bursts(data, tags, tsb_tag_key, vlen=1): for pos in range(len(data)): if pos in lengths: if in_packet: - print("Got tag at pos {0} current packet_pos is {1}".format(pos, packet_pos)) + print("Got tag at pos {0} current packet_pos is {1}".format( + pos, packet_pos)) raise Exception("Received packet tag while in packet.") packet_pos = -1 packet_length = lengths[pos] @@ -72,11 +79,12 @@ def count_bursts(data, tags, tsb_tag_key, vlen=1): in_burst = False if in_packet: packet_pos += 1 - if packet_pos == packet_length-1: + if packet_pos == packet_length - 1: in_packet = False packet_pos = None return burst_count + def vectors_to_packets(data, tags, tsb_tag_key, vlen=1): lengthtags = [t for t in tags if pmt.symbol_to_string(t.key) == tsb_tag_key] @@ -86,7 +94,7 @@ def vectors_to_packets(data, tags, tsb_tag_key, vlen=1): raise ValueError( "More than one tags with key {0} with the same offset={1}." .format(tsb_tag_key, tag.offset)) - lengths[tag.offset] = pmt.to_long(tag.value)*vlen + lengths[tag.offset] = pmt.to_long(tag.value) * vlen if 0 not in lengths: raise ValueError("There is no tag with key {0} and an offset of 0" .format(tsb_tag_key)) @@ -100,12 +108,13 @@ def vectors_to_packets(data, tags, tsb_tag_key, vlen=1): length = lengths[pos] if length == 0: raise ValueError("Packets cannot have zero length.") - if pos+length > len(data): + if pos + length > len(data): raise ValueError("The final packet is incomplete.") - packets.append(data[pos: pos+length]) + packets.append(data[pos: pos + length]) pos += length return packets + def packets_to_vectors(packets, tsb_tag_key, vlen=1): """ Returns a single data vector and a set of tags. If used with blocks.vector_source_X, this set of data @@ -122,4 +131,3 @@ def packets_to_vectors(packets, tsb_tag_key, vlen=1): tags.append(tag) offset = offset + len(packet) return data, tags - diff --git a/gnuradio-runtime/python/gnuradio/gr/pubsub.py b/gnuradio-runtime/python/gnuradio/gr/pubsub.py index 11f53d55977..87e99785a62 100644 --- a/gnuradio-runtime/python/gnuradio/gr/pubsub.py +++ b/gnuradio-runtime/python/gnuradio/gr/pubsub.py @@ -17,9 +17,9 @@ class pubsub(dict): def __init__(self): - self._publishers = { } - self._subscribers = { } - self._proxies = { } + self._publishers = {} + self._subscribers = {} + self._proxies = {} def __missing__(self, key, value=None): dict.__setitem__(self, key, value) @@ -41,7 +41,8 @@ def __setitem__(self, key, val): sub(val) def __getitem__(self, key): - if key not in self: self.__missing__(key) + if key not in self: + self.__missing__(key) if self._proxies[key] is not None: (p, newkey) = self._proxies[key] return p[newkey] @@ -51,7 +52,8 @@ def __getitem__(self, key): return dict.__getitem__(self, key) def publish(self, key, publisher): - if key not in self: self.__missing__(key) + if key not in self: + self.__missing__(key) if self._proxies[key] is not None: (p, newkey) = self._proxies[key] p.publish(newkey, publisher) @@ -59,7 +61,8 @@ def publish(self, key, publisher): self._publishers[key] = publisher def subscribe(self, key, subscriber): - if key not in self: self.__missing__(key) + if key not in self: + self.__missing__(key) if self._proxies[key] is not None: (p, newkey) = self._proxies[key] p.subscribe(newkey, subscriber) @@ -81,13 +84,16 @@ def unsubscribe(self, key, subscriber): self._subscribers[key].remove(subscriber) def proxy(self, key, p, newkey=None): - if key not in self: self.__missing__(key) - if newkey is None: newkey = key + if key not in self: + self.__missing__(key) + if newkey is None: + newkey = key self._proxies[key] = (p, newkey) def unproxy(self, key): self._proxies[key] = None + # Test code if __name__ == "__main__": import sys @@ -106,27 +112,28 @@ def print_len(x): class subber(object): def __init__(self, param): self._param = param + def printer(self, x): print(self._param, repr(x)) s = subber('param') o.subscribe('foo', s.printer) # The third is a lambda function - o.subscribe('foo', lambda x: sys.stdout.write('val='+repr(x)+'\n')) + o.subscribe('foo', lambda x: sys.stdout.write('val=' + repr(x) + '\n')) # Update key 'foo', will notify subscribers print("Updating 'foo' with three subscribers:") - o['foo'] = 'bar'; + o['foo'] = 'bar' # Remove first subscriber o.unsubscribe('foo', print_len) # Update now will only trigger second and third subscriber print("Updating 'foo' after removing a subscriber:") - o['foo'] = 'bar2'; + o['foo'] = 'bar2' # Publish a key as a function, in this case, a lambda function - o.publish('baz', lambda : 42) + o.publish('baz', lambda: 42) print("Published value of 'baz':", o['baz']) # Unpublish the key diff --git a/gnuradio-runtime/python/gnuradio/gr/qa_flowgraph.py b/gnuradio-runtime/python/gnuradio/gr/qa_flowgraph.py index bbf979d0eb1..78eb72222c0 100644 --- a/gnuradio-runtime/python/gnuradio/gr/qa_flowgraph.py +++ b/gnuradio-runtime/python/gnuradio/gr/qa_flowgraph.py @@ -25,5 +25,6 @@ def test_000_empty_fg(self): self.tb.start() self.tb.stop() + if __name__ == '__main__': gr_unittest.run(test_flowgraph) diff --git a/gnuradio-runtime/python/gnuradio/gr/qa_hier_block2.py b/gnuradio-runtime/python/gnuradio/gr/qa_hier_block2.py index 33a758902b0..70075013fbd 100644 --- a/gnuradio-runtime/python/gnuradio/gr/qa_hier_block2.py +++ b/gnuradio-runtime/python/gnuradio/gr/qa_hier_block2.py @@ -106,7 +106,7 @@ def test_009(self): def test_010_end_with_head(self): import math exp = 1j * 440 / 44100 - src = blocks.vector_source_c([math.e**(exp*n) for n in range(10**6)]) + src = blocks.vector_source_c([math.e**(exp * n) for n in range(10**6)]) head = blocks.head(gr.sizeof_gr_complex, 1000) test = test_hblk([gr.sizeof_gr_complex], 0) tb = gr.top_block() @@ -116,7 +116,7 @@ def test_010_end_with_head(self): def test_011_test_message_connect(self): import math exp = 1j * 440 / 44100 - src = blocks.vector_source_c([math.e**(exp*n) for n in range(10**6)]) + src = blocks.vector_source_c([math.e**(exp * n) for n in range(10**6)]) strobe = blocks.message_strobe(pmt.PMT_NIL, 100) head = blocks.head(gr.sizeof_gr_complex, 1000) test = test_hblk([gr.sizeof_gr_complex], 1) @@ -131,7 +131,7 @@ def test_011_test_message_connect(self): def test_012(self): import math exp = 1j * 440 / 44100 - src = blocks.vector_source_c([math.e**(exp*n) for n in range(10**6)]) + src = blocks.vector_source_c([math.e**(exp * n) for n in range(10**6)]) strobe = blocks.message_strobe(pmt.PMT_NIL, 100) head = blocks.head(gr.sizeof_gr_complex, 1000) test = test_hblk([gr.sizeof_gr_complex], 16) diff --git a/gnuradio-runtime/python/gnuradio/gr/qa_random.py b/gnuradio-runtime/python/gnuradio/gr/qa_random.py index d7f4bb65a5f..1f4b8aee158 100644 --- a/gnuradio-runtime/python/gnuradio/gr/qa_random.py +++ b/gnuradio-runtime/python/gnuradio/gr/qa_random.py @@ -95,10 +95,11 @@ def test_007_xoroshiro128p_range(self): N = 10**6 self.assertEqual(gr.xoroshiro128p_prng.min(), 0) - self.assertEqual(gr.xoroshiro128p_prng.max(), 2**64-1) + self.assertEqual(gr.xoroshiro128p_prng.max(), 2**64 - 1) rng = gr.xoroshiro128p_prng(42) arr = all((0 <= rng() <= 2**64 - 1 for _ in range(N))) self.assertTrue(arr) + if __name__ == '__main__': gr_unittest.run(test_random) diff --git a/gnuradio-runtime/python/gnuradio/gr/tag_utils.py b/gnuradio-runtime/python/gnuradio/gr/tag_utils.py index d48bf8eb783..7d415c28c9c 100644 --- a/gnuradio-runtime/python/gnuradio/gr/tag_utils.py +++ b/gnuradio-runtime/python/gnuradio/gr/tag_utils.py @@ -2,13 +2,16 @@ from . import gr_python as gr + class PythonTag(object): " Python container for tags " + def __init__(self): self.offset = None - self.key = None - self.value = None - self.srcid = False + self.key = None + self.value = None + self.srcid = False + def tag_to_python(tag): """ Convert a stream tag to a Python-readable object """ @@ -19,6 +22,7 @@ def tag_to_python(tag): newtag.srcid = pmt.to_python(tag.srcid) return newtag + def python_to_tag(tag_struct): """ Convert a Python list/tuple/dictionary to a stream tag. diff --git a/gnuradio-runtime/python/gnuradio/gr/top_block.py b/gnuradio-runtime/python/gnuradio/gr/top_block.py index d44c6c46d40..b3cb06d41c1 100644 --- a/gnuradio-runtime/python/gnuradio/gr/top_block.py +++ b/gnuradio-runtime/python/gnuradio/gr/top_block.py @@ -9,15 +9,16 @@ from .gr_python import (top_block_pb, - top_block_wait_unlocked, top_block_run_unlocked, - top_block_start_unlocked, top_block_stop_unlocked, - top_block_unlock_unlocked) #, dot_graph_tb) + top_block_wait_unlocked, top_block_run_unlocked, + top_block_start_unlocked, top_block_stop_unlocked, + top_block_unlock_unlocked) # , dot_graph_tb) from .hier_block2 import hier_block2 import threading from .hier_block2 import hier_block2 + class _top_block_waiter(threading.Thread): """ This kludge allows ^C to interrupt top_block.run and top_block.wait @@ -41,6 +42,7 @@ class _top_block_waiter(threading.Thread): See also top_block.wait (below), which uses this class to implement the interruptible wait. """ + def __init__(self, tb): threading.Thread.__init__(self) self.setDaemon(1) diff --git a/gnuradio-runtime/python/gnuradio/gr_unittest.py b/gnuradio-runtime/python/gnuradio/gr_unittest.py index ebd47019a5c..8a98cd473d9 100644 --- a/gnuradio-runtime/python/gnuradio/gr_unittest.py +++ b/gnuradio-runtime/python/gnuradio/gr_unittest.py @@ -17,6 +17,7 @@ # We allow snakeCase here for consistency with unittest # pylint: disable=invalid-name + class TestCase(unittest.TestCase): """A subclass of unittest.TestCase that adds additional assertions @@ -32,15 +33,14 @@ def assertComplexAlmostEqual(self, first, second, places=7, msg=None): Note that decimal places (from zero) is usually not the same as significant digits (measured from the most significant digit). """ - if round(second.real-first.real, places) != 0: + if round(second.real - first.real, places) != 0: raise self.failureException( msg or '%r != %r within %r places' % (first, second, places)) - if round(second.imag-first.imag, places) != 0: + if round(second.imag - first.imag, places) != 0: raise self.failureException( msg or '%r != %r within %r places' % (first, second, places) ) - def assertComplexAlmostEqual2(self, ref, x, abs_eps=1e-12, rel_eps=1e-6, msg=None): """ Fail if the two complex objects are unequal as determined by both @@ -50,20 +50,19 @@ def assertComplexAlmostEqual2(self, ref, x, abs_eps=1e-12, rel_eps=1e-6, msg=Non return if abs(ref) > abs_eps: - if abs(ref-x) / abs(ref) > rel_eps: + if abs(ref - x) / abs(ref) > rel_eps: raise self.failureException( msg or '%r != %r rel_error = %r rel_limit = %r' % ( - ref, x, abs(ref-x) / abs(ref), rel_eps + ref, x, abs(ref - x) / abs(ref), rel_eps ) ) else: raise self.failureException( msg or '%r != %r rel_error = %r rel_limit = %r' % ( - ref, x, abs(ref-x) / abs(ref), rel_eps + ref, x, abs(ref - x) / abs(ref), rel_eps ) ) - def assertComplexTuplesAlmostEqual(self, a, b, places=7, msg=None): """ Fail if the two complex tuples are not approximately equal. @@ -76,7 +75,6 @@ def assertComplexTuplesAlmostEqual(self, a, b, places=7, msg=None): for (x, y) in zip(a, b) ]) - def assertComplexTuplesAlmostEqual2(self, a, b, abs_eps=1e-12, rel_eps=1e-6, msg=None): """ @@ -89,7 +87,6 @@ def assertComplexTuplesAlmostEqual2(self, a, b, for (x, y) in zip(a, b) ]) - def assertFloatTuplesAlmostEqual(self, a, b, places=7, msg=None): """ Fail if the two real-valued tuples are not approximately equal. @@ -102,7 +99,6 @@ def assertFloatTuplesAlmostEqual(self, a, b, places=7, msg=None): for (x, y) in zip(a, b) ]) - def assertFloatTuplesAlmostEqual2(self, a, b, abs_eps=1e-12, rel_eps=1e-6, msg=None): self.assertEqual(len(a), len(b)) @@ -110,25 +106,25 @@ def assertFloatTuplesAlmostEqual2(self, a, b, self.assertComplexAlmostEqual2(x, y, abs_eps, rel_eps, msg) for (x, y) in zip(a, b) ]) - - + def assertSequenceEqualGR(self, data_in, data_out): - """ + """ Note this function exists because of this bug: https://bugs.python.org/issue19217 Calling self.assertEqual(seqA, seqB) can hang if seqA and seqB are not equal. """ if len(data_in) != len(data_out): - print('Lengths do not match: {:d} -- {:d}'.format(len(data_in), len(data_out))) + print( + 'Lengths do not match: {:d} -- {:d}'.format(len(data_in), len(data_out))) self.assertTrue(len(data_in) == len(data_out)) total_miscompares = 0 for idx, item in enumerate(zip(data_in, data_out)): if item[0] != item[1]: total_miscompares += 1 - print('Miscompare at: {:d} ({:d} -- {:d})'.format(idx, item[0], item[1])) + print( + 'Miscompare at: {:d} ({:d} -- {:d})'.format(idx, item[0], item[1])) if total_miscompares > 0: print('Total miscompares: {:d}'.format(total_miscompares)) self.assertTrue(total_miscompares == 0) - def waitFor( self, diff --git a/gnuradio-runtime/python/pmt/__init__.py b/gnuradio-runtime/python/pmt/__init__.py index d654ad542cd..9b313330b01 100644 --- a/gnuradio-runtime/python/pmt/__init__.py +++ b/gnuradio-runtime/python/pmt/__init__.py @@ -24,7 +24,7 @@ The PMT library supports the following major types: bool, symbol (string), integer, real, complex, null, pair, list, -vector, dict, uniform_vector, any (std::any cast) +vector, dict, uniform_vector, any (boost::any cast) ''' diff --git a/gnuradio-runtime/python/pmt/pmt_to_python.py b/gnuradio-runtime/python/pmt/pmt_to_python.py index b2777c7c4c3..5c65564940f 100644 --- a/gnuradio-runtime/python/pmt/pmt_to_python.py +++ b/gnuradio-runtime/python/pmt/pmt_to_python.py @@ -13,7 +13,9 @@ # getting the singleton locally. PMT_NIL = pmt.get_PMT_NIL() -#define missing +# define missing + + def pmt_to_tuple(p): elems = list() for i in range(pmt.length(p)): @@ -21,10 +23,12 @@ def pmt_to_tuple(p): elems.append(pmt_to_python(elem)) return tuple(elems) + def pmt_from_tuple(p): args = list(map(python_to_pmt, p)) return pmt.make_tuple(*args) + def pmt_to_vector(p): v = list() for i in range(pmt.length(p)): @@ -32,12 +36,14 @@ def pmt_to_vector(p): v.append(pmt_to_python(elem)) return v + def pmt_from_vector(p): v = pmt.make_vector(len(p), PMT_NIL) for i, elem in enumerate(p): pmt.vector_set(v, i, python_to_pmt(elem)) return v + def pmt_to_dict(p): d = dict() items = pmt.dict_items(p) @@ -48,13 +54,15 @@ def pmt_to_dict(p): d[pmt_to_python(k)] = pmt_to_python(v) return d + def pmt_from_dict(p): d = pmt.make_dict() for k, v in list(p.items()): - #dict is immutable -> therefore pmt_dict_add returns the new dict + # dict is immutable -> therefore pmt_dict_add returns the new dict d = pmt.dict_add(d, python_to_pmt(k), python_to_pmt(v)) return d + numpy_mappings = { numpy.dtype(numpy.float32): (pmt.init_f32vector, float, pmt.f32vector_elements, pmt.is_f32vector), numpy.dtype(numpy.float64): (pmt.init_f64vector, float, pmt.f64vector_elements, pmt.is_f64vector), @@ -63,15 +71,17 @@ def pmt_from_dict(p): numpy.dtype(numpy.int8): (pmt.init_s8vector, int, pmt.s8vector_elements, pmt.is_s8vector), numpy.dtype(numpy.int16): (pmt.init_s16vector, int, pmt.s16vector_elements, pmt.is_s16vector), numpy.dtype(numpy.int32): (pmt.init_s32vector, int, pmt.s32vector_elements, pmt.is_s32vector), -# numpy.dtype(numpy.int64): (pmt.init_s64vector, int, pmt.s64vector_elements, pmt.is_s64vector), + # numpy.dtype(numpy.int64): (pmt.init_s64vector, int, pmt.s64vector_elements, pmt.is_s64vector), numpy.dtype(numpy.uint8): (pmt.init_u8vector, int, pmt.u8vector_elements, pmt.is_u8vector), numpy.dtype(numpy.uint16): (pmt.init_u16vector, int, pmt.u16vector_elements, pmt.is_u16vector), numpy.dtype(numpy.uint32): (pmt.init_u32vector, int, pmt.u32vector_elements, pmt.is_u32vector), -# numpy.dtype(numpy.uint64): (pmt.init_u64vector, int, pmt.u64vector_elements, pmt.is_u64vector), + # numpy.dtype(numpy.uint64): (pmt.init_u64vector, int, pmt.u64vector_elements, pmt.is_u64vector), numpy.dtype(numpy.byte): (pmt.init_u8vector, int, pmt.u8vector_elements, pmt.is_u8vector), } -uvector_mappings = dict([ (numpy_mappings[key][3], (numpy_mappings[key][2], key)) for key in numpy_mappings ]) +uvector_mappings = dict( + [(numpy_mappings[key][3], (numpy_mappings[key][2], key)) for key in numpy_mappings]) + def numpy_to_uvector(numpy_array): try: @@ -79,18 +89,22 @@ def numpy_to_uvector(numpy_array): pc = list(map(mapping[1], numpy.ravel(numpy_array))) return mapping[0](numpy_array.size, pc) except KeyError: - raise ValueError("unsupported numpy array dtype for conversion to pmt %s"%(numpy_array.dtype)) + raise ValueError( + "unsupported numpy array dtype for conversion to pmt %s" % (numpy_array.dtype)) + def uvector_to_numpy(uvector): - match = None - for test_func in list(uvector_mappings.keys()): - if test_func(uvector): - match = uvector_mappings[test_func] - return numpy.array(match[0](uvector), dtype = match[1]) - else: - raise ValueError("unsupported uvector data type for conversion to numpy array %s"%(uvector)) - -type_mappings = ( #python type, check pmt type, to python, from python + match = None + for test_func in list(uvector_mappings.keys()): + if test_func(uvector): + match = uvector_mappings[test_func] + return numpy.array(match[0](uvector), dtype=match[1]) + else: + raise ValueError( + "unsupported uvector data type for conversion to numpy array %s" % (uvector)) + + +type_mappings = ( # python type, check pmt type, to python, from python (None, pmt.is_null, lambda x: None, lambda x: PMT_NIL), (bool, pmt.is_bool, pmt.to_bool, pmt.from_bool), (str, pmt.is_symbol, pmt.symbol_to_string, pmt.string_to_symbol), @@ -102,23 +116,29 @@ def uvector_to_numpy(uvector): (tuple, pmt.is_tuple, pmt_to_tuple, pmt_from_tuple), (list, pmt.is_vector, pmt_to_vector, pmt_from_vector), (dict, pmt.is_dict, pmt_to_dict, pmt_from_dict), - (tuple, pmt.is_pair, lambda x: (pmt_to_python(pmt.car(x)), pmt_to_python(pmt.cdr(x))), lambda x: pmt.cons(python_to_pmt(x[0]), python_to_pmt(x[1]))), + (tuple, pmt.is_pair, lambda x: (pmt_to_python(pmt.car(x)), pmt_to_python( + pmt.cdr(x))), lambda x: pmt.cons(python_to_pmt(x[0]), python_to_pmt(x[1]))), (numpy.ndarray, pmt.is_uniform_vector, uvector_to_numpy, numpy_to_uvector), ) + def pmt_to_python(p): for python_type, pmt_check, to_python, from_python in type_mappings: if pmt_check(p): try: return to_python(p) - except (RuntimeError, TypeError, ValueError): # TODO: make pybind11 handle wrong_type, convert to type error + # TODO: make pybind11 handle wrong_type, convert to type error + except (RuntimeError, TypeError, ValueError): # This exception will be handled by the general failure case pass - raise ValueError("can't convert %s type to pmt (%s)"%(type(p),p)) + raise ValueError("can't convert %s type to pmt (%s)" % (type(p), p)) + def python_to_pmt(p): for python_type, pmt_check, to_python, from_python in type_mappings: if python_type is None: - if p is None: return from_python(p) - elif isinstance(p, python_type): return from_python(p) - raise ValueError("can't convert %s type to pmt (%s)"%(type(p),p)) + if p is None: + return from_python(p) + elif isinstance(p, python_type): + return from_python(p) + raise ValueError("can't convert %s type to pmt (%s)" % (type(p), p)) diff --git a/gr-analog/examples/fm_demod.py b/gr-analog/examples/fm_demod.py index 961f06ff4d8..190febb0015 100644 --- a/gr-analog/examples/fm_demod.py +++ b/gr-analog/examples/fm_demod.py @@ -15,9 +15,12 @@ from gnuradio import audio from gnuradio.filter import firdes from gnuradio.fft import window -import sys, math +import sys +import math # Create a top_block + + class build_graph(gr.top_block): def __init__(self): gr.top_block.__init__(self) @@ -35,7 +38,7 @@ def __init__(self): # Set the demodulator using the same deviation as the receiver. max_dev = 75e3 - fm_demod_gain = input_rate / (2*math.pi*max_dev/8.0) + fm_demod_gain = input_rate / (2 * math.pi * max_dev / 8.0) fm_demod = analog.quadrature_demod_cf(fm_demod_gain) # Create a filter for the resampler and filter the audio @@ -45,8 +48,8 @@ def __init__(self): # building the filter. volume = 0.20 nfilts = 32 - resamp_taps = firdes.low_pass_2(volume*nfilts, # gain - nfilts*input_rate, # sampling rate + resamp_taps = firdes.low_pass_2(volume * nfilts, # gain + nfilts * input_rate, # sampling rate 15e3, # low pass cutoff freq 1e3, # width of trans. band 60, # stop band attenuaton @@ -64,7 +67,8 @@ def __init__(self): # now wire it all together self.connect(src, fm_demod) self.connect(fm_demod, resamp_filter) - self.connect(resamp_filter, (audio_sink,0)) + self.connect(resamp_filter, (audio_sink, 0)) + def main(args): tb = build_graph() @@ -72,7 +76,6 @@ def main(args): input('Press Enter to quit: ') tb.stop() + if __name__ == '__main__': main(sys.argv[1:]) - - diff --git a/gr-analog/examples/fmtest.py b/gr-analog/examples/fmtest.py index 0664238b6b2..a93b3ff250a 100644 --- a/gr-analog/examples/fmtest.py +++ b/gr-analog/examples/fmtest.py @@ -14,7 +14,9 @@ from gnuradio.fft import window from gnuradio import analog from gnuradio import channels -import sys, math, time +import sys +import math +import time import numpy try: @@ -32,11 +34,11 @@ def __init__(self, lo_freq, audio_rate, if_rate): gr.io_signature(1, 1, gr.sizeof_gr_complex)) fmtx = analog.nbfm_tx(audio_rate, if_rate, max_dev=5e3, - tau=75e-6, fh=0.925*if_rate/2.0) + tau=75e-6, fh=0.925 * if_rate / 2.0) # Local oscillator lo = analog.sig_source_c(if_rate, # sample rate - analog.GR_SIN_WAVE, # waveform type + analog.GR_SIN_WAVE, # waveform type lo_freq, # frequency 1.0, # amplitude 0) # DC Offset @@ -46,6 +48,7 @@ def __init__(self, lo_freq, audio_rate, if_rate): self.connect(lo, (mixer, 1)) self.connect(mixer, self) + class fmtest(gr.top_block): def __init__(self): gr.top_block.__init__(self) @@ -57,14 +60,16 @@ def __init__(self): self._N = 5 chspacing = 16000 freq = [10, 20, 30, 40, 50] - f_lo = [0, 1*chspacing, -1*chspacing, 2*chspacing, -2*chspacing] + f_lo = [0, 1 * chspacing, -1 * chspacing, + 2 * chspacing, -2 * chspacing] - self._if_rate = 4*self._N*self._audio_rate + self._if_rate = 4 * self._N * self._audio_rate # Create a signal source and frequency modulate it self.sum = blocks.add_cc() for n in range(self._N): - sig = analog.sig_source_f(self._audio_rate, analog.GR_SIN_WAVE, freq[n], 0.5) + sig = analog.sig_source_f( + self._audio_rate, analog.GR_SIN_WAVE, freq[n], 0.5) fm = fmtx(f_lo[n], self._audio_rate, self._if_rate) self.connect(sig, fm) self.connect(fm, (self.sum, n)) @@ -75,7 +80,6 @@ def __init__(self): self.connect(self.sum, self.head, self.channel, self.snk_tx) - # Design the channlizer self._M = 10 bw = chspacing / 2.0 @@ -99,10 +103,12 @@ def __init__(self): self.squelch = list() self.snks = list() for i in range(self._M): - self.fmdet.append(analog.nbfm_rx(self._audio_rate, self._chan_rate)) - self.squelch.append(analog.standard_squelch(self._audio_rate*10)) + self.fmdet.append(analog.nbfm_rx( + self._audio_rate, self._chan_rate)) + self.squelch.append(analog.standard_squelch(self._audio_rate * 10)) self.snks.append(blocks.vector_sink_f()) - self.connect((self.pfb, i), self.fmdet[i], self.squelch[i], self.snks[i]) + self.connect( + (self.pfb, i), self.fmdet[i], self.squelch[i], self.snks[i]) def num_tx_channels(self): return self._N @@ -110,6 +116,7 @@ def num_tx_channels(self): def num_rx_channels(self): return self._M + def main(): fm = fmtest() @@ -119,9 +126,9 @@ def main(): tend = time.time() if 1: - fig1 = pylab.figure(1, figsize=(12,10), facecolor="w") - fig2 = pylab.figure(2, figsize=(12,10), facecolor="w") - fig3 = pylab.figure(3, figsize=(12,10), facecolor="w") + fig1 = pylab.figure(1, figsize=(12, 10), facecolor="w") + fig2 = pylab.figure(2, figsize=(12, 10), facecolor="w") + fig3 = pylab.figure(3, figsize=(12, 10), facecolor="w") Ns = 10000 Ne = 100000 @@ -132,16 +139,16 @@ def main(): # Plot transmitted signal fs = fm._if_rate - d = fm.snk_tx.data()[Ns:Ns+Ne] + d = fm.snk_tx.data()[Ns:Ns + Ne] sp1_f = fig1.add_subplot(2, 1, 1) - X,freq = sp1_f.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, - window = lambda d: d*winfunc(fftlen), - visible=False) - X_in = 10.0*numpy.log10(abs(numpy.fft.fftshift(X))) + X, freq = sp1_f.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, + window=lambda d: d * winfunc(fftlen), + visible=False) + X_in = 10.0 * numpy.log10(abs(numpy.fft.fftshift(X))) f_in = numpy.arange(-fs / 2.0, fs / 2.0, fs / float(X_in.size)) p1_f = sp1_f.plot(f_in, X_in, "b") - sp1_f.set_xlim([min(f_in), max(f_in)+1]) + sp1_f.set_xlim([min(f_in), max(f_in) + 1]) sp1_f.set_ylim([-120.0, 20.0]) sp1_f.set_title("Input Signal", weight="bold") @@ -149,7 +156,7 @@ def main(): sp1_f.set_ylabel("Power (dBW)") Ts = 1.0 / fs - Tmax = len(d)*Ts + Tmax = len(d) * Ts t_in = numpy.arange(0, Tmax, Ts) x_in = numpy.array(d) @@ -173,16 +180,16 @@ def main(): # this is a bug, probably due to the corner cases d = fm.snks[i].data()[Ns:Ne] - sp2_f = fig2.add_subplot(Nrows, Ncols, 1+i) - X,freq = sp2_f.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs_o, - window = lambda d: d*winfunc(fftlen), - visible=False) + sp2_f = fig2.add_subplot(Nrows, Ncols, 1 + i) + X, freq = sp2_f.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs_o, + window=lambda d: d * winfunc(fftlen), + visible=False) #X_o = 10.0*numpy.log10(abs(numpy.fft.fftshift(X))) - X_o = 10.0*numpy.log10(abs(X)) + X_o = 10.0 * numpy.log10(abs(X)) #f_o = numpy.arange(-fs_o/2.0, fs_o/2.0, fs_o/float(X_o.size)) - f_o = numpy.arange(0, fs_o / 2.0, fs_o/2.0/float(X_o.size)) + f_o = numpy.arange(0, fs_o / 2.0, fs_o / 2.0 / float(X_o.size)) p2_f = sp2_f.plot(f_o, X_o, "b") - sp2_f.set_xlim([min(f_o), max(f_o)+0.1]) + sp2_f.set_xlim([min(f_o), max(f_o) + 0.1]) sp2_f.set_ylim([-120.0, 20.0]) sp2_f.grid(True) @@ -190,22 +197,20 @@ def main(): sp2_f.set_xlabel("Frequency (kHz)") sp2_f.set_ylabel("Power (dBW)") - Ts = 1.0 / fs_o - Tmax = len(d)*Ts + Tmax = len(d) * Ts t_o = numpy.arange(0, Tmax, Ts) x_t = numpy.array(d) - sp2_t = fig3.add_subplot(Nrows, Ncols, 1+i) + sp2_t = fig3.add_subplot(Nrows, Ncols, 1 + i) p2_t = sp2_t.plot(t_o, x_t.real, "b") p2_t = sp2_t.plot(t_o, x_t.imag, "r") - sp2_t.set_xlim([min(t_o), max(t_o)+1]) + sp2_t.set_xlim([min(t_o), max(t_o) + 1]) sp2_t.set_ylim([-1, 1]) sp2_t.set_xlabel("Time (s)") sp2_t.set_ylabel("Amplitude") - pylab.show() diff --git a/gr-analog/examples/tags/uhd_burst_detector.py b/gr-analog/examples/tags/uhd_burst_detector.py index 0e017e47a25..0c4a68de8f0 100644 --- a/gr-analog/examples/tags/uhd_burst_detector.py +++ b/gr-analog/examples/tags/uhd_burst_detector.py @@ -17,6 +17,7 @@ from gnuradio.filter import firdes from argparse import ArgumentParser + class uhd_burst_detector(gr.top_block): def __init__(self, uhd_address, options): @@ -42,24 +43,24 @@ def __init__(self, uhd_address, options): self.tagger = blocks.burst_tagger(gr.sizeof_gr_complex) # Dummy signaler to collect a burst on known periods - data = 1000*[0,] + 1000*[1,] + data = 1000 * [0, ] + 1000 * [1, ] self.signal = blocks.vector_source_s(data, True) # Energy detector to get signal burst - ## use squelch to detect energy - self.det = analog.simple_squelch_cc(self.threshold, 0.01) - ## convert to mag squared (float) + # use squelch to detect energy + self.det = analog.simple_squelch_cc(self.threshold, 0.01) + # convert to mag squared (float) self.c2m = blocks.complex_to_mag_squared() - ## average to debounce + # average to debounce self.avg = filter.single_pole_iir_filter_ff(0.01) - ## rescale signal for conversion to short + # rescale signal for conversion to short self.scale = blocks.multiply_const_ff(2**16) - ## signal input uses shorts + # signal input uses shorts self.f2s = blocks.float_to_short() # Use file sink burst tagger to capture bursts - self.fsnk = blocks.tagged_file_sink(gr.sizeof_gr_complex, self.samp_rate) - + self.fsnk = blocks.tagged_file_sink( + gr.sizeof_gr_complex, self.samp_rate) ################################################## # Connections @@ -81,22 +82,23 @@ def set_samp_rate(self, samp_rate): self.samp_rate = samp_rate self.uhd_src_0.set_samp_rate(self.samp_rate) + if __name__ == '__main__': parser = ArgumentParser() parser.add_argument("-a", "--address", default="addr=192.168.10.2", - help="select address of the device [default=%(default)r]") - #parser.add_argument("-A", "--antenna", default=None, + help="select address of the device [default=%(default)r]") + # parser.add_argument("-A", "--antenna", default=None, # help="select Rx Antenna (only on RFX-series boards)") parser.add_argument("-f", "--freq", type=eng_float, default=450e6, - help="set frequency to FREQ", metavar="FREQ") + help="set frequency to FREQ", metavar="FREQ") parser.add_argument("-g", "--gain", type=eng_float, default=0, - help="set gain in dB [default=%(default)r]") + help="set gain in dB [default=%(default)r]") parser.add_argument("-R", "--samp-rate", type=eng_float, default=200000, - help="set USRP sample rate [default=%(default)r]") + help="set USRP sample rate [default=%(default)r]") parser.add_argument("-t", "--threshold", type=float, default=-60, - help="Set the detection power threshold (dBm) [default=%(default)r") + help="Set the detection power threshold (dBm) [default=%(default)r") parser.add_argument("-T", "--trigger", action="store_true", default=False, - help="Use internal trigger instead of detector [default=%(default)r]") + help="Use internal trigger instead of detector [default=%(default)r]") args = parser.parse_args() uhd_addr = args.address diff --git a/gr-analog/python/analog/am_demod.py b/gr-analog/python/analog/am_demod.py index a3c2a8e9de3..34b7ddaf745 100644 --- a/gr-analog/python/analog/am_demod.py +++ b/gr-analog/python/analog/am_demod.py @@ -11,6 +11,7 @@ from gnuradio import blocks from gnuradio import filter + class am_demod_cf(gr.hier_block2): """ Generalized AM demodulation block with audio filtering. @@ -26,16 +27,18 @@ class am_demod_cf(gr.hier_block2): audio_pass: audio low pass filter passband frequency (float) audio_stop: audio low pass filter stop frequency (float) """ + def __init__(self, channel_rate, audio_decim, audio_pass, audio_stop): gr.hier_block2.__init__(self, "am_demod_cf", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_float)) # Input signature MAG = blocks.complex_to_mag() DCR = blocks.add_const_ff(-1.0) audio_taps = filter.optfir.low_pass(0.5, # Filter gain - channel_rate, # Sample rate + channel_rate, # Sample rate audio_pass, # Audio passband audio_stop, # Audio stopband 0.1, # Passband ripple @@ -44,6 +47,7 @@ def __init__(self, channel_rate, audio_decim, audio_pass, audio_stop): self.connect(self, MAG, DCR, LPF, self) + class demod_10k0a3e_cf(am_demod_cf): """ AM demodulation block, 10 KHz channel. @@ -55,7 +59,8 @@ class demod_10k0a3e_cf(am_demod_cf): channel_rate: incoming sample rate of the AM baseband (integer) audio_decim: input to output decimation rate (integer) """ + def __init__(self, channel_rate, audio_decim): am_demod_cf.__init__(self, channel_rate, audio_decim, - 5000, # Audio passband - 5500) # Audio stopband + 5000, # Audio passband + 5500) # Audio stopband diff --git a/gr-analog/python/analog/fm_demod.py b/gr-analog/python/analog/fm_demod.py index 96fed682ff4..e829871df80 100644 --- a/gr-analog/python/analog/fm_demod.py +++ b/gr-analog/python/analog/fm_demod.py @@ -34,13 +34,15 @@ class fm_demod_cf(gr.hier_block2): gain: gain applied to audio output (default = 1.0) (float) tau: deemphasis time constant (default = 75e-6), specify tau=0.0 to prevent deemphasis (float) """ + def __init__(self, channel_rate, audio_decim, deviation, audio_pass, audio_stop, gain=1.0, tau=75e-6): gr.hier_block2.__init__(self, "fm_demod_cf", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_float)) # Output signature - k = channel_rate / (2*pi*deviation) + k = channel_rate / (2 * pi * deviation) QUAD = analog.quadrature_demod_cf(k) audio_taps = filter.optfir.low_pass( @@ -72,6 +74,7 @@ class demod_20k0f3e_cf(fm_demod_cf): sample_rate: incoming sample rate of the FM baseband (integer) audio_decim: input to output decimation rate (integer) """ + def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 5000, # Deviation @@ -91,6 +94,7 @@ class demod_200kf3e_cf(fm_demod_cf): sample_rate: incoming sample rate of the FM baseband (integer) audio_decim: input to output decimation rate (integer) """ + def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 75000, # Deviation diff --git a/gr-analog/python/analog/fm_emph.py b/gr-analog/python/analog/fm_emph.py index 9c1107bb14d..a581bdf2ac6 100644 --- a/gr-analog/python/analog/fm_emph.py +++ b/gr-analog/python/analog/fm_emph.py @@ -16,22 +16,22 @@ class fm_deemph(gr.hier_block2): r""" FM Deemphasis IIR filter - + Args: fs: sampling frequency in Hz (float) tau: Time constant in seconds (75us in US, 50us in EUR) (float) - + An analog deemphasis filter: - + R o------/\/\/\/---+----o | = C | --- - + Has this transfer function: - + 1 1 ---- --- RC tau @@ -39,39 +39,39 @@ class fm_deemph(gr.hier_block2): 1 1 s + ---- s + --- RC tau - + And has its -3 dB response, due to the pole, at - + |H(j w_c)|^2 = 1/2 => s = j w_c = j (1/(RC)) - + Historically, this corner frequency of analog audio deemphasis filters been specified by the RC time constant used, called tau. So w_c = 1/tau. - + FWIW, for standard tau values, some standard analog components would be: tau = 75 us = (50K)(1.5 nF) = (50 ohms)(1.5 uF) tau = 50 us = (50K)(1.0 nF) = (50 ohms)(1.0 uF) - + In specifying tau for this digital deemphasis filter, tau specifies the *digital* corner frequency, w_c, desired. - + The digital deemphasis filter design below, uses the "bilinear transformation" method of designing digital filters: - + 1. Convert digital specifications into the analog domain, by prewarping digital frequency specifications into analog frequencies. - + w_a = (2/T)tan(wT/2) - + 2. Use an analog filter design technique to design the filter. - + 3. Use the bilinear transformation to convert the analog filter design to a digital filter design. - + H(z) = H(s)| s = (2/T)(1-z^-1)/(1+z^-1) - - + + w_ca 1 1 - (-1) z^-1 H(z) = ---- * ----------- * ----------------------- 2 fs -w_ca -w_ca @@ -81,20 +81,21 @@ class fm_deemph(gr.hier_block2): -w_ca 1 - ----- 2 fs - + We use this design technique, because it is an easy way to obtain a filter design with the -6 dB/octave roll-off required of the deemphasis filter. - + Jackson, Leland B., _Digital_Filters_and_Signal_Processing_Second_Edition_, Kluwer Academic Publishers, 1989, pp 201-212 - + Orfanidis, Sophocles J., _Introduction_to_Signal_Processing_, Prentice Hall, 1996, pp 573-583 """ def __init__(self, fs, tau=75e-6): gr.hier_block2.__init__(self, "fm_deemph", - gr.io_signature(1, 1, gr.sizeof_float), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(1, 1, gr.sizeof_float)) # Output signature # Digital corner frequency @@ -111,8 +112,8 @@ def __init__(self, fs, tau=75e-6): p1 = (1.0 + k) / (1.0 - k) b0 = -k / (1.0 - k) - btaps = [ b0 * 1.0, b0 * -z1 ] - ataps = [ 1.0, -p1 ] + btaps = [b0 * 1.0, b0 * -z1] + ataps = [1.0, -p1] # Since H(s = 0) = 1.0, then H(z = 1) = 1.0 and has 0 dB gain at DC @@ -120,18 +121,17 @@ def __init__(self, fs, tau=75e-6): self.connect(self, deemph, self) - class fm_preemph(gr.hier_block2): r""" FM Preemphasis IIR filter. - + Args: fs: sampling frequency in Hz (float) tau: Time constant in seconds (75us in US, 50us in EUR) (float) - fh: High frequency at which to flatten out (< 0 means default of 0.925*fs/2.0) (float) - + fh: High frequency at which to flatten out (< 0 means default of 0.925*fs/2.0) (float) + An analog preemphasis filter, that flattens out again at the high end: - + C +-----||------+ | | @@ -144,12 +144,12 @@ class fm_preemph(gr.hier_block2): \ | o--------------------------+--------o - + (This fine ASCII rendition is based on Figure 5-15 in "Digital and Analog Communication Systems", Leon W. Couch II) - + Has this transfer function: - + 1 s + --- R1C @@ -157,58 +157,58 @@ class fm_preemph(gr.hier_block2): 1 R1 s + --- (1 + --) R1C R2 - - + + It has a corner due to the numerator, where the rise starts, at - + |Hn(j w_cl)|^2 = 2*|Hn(0)|^2 => s = j w_cl = j (1/(R1C)) - + It has a corner due to the denominator, where it levels off again, at - + |Hn(j w_ch)|^2 = 1/2*|Hd(0)|^2 => s = j w_ch = j (1/(R1C) * (1 + R1/R2)) - + Historically, the corner frequency of analog audio preemphasis filters been specified by the R1C time constant used, called tau. - + So w_cl = 1/tau = 1/R1C; f_cl = 1/(2*pi*tau) = 1/(2*pi*R1*C) w_ch = 1/tau2 = (1+R1/R2)/R1C; f_ch = 1/(2*pi*tau2) = (1+R1/R2)/(2*pi*R1*C) - + and note f_ch = f_cl * (1 + R1/R2). - + For broadcast FM audio, tau is 75us in the United States and 50us in Europe. f_ch should be higher than our digital audio bandwidth. - + The Bode plot looks like this: - - + + /---------------- / / <-- slope = 20dB/decade / -------------/ f_cl f_ch - + In specifying tau for this digital preemphasis filter, tau specifies the *digital* corner frequency, w_cl, desired. - + The digital preemphasis filter design below, uses the "bilinear transformation" method of designing digital filters: - + 1. Convert digital specifications into the analog domain, by prewarping digital frequency specifications into analog frequencies. - + w_a = (2/T)tan(wT/2) - + 2. Use an analog filter design technique to design the filter. - + 3. Use the bilinear transformation to convert the analog filter design to a digital filter design. - + H(z) = H(s)| s = (2/T)(1-z^-1)/(1+z^-1) - - + + -w_cla 1 + ------ 2 fs @@ -224,19 +224,21 @@ class fm_preemph(gr.hier_block2): -w_cha 1 - ------ 2 fs - + We use this design technique, because it is an easy way to obtain a filter design with the 6 dB/octave rise required of the premphasis filter. - + Jackson, Leland B., _Digital_Filters_and_Signal_Processing_Second_Edition_, Kluwer Academic Publishers, 1989, pp 201-212 - + Orfanidis, Sophocles J., _Introduction_to_Signal_Processing_, Prentice Hall, 1996, pp 573-583 """ + def __init__(self, fs, tau=75e-6, fh=-1.0): gr.hier_block2.__init__(self, "fm_preemph", - gr.io_signature(1, 1, gr.sizeof_float), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(1, 1, gr.sizeof_float)) # Output signature # Set fh to something sensible, if needed. @@ -244,7 +246,7 @@ def __init__(self, fs, tau=75e-6, fh=-1.0): # at z = -1.0 or z = 1.0 respectively. That makes the filter unstable # and useless. if fh <= 0.0 or fh >= fs / 2.0: - fh = 0.925 * fs/2.0 + fh = 0.925 * fs / 2.0 # Digital corner frequencies w_cl = 1.0 / tau @@ -268,11 +270,11 @@ def __init__(self, fs, tau=75e-6, fh=-1.0): # That isn't what users are going to expect, so adjust with a # gain, g, so that H(z = 1) = 1.0 for 0 dB gain at DC. w_0dB = 2.0 * math.pi * 0.0 - g = abs(1.0 - p1 * cmath.rect(1.0, -w_0dB)) \ + g = abs(1.0 - p1 * cmath.rect(1.0, -w_0dB)) \ / (b0 * abs(1.0 - z1 * cmath.rect(1.0, -w_0dB))) - btaps = [ g * b0 * 1.0, g * b0 * -z1 ] - ataps = [ 1.0, -p1 ] + btaps = [g * b0 * 1.0, g * b0 * -z1] + ataps = [1.0, -p1] preemph = filter.iir_filter_ffd(btaps, ataps, False) self.connect(self, preemph, self) diff --git a/gr-analog/python/analog/nbfm_rx.py b/gr-analog/python/analog/nbfm_rx.py index 72b2dcc936e..232c8ab7255 100644 --- a/gr-analog/python/analog/nbfm_rx.py +++ b/gr-analog/python/analog/nbfm_rx.py @@ -38,9 +38,11 @@ class nbfm_rx(gr.hier_block2): deemph audio_filter """ + def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=5e3): gr.hier_block2.__init__(self, "nbfm_rx", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_float)) # Output signature # FIXME audio_rate and quad_rate ought to be exact rationals @@ -48,13 +50,14 @@ def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=5e3): self._quad_rate = quad_rate = int(quad_rate) if quad_rate % audio_rate != 0: - raise ValueError("quad_rate is not an integer multiple of audio_rate") + raise ValueError( + "quad_rate is not an integer multiple of audio_rate") squelch_threshold = 20 # dB #self.squelch = analog.simple_squelch_cc(squelch_threshold, 0.001) # FM Demodulator input: complex; output: float - k = quad_rate / (2*math.pi*max_dev) + k = quad_rate / (2 * math.pi * max_dev) self.quad_demod = analog.quadrature_demod_cf(k) # FM Deemphasis IIR filter @@ -74,8 +77,9 @@ def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=5e3): # input: float; output: float; taps: float self.audio_filter = filter.fir_filter_fff(audio_decim, audio_taps) - self.connect(self, self.quad_demod, self.deemph, self.audio_filter, self) + self.connect(self, self.quad_demod, self.deemph, + self.audio_filter, self) def set_max_deviation(self, max_dev): - k = self._quad_rate / (2*math.pi*max_dev) + k = self._quad_rate / (2 * math.pi * max_dev) self.quad_demod.set_gain(k) diff --git a/gr-analog/python/analog/nbfm_tx.py b/gr-analog/python/analog/nbfm_tx.py index df7c6c6a580..653fb2c5dc6 100644 --- a/gr-analog/python/analog/nbfm_tx.py +++ b/gr-analog/python/analog/nbfm_tx.py @@ -32,23 +32,26 @@ class nbfm_tx(gr.hier_block2): quad_rate must be an integer multiple of audio_rate. """ + def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=5e3, fh=-1.0): gr.hier_block2.__init__(self, "nbfm_tx", - gr.io_signature(1, 1, gr.sizeof_float), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_float), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature # FIXME audio_rate and quad_rate ought to be exact rationals self._audio_rate = audio_rate = int(audio_rate) self._quad_rate = quad_rate = int(quad_rate) if quad_rate % audio_rate != 0: - raise ValueError("quad_rate is not an integer multiple of audio_rate") - + raise ValueError( + "quad_rate is not an integer multiple of audio_rate") do_interp = audio_rate != quad_rate if do_interp: - interp_factor = int(quad_rate / audio_rate) # force integer + # force integer + interp_factor = int(quad_rate / audio_rate) interp_taps = filter.optfir.low_pass(interp_factor, # gain quad_rate, # Fs 4500, # passband cutoff @@ -57,7 +60,8 @@ def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=5e3, fh=-1.0): 40) # stopband atten dB #print("len(interp_taps) =", len(interp_taps)) - self.interpolator = filter.interp_fir_filter_fff (interp_factor, interp_taps) + self.interpolator = filter.interp_fir_filter_fff( + interp_factor, interp_taps) self.preemph = fm_preemph(quad_rate, tau=tau, fh=fh) @@ -65,7 +69,8 @@ def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=5e3, fh=-1.0): self.modulator = analog.frequency_modulator_fc(k) if do_interp: - self.connect(self, self.interpolator, self.preemph, self.modulator, self) + self.connect(self, self.interpolator, + self.preemph, self.modulator, self) else: self.connect(self, self.preemph, self.modulator, self) @@ -74,12 +79,12 @@ def set_max_deviation(self, max_dev): self.modulator.set_sensitivity(k) - class ctcss_gen_f(gr.hier_block2): def __init__(self, sample_rate, tone_freq): gr.hier_block2.__init__(self, "ctcss_gen_f", - gr.io_signature(0, 0, 0), # Input signature - gr.io_signature(1, 1, gr.sizeof_float)) # Output signature + # Input signature + gr.io_signature(0, 0, 0), + gr.io_signature(1, 1, gr.sizeof_float)) # Output signature self.plgen = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, tone_freq, 0.1, 0.0) diff --git a/gr-analog/python/analog/qa_agc.py b/gr-analog/python/analog/qa_agc.py index 9368dd5d2a8..b6d1f8957be 100644 --- a/gr-analog/python/analog/qa_agc.py +++ b/gr-analog/python/analog/qa_agc.py @@ -369,7 +369,7 @@ def test_005(self): tb = self.tb expected_result = \ - ((100+0j), + ((100 + 0j), (0.8090173602104187 + 0.5877856016159058j), (0.3090175688266754 + 0.9510582685470581j), (-0.309017539024353 + 0.9510582089424133j), diff --git a/gr-analog/python/analog/standard_squelch.py b/gr-analog/python/analog/standard_squelch.py index 49c4b589b75..e70efce7009 100644 --- a/gr-analog/python/analog/standard_squelch.py +++ b/gr-analog/python/analog/standard_squelch.py @@ -12,26 +12,33 @@ from gnuradio import blocks from gnuradio import filter + class standard_squelch(gr.hier_block2): def __init__(self, audio_rate): gr.hier_block2.__init__(self, "standard_squelch", - gr.io_signature(1, 1, gr.sizeof_float), # Input signature - gr.io_signature(1, 1, gr.sizeof_float)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_float), + gr.io_signature(1, 1, gr.sizeof_float)) # Output signature self.input_node = blocks.add_const_ff(0) # FIXME kludge - self.low_iir = filter.iir_filter_ffd((0.0193,0,-0.0193),(1,1.9524,-0.9615)) + self.low_iir = filter.iir_filter_ffd( + (0.0193, 0, -0.0193), (1, 1.9524, -0.9615)) self.low_square = blocks.multiply_ff() - self.low_smooth = filter.single_pole_iir_filter_ff(1 / (0.01*audio_rate)) # 100ms time constant + self.low_smooth = filter.single_pole_iir_filter_ff( + 1 / (0.01 * audio_rate)) # 100ms time constant - self.hi_iir = filter.iir_filter_ffd((0.0193,0,-0.0193),(1,1.3597,-0.9615)) + self.hi_iir = filter.iir_filter_ffd( + (0.0193, 0, -0.0193), (1, 1.3597, -0.9615)) self.hi_square = blocks.multiply_ff() - self.hi_smooth = filter.single_pole_iir_filter_ff(1 / (0.01*audio_rate)) + self.hi_smooth = filter.single_pole_iir_filter_ff( + 1 / (0.01 * audio_rate)) - self.sub = blocks.sub_ff(); - self.add = blocks.add_ff(); - self.gate = blocks.threshold_ff(0.3,0.43,0) - self.squelch_lpf = filter.single_pole_iir_filter_ff(1 / (0.01*audio_rate)) + self.sub = blocks.sub_ff() + self.add = blocks.add_ff() + self.gate = blocks.threshold_ff(0.3, 0.43, 0) + self.squelch_lpf = filter.single_pole_iir_filter_ff( + 1 / (0.01 * audio_rate)) self.div = blocks.divide_ff() self.squelch_mult = blocks.multiply_ff() @@ -39,21 +46,22 @@ def __init__(self, audio_rate): self.connect(self, self.input_node) self.connect(self.input_node, (self.squelch_mult, 0)) - self.connect(self.input_node,self.low_iir) - self.connect(self.low_iir,(self.low_square,0)) - self.connect(self.low_iir,(self.low_square,1)) - self.connect(self.low_square,self.low_smooth,(self.sub,0)) - self.connect(self.low_smooth, (self.add,0)) + self.connect(self.input_node, self.low_iir) + self.connect(self.low_iir, (self.low_square, 0)) + self.connect(self.low_iir, (self.low_square, 1)) + self.connect(self.low_square, self.low_smooth, (self.sub, 0)) + self.connect(self.low_smooth, (self.add, 0)) - self.connect(self.input_node,self.hi_iir) - self.connect(self.hi_iir,(self.hi_square,0)) - self.connect(self.hi_iir,(self.hi_square,1)) - self.connect(self.hi_square,self.hi_smooth,(self.sub,1)) - self.connect(self.hi_smooth, (self.add,1)) + self.connect(self.input_node, self.hi_iir) + self.connect(self.hi_iir, (self.hi_square, 0)) + self.connect(self.hi_iir, (self.hi_square, 1)) + self.connect(self.hi_square, self.hi_smooth, (self.sub, 1)) + self.connect(self.hi_smooth, (self.add, 1)) self.connect(self.sub, (self.div, 0)) self.connect(self.add, (self.div, 1)) - self.connect(self.div, self.gate, self.squelch_lpf, (self.squelch_mult,1)) + self.connect(self.div, self.gate, self.squelch_lpf, + (self.squelch_mult, 1)) self.connect(self.squelch_mult, self) def set_threshold(self, threshold): diff --git a/gr-analog/python/analog/wfm_rcv.py b/gr-analog/python/analog/wfm_rcv.py index 34ba9787dbd..d6e81ea7cdc 100644 --- a/gr-analog/python/analog/wfm_rcv.py +++ b/gr-analog/python/analog/wfm_rcv.py @@ -17,7 +17,7 @@ class wfm_rcv(gr.hier_block2): - def __init__ (self, quad_rate, audio_decimation): + def __init__(self, quad_rate, audio_decimation): """ Hierarchical block for demodulating a broadcast FM signal. @@ -29,7 +29,8 @@ def __init__ (self, quad_rate, audio_decimation): audio_decimation: how much to decimate quad_rate to get to audio. (integer) """ gr.hier_block2.__init__(self, "wfm_rcv", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_float)) # Output signature if audio_decimation != int(audio_decimation): raise ValueError("audio_decimation needs to be an integer") @@ -38,10 +39,9 @@ def __init__ (self, quad_rate, audio_decimation): volume = 20. max_dev = 75e3 - fm_demod_gain = quad_rate / (2*math.pi*max_dev) + fm_demod_gain = quad_rate / (2 * math.pi * max_dev) audio_rate = quad_rate / audio_decimation - # We assign to self so that outsiders can grab the demodulator # if they need to. E.g., to plot its output. # @@ -59,6 +59,7 @@ def __init__ (self, quad_rate, audio_decimation): width_of_transition_band, fft.window.WIN_HAMMING) # input: float; output: float - self.audio_filter = filter.fir_filter_fff(audio_decimation, audio_coeffs) + self.audio_filter = filter.fir_filter_fff( + audio_decimation, audio_coeffs) - self.connect (self, self.fm_demod, self.audio_filter, self.deemph, self) + self.connect(self, self.fm_demod, self.audio_filter, self.deemph, self) diff --git a/gr-analog/python/analog/wfm_rcv_fmdet.py b/gr-analog/python/analog/wfm_rcv_fmdet.py index 3b587cc44c5..d9289aa3338 100644 --- a/gr-analog/python/analog/wfm_rcv_fmdet.py +++ b/gr-analog/python/analog/wfm_rcv_fmdet.py @@ -19,7 +19,7 @@ class wfm_rcv_fmdet(gr.hier_block2): - def __init__ (self, demod_rate, audio_decimation): + def __init__(self, demod_rate, audio_decimation): """ Hierarchical block for demodulating a broadcast FM signal. @@ -32,9 +32,10 @@ def __init__ (self, demod_rate, audio_decimation): audio_decimation: how much to decimate demod_rate to get to audio. (integer) """ gr.hier_block2.__init__(self, "wfm_rcv_fmdet", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(2, 2, gr.sizeof_float)) # Output signature - + if audio_decimation != int(audio_decimation): raise ValueError("audio_decimation needs to be an integer") audio_decimation = int(audio_decimation) @@ -51,26 +52,27 @@ def __init__ (self, demod_rate, audio_decimation): self.fm_demod = analog.fmdet_cf(demod_rate, lowfreq, highfreq, 0.05) # input: float; output: float - self.deemph_Left = fm_deemph(audio_rate) + self.deemph_Left = fm_deemph(audio_rate) self.deemph_Right = fm_deemph(audio_rate) # compute FIR filter taps for audio filter width_of_transition_band = audio_rate / 32 - audio_coeffs = filter.firdes.low_pass(1.0 , # gain + audio_coeffs = filter.firdes.low_pass(1.0, # gain demod_rate, # sampling rate - 15000 , + 15000, width_of_transition_band, fft.window.WIN_HAMMING) # input: float; output: float - self.audio_filter = filter.fir_filter_fff(audio_decimation, audio_coeffs) + self.audio_filter = filter.fir_filter_fff( + audio_decimation, audio_coeffs) if 1: # Pick off the stereo carrier/2 with this filter. It # attenuated 10 dB so apply 10 dB gain We pick off the # negative frequency half because we want to base band by # it! - ## NOTE THIS WAS HACKED TO OFFSET INSERTION LOSS DUE TO - ## DEEMPHASIS + # NOTE THIS WAS HACKED TO OFFSET INSERTION LOSS DUE TO + # DEEMPHASIS stereo_carrier_filter_coeffs = \ filter.firdes.complex_band_pass(10.0, @@ -80,9 +82,9 @@ def __init__ (self, demod_rate, audio_decimation): width_of_transition_band, fft.window.WIN_HAMMING) - #print "len stereo carrier filter = ",len(stereo_carrier_filter_coeffs) - #print "stereo carrier filter ", stereo_carrier_filter_coeffs - #print "width of transition band = ",width_of_transition_band, " audio rate = ", audio_rate + # print "len stereo carrier filter = ",len(stereo_carrier_filter_coeffs) + # print "stereo carrier filter ", stereo_carrier_filter_coeffs + # print "width of transition band = ",width_of_transition_band, " audio rate = ", audio_rate # Pick off the double side band suppressed carrier # Left-Right audio. It is attenuated 10 dB so apply 10 dB @@ -91,12 +93,12 @@ def __init__ (self, demod_rate, audio_decimation): stereo_dsbsc_filter_coeffs = \ filter.firdes.complex_band_pass(20.0, demod_rate, - 38000-15000 / 2, - 38000+15000 / 2, + 38000 - 15000 / 2, + 38000 + 15000 / 2, width_of_transition_band, fft.window.WIN_HAMMING) - #print "len stereo dsbsc filter = ",len(stereo_dsbsc_filter_coeffs) - #print "stereo dsbsc filter ", stereo_dsbsc_filter_coeffs + # print "len stereo dsbsc filter = ",len(stereo_dsbsc_filter_coeffs) + # print "stereo dsbsc filter ", stereo_dsbsc_filter_coeffs # construct overlap add filter system from coefficients # for stereo carrier @@ -106,7 +108,7 @@ def __init__ (self, demod_rate, audio_decimation): # carrier is twice the picked off carrier so arrange to do # a complex multiply - self.stereo_carrier_generator = blocks.multiply_cc(); + self.stereo_carrier_generator = blocks.multiply_cc() # Pick off the rds signal stereo_rds_filter_coeffs = \ @@ -116,90 +118,96 @@ def __init__ (self, demod_rate, audio_decimation): 57000 + 1500, width_of_transition_band, fft.window.WIN_HAMMING) - #print "len stereo dsbsc filter = ",len(stereo_dsbsc_filter_coeffs) - #print "stereo dsbsc filter ", stereo_dsbsc_filter_coeffs + # print "len stereo dsbsc filter = ",len(stereo_dsbsc_filter_coeffs) + # print "stereo dsbsc filter ", stereo_dsbsc_filter_coeffs # construct overlap add filter system from coefficients for stereo carrier self.rds_signal_filter = \ filter.fir_filter_fcc(audio_decimation, stereo_rds_filter_coeffs) - self.rds_carrier_generator = blocks.multiply_cc(); - self.rds_signal_generator = blocks.multiply_cc(); - self_rds_signal_processor = blocks.null_sink(gr.sizeof_gr_complex); + self.rds_carrier_generator = blocks.multiply_cc() + self.rds_signal_generator = blocks.multiply_cc() + self_rds_signal_processor = blocks.null_sink(gr.sizeof_gr_complex) - loop_bw = 2*math.pi/100.0 - max_freq = -2.0*math.pi*18990/audio_rate; - min_freq = -2.0*math.pi*19010/audio_rate; + loop_bw = 2 * math.pi / 100.0 + max_freq = -2.0 * math.pi * 18990 / audio_rate + min_freq = -2.0 * math.pi * 19010 / audio_rate self.stereo_carrier_pll_recovery = analog.pll_refout_cc(loop_bw, max_freq, - min_freq); + min_freq) - #self.stereo_carrier_pll_recovery.squelch_enable(False) - ##pll_refout does not have squelch yet, so disabled for - #now + # self.stereo_carrier_pll_recovery.squelch_enable(False) + # pll_refout does not have squelch yet, so disabled for + # now # set up mixer (multiplier) to get the L-R signal at # baseband - self.stereo_basebander = blocks.multiply_cc(); + self.stereo_basebander = blocks.multiply_cc() # pick off the real component of the basebanded L-R # signal. The imaginary SHOULD be zero - self.LmR_real = blocks.complex_to_real(); - self.Make_Left = blocks.add_ff(); - self.Make_Right = blocks.sub_ff(); + self.LmR_real = blocks.complex_to_real() + self.Make_Left = blocks.add_ff() + self.Make_Right = blocks.sub_ff() self.stereo_dsbsc_filter = \ filter.fir_filter_fcc(audio_decimation, stereo_dsbsc_filter_coeffs) - if 1: # send the real signal to complex filter to pick off the # carrier and then to one side of a multiplier self.connect(self, self.fm_demod, self.stereo_carrier_filter, self.stereo_carrier_pll_recovery, - (self.stereo_carrier_generator,0)) + (self.stereo_carrier_generator, 0)) # send the already filtered carrier to the otherside of the carrier # the resulting signal from this multiplier is the carrier # with correct phase but at -38000 Hz. - self.connect(self.stereo_carrier_pll_recovery, (self.stereo_carrier_generator,1)) + self.connect(self.stereo_carrier_pll_recovery, + (self.stereo_carrier_generator, 1)) # send the new carrier to one side of the mixer (multiplier) - self.connect(self.stereo_carrier_generator, (self.stereo_basebander,0)) + self.connect(self.stereo_carrier_generator, + (self.stereo_basebander, 0)) # send the demphasized audio to the DSBSC pick off filter, the complex # DSBSC signal at +38000 Hz is sent to the other side of the mixer/multiplier # the result is BASEBANDED DSBSC with phase zero! - self.connect(self.fm_demod,self.stereo_dsbsc_filter, (self.stereo_basebander,1)) + self.connect(self.fm_demod, self.stereo_dsbsc_filter, + (self.stereo_basebander, 1)) # Pick off the real part since the imaginary is # theoretically zero and then to one side of a summer - self.connect(self.stereo_basebander, self.LmR_real, (self.Make_Left,0)) + self.connect(self.stereo_basebander, + self.LmR_real, (self.Make_Left, 0)) - #take the same real part of the DSBSC baseband signal and - #send it to negative side of a subtracter - self.connect(self.LmR_real,(self.Make_Right,1)) + # take the same real part of the DSBSC baseband signal and + # send it to negative side of a subtracter + self.connect(self.LmR_real, (self.Make_Right, 1)) # Make rds carrier by taking the squared pilot tone and # multiplying by pilot tone - self.connect(self.stereo_basebander,(self.rds_carrier_generator,0)) - self.connect(self.stereo_carrier_pll_recovery,(self.rds_carrier_generator,1)) + self.connect(self.stereo_basebander, + (self.rds_carrier_generator, 0)) + self.connect(self.stereo_carrier_pll_recovery, + (self.rds_carrier_generator, 1)) # take signal, filter off rds, send into mixer 0 channel - self.connect(self.fm_demod,self.rds_signal_filter,(self.rds_signal_generator,0)) + self.connect(self.fm_demod, self.rds_signal_filter, + (self.rds_signal_generator, 0)) # take rds_carrier_generator output and send into mixer 1 # channel - self.connect(self.rds_carrier_generator,(self.rds_signal_generator,1)) + self.connect(self.rds_carrier_generator, + (self.rds_signal_generator, 1)) # send basebanded rds signal and send into "processor" # which for now is a null sink - self.connect(self.rds_signal_generator,self_rds_signal_processor) - + self.connect(self.rds_signal_generator, self_rds_signal_processor) if 1: # pick off the audio, L+R that is what we used to have and @@ -208,14 +216,14 @@ def __init__ (self, demod_rate, audio_decimation): # take the picked off L+R audio and send it to the PLUS # side of the subtractor - self.connect(self.audio_filter,(self.Make_Right, 0)) + self.connect(self.audio_filter, (self.Make_Right, 0)) # The result of Make_Left gets (L+R) + (L-R) and results in 2*L # The result of Make_Right gets (L+R) - (L-R) and results in 2*R - self.connect(self.Make_Left , self.deemph_Left, (self, 0)) + self.connect(self.Make_Left, self.deemph_Left, (self, 0)) self.connect(self.Make_Right, self.deemph_Right, (self, 1)) # NOTE: mono support will require variable number of outputs in hier_block2s # See ticket:174 in Trac database - #else: + # else: # self.connect (self.fm_demod, self.audio_filter, self) diff --git a/gr-analog/python/analog/wfm_rcv_pll.py b/gr-analog/python/analog/wfm_rcv_pll.py index 04ea9b1430f..ce0e357d7de 100644 --- a/gr-analog/python/analog/wfm_rcv_pll.py +++ b/gr-analog/python/analog/wfm_rcv_pll.py @@ -16,6 +16,7 @@ from gnuradio.filter import firdes from gnuradio import analog + class wfm_rcv_pll(gr.hier_block2): def __init__(self, demod_rate, audio_decimation, deemph_tau): """ @@ -30,7 +31,8 @@ def __init__(self, demod_rate, audio_decimation, deemph_tau): deemph_tau: deemphasis ime constant in seconds (75us in US, 50us in EUR). (float) """ gr.hier_block2.__init__(self, "wfm_rcv_pll", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(2, 2, gr.sizeof_float)) # Output signature if audio_decimation != int(audio_decimation): @@ -42,56 +44,80 @@ def __init__(self, demod_rate, audio_decimation, deemph_tau): ################################################## self.demod_rate = demod_rate self.deemph_tau = deemph_tau - self.stereo_carrier_filter_coeffs = stereo_carrier_filter_coeffs = firdes.band_pass(-2.0, demod_rate, 37600, 38400, 400, fft.window.WIN_HAMMING, 6.76) - self.pilot_carrier_filter_coeffs = pilot_carrier_filter_coeffs = firdes.complex_band_pass(1.0, demod_rate, 18980, 19020, 1500, fft.window.WIN_HAMMING, 6.76) + self.stereo_carrier_filter_coeffs = stereo_carrier_filter_coeffs = firdes.band_pass( + -2.0, demod_rate, 37600, 38400, 400, fft.window.WIN_HAMMING, 6.76) + self.pilot_carrier_filter_coeffs = pilot_carrier_filter_coeffs = firdes.complex_band_pass( + 1.0, demod_rate, 18980, 19020, 1500, fft.window.WIN_HAMMING, 6.76) self.deviation = deviation = 75000 - self.audio_filter_coeffs = audio_filter_coeffs = firdes.low_pass(1, demod_rate, 15000,1500, fft.window.WIN_HAMMING, 6.76) + self.audio_filter_coeffs = audio_filter_coeffs = firdes.low_pass( + 1, demod_rate, 15000, 1500, fft.window.WIN_HAMMING, 6.76) self.audio_decim = audio_decim = audio_decimation self.audio_rate = audio_rate = demod_rate / audio_decim - self.samp_delay = samp_delay = (len(pilot_carrier_filter_coeffs) - 1) // 2 + (len(stereo_carrier_filter_coeffs) - 1) // 2 + self.samp_delay = samp_delay = (len( + pilot_carrier_filter_coeffs) - 1) // 2 + (len(stereo_carrier_filter_coeffs) - 1) // 2 ################################################## # Blocks ################################################## - self.pilot_carrier_bpf = filter.fir_filter_fcc(1, pilot_carrier_filter_coeffs) + self.pilot_carrier_bpf = filter.fir_filter_fcc( + 1, pilot_carrier_filter_coeffs) self.pilot_carrier_bpf.declare_sample_delay(0) - self.stereo_carrier_bpf = filter.fft_filter_fff(1, stereo_carrier_filter_coeffs, 1) + self.stereo_carrier_bpf = filter.fft_filter_fff( + 1, stereo_carrier_filter_coeffs, 1) self.stereo_carrier_bpf.declare_sample_delay(0) - self.stereo_audio_lpf = filter.fft_filter_fff(audio_decim, audio_filter_coeffs, 1) + self.stereo_audio_lpf = filter.fft_filter_fff( + audio_decim, audio_filter_coeffs, 1) self.stereo_audio_lpf.declare_sample_delay(0) - self.mono_audio_lpf = filter.fft_filter_fff(audio_decim, audio_filter_coeffs, 1) + self.mono_audio_lpf = filter.fft_filter_fff( + audio_decim, audio_filter_coeffs, 1) self.mono_audio_lpf.declare_sample_delay(0) self.blocks_stereo_multiply = blocks.multiply_ff(1) self.blocks_pilot_multiply = blocks.multiply_cc(1) self.blocks_complex_to_imag = blocks.complex_to_imag(1) self.blocks_right_sub = blocks.sub_ff(1) self.blocks_left_add = blocks.add_ff(1) - self.analog_quadrature_demod_cf = analog.quadrature_demod_cf(demod_rate/(2*math.pi*deviation)) - self.analog_pll_refout_cc = analog.pll_refout_cc(0.001, 2*math.pi * 19200 / demod_rate, 2*math.pi * 18800 / demod_rate) - self.analog_right_fm_deemph = analog.fm_deemph(fs=audio_rate, tau=deemph_tau) - self.analog_left_fm_deemph = analog.fm_deemph(fs=audio_rate, tau=deemph_tau) - self.blocks_delay_0 = blocks.delay(gr.sizeof_float*1, samp_delay) + self.analog_quadrature_demod_cf = analog.quadrature_demod_cf( + demod_rate / (2 * math.pi * deviation)) + self.analog_pll_refout_cc = analog.pll_refout_cc( + 0.001, 2 * math.pi * 19200 / demod_rate, 2 * math.pi * 18800 / demod_rate) + self.analog_right_fm_deemph = analog.fm_deemph( + fs=audio_rate, tau=deemph_tau) + self.analog_left_fm_deemph = analog.fm_deemph( + fs=audio_rate, tau=deemph_tau) + self.blocks_delay_0 = blocks.delay(gr.sizeof_float * 1, samp_delay) ################################################## # Connections ################################################## self.connect((self.analog_left_fm_deemph, 0), (self, 0)) self.connect((self.analog_right_fm_deemph, 0), (self, 1)) - self.connect((self.analog_pll_refout_cc, 0), (self.blocks_pilot_multiply, 1)) - self.connect((self.analog_pll_refout_cc, 0), (self.blocks_pilot_multiply, 0)) - self.connect((self.analog_quadrature_demod_cf, 0), (self.blocks_delay_0, 0)) - self.connect((self.blocks_delay_0, 0), (self.blocks_stereo_multiply, 0)) + self.connect((self.analog_pll_refout_cc, 0), + (self.blocks_pilot_multiply, 1)) + self.connect((self.analog_pll_refout_cc, 0), + (self.blocks_pilot_multiply, 0)) + self.connect((self.analog_quadrature_demod_cf, 0), + (self.blocks_delay_0, 0)) + self.connect((self.blocks_delay_0, 0), + (self.blocks_stereo_multiply, 0)) self.connect((self.blocks_delay_0, 0), (self.mono_audio_lpf, 0)) - self.connect((self.analog_quadrature_demod_cf, 0), (self.pilot_carrier_bpf, 0)) - self.connect((self.blocks_left_add, 0), (self.analog_left_fm_deemph, 0)) - self.connect((self.blocks_right_sub, 0), (self.analog_right_fm_deemph, 0)) - self.connect((self.blocks_complex_to_imag, 0), (self.stereo_carrier_bpf, 0)) - self.connect((self.blocks_pilot_multiply, 0), (self.blocks_complex_to_imag, 0)) - self.connect((self.blocks_stereo_multiply, 0), (self.stereo_audio_lpf, 0)) # L - R path + self.connect((self.analog_quadrature_demod_cf, 0), + (self.pilot_carrier_bpf, 0)) + self.connect((self.blocks_left_add, 0), + (self.analog_left_fm_deemph, 0)) + self.connect((self.blocks_right_sub, 0), + (self.analog_right_fm_deemph, 0)) + self.connect((self.blocks_complex_to_imag, 0), + (self.stereo_carrier_bpf, 0)) + self.connect((self.blocks_pilot_multiply, 0), + (self.blocks_complex_to_imag, 0)) + self.connect((self.blocks_stereo_multiply, 0), + (self.stereo_audio_lpf, 0)) # L - R path self.connect((self.mono_audio_lpf, 0), (self.blocks_left_add, 1)) self.connect((self.mono_audio_lpf, 0), (self.blocks_right_sub, 0)) self.connect((self.stereo_audio_lpf, 0), (self.blocks_left_add, 0)) self.connect((self.stereo_audio_lpf, 0), (self.blocks_right_sub, 1)) - self.connect((self.stereo_carrier_bpf, 0), (self.blocks_stereo_multiply, 1)) - self.connect((self.pilot_carrier_bpf, 0), (self.analog_pll_refout_cc, 0)) + self.connect((self.stereo_carrier_bpf, 0), + (self.blocks_stereo_multiply, 1)) + self.connect((self.pilot_carrier_bpf, 0), + (self.analog_pll_refout_cc, 0)) self.connect((self, 0), (self.analog_quadrature_demod_cf, 0)) diff --git a/gr-analog/python/analog/wfm_tx.py b/gr-analog/python/analog/wfm_tx.py index 11f90ae5456..70e91f82616 100644 --- a/gr-analog/python/analog/wfm_tx.py +++ b/gr-analog/python/analog/wfm_tx.py @@ -35,16 +35,17 @@ def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=75e3, fh=-1.0): quad_rate must be an integer multiple of audio_rate. """ gr.hier_block2.__init__(self, "wfm_tx", - gr.io_signature(1, 1, gr.sizeof_float), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_float), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature # FIXME audio_rate and quad_rate ought to be exact rationals audio_rate = int(audio_rate) quad_rate = int(quad_rate) if quad_rate % audio_rate != 0: - raise ValueError("quad_rate is not an integer multiple of audio_rate") - + raise ValueError( + "quad_rate is not an integer multiple of audio_rate") do_interp = audio_rate != quad_rate @@ -58,14 +59,16 @@ def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=75e3, fh=-1.0): 40) # stopband atten dB print("len(interp_taps) =", len(interp_taps)) - self.interpolator = filter.interp_fir_filter_fff (interp_factor, interp_taps) + self.interpolator = filter.interp_fir_filter_fff( + interp_factor, interp_taps) self.preemph = fm_preemph(quad_rate, tau=tau, fh=fh) k = 2 * math.pi * max_dev / quad_rate - self.modulator = analog.frequency_modulator_fc (k) + self.modulator = analog.frequency_modulator_fc(k) if do_interp: - self.connect(self, self.interpolator, self.preemph, self.modulator, self) + self.connect(self, self.interpolator, + self.preemph, self.modulator, self) else: self.connect(self, self.preemph, self.modulator, self) diff --git a/gr-audio/examples/python/audio_copy.py b/gr-audio/examples/python/audio_copy.py index 6cdb7bfdb57..274a539aa1a 100644 --- a/gr-audio/examples/python/audio_copy.py +++ b/gr-audio/examples/python/audio_copy.py @@ -13,6 +13,7 @@ from gnuradio.eng_arg import eng_float from argparse import ArgumentParser + class my_top_block(gr.top_block): def __init__(self): @@ -20,25 +21,25 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-I", "--audio-input", default="", - help="pcm input device name. E.g., hw:0,0 or /dev/dsp") + help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-O", "--audio-output", default="", - help="pcm output device name. E.g., hw:0,0 or /dev/dsp") + help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-r", "--sample-rate", type=eng_float, default=48000, - help="set sample rate, default=%(default)s") - args = parser.parse_args () + help="set sample rate, default=%(default)s") + args = parser.parse_args() sample_rate = int(args.sample_rate) - src = audio.source (sample_rate, args.audio_input) - dst = audio.sink (sample_rate, args.audio_output) + src = audio.source(sample_rate, args.audio_input) + dst = audio.sink(sample_rate, args.audio_output) # Determine the maximum number of outputs on the source and # maximum number of inputs on the sink, then connect together # the most channels we can without overlap - nchan = min (src.output_signature().max_streams(), - dst.input_signature().max_streams()) + nchan = min(src.output_signature().max_streams(), + dst.input_signature().max_streams()) - for i in range (nchan): - self.connect ((src, i), (dst, i)) + for i in range(nchan): + self.connect((src, i), (dst, i)) if __name__ == '__main__': @@ -46,4 +47,3 @@ def __init__(self): my_top_block().run() except KeyboardInterrupt: pass - diff --git a/gr-audio/examples/python/audio_play.py b/gr-audio/examples/python/audio_play.py index 1fc4b5128ab..d93e187d689 100644 --- a/gr-audio/examples/python/audio_play.py +++ b/gr-audio/examples/python/audio_play.py @@ -22,12 +22,12 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-F", "--filename", default="audio.dat", - help="read input from FILENAME default=%(default)r") + help="read input from FILENAME default=%(default)r") parser.add_argument("-r", "--sample-rate", type=eng_float, default=48000, - help="set sample rate (default=%(default)r)") + help="set sample rate (default=%(default)r)") parser.add_argument("-R", "--repeat", action="store_true") parser.add_argument("-O", "--audio-output", default="", - help="pcm output device name. E.g., hw:0,0 or /dev/dsp") + help="pcm output device name. E.g., hw:0,0 or /dev/dsp") args = parser.parse_args() sample_rate = int(args.sample_rate) src = blocks.file_source(gr.sizeof_float, args.filename, args.repeat) diff --git a/gr-audio/examples/python/audio_to_file.py b/gr-audio/examples/python/audio_to_file.py index 19335a82790..7221e39d1a8 100644 --- a/gr-audio/examples/python/audio_to_file.py +++ b/gr-audio/examples/python/audio_to_file.py @@ -14,6 +14,7 @@ from gnuradio.eng_arg import eng_float from argparse import ArgumentParser + class my_top_block(gr.top_block): def __init__(self): @@ -21,13 +22,13 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-I", "--audio-input", default="", - help="pcm input device name. E.g., hw:0,0 or /dev/dsp") + help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-r", "--sample-rate", type=eng_float, default=48000, - help="set sample rate to RATE (%(default)r)") + help="set sample rate to RATE (%(default)r)") parser.add_argument("-N", "--nsamples", type=eng_float, - help="number of samples to collect [default=+inf]") + help="number of samples to collect [default=+inf]") parser.add_argument('file_name', metavar='FILE-NAME', - help="Output file path") + help="Output file path") args = parser.parse_args() diff --git a/gr-audio/examples/python/dial_tone.py b/gr-audio/examples/python/dial_tone.py index a38221facab..b175f8964cd 100644 --- a/gr-audio/examples/python/dial_tone.py +++ b/gr-audio/examples/python/dial_tone.py @@ -19,6 +19,7 @@ sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) + class my_top_block(gr.top_block): def __init__(self): @@ -26,9 +27,9 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-O", "--audio-output", default="", - help="pcm output device name. E.g., hw:0,0 or /dev/dsp") + help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-r", "--sample-rate", type=eng_float, default=48000, - help="set sample rate, default=%(default)s") + help="set sample rate, default=%(default)s") args = parser.parse_args() sample_rate = int(args.sample_rate) @@ -40,6 +41,7 @@ def __init__(self): self.connect(src0, (dst, 0)) self.connect(src1, (dst, 1)) + if __name__ == '__main__': try: my_top_block().run() diff --git a/gr-audio/examples/python/dial_tone_wav.py b/gr-audio/examples/python/dial_tone_wav.py index 58bf412c216..db576140ea4 100644 --- a/gr-audio/examples/python/dial_tone_wav.py +++ b/gr-audio/examples/python/dial_tone_wav.py @@ -21,6 +21,7 @@ sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) + class my_top_block(gr.top_block): def __init__(self): @@ -28,11 +29,11 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-r", "--sample-rate", type=eng_float, default=48000, - help="set sample rate to RATE (%(default)r)") + help="set sample rate to RATE (%(default)r)") parser.add_argument("-N", "--samples", type=eng_float, required=True, - help="number of samples to record") + help="number of samples to record") parser.add_argument('file_name', metavar='WAV-FILE', - help='Output WAV file name', nargs=1) + help='Output WAV file name', nargs=1) args = parser.parse_args() sample_rate = int(args.sample_rate) @@ -48,6 +49,7 @@ def __init__(self): self.connect(src0, head0, (dst, 0)) self.connect(src1, head1, (dst, 1)) + if __name__ == '__main__': try: my_top_block().run() diff --git a/gr-audio/examples/python/mono_tone.py b/gr-audio/examples/python/mono_tone.py index 411af929240..3feb495c54c 100644 --- a/gr-audio/examples/python/mono_tone.py +++ b/gr-audio/examples/python/mono_tone.py @@ -20,9 +20,10 @@ sys.exit(1) #import os -#print os.getpid() +# print os.getpid() #raw_input('Attach gdb and press Enter: ') + class my_top_block(gr.top_block): def __init__(self): @@ -30,11 +31,11 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-O", "--audio-output", default="", - help="pcm output device name. E.g., hw:0,0 or /dev/dsp") + help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-r", "--sample-rate", type=eng_float, default=48000, - help="set sample rate to RATE %(default)r)") + help="set sample rate to RATE %(default)r)") parser.add_argument("-D", "--dont-block", action="store_false", default=True, - dest="ok_to_block") + dest="ok_to_block") args = parser.parse_args() sample_rate = int(args.sample_rate) @@ -46,7 +47,7 @@ def __init__(self): args.audio_output, args.ok_to_block) - self.connect (src0, (dst, 0)) + self.connect(src0, (dst, 0)) if __name__ == '__main__': diff --git a/gr-audio/examples/python/multi_tone.py b/gr-audio/examples/python/multi_tone.py index 44800b69ff9..608b9a75bc6 100644 --- a/gr-audio/examples/python/multi_tone.py +++ b/gr-audio/examples/python/multi_tone.py @@ -20,9 +20,10 @@ sys.exit(1) #import os -#print os.getpid() +# print os.getpid() #raw_input('Attach gdb and press Enter: ') + class my_top_block(gr.top_block): def __init__(self): @@ -30,13 +31,13 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-O", "--audio-output", default="", - help="pcm output device name. E.g., hw:0,0 or /dev/dsp") + help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-r", "--sample-rate", type=eng_float, default=48000, - help="set sample rate to RATE (%(default)r)") - parser.add_argument ("-m", "--max-channels", type=int, default=16, - help="set maximum channels to use") + help="set sample rate to RATE (%(default)r)") + parser.add_argument("-m", "--max-channels", type=int, default=16, + help="set maximum channels to use") parser.add_argument("-D", "--dont-block", action="store_false", - dest="ok_to_block") + dest="ok_to_block") args = parser.parse_args() sample_rate = int(args.sample_rate) limit_channels = args.max_channels @@ -46,12 +47,12 @@ def __init__(self): # With a tip of the hat to Harry Partch, may he R.I.P. # See "Genesis of a Music". He was into some very wild tunings... base = 392 - ratios = { 1 : 1.0, - 3 : 3.0 / 2, - 5 : 5.0 / 4, - 7 : 7.0 / 4, - 9 : 9.0 / 8, - 11 : 11.0 / 8 } + ratios = {1: 1.0, + 3: 3.0 / 2, + 5: 5.0 / 4, + 7: 7.0 / 4, + 9: 9.0 / 8, + 11: 11.0 / 8} # progression = (1, 5, 3, 7) # progression = (1, 9, 3, 7) @@ -68,11 +69,13 @@ def __init__(self): max_chan = limit_channels for i in range(max_chan): - quo, rem = divmod(i, len (progression)) + quo, rem = divmod(i, len(progression)) freq = base * ratios[progression[rem]] * (quo + 1) - src = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, freq, ampl) + src = analog.sig_source_f( + sample_rate, analog.GR_SIN_WAVE, freq, ampl) self.connect(src, (dst, i)) + if __name__ == '__main__': try: my_top_block().run() diff --git a/gr-audio/examples/python/noise.py b/gr-audio/examples/python/noise.py index 7c8e29cddef..45f41d78b33 100644 --- a/gr-audio/examples/python/noise.py +++ b/gr-audio/examples/python/noise.py @@ -14,6 +14,7 @@ from gnuradio.eng_arg import eng_float from argparse import ArgumentParser + class my_top_block(gr.top_block): def __init__(self): @@ -21,9 +22,9 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-O", "--audio-output", default="", - help="pcm output device name. E.g., hw:0,0 or /dev/dsp") + help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-r", "--sample-rate", type=eng_float, default=48000, - help="set sample rate to RATE (48000)") + help="set sample rate to RATE (48000)") args = parser.parse_args() sample_rate = int(args.sample_rate) ampl = 0.1 @@ -33,6 +34,7 @@ def __init__(self): dst = audio.sink(sample_rate, args.audio_output) self.connect(src, b2f, dst) + if __name__ == '__main__': try: my_top_block().run() diff --git a/gr-audio/examples/python/spectrum_inversion.py b/gr-audio/examples/python/spectrum_inversion.py index d9b7a2d0089..8b293b9ce01 100644 --- a/gr-audio/examples/python/spectrum_inversion.py +++ b/gr-audio/examples/python/spectrum_inversion.py @@ -20,6 +20,7 @@ from gnuradio.eng_arg import eng_float, intx from argparse import ArgumentParser + class my_top_block(gr.top_block): def __init__(self): @@ -27,15 +28,15 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-I", "--audio-input", default="", - help="pcm input device name. E.g., hw:0,0 or /dev/dsp") + help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-O", "--audio-output", default="", - help="pcm output device name. E.g., hw:0,0 or /dev/dsp") + help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-r", "--sample-rate", type=eng_float, default=8000, - help="set sample rate to RATE (%(default)r)") + help="set sample rate to RATE (%(default)r)") args = parser.parse_args() sample_rate = int(args.sample_rate) - src = audio.source (sample_rate, args.audio_input) - dst = audio.sink (sample_rate, args.audio_output) + src = audio.source(sample_rate, args.audio_input) + dst = audio.sink(sample_rate, args.audio_output) vec1 = [1, -1] vsource = blocks.vector_source_f(vec1, True) diff --git a/gr-audio/examples/python/test_resampler.py b/gr-audio/examples/python/test_resampler.py index e97836c61a7..3da9b20e61c 100644 --- a/gr-audio/examples/python/test_resampler.py +++ b/gr-audio/examples/python/test_resampler.py @@ -27,6 +27,7 @@ sys.stderr.write("Error: Program requires gr-blocks.\n") sys.exit(1) + class my_top_block(gr.top_block): def __init__(self): @@ -34,11 +35,11 @@ def __init__(self): parser = ArgumentParser() parser.add_argument("-O", "--audio-output", default="", - help="pcm output device name. E.g., hw:0,0 or /dev/dsp") + help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_argument("-i", "--input-rate", type=eng_float, default=8000, - help="set input sample rate to RATE %(default)r") + help="set input sample rate to RATE %(default)r") parser.add_argument("-o", "--output-rate", type=eng_float, default=48000, - help="set output sample rate to RATE %(default)r") + help="set output sample rate to RATE %(default)r") args = parser.parse_args() input_rate = int(args.input_rate) output_rate = int(args.output_rate) @@ -55,6 +56,7 @@ def __init__(self): dst = audio.sink(output_rate, args.audio_output) self.connect(src0, rr, (dst, 0)) + if __name__ == '__main__': try: my_top_block().run() diff --git a/gr-audio/python/audio/__init__.py b/gr-audio/python/audio/__init__.py index 4731c2949dd..ca1316f8269 100644 --- a/gr-audio/python/audio/__init__.py +++ b/gr-audio/python/audio/__init__.py @@ -17,8 +17,8 @@ import os try: - from .audio_python import * + from .audio_python import * except ImportError: - dirname, filename = os.path.split(os.path.abspath(__file__)) - __path__.append(os.path.join(dirname, "bindings")) - from .audio_python import * + dirname, filename = os.path.split(os.path.abspath(__file__)) + __path__.append(os.path.join(dirname, "bindings")) + from .audio_python import * diff --git a/gr-blocks/examples/ctrlport/simple_copy_controller.py b/gr-blocks/examples/ctrlport/simple_copy_controller.py index a3c16c3a23f..1d1ece37d0d 100755 --- a/gr-blocks/examples/ctrlport/simple_copy_controller.py +++ b/gr-blocks/examples/ctrlport/simple_copy_controller.py @@ -6,13 +6,15 @@ args = sys.argv if(len(args) < 4): - sys.stderr.write('Not enough arguments: simple_copy_controller.py [true|false]\n\n') + sys.stderr.write( + 'Not enough arguments: simple_copy_controller.py [true|false]\n\n') sys.exit(1) hostname = args[1] portnum = int(args[2]) msg = args[3].lower() -radiosys = GNURadioControlPortClient(host=hostname, port=portnum, rpcmethod='thrift') +radiosys = GNURadioControlPortClient( + host=hostname, port=portnum, rpcmethod='thrift') radio = radiosys.client if(msg == 'true'): diff --git a/gr-blocks/examples/ctrlport/usrp_sink_controller.py b/gr-blocks/examples/ctrlport/usrp_sink_controller.py index 27360280ab1..310f96f6528 100644 --- a/gr-blocks/examples/ctrlport/usrp_sink_controller.py +++ b/gr-blocks/examples/ctrlport/usrp_sink_controller.py @@ -7,11 +7,11 @@ parser = ArgumentParser() parser.add_argument("-H", "--host", default="localhost", - help="Hostname to connect to (default=%(default)r)") + help="Hostname to connect to (default=%(default)r)") parser.add_argument("-p", "--port", type=int, default=9090, - help="Port of Controlport instance on host (default=%(default)r)") + help="Port of Controlport instance on host (default=%(default)r)") parser.add_argument("-a", "--alias", default="gr uhd usrp sink0", - help="The UHD block's alias to control (default=%(default)r)") + help="The UHD block's alias to control (default=%(default)r)") parser.add_argument("command", metavar="COMMAND") parser.add_argument("value", metavar="VALUE") args = parser.parse_args() @@ -29,7 +29,8 @@ else: val = pmt.from_double(float(val)) -radiosys = GNURadioControlPortClient(host=args.host, port=args.port, rpcmethod='thrift') +radiosys = GNURadioControlPortClient( + host=args.host, port=args.port, rpcmethod='thrift') radio = radiosys.client radio.postMessage(args.alias, port, pmt.cons(pmt.intern(cmd), val)) diff --git a/gr-blocks/examples/ctrlport/usrp_source_controller.py b/gr-blocks/examples/ctrlport/usrp_source_controller.py index 21864aba496..cc2c638f067 100755 --- a/gr-blocks/examples/ctrlport/usrp_source_controller.py +++ b/gr-blocks/examples/ctrlport/usrp_source_controller.py @@ -7,11 +7,11 @@ parser = ArgumentParser() parser.add_argument("-H", "--host", default="localhost", - help="Hostname to connect to (default=%(default)r)") + help="Hostname to connect to (default=%(default)r)") parser.add_argument("-p", "--port", type=int, default=9090, - help="Port of Controlport instance on host (default=%(default)r)") + help="Port of Controlport instance on host (default=%(default)r)") parser.add_argument("-a", "--alias", default="gr uhd usrp source0", - help="The UHD block's alias to control (default=%(default)r)") + help="The UHD block's alias to control (default=%(default)r)") parser.add_argument("command", metavar="COMMAND") parser.add_argument("value", metavar="VALUE") args = parser.parse_args() @@ -29,7 +29,8 @@ else: val = pmt.from_double(float(val)) -radiosys = GNURadioControlPortClient(host=args.host, port=args.port, rpcmethod='thrift') +radiosys = GNURadioControlPortClient( + host=args.host, port=args.port, rpcmethod='thrift') radio = radiosys.client radio.postMessage(args.alias, port, pmt.cons(pmt.intern(cmd), val)) diff --git a/gr-blocks/examples/tags/test_file_tags.py b/gr-blocks/examples/tags/test_file_tags.py index df81bbb1a97..8cbd743fceb 100644 --- a/gr-blocks/examples/tags/test_file_tags.py +++ b/gr-blocks/examples/tags/test_file_tags.py @@ -14,9 +14,10 @@ import sys import numpy + def main(): data = numpy.arange(0, 32000, 1).tolist() - trig = 100*[0,] + 100*[1,] + trig = 100 * [0, ] + 100 * [1, ] src = blocks.vector_source_s(data, True) trigger = blocks.vector_source_s(trig, True) @@ -34,5 +35,6 @@ def main(): tb.run() + if __name__ == "__main__": main() diff --git a/gr-blocks/lib/qa_block_tags.cc b/gr-blocks/lib/qa_block_tags.cc index 65f4c9a070b..92392f4d98e 100644 --- a/gr-blocks/lib/qa_block_tags.cc +++ b/gr-blocks/lib/qa_block_tags.cc @@ -25,6 +25,7 @@ #include #include +#include // ---------------------------------------------------------------- @@ -114,7 +115,7 @@ BOOST_AUTO_TEST_CASE(t1) BOOST_REQUIRE_EQUAL(tags4.size(), (size_t)8); #if QA_TAGS_DEBUG - GR_LOG_GET_CONFIGURED_LOGGER(logger, "qa_block_tags::t1"); + auto logger = std::make_shared("qa_block_tags::t1"); // Kludge together the tags that we know should result from the above graph std::stringstream str0, str1, str2; @@ -213,7 +214,7 @@ BOOST_AUTO_TEST_CASE(t2) #if QA_TAGS_DEBUG - GR_LOG_GET_CONFIGURED_LOGGER(logger, "qa_block_tags::t2"); + auto logger = std::make_shared("qa_block_tags::t2"); // Kludge together the tags that we know should result from the above graph std::stringstream str0, str1; @@ -314,7 +315,7 @@ BOOST_AUTO_TEST_CASE(t3) BOOST_REQUIRE_EQUAL(tags4.size(), (size_t)8); #if QA_TAGS_DEBUG - GR_LOG_GET_CONFIGURED_LOGGER(logger, "qa_block_tags::t3"); + auto logger = std::make_shared("qa_block_tags::t3"); // Kludge together the tags that we know should result from the above graph std::stringstream str0, str1, str2; @@ -377,7 +378,7 @@ BOOST_AUTO_TEST_CASE(t4) gr::block_sptr snk0(gr::blocks::null_sink::make(sizeof(int))); gr::block_sptr snk1(gr::blocks::null_sink::make(sizeof(int))); - GR_LOG_GET_CONFIGURED_LOGGER(logger, "qa_block_tags::t4"); + auto logger = std::make_shared("qa_block_tags::t4"); // using 1-to-1 tag propagation without having equal number of // ins and outs. Make sure this works; will just exit run early. @@ -432,7 +433,7 @@ BOOST_AUTO_TEST_CASE(t5) #if QA_TAGS_DEBUG - GR_LOG_GET_CONFIGURED_LOGGER(logger, "qa_block_tags::t5"); + auto logger = std::make_shared("qa_block_tags::t5"); // Kludge together the tags that we know should result from the above graph std::stringstream str0, str1, str2; diff --git a/gr-blocks/python/blocks/__init__.py b/gr-blocks/python/blocks/__init__.py index c9a4b3f756a..7178e376dd4 100644 --- a/gr-blocks/python/blocks/__init__.py +++ b/gr-blocks/python/blocks/__init__.py @@ -27,7 +27,7 @@ from .var_to_msg import var_to_msg_pair from .matrix_interleaver import * -#alias old add_vXX and multiply_vXX +# alias old add_vXX and multiply_vXX add_vcc = add_cc add_vff = add_ff add_vii = add_ii diff --git a/gr-blocks/python/blocks/matrix_interleaver.py b/gr-blocks/python/blocks/matrix_interleaver.py index 26a8e86a6ea..3cd962623ba 100644 --- a/gr-blocks/python/blocks/matrix_interleaver.py +++ b/gr-blocks/python/blocks/matrix_interleaver.py @@ -10,6 +10,7 @@ from gnuradio import gr, blocks + class matrix_interleaver(gr.hier_block2): """ Block interleaver writes inputs into conceptual rows of the matrix @@ -21,8 +22,8 @@ class matrix_interleaver(gr.hier_block2): def __init__(self, itemsize, rows=1, cols=1, deint=False): gr.hier_block2.__init__( self, "Matrix Interleaver", - gr.io_signature(1, 1, itemsize), - gr.io_signature(1, 1, itemsize), + gr.io_signature(1, 1, itemsize), + gr.io_signature(1, 1, itemsize), ) self.itemsize = itemsize @@ -47,12 +48,14 @@ def set_rowsandcols(self, rows, cols, deint): ################################################## # short circuit for unitary rows / columns if rows == 1 or cols == 1: - self.passthrough = blocks.copy(self.itemsize) - self.connect((self, 0), (self.passthrough, 0), (self, 0)) - return + self.passthrough = blocks.copy(self.itemsize) + self.connect((self, 0), (self.passthrough, 0), (self, 0)) + return - self.deinterleaver = blocks.deinterleave(self.itemsize, 1 if deint else cols) - self.interleaver = blocks.interleave(self.itemsize, cols if deint else 1) + self.deinterleaver = blocks.deinterleave( + self.itemsize, 1 if deint else cols) + self.interleaver = blocks.interleave( + self.itemsize, cols if deint else 1) ################################################## # Connections diff --git a/gr-blocks/python/blocks/msg_meta_to_pair.py b/gr-blocks/python/blocks/msg_meta_to_pair.py index 1c6dde2f61a..6178c64b6ab 100644 --- a/gr-blocks/python/blocks/msg_meta_to_pair.py +++ b/gr-blocks/python/blocks/msg_meta_to_pair.py @@ -11,6 +11,7 @@ from gnuradio import gr import pmt + class meta_to_pair(gr.sync_block): """ This block converts a metadata dictionary item to a pmt pair that is @@ -18,8 +19,10 @@ class meta_to_pair(gr.sync_block): which item in the incoming metadata to output as a pair and what the pair name is. """ + def __init__(self, incomingKeyName, outgoingPairName): - gr.sync_block.__init__(self, name="meta_to_pair", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="meta_to_pair", + in_sig=None, out_sig=None) self.incomingKeyName = str(incomingKeyName) self.outgoingPairName = str(outgoingPairName) @@ -51,7 +54,8 @@ def msg_handler(self, msg): new_pair = None try: - new_pair = pmt.cons(pmt.intern(self.outgoingPairName), pmt.to_pmt(incomingVal)) + new_pair = pmt.cons(pmt.intern( + self.outgoingPairName), pmt.to_pmt(incomingVal)) except Exception as e: gr.log.error("Cannot construct new message: %s" % str(e)) return diff --git a/gr-blocks/python/blocks/msg_pair_to_var.py b/gr-blocks/python/blocks/msg_pair_to_var.py index 97f73f85f8d..ab0fd149735 100644 --- a/gr-blocks/python/blocks/msg_pair_to_var.py +++ b/gr-blocks/python/blocks/msg_pair_to_var.py @@ -11,6 +11,7 @@ from gnuradio import gr import pmt + class msg_pair_to_var(gr.sync_block): """ This block will take an input message pair and allow you to set a flowgraph variable @@ -18,8 +19,10 @@ class msg_pair_to_var(gr.sync_block): of the datatype expected by the flowgraph the behavior of the flowgraph may be unpredictable. """ + def __init__(self, callback): - gr.sync_block.__init__(self, name="msg_pair_to_var", in_sig=None, out_sig=None) + gr.sync_block.__init__( + self, name="msg_pair_to_var", in_sig=None, out_sig=None) self.callback = callback @@ -28,15 +31,16 @@ def __init__(self, callback): def msg_handler(self, msg): if not pmt.is_pair(msg) or pmt.is_dict(msg) or pmt.is_pdu(msg): - gr.log.warn("Input message %s is not a simple pair, dropping" % repr(msg)) + gr.log.warn( + "Input message %s is not a simple pair, dropping" % repr(msg)) return new_val = pmt.to_python(pmt.cdr(msg)) try: self.callback(new_val) except Exception as e: - gr.log.error("Error when calling " + repr(self.callback.name()) + " with " - + repr(new_val) + " (reason: %s)" % repr(e)) + gr.log.error("Error when calling " + repr(self.callback.name()) + " with " + + repr(new_val) + " (reason: %s)" % repr(e)) def stop(self): return True diff --git a/gr-blocks/python/blocks/parse_file_metadata.py b/gr-blocks/python/blocks/parse_file_metadata.py index d98a6c6127b..a6128682d76 100644 --- a/gr-blocks/python/blocks/parse_file_metadata.py +++ b/gr-blocks/python/blocks/parse_file_metadata.py @@ -31,23 +31,25 @@ blocks.GR_FILE_LONG: "long", blocks.GR_FILE_LONG_LONG: "long long", blocks.GR_FILE_FLOAT: "float", - blocks.GR_FILE_DOUBLE: "double" } + blocks.GR_FILE_DOUBLE: "double"} ftype_to_size = {blocks.GR_FILE_BYTE: gr.sizeof_char, blocks.GR_FILE_SHORT: gr.sizeof_short, blocks.GR_FILE_INT: gr.sizeof_int, blocks.GR_FILE_LONG: gr.sizeof_int, - blocks.GR_FILE_LONG_LONG: 2*gr.sizeof_int, + blocks.GR_FILE_LONG_LONG: 2 * gr.sizeof_int, blocks.GR_FILE_FLOAT: gr.sizeof_float, blocks.GR_FILE_DOUBLE: gr.sizeof_double} + def parse_header(p, VERBOSE=False): dump = pmt.PMT_NIL info = dict() if(pmt.is_dict(p) is False): - sys.stderr.write("Header is not a PMT dictionary: invalid or corrupt data file.\n") + sys.stderr.write( + "Header is not a PMT dictionary: invalid or corrupt data file.\n") sys.exit(1) # GET FILE FORMAT VERSION NUMBER @@ -57,7 +59,8 @@ def parse_header(p, VERBOSE=False): if(VERBOSE): print("Version Number: {0}".format(version)) else: - sys.stderr.write("Could not find key 'version': invalid or corrupt data file.\n") + sys.stderr.write( + "Could not find key 'version': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT SAMPLE RATE @@ -68,7 +71,8 @@ def parse_header(p, VERBOSE=False): if(VERBOSE): print("Sample Rate: {0:.2f} sps".format(samp_rate)) else: - sys.stderr.write("Could not find key 'sr': invalid or corrupt data file.\n") + sys.stderr.write( + "Could not find key 'sr': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT TIME STAMP @@ -83,15 +87,16 @@ def parse_header(p, VERBOSE=False): info["rx_time_fracs"] = fracs info["rx_time"] = t if(VERBOSE): - # We need are going to print with ~1e-16 resolution, - # which is the precision we can expect in secs. - # The default value of precision for decimal - # is 28. The value of secs is not expected to be larger - # than 1e12, so this precision is enough. - s = decimal.Decimal(secs) + decimal.Decimal(fracs) - print("Seconds: {0:.16f}".format(s)) + # We need are going to print with ~1e-16 resolution, + # which is the precision we can expect in secs. + # The default value of precision for decimal + # is 28. The value of secs is not expected to be larger + # than 1e12, so this precision is enough. + s = decimal.Decimal(secs) + decimal.Decimal(fracs) + print("Seconds: {0:.16f}".format(s)) else: - sys.stderr.write("Could not find key 'time': invalid or corrupt data file.\n") + sys.stderr.write( + "Could not find key 'time': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT ITEM SIZE @@ -102,7 +107,8 @@ def parse_header(p, VERBOSE=False): if(VERBOSE): print("Item size: {0}".format(dsize)) else: - sys.stderr.write("Could not find key 'size': invalid or corrupt data file.\n") + sys.stderr.write( + "Could not find key 'size': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT DATA TYPE @@ -114,7 +120,8 @@ def parse_header(p, VERBOSE=False): if(VERBOSE): print("Data Type: {0} ({1})".format(stype, dtype)) else: - sys.stderr.write("Could not find key 'type': invalid or corrupt data file.\n") + sys.stderr.write( + "Could not find key 'type': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT COMPLEX @@ -125,7 +132,8 @@ def parse_header(p, VERBOSE=False): if(VERBOSE): print("Complex? {0}".format(cplx)) else: - sys.stderr.write("Could not find key 'cplx': invalid or corrupt data file.\n") + sys.stderr.write( + "Could not find key 'cplx': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT WHERE CURRENT SEGMENT STARTS @@ -140,7 +148,8 @@ def parse_header(p, VERBOSE=False): print("Extra Length: {0}".format((info["extra_len"]))) print("Extra Header? {0}".format(info["has_extra"])) else: - sys.stderr.write("Could not find key 'strt': invalid or corrupt data file.\n") + sys.stderr.write( + "Could not find key 'strt': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT SIZE OF DATA @@ -156,15 +165,19 @@ def parse_header(p, VERBOSE=False): print("Size of Data: {0} bytes".format(nbytes)) print(" {0} items".format(nitems)) else: - sys.stderr.write("Could not find key 'size': invalid or corrupt data file.\n") + sys.stderr.write( + "Could not find key 'size': invalid or corrupt data file.\n") sys.exit(1) return info # IF THERE IS EXTRA DATA, PULL OUT THE DICTIONARY AND PARSE IT + + def parse_extra_dict(p, info, VERBOSE=False): if(pmt.is_dict(p) is False): - sys.stderr.write("Extra header is not a PMT dictionary: invalid or corrupt data file.\n") + sys.stderr.write( + "Extra header is not a PMT dictionary: invalid or corrupt data file.\n") sys.exit(1) items = pmt.dict_items(p) diff --git a/gr-blocks/python/blocks/pdu_compatibility.py b/gr-blocks/python/blocks/pdu_compatibility.py index 3d6af5f5483..ed730055ac4 100644 --- a/gr-blocks/python/blocks/pdu_compatibility.py +++ b/gr-blocks/python/blocks/pdu_compatibility.py @@ -16,34 +16,46 @@ ######## PDU BLOCKS MOVED TO GR-PDU ######## + class pdu_filter(pdu.pdu_filter): def __init__(self, *args, **kwargs): - gr.log.warn('`pdu_filter` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.pdu_filter()') + gr.log.warn( + '`pdu_filter` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.pdu_filter()') pdu.pdu_filter.__init__(self, *args, **kwargs) + class pdu_remove(pdu.pdu_remove): def __init__(self, *args, **kwargs): - gr.log.warn('`pdu_remove` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.pdu_remove()') + gr.log.warn( + '`pdu_remove` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.pdu_remove()') pdu.pdu_remove.__init__(self, *args, **kwargs) + class pdu_set(pdu.pdu_set): def __init__(self, *args, **kwargs): - gr.log.warn('`pdu_set` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.pdu_set()') + gr.log.warn( + '`pdu_set` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.pdu_set()') pdu.pdu_set.__init__(self, *args, **kwargs) + class pdu_to_tagged_stream(pdu.pdu_to_tagged_stream): def __init__(self, *args, **kwargs): - gr.log.warn('`pdu_to_tagged_stream` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.pdu_to_tagged_stream()') + gr.log.warn( + '`pdu_to_tagged_stream` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.pdu_to_tagged_stream()') pdu.pdu_to_tagged_stream.__init__(self, *args, **kwargs) + class random_pdu(pdu.random_pdu): def __init__(self, *args, **kwargs): - gr.log.warn('`random_pdu` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.random_pdu()') + gr.log.warn( + '`random_pdu` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.random_pdu()') pdu.random_pdu.__init__(self, *args, **kwargs) + class tagged_stream_to_pdu(pdu.tagged_stream_to_pdu): def __init__(self, *args, **kwargs): - gr.log.warn('`tagged_stream_to_pdu` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.tagged_stream_to_pdu()') + gr.log.warn( + '`tagged_stream_to_pdu` has moved to gr-pdu and will be removed from gr-blocks soon. Please update to use pdu.tagged_stream_to_pdu()') pdu.tagged_stream_to_pdu.__init__(self, *args, **kwargs) @@ -51,10 +63,13 @@ def __init__(self, *args, **kwargs): class socket_pdu(network.socket_pdu): def __init__(self, *args, **kwargs): - gr.log.warn('`socket_pdu` has moved to gr-network and will be removed from gr-blocks soon. Please update to use network.socket_pdu()') + gr.log.warn( + '`socket_pdu` has moved to gr-network and will be removed from gr-blocks soon. Please update to use network.socket_pdu()') network.socket_pdu.__init__(self, *args, **kwargs) + class tuntap_pdu(network.tuntap_pdu): def __init__(self, *args, **kwargs): - gr.log.warn('`tuntap_pdu` has moved to gr-network and will be removed from gr-blocks soon. Please update to use network.tuntap_pdu()') + gr.log.warn( + '`tuntap_pdu` has moved to gr-network and will be removed from gr-blocks soon. Please update to use network.tuntap_pdu()') network.tuntap_pdu.__init__(self, *args, **kwargs) diff --git a/gr-blocks/python/blocks/qa_add_mult_v.py b/gr-blocks/python/blocks/qa_add_mult_v.py index 39f11bc4beb..5568b205363 100644 --- a/gr-blocks/python/blocks/qa_add_mult_v.py +++ b/gr-blocks/python/blocks/qa_add_mult_v.py @@ -344,8 +344,8 @@ def test_multiply_vcc_five(self): 25.0 + 26.0j, 27.0 + 28.0j, 29.0 + 30.0j] - expected_result = [-1021.0 + 428.0j, -2647.0 + 1754.0j, - \ - 4945.0 + 3704.0j, -8011.0 + 6374.0j, -11941.0 + 9860.0j] + expected_result = [-1021.0 + 428.0j, -2647.0 + 1754.0j, - + 4945.0 + 3704.0j, -8011.0 + 6374.0j, -11941.0 + 9860.0j] op = blocks.multiply_cc(5) self.help_cc(5, (src1_data, src2_data, src3_data), expected_result, op) diff --git a/gr-blocks/python/blocks/qa_block_gateway.py b/gr-blocks/python/blocks/qa_block_gateway.py index 8088b59a852..7205fe3315b 100644 --- a/gr-blocks/python/blocks/qa_block_gateway.py +++ b/gr-blocks/python/blocks/qa_block_gateway.py @@ -125,7 +125,7 @@ def work(self, input_items, output_items): if self.nitems_written(0) == 0: # skip tagging in the first work block return num_output_items - + # make a new tag on the middle element every time work is called count = self.nitems_written(0) + num_output_items // 2 key = pmt.string_to_symbol("example_key") diff --git a/gr-blocks/python/blocks/qa_logger.py b/gr-blocks/python/blocks/qa_logger.py index f3714afbb3c..aa36e025621 100644 --- a/gr-blocks/python/blocks/qa_logger.py +++ b/gr-blocks/python/blocks/qa_logger.py @@ -1,6 +1,7 @@ #!/usr/bin/env python # # Copyright 2016 Free Software Foundation, Inc. +# Copyright 2021 Marcus Müller # # This file is part of GNU Radio # @@ -20,31 +21,30 @@ def setUp(self): def tearDown(self): pass - def set_and_assert_log_level(self, block, level): + def set_and_assert_log_level(self, block, level, ref=None): + if ref is None: + ref = level block.set_log_level(level) - self.assertEqual(block.log_level(), level) + self.assertEqual(block.log_level(), ref) def test_log_level_for_block(self): # Test the python API for getting and setting log levels of individual block # go through all of the documented log_levels ns = blocks.null_source(1) - self.set_and_assert_log_level(ns, "notset") self.set_and_assert_log_level(ns, "debug") self.set_and_assert_log_level(ns, "info") - self.set_and_assert_log_level(ns, "notice") - self.set_and_assert_log_level(ns, "warn") + self.set_and_assert_log_level(ns, "notice", "info") + self.set_and_assert_log_level(ns, "warn", "warning") + self.set_and_assert_log_level(ns, "warning") self.set_and_assert_log_level(ns, "error") - self.set_and_assert_log_level(ns, "crit") - self.set_and_assert_log_level(ns, "alert") - self.set_and_assert_log_level(ns, "emerg") + self.set_and_assert_log_level(ns, "crit", "critical") + self.set_and_assert_log_level(ns, "critical") + self.set_and_assert_log_level(ns, "alert", "critical") + self.set_and_assert_log_level(ns, "emerg", "critical") # There's a couple of special cases. "off" == "notset" (specific to gr) # and "fatal" == "emerg" (built in to log4cpp) ns.set_log_level("off") - self.assertEqual(ns.log_level(), "notset") - ns.set_log_level("fatal") - self.assertEqual(ns.log_level(), "emerg") - # Make sure exception is throw on bogus data - self.assertRaises(RuntimeError, ns.set_log_level, "11") + self.assertEqual(ns.log_level(), "off") def test_log_level_for_tb(self): # Test the python API for getting and setting log levels for a @@ -59,10 +59,10 @@ def test_log_level_for_tb(self): # confirm that the tb has log_level of first block self.assertEqual(tb.log_level(), "debug") # confirm that changing tb log_level propagates to connected blocks - tb.set_log_level("alert") - self.assertEqual(tb.log_level(), "alert") - self.assertEqual(nsrc.log_level(), "alert") - self.assertEqual(nsnk.log_level(), "alert") + tb.set_log_level("critical") + self.assertEqual(tb.log_level(), "critical") + self.assertEqual(nsrc.log_level(), "critical") + self.assertEqual(nsnk.log_level(), "critical") def test_log_level_for_hier_block(self): # Test the python API for getting and setting log levels for hier @@ -78,11 +78,11 @@ def test_log_level_for_hier_block(self): self.assertEqual(nsrc.log_level(), "debug") self.assertEqual(nsnk.log_level(), "debug") self.assertEqual(b.one_in_n.log_level(), "debug") - tb.set_log_level("alert") - self.assertEqual(tb.log_level(), "alert") - self.assertEqual(nsrc.log_level(), "alert") - self.assertEqual(nsnk.log_level(), "alert") - self.assertEqual(b.one_in_n.log_level(), "alert") + tb.set_log_level("critical") + self.assertEqual(tb.log_level(), "critical") + self.assertEqual(nsrc.log_level(), "critical") + self.assertEqual(nsnk.log_level(), "critical") + self.assertEqual(b.one_in_n.log_level(), "critical") if __name__ == '__main__': diff --git a/gr-blocks/python/blocks/qa_matrix_interleaver.py b/gr-blocks/python/blocks/qa_matrix_interleaver.py index d254ef6b55d..70a9c235590 100755 --- a/gr-blocks/python/blocks/qa_matrix_interleaver.py +++ b/gr-blocks/python/blocks/qa_matrix_interleaver.py @@ -12,6 +12,7 @@ from gnuradio import blocks from matrix_interleaver import matrix_interleaver + class qa_matrix_interleaver(gr_unittest.TestCase): def setUp(self): @@ -25,7 +26,7 @@ def test_interleave(self): # set up fg cols, rows = 4, 10 - vec = sum((cols * [x,] for x in range(rows)), []) + vec = sum((cols * [x, ] for x in range(rows)), []) expected = cols * list(range(rows)) src = blocks.vector_source_f(vec, False) @@ -44,11 +45,12 @@ def test_deinterleave(self): # set up fg cols, rows = 4, 10 - vec = sum((rows * [x,] for x in range(cols)), []) + vec = sum((rows * [x, ] for x in range(cols)), []) expected = rows * list(range(cols)) src = blocks.vector_source_f(vec, False) - itlv = matrix_interleaver(gr.sizeof_float, rows=rows, cols=cols, deint=True) + itlv = matrix_interleaver( + gr.sizeof_float, rows=rows, cols=cols, deint=True) snk = blocks.vector_sink_f() tb.connect(src, itlv, snk) @@ -58,5 +60,6 @@ def test_deinterleave(self): # check data self.assertFloatTuplesAlmostEqual(expected, result) + if __name__ == '__main__': gr_unittest.run(qa_matrix_interleaver) diff --git a/gr-blocks/python/blocks/qa_message_debug.py b/gr-blocks/python/blocks/qa_message_debug.py index 0f1dcff6fef..d9f108ab0ed 100644 --- a/gr-blocks/python/blocks/qa_message_debug.py +++ b/gr-blocks/python/blocks/qa_message_debug.py @@ -18,6 +18,8 @@ # this tests only the store port and the message retrival methods of the debug block # print() and print_pdu() were omitted as they print to stdout + + class qa_message_debug(gr_unittest.TestCase): def setUp(self): @@ -30,18 +32,22 @@ def test_001_t(self): test_str = "test_msg" new_msg = "new_msg" message_period_ms = 100 - msg_strobe = blocks.message_strobe(pmt.intern(test_str), message_period_ms) + msg_strobe = blocks.message_strobe( + pmt.intern(test_str), message_period_ms) msg_debug = blocks.message_debug() self.tb.msg_connect(msg_strobe, "strobe", msg_debug, "store") self.tb.start() - self.assertAlmostEqual(msg_debug.num_messages(), 0, delta=2) # 1st call, expect 0 - time.sleep(1) # floor(1000/100) = 10 - self.assertAlmostEqual(msg_debug.num_messages(), 10, delta=3) # 2nd call == 1 - time.sleep(1) # floor(2000/100) = 15 - self.assertAlmostEqual(msg_debug.num_messages(), 20, delta=3) # 3th call == 3 + self.assertAlmostEqual(msg_debug.num_messages(), + 0, delta=2) # 1st call, expect 0 + time.sleep(1) # floor(1000/100) = 10 + self.assertAlmostEqual(msg_debug.num_messages(), + 10, delta=3) # 2nd call == 1 + time.sleep(1) # floor(2000/100) = 15 + self.assertAlmostEqual(msg_debug.num_messages(), + 20, delta=3) # 3th call == 3 # change test message msg_strobe.to_basic_block()._post(pmt.intern("set_msg"), pmt.intern(new_msg)) @@ -51,10 +57,14 @@ def test_001_t(self): self.tb.wait() # check data # first received message matchs initial test message - self.assertAlmostEqual(pmt.to_python(msg_debug.get_message(0)), test_str, "mismatch initial test string") + self.assertAlmostEqual(pmt.to_python(msg_debug.get_message( + 0)), test_str, "mismatch initial test string") # last message matches changed test message no_msgs = msg_debug.num_messages() - self.assertAlmostEqual(pmt.to_python(msg_debug.get_message(no_msgs - 1)), new_msg, "failed to update string") + self.assertAlmostEqual(pmt.to_python(msg_debug.get_message( + no_msgs - 1)), new_msg, "failed to update string") + + if __name__ == '__main__': gr_unittest.run(qa_message_debug) diff --git a/gr-blocks/python/blocks/qa_message_strobe.py b/gr-blocks/python/blocks/qa_message_strobe.py index 2f11a1d5c83..8e5eb917386 100644 --- a/gr-blocks/python/blocks/qa_message_strobe.py +++ b/gr-blocks/python/blocks/qa_message_strobe.py @@ -17,6 +17,8 @@ # similar tests contained in message_debug class # this tests the periodic message output and the input port to change the message + + class qa_message_strobe(gr_unittest.TestCase): def setUp(self): @@ -29,18 +31,22 @@ def test_001_t(self): test_str = "test_msg" new_msg = "new_msg" message_period_ms = 100 - msg_strobe = blocks.message_strobe(pmt.intern(test_str), message_period_ms) + msg_strobe = blocks.message_strobe( + pmt.intern(test_str), message_period_ms) msg_debug = blocks.message_debug() self.tb.msg_connect(msg_strobe, "strobe", msg_debug, "store") self.tb.start() - self.assertAlmostEqual(msg_debug.num_messages(), 0, delta=2) # 1st call, expect 0 - time.sleep(1) # floor(1000/100) = 10 - self.assertAlmostEqual(msg_debug.num_messages(), 10, delta=3) # 2nd call == 1 - time.sleep(1) # floor(2000/100) = 15 - self.assertAlmostEqual(msg_debug.num_messages(), 20, delta=3) # 3th call == 3 + self.assertAlmostEqual(msg_debug.num_messages(), + 0, delta=2) # 1st call, expect 0 + time.sleep(1) # floor(1000/100) = 10 + self.assertAlmostEqual(msg_debug.num_messages(), + 10, delta=3) # 2nd call == 1 + time.sleep(1) # floor(2000/100) = 15 + self.assertAlmostEqual(msg_debug.num_messages(), + 20, delta=3) # 3th call == 3 # change test message msg_strobe.to_basic_block()._post(pmt.intern("set_msg"), pmt.intern(new_msg)) @@ -51,11 +57,14 @@ def test_001_t(self): # check data # first received message matchs initial test message - self.assertAlmostEqual(pmt.to_python(msg_debug.get_message(0)), test_str, "mismatch initial test string") + self.assertAlmostEqual(pmt.to_python(msg_debug.get_message( + 0)), test_str, "mismatch initial test string") # last message matches changed test message no_msgs = msg_debug.num_messages() - self.assertAlmostEqual(pmt.to_python(msg_debug.get_message(no_msgs - 1)), new_msg, "failed to update string") + self.assertAlmostEqual(pmt.to_python(msg_debug.get_message( + no_msgs - 1)), new_msg, "failed to update string") + if __name__ == '__main__': gr_unittest.run(qa_message_strobe) diff --git a/gr-blocks/python/blocks/qa_pack_k_bits.py b/gr-blocks/python/blocks/qa_pack_k_bits.py index c4cfd6545ea..5c5d077d44b 100644 --- a/gr-blocks/python/blocks/qa_pack_k_bits.py +++ b/gr-blocks/python/blocks/qa_pack_k_bits.py @@ -14,6 +14,7 @@ from gnuradio import gr, gr_unittest, blocks import pmt + class test_pack(gr_unittest.TestCase): def setUp(self): @@ -56,27 +57,27 @@ def test_003(self): def test_004(self): # Test tags propagation - #Tags on the incoming bits + # Tags on the incoming bits src_data = [1, 0, 1, 1, 0, 0, 0, 1] #src_tag_offsets = [1, 2, 3, 5, 6] src_tag_offsets = [1, 2, 3, 5, 6, 7] - #Ground Truth - expected_data= [2, 3, 0, 1] + # Ground Truth + expected_data = [2, 3, 0, 1] expected_tag_offsets = [0, 1, 1, 2, 3, 3] test_tags = list() tag_indexs = range(len(src_tag_offsets)) for src_tag in tag_indexs: test_tags.append( - gr.tag_utils.python_to_tag(( src_tag_offsets[src_tag], - pmt.intern('tag_byte'), - pmt.from_long(src_tag), - None - )) - ) - - src = blocks.vector_source_b(src_data, False,1, test_tags ) + gr.tag_utils.python_to_tag((src_tag_offsets[src_tag], + pmt.intern('tag_byte'), + pmt.from_long(src_tag), + None + )) + ) + + src = blocks.vector_source_b(src_data, False, 1, test_tags) op = blocks.pack_k_bits_bb(2) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) @@ -86,11 +87,11 @@ def test_004(self): self.assertEqual(expected_data, dst.data()) # Check the tag values - self.assertEqual( list(tag_indexs), [ pmt.to_python(x.value) for x in dst.tags()]) + self.assertEqual(list(tag_indexs), [ + pmt.to_python(x.value) for x in dst.tags()]) # Check the tag offsets - self.assertEqual( expected_tag_offsets, [ x.offset for x in dst.tags()]) - + self.assertEqual(expected_tag_offsets, [x.offset for x in dst.tags()]) if __name__ == '__main__': diff --git a/gr-blocks/python/blocks/qa_peak_detector2.py b/gr-blocks/python/blocks/qa_peak_detector2.py index d8055d61f7c..fe5ab6e3ea1 100644 --- a/gr-blocks/python/blocks/qa_peak_detector2.py +++ b/gr-blocks/python/blocks/qa_peak_detector2.py @@ -116,7 +116,7 @@ def test_peak4(self): self.assertEqual(expected_result[0:len(dst_data)], dst_data) def test_peak5(self): - #print "\n\nTEST 5" + # print "\n\nTEST 5" tb = self.tb data = [0, 0, 0, 10, 0, 0, 0, 0] @@ -124,7 +124,8 @@ def test_peak5(self): expected_result_peak = [0, 0, 0, 1, 0, 0, 0, 0] expected_result_average = [0] for i in data: - expected_result_average.append(expected_result_average[-1] * (1 - alpha) + i * alpha) + expected_result_average.append( + expected_result_average[-1] * (1 - alpha) + i * alpha) src = blocks.vector_source_f(data, False) regen = blocks.peak_detector2_fb(2.0, 2, alpha) @@ -142,5 +143,6 @@ def test_peak5(self): self.assertEqual(expected_result_peak, dst_data) self.assertFloatTuplesAlmostEqual(expected_result_average[1:], dst_avg) + if __name__ == '__main__': gr_unittest.run(test_peak_detector2) diff --git a/gr-blocks/python/blocks/qa_stream_demux.py b/gr-blocks/python/blocks/qa_stream_demux.py index 629c35283c9..a03a125d01f 100755 --- a/gr-blocks/python/blocks/qa_stream_demux.py +++ b/gr-blocks/python/blocks/qa_stream_demux.py @@ -69,8 +69,8 @@ def help_stream_ramp_2ff(self, N, stream_sizes): return (dst0.data(), dst1.data()) def help_stream_tag_propagation(self, N, stream_sizes): - src_data = (stream_sizes[0] * [1, ] + stream_sizes[1] - * [2, ] + stream_sizes[2] * [3, ]) * N + src_data = (stream_sizes[0] * [1, ] + stream_sizes[1] * + [2, ] + stream_sizes[2] * [3, ]) * N src = blocks.vector_source_f(src_data, False) diff --git a/gr-blocks/python/blocks/qa_stream_mux.py b/gr-blocks/python/blocks/qa_stream_mux.py index 4c935245db9..57ebbe97afe 100644 --- a/gr-blocks/python/blocks/qa_stream_mux.py +++ b/gr-blocks/python/blocks/qa_stream_mux.py @@ -203,19 +203,19 @@ def test_tag_propagation(self): N = 10 # Block length stream_sizes = [1, 2, 3] - expected_result = N * (stream_sizes[0] * [1, ] - + stream_sizes[1] * [2, ] - + stream_sizes[2] * [3, ]) + expected_result = N * (stream_sizes[0] * [1, ] + + stream_sizes[1] * [2, ] + + stream_sizes[2] * [3, ]) # check the data (result, tags) = self.help_stream_tag_propagation(N, stream_sizes) self.assertFloatTuplesAlmostEqual(expected_result, result, places=6) # check the tags expected_tag_offsets_src1 = [sum(stream_sizes) * i for i in range(N)] - expected_tag_offsets_src2 = [stream_sizes[0] - + sum(stream_sizes) * i for i in range(N)] - expected_tag_offsets_src3 = [stream_sizes[0] + stream_sizes[1] - + sum(stream_sizes) * i for i in range(N)] + expected_tag_offsets_src2 = [stream_sizes[0] + + sum(stream_sizes) * i for i in range(N)] + expected_tag_offsets_src3 = [stream_sizes[0] + stream_sizes[1] + + sum(stream_sizes) * i for i in range(N)] tags_src1 = [ tag for tag in tags if pmt.eq( tag.key, pmt.intern('src1'))] diff --git a/gr-blocks/python/blocks/qa_unpack_k_bits.py b/gr-blocks/python/blocks/qa_unpack_k_bits.py index 82ea23c819f..0ff70e0b59b 100644 --- a/gr-blocks/python/blocks/qa_unpack_k_bits.py +++ b/gr-blocks/python/blocks/qa_unpack_k_bits.py @@ -46,11 +46,11 @@ def test_002(self): def test_003(self): - #Tags on the incoming bytes - src_data= [2, 3, 0, 1] + # Tags on the incoming bytes + src_data = [2, 3, 0, 1] src_tag_offsets = [0, 1, 1, 2, 3] - #Ground Truth + # Ground Truth expected_data = [1, 0, 1, 1, 0, 0, 0, 1] expected_tag_offsets = [0, 2, 2, 4, 6] @@ -58,14 +58,14 @@ def test_003(self): tag_indexs = range(len(src_tag_offsets)) for src_tag in tag_indexs: test_tags.append( - gr.tag_utils.python_to_tag(( src_tag_offsets[src_tag], - pmt.intern('tag_byte'), - pmt.from_long(src_tag), - None - )) - ) - - src = blocks.vector_source_b(src_data, False,1, test_tags ) + gr.tag_utils.python_to_tag((src_tag_offsets[src_tag], + pmt.intern('tag_byte'), + pmt.from_long(src_tag), + None + )) + ) + + src = blocks.vector_source_b(src_data, False, 1, test_tags) op = blocks.unpack_k_bits_bb(2) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) @@ -75,10 +75,12 @@ def test_003(self): self.assertEqual(expected_data, dst.data()) # Check the tag values - self.assertEqual( list(tag_indexs), [ pmt.to_python(x.value) for x in dst.tags()]) + self.assertEqual(list(tag_indexs), [ + pmt.to_python(x.value) for x in dst.tags()]) # Check the tag offsets - self.assertEqual( expected_tag_offsets, [ x.offset for x in dst.tags()]) + self.assertEqual(expected_tag_offsets, [x.offset for x in dst.tags()]) + if __name__ == '__main__': gr_unittest.run(test_unpack) diff --git a/gr-blocks/python/blocks/stream_to_vector_decimator.py b/gr-blocks/python/blocks/stream_to_vector_decimator.py index 2e1a383f32a..e84bfc63b45 100644 --- a/gr-blocks/python/blocks/stream_to_vector_decimator.py +++ b/gr-blocks/python/blocks/stream_to_vector_decimator.py @@ -32,11 +32,12 @@ def __init__(self, item_size, sample_rate, vec_rate, vec_len): self._sample_rate = sample_rate gr.hier_block2.__init__(self, "stream_to_vector_decimator", - gr.io_signature(1, 1, item_size), # Input signature - gr.io_signature(1, 1, item_size*vec_len)) # Output signature + # Input signature + gr.io_signature(1, 1, item_size), + gr.io_signature(1, 1, item_size * vec_len)) # Output signature s2v = blocks.stream_to_vector(item_size, vec_len) - self.one_in_n = blocks.keep_one_in_n(item_size*vec_len, 1) + self.one_in_n = blocks.keep_one_in_n(item_size * vec_len, 1) self._update_decimator() self.connect(self, s2v, self.one_in_n, self) @@ -71,7 +72,7 @@ def set_decimation(self, decim): self.one_in_n.set_n(self._decim) def _update_decimator(self): - self.set_decimation(self._sample_rate/self._vec_len/self._vec_rate) + self.set_decimation(self._sample_rate / self._vec_len / self._vec_rate) def decimation(self): """ @@ -89,4 +90,4 @@ def frame_rate(self): """ Returns actual frame rate """ - return self._sample_rate/self._vec_len/self._decim + return self._sample_rate / self._vec_len / self._decim diff --git a/gr-blocks/python/blocks/var_to_msg.py b/gr-blocks/python/blocks/var_to_msg.py index 823609182c7..0a317830cf5 100644 --- a/gr-blocks/python/blocks/var_to_msg.py +++ b/gr-blocks/python/blocks/var_to_msg.py @@ -11,14 +11,17 @@ from gnuradio import gr import pmt + class var_to_msg_pair(gr.sync_block): """ This block has a callback that will emit a message pair with the updated variable value when called. This is useful for monitoring a GRC variable and emitting a message when it is changed. """ + def __init__(self, pairname): - gr.sync_block.__init__(self, name="var_to_msg_pair", in_sig=None, out_sig=None) + gr.sync_block.__init__( + self, name="var_to_msg_pair", in_sig=None, out_sig=None) self.pairname = pairname @@ -37,11 +40,12 @@ def variable_changed(self, value): else: p = pmt.to_pmt(value) - self.message_port_pub(pmt.intern("msgout"), pmt.cons(pmt.intern(self.pairname), p)) + self.message_port_pub(pmt.intern("msgout"), + pmt.cons(pmt.intern(self.pairname), p)) except Exception as e: - gr.log.error("Unable to convert " + repr(value) + " to PDU, no message will be emitted (reason: %s)" % repr(e)) - + gr.log.error("Unable to convert " + repr(value) + + " to PDU, no message will be emitted (reason: %s)" % repr(e)) def stop(self): return True diff --git a/gr-channels/python/channels/amp_bal.py b/gr-channels/python/channels/amp_bal.py index 30e0f0d8e2f..ec6025b4d8c 100644 --- a/gr-channels/python/channels/amp_bal.py +++ b/gr-channels/python/channels/amp_bal.py @@ -11,13 +11,14 @@ from gnuradio import gr from gnuradio.filter import firdes + class amp_bal(gr.hier_block2): def __init__(self, alpha=0): gr.hier_block2.__init__( self, "Amplitude Balance", - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), ) ################################################## @@ -40,17 +41,20 @@ def __init__(self, alpha=0): ################################################## self.connect((self.blocks_float_to_complex, 0), (self, 0)) self.connect((self, 0), (self.blocks_complex_to_float, 0)) - self.connect((self.blocks_complex_to_float, 0), (self.blocks_rms_xx, 0)) - self.connect((self.blocks_complex_to_float, 1), (self.blocks_rms_xx0, 0)) + self.connect((self.blocks_complex_to_float, 0), + (self.blocks_rms_xx, 0)) + self.connect((self.blocks_complex_to_float, 1), + (self.blocks_rms_xx0, 0)) self.connect((self.blocks_rms_xx, 0), (self.blocks_divide_xx, 0)) self.connect((self.blocks_rms_xx0, 0), (self.blocks_divide_xx, 1)) - self.connect((self.blocks_complex_to_float, 0), (self.blocks_float_to_complex, 0)) - self.connect((self.blocks_complex_to_float, 1), (self.blocks_multiply_vxx1, 1)) - self.connect((self.blocks_divide_xx, 0), (self.blocks_multiply_vxx1, 0)) - self.connect((self.blocks_multiply_vxx1, 0), (self.blocks_float_to_complex, 1)) - - -# QT sink close method reimplementation + self.connect((self.blocks_complex_to_float, 0), + (self.blocks_float_to_complex, 0)) + self.connect((self.blocks_complex_to_float, 1), + (self.blocks_multiply_vxx1, 1)) + self.connect((self.blocks_divide_xx, 0), + (self.blocks_multiply_vxx1, 0)) + self.connect((self.blocks_multiply_vxx1, 0), + (self.blocks_float_to_complex, 1)) def get_alpha(self): return self.alpha @@ -59,5 +63,3 @@ def set_alpha(self, alpha): self.alpha = alpha self.blocks_rms_xx.set_alpha(self.alpha) self.blocks_rms_xx0.set_alpha(self.alpha) - - diff --git a/gr-channels/python/channels/conj_fs_iqcorr.py b/gr-channels/python/channels/conj_fs_iqcorr.py index 700eb645c23..0b6371dd308 100644 --- a/gr-channels/python/channels/conj_fs_iqcorr.py +++ b/gr-channels/python/channels/conj_fs_iqcorr.py @@ -12,13 +12,14 @@ from gnuradio import gr from gnuradio.filter import firdes + class conj_fs_iqcorr(gr.hier_block2): def __init__(self, delay=0, taps=[]): gr.hier_block2.__init__( self, "Conj FS IQBal", - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), ) ################################################## @@ -31,7 +32,7 @@ def __init__(self, delay=0, taps=[]): # Blocks ################################################## self.filter_fir_filter_xxx_0 = filter.fir_filter_ccc(1, (taps)) - self.delay_0 = blocks.delay(gr.sizeof_gr_complex*1, delay) + self.delay_0 = blocks.delay(gr.sizeof_gr_complex * 1, delay) self.blocks_conjugate_cc_0 = blocks.conjugate_cc() self.blocks_add_xx_0 = blocks.add_vcc(1) @@ -40,14 +41,13 @@ def __init__(self, delay=0, taps=[]): ################################################## self.connect((self.blocks_add_xx_0, 0), (self, 0)) self.connect((self, 0), (self.blocks_conjugate_cc_0, 0)) - self.connect((self.filter_fir_filter_xxx_0, 0), (self.blocks_add_xx_0, 1)) - self.connect((self.blocks_conjugate_cc_0, 0), (self.filter_fir_filter_xxx_0, 0)) + self.connect((self.filter_fir_filter_xxx_0, 0), + (self.blocks_add_xx_0, 1)) + self.connect((self.blocks_conjugate_cc_0, 0), + (self.filter_fir_filter_xxx_0, 0)) self.connect((self, 0), (self.delay_0, 0)) self.connect((self.delay_0, 0), (self.blocks_add_xx_0, 0)) - -# QT sink close method reimplementation - def get_delay(self): return self.delay @@ -61,5 +61,3 @@ def get_taps(self): def set_taps(self, taps): self.taps = taps self.filter_fir_filter_xxx_0.set_taps((self.taps)) - - diff --git a/gr-channels/python/channels/distortion_2_gen.py b/gr-channels/python/channels/distortion_2_gen.py index 28b50196861..20ab6fe5631 100644 --- a/gr-channels/python/channels/distortion_2_gen.py +++ b/gr-channels/python/channels/distortion_2_gen.py @@ -11,13 +11,14 @@ from gnuradio.filter import firdes import math + class distortion_2_gen(gr.hier_block2): def __init__(self, beta=0): gr.hier_block2.__init__( self, "Second Order Distortion", - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), ) ################################################## @@ -38,20 +39,22 @@ def __init__(self, beta=0): ################################################## # Connections ################################################## - self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_add_xx_0, 1)) + self.connect((self.blocks_multiply_const_vxx_0, 0), + (self.blocks_add_xx_0, 1)) self.connect((self, 0), (self.blocks_multiply_xx_0, 0)) self.connect((self, 0), (self.blocks_add_xx_0, 0)) self.connect((self.blocks_add_xx_0, 0), (self, 0)) self.connect((self, 0), (self.blocks_conjugate_cc_0, 0)) - self.connect((self.blocks_conjugate_cc_0, 0), (self.blocks_multiply_xx_0_0, 1)) + self.connect((self.blocks_conjugate_cc_0, 0), + (self.blocks_multiply_xx_0_0, 1)) self.connect((self, 0), (self.blocks_multiply_xx_0, 1)) self.connect((self, 0), (self.blocks_multiply_xx_0_0, 0)) - self.connect((self.blocks_multiply_xx_0_0, 0), (self.blocks_add_xx_0_0, 1)) - self.connect((self.blocks_multiply_xx_0, 0), (self.blocks_add_xx_0_0, 0)) - self.connect((self.blocks_add_xx_0_0, 0), (self.blocks_multiply_const_vxx_0, 0)) - - -# QT sink close method reimplementation + self.connect((self.blocks_multiply_xx_0_0, 0), + (self.blocks_add_xx_0_0, 1)) + self.connect((self.blocks_multiply_xx_0, 0), + (self.blocks_add_xx_0_0, 0)) + self.connect((self.blocks_add_xx_0_0, 0), + (self.blocks_multiply_const_vxx_0, 0)) def get_beta(self): return self.beta diff --git a/gr-channels/python/channels/distortion_3_gen.py b/gr-channels/python/channels/distortion_3_gen.py index 1607e01bf23..eda558c3f52 100644 --- a/gr-channels/python/channels/distortion_3_gen.py +++ b/gr-channels/python/channels/distortion_3_gen.py @@ -11,13 +11,14 @@ from gnuradio.filter import firdes import math + class distortion_3_gen(gr.hier_block2): def __init__(self, beta=0): gr.hier_block2.__init__( self, "Third Order Distortion", - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), ) ################################################## @@ -28,7 +29,7 @@ def __init__(self, beta=0): ################################################## # Blocks ################################################## - self.blocks_null_source_0 = blocks.null_source(gr.sizeof_float*1) + self.blocks_null_source_0 = blocks.null_source(gr.sizeof_float * 1) self.blocks_multiply_xx_0 = blocks.multiply_vcc(1) self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vcc((beta, )) self.blocks_float_to_complex_0 = blocks.float_to_complex(1) @@ -38,24 +39,24 @@ def __init__(self, beta=0): ################################################## # Connections ################################################## - self.connect((self.blocks_float_to_complex_0, 0), (self.blocks_multiply_xx_0, 1)) - self.connect((self.blocks_null_source_0, 0), (self.blocks_float_to_complex_0, 1)) - self.connect((self.blocks_complex_to_mag_squared_0, 0), (self.blocks_float_to_complex_0, 0)) - self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_add_xx_0, 1)) - self.connect((self.blocks_multiply_xx_0, 0), (self.blocks_multiply_const_vxx_0, 0)) + self.connect((self.blocks_float_to_complex_0, 0), + (self.blocks_multiply_xx_0, 1)) + self.connect((self.blocks_null_source_0, 0), + (self.blocks_float_to_complex_0, 1)) + self.connect((self.blocks_complex_to_mag_squared_0, 0), + (self.blocks_float_to_complex_0, 0)) + self.connect((self.blocks_multiply_const_vxx_0, 0), + (self.blocks_add_xx_0, 1)) + self.connect((self.blocks_multiply_xx_0, 0), + (self.blocks_multiply_const_vxx_0, 0)) self.connect((self, 0), (self.blocks_complex_to_mag_squared_0, 0)) self.connect((self, 0), (self.blocks_multiply_xx_0, 0)) self.connect((self, 0), (self.blocks_add_xx_0, 0)) self.connect((self.blocks_add_xx_0, 0), (self, 0)) - -# QT sink close method reimplementation - def get_beta(self): return self.beta def set_beta(self, beta): self.beta = beta self.blocks_multiply_const_vxx_0.set_k((self.beta, )) - - diff --git a/gr-channels/python/channels/impairments.py b/gr-channels/python/channels/impairments.py index b81706bf97b..e57b7522f9a 100644 --- a/gr-channels/python/channels/impairments.py +++ b/gr-channels/python/channels/impairments.py @@ -12,12 +12,13 @@ from gnuradio import gr from gnuradio.filter import firdes -#Import locally +# Import locally from .phase_noise_gen import phase_noise_gen from .iqbal_gen import iqbal_gen from .distortion_2_gen import distortion_2_gen from .distortion_3_gen import distortion_3_gen + class impairments(gr.hier_block2): def __init__(self, @@ -31,8 +32,8 @@ def __init__(self, beta=0): gr.hier_block2.__init__( self, "Radio Impairments Model", - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), ) ################################################## @@ -55,10 +56,11 @@ def __init__(self, self.channels_distortion_3_gen_0 = distortion_3_gen(beta) self.channels_distortion_2_gen_0 = distortion_2_gen(gamma) self.freq_modulator = blocks.multiply_cc() - self.freq_offset_gen = analog.sig_source_c(1.0, analog.GR_COS_WAVE, freq_offset, 1, 0) + self.freq_offset_gen = analog.sig_source_c( + 1.0, analog.GR_COS_WAVE, freq_offset, 1, 0) self.freq_modulator_dcoffs = blocks.multiply_cc() self.freq_offset_conj = blocks.conjugate_cc() - self.dc_offset = blocks.add_const_vcc((i_ofs + q_ofs* 1j, )) + self.dc_offset = blocks.add_const_vcc((i_ofs + q_ofs * 1j, )) ################################################## # Frequency offset @@ -75,13 +77,11 @@ def __init__(self, (self.dc_offset, 0), ) # Frequency offset again - self.connect((self.freq_offset_gen, 0), (self.freq_modulator_dcoffs, 0)) + self.connect((self.freq_offset_gen, 0), + (self.freq_modulator_dcoffs, 0)) self.connect((self.dc_offset, 0), (self.freq_modulator_dcoffs, 1)) self.connect((self.freq_modulator_dcoffs, 0), (self, 0)) - -# QT sink close method reimplementation - def get_phase_noise_mag(self): return self.phase_noise_mag @@ -108,7 +108,7 @@ def get_q_ofs(self): def set_q_ofs(self, q_ofs): self.q_ofs = q_ofs - self.dc_offset.set_k((self.i_ofs + self.q_ofs* 1j, )) + self.dc_offset.set_k((self.i_ofs + self.q_ofs * 1j, )) def get_i_ofs(self): return self.i_ofs @@ -116,7 +116,7 @@ def get_i_ofs(self): def set_i_ofs(self, i_ofs): """Set inphase part of DC offset""" self.i_ofs = i_ofs - self.dc_offset.set_k((self.i_ofs + self.q_ofs* 1j, )) + self.dc_offset.set_k((self.i_ofs + self.q_ofs * 1j, )) def get_freq_offset(self): """Return frequency offset (normalized to 1.0)""" diff --git a/gr-channels/python/channels/iqbal_gen.py b/gr-channels/python/channels/iqbal_gen.py index 42b8f649926..afc00ada84d 100644 --- a/gr-channels/python/channels/iqbal_gen.py +++ b/gr-channels/python/channels/iqbal_gen.py @@ -11,6 +11,7 @@ from gnuradio.filter import firdes import math + class iqbal_gen(gr.hier_block2): def __init__(self, magnitude=0, phase=0, mode=0): @@ -47,8 +48,8 @@ def __init__(self, magnitude=0, phase=0, mode=0): ''' gr.hier_block2.__init__( self, "IQ Imbalance Generator", - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), ) ################################################## @@ -62,9 +63,12 @@ def __init__(self, magnitude=0, phase=0, mode=0): # Blocks ################################################## # Same blocks for Transmitter and Receiver - self.mag = blocks.multiply_const_vff((math.pow(10,magnitude/20.0), )) - self.sin_phase = blocks.multiply_const_vff((math.sin(phase*math.pi/180.0), )) - self.cos_phase = blocks.multiply_const_vff((math.cos(phase*math.pi/180.0), )) + self.mag = blocks.multiply_const_vff( + (math.pow(10, magnitude / 20.0), )) + self.sin_phase = blocks.multiply_const_vff( + (math.sin(phase * math.pi / 180.0), )) + self.cos_phase = blocks.multiply_const_vff( + (math.cos(phase * math.pi / 180.0), )) self.f2c = blocks.float_to_complex(1) self.c2f = blocks.complex_to_float(1) self.adder = blocks.add_vff(1) @@ -95,7 +99,6 @@ def __init__(self, magnitude=0, phase=0, mode=0): self.connect((self.adder, 0), (self.f2c, 1)) self.connect((self.f2c, 0), (self, 0)) - # QT sink close method reimplementation def get_magnitude(self): @@ -103,14 +106,12 @@ def get_magnitude(self): def set_magnitude(self, magnitude): self.magnitude = magnitude - self.mag.set_k((math.pow(10,self.magnitude / 20.0), )) + self.mag.set_k((math.pow(10, self.magnitude / 20.0), )) def get_phase(self): return self.phase def set_phase(self, phase): self.phase = phase - self.sin_phase.set_k((math.sin(self.phase*math.pi/180.0), )) - self.cos_phase.set_k((math.cos(self.phase*math.pi/180.0), )) - - + self.sin_phase.set_k((math.sin(self.phase * math.pi / 180.0), )) + self.cos_phase.set_k((math.cos(self.phase * math.pi / 180.0), )) diff --git a/gr-channels/python/channels/phase_bal.py b/gr-channels/python/channels/phase_bal.py index b760e6f4392..4bece67fa9f 100644 --- a/gr-channels/python/channels/phase_bal.py +++ b/gr-channels/python/channels/phase_bal.py @@ -11,13 +11,14 @@ from gnuradio import gr from gnuradio.filter import firdes + class phase_bal(gr.hier_block2): def __init__(self, alpha=0): gr.hier_block2.__init__( self, "IQ Phase Balancer", - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), ) ################################################## @@ -28,7 +29,8 @@ def __init__(self, alpha=0): ################################################## # Blocks ################################################## - self.filter_single_pole_iir_filter_xx_0 = filter.single_pole_iir_filter_ff(alpha, 1) + self.filter_single_pole_iir_filter_xx_0 = filter.single_pole_iir_filter_ff( + alpha, 1) self.blocks_sub_xx_1 = blocks.sub_ff(1) self.blocks_sub_xx_0 = blocks.sub_ff(1) self.blocks_multiply_xx_2 = blocks.multiply_vff(1) @@ -43,28 +45,39 @@ def __init__(self, alpha=0): ################################################## # Connections ################################################## - self.connect((self.blocks_complex_to_float_0, 0), (self.blocks_multiply_xx_0, 0)) - self.connect((self.blocks_complex_to_float_0, 1), (self.blocks_multiply_xx_0, 1)) - self.connect((self.blocks_multiply_xx_0, 0), (self.blocks_divide_xx_0, 0)) - self.connect((self.blocks_sub_xx_0, 0), (self.blocks_float_to_complex_0, 1)) + self.connect((self.blocks_complex_to_float_0, 0), + (self.blocks_multiply_xx_0, 0)) + self.connect((self.blocks_complex_to_float_0, 1), + (self.blocks_multiply_xx_0, 1)) + self.connect((self.blocks_multiply_xx_0, 0), + (self.blocks_divide_xx_0, 0)) + self.connect((self.blocks_sub_xx_0, 0), + (self.blocks_float_to_complex_0, 1)) self.connect((self.blocks_multiply_xx_1, 0), (self.blocks_sub_xx_0, 1)) - self.connect((self.filter_single_pole_iir_filter_xx_0, 0), (self.blocks_multiply_xx_1, 1)) - self.connect((self.blocks_complex_to_float_0, 0), (self.blocks_multiply_xx_1, 0)) + self.connect((self.filter_single_pole_iir_filter_xx_0, 0), + (self.blocks_multiply_xx_1, 1)) + self.connect((self.blocks_complex_to_float_0, 0), + (self.blocks_multiply_xx_1, 0)) self.connect((self.blocks_multiply_xx_2, 0), (self.blocks_sub_xx_1, 1)) - self.connect((self.blocks_complex_to_float_0, 1), (self.blocks_sub_xx_0, 0)) - self.connect((self.blocks_sub_xx_1, 0), (self.blocks_float_to_complex_0, 0)) - self.connect((self.blocks_complex_to_mag_squared_0, 0), (self.blocks_divide_xx_0, 1)) - self.connect((self.blocks_complex_to_float_0, 0), (self.blocks_sub_xx_1, 0)) - self.connect((self.blocks_divide_xx_0, 0), (self.blocks_multiply_const_vxx_0, 0)) - self.connect((self.blocks_multiply_const_vxx_0, 0), (self.filter_single_pole_iir_filter_xx_0, 0)) + self.connect((self.blocks_complex_to_float_0, 1), + (self.blocks_sub_xx_0, 0)) + self.connect((self.blocks_sub_xx_1, 0), + (self.blocks_float_to_complex_0, 0)) + self.connect((self.blocks_complex_to_mag_squared_0, 0), + (self.blocks_divide_xx_0, 1)) + self.connect((self.blocks_complex_to_float_0, 0), + (self.blocks_sub_xx_1, 0)) + self.connect((self.blocks_divide_xx_0, 0), + (self.blocks_multiply_const_vxx_0, 0)) + self.connect((self.blocks_multiply_const_vxx_0, 0), + (self.filter_single_pole_iir_filter_xx_0, 0)) self.connect((self, 0), (self.blocks_complex_to_float_0, 0)) self.connect((self, 0), (self.blocks_complex_to_mag_squared_0, 0)) self.connect((self.blocks_float_to_complex_0, 0), (self, 0)) - self.connect((self.filter_single_pole_iir_filter_xx_0, 0), (self.blocks_multiply_xx_2, 0)) - self.connect((self.blocks_complex_to_float_0, 1), (self.blocks_multiply_xx_2, 1)) - - -# QT sink close method reimplementation + self.connect((self.filter_single_pole_iir_filter_xx_0, 0), + (self.blocks_multiply_xx_2, 0)) + self.connect((self.blocks_complex_to_float_0, 1), + (self.blocks_multiply_xx_2, 1)) def get_alpha(self): return self.alpha @@ -72,5 +85,3 @@ def get_alpha(self): def set_alpha(self, alpha): self.alpha = alpha self.filter_single_pole_iir_filter_xx_0.set_taps(self.alpha) - - diff --git a/gr-channels/python/channels/phase_noise_gen.py b/gr-channels/python/channels/phase_noise_gen.py index 95c5676e401..4c4f39c8603 100644 --- a/gr-channels/python/channels/phase_noise_gen.py +++ b/gr-channels/python/channels/phase_noise_gen.py @@ -12,13 +12,14 @@ from gnuradio import gr from gnuradio.filter import firdes + class phase_noise_gen(gr.hier_block2): def __init__(self, noise_mag=0, alpha=0.1): gr.hier_block2.__init__( self, "Phase Noise Generator", - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), - gr.io_signature(1, 1, gr.sizeof_gr_complex*1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), + gr.io_signature(1, 1, gr.sizeof_gr_complex * 1), ) ################################################## @@ -30,27 +31,32 @@ def __init__(self, noise_mag=0, alpha=0.1): ################################################## # Blocks ################################################## - self.filter_single_pole_iir_filter_xx_0 = filter.single_pole_iir_filter_ff(alpha, 1) + self.filter_single_pole_iir_filter_xx_0 = filter.single_pole_iir_filter_ff( + alpha, 1) self.blocks_transcendental_0_0 = blocks.transcendental("sin", "float") self.blocks_transcendental_0 = blocks.transcendental("cos", "float") self.blocks_multiply_xx_0 = blocks.multiply_vcc(1) self.blocks_float_to_complex_0 = blocks.float_to_complex(1) - self.analog_noise_source_x_0 = analog.noise_source_f(analog.GR_GAUSSIAN, noise_mag, 42) + self.analog_noise_source_x_0 = analog.noise_source_f( + analog.GR_GAUSSIAN, noise_mag, 42) ################################################## # Connections ################################################## - self.connect((self.blocks_float_to_complex_0, 0), (self.blocks_multiply_xx_0, 1)) - self.connect((self.analog_noise_source_x_0, 0), (self.filter_single_pole_iir_filter_xx_0, 0)) + self.connect((self.blocks_float_to_complex_0, 0), + (self.blocks_multiply_xx_0, 1)) + self.connect((self.analog_noise_source_x_0, 0), + (self.filter_single_pole_iir_filter_xx_0, 0)) self.connect((self.blocks_multiply_xx_0, 0), (self, 0)) self.connect((self, 0), (self.blocks_multiply_xx_0, 0)) - self.connect((self.filter_single_pole_iir_filter_xx_0, 0), (self.blocks_transcendental_0, 0)) - self.connect((self.filter_single_pole_iir_filter_xx_0, 0), (self.blocks_transcendental_0_0, 0)) - self.connect((self.blocks_transcendental_0, 0), (self.blocks_float_to_complex_0, 0)) - self.connect((self.blocks_transcendental_0_0, 0), (self.blocks_float_to_complex_0, 1)) - - -# QT sink close method reimplementation + self.connect((self.filter_single_pole_iir_filter_xx_0, 0), + (self.blocks_transcendental_0, 0)) + self.connect((self.filter_single_pole_iir_filter_xx_0, 0), + (self.blocks_transcendental_0_0, 0)) + self.connect((self.blocks_transcendental_0, 0), + (self.blocks_float_to_complex_0, 0)) + self.connect((self.blocks_transcendental_0_0, 0), + (self.blocks_float_to_complex_0, 1)) def get_noise_mag(self): return self.noise_mag @@ -65,5 +71,3 @@ def get_alpha(self): def set_alpha(self, alpha): self.alpha = alpha self.filter_single_pole_iir_filter_xx_0.set_taps(self.alpha) - - diff --git a/gr-channels/python/channels/quantizer.py b/gr-channels/python/channels/quantizer.py index cedeb368d07..ef009845b6b 100644 --- a/gr-channels/python/channels/quantizer.py +++ b/gr-channels/python/channels/quantizer.py @@ -9,13 +9,14 @@ from gnuradio import gr from gnuradio.filter import firdes + class quantizer(gr.hier_block2): def __init__(self, bits=16): gr.hier_block2.__init__( self, "Quantizer", - gr.io_signature(1, 1, gr.sizeof_float*1), - gr.io_signature(1, 1, gr.sizeof_float*1), + gr.io_signature(1, 1, gr.sizeof_float * 1), + gr.io_signature(1, 1, gr.sizeof_float * 1), ) ################################################## @@ -27,28 +28,29 @@ def __init__(self, bits=16): # Blocks ################################################## self.blocks_short_to_float_0 = blocks.short_to_float(1, 1) - self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vff((1.0 / pow(2.0,bits-1.0), )) - self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((pow(2,bits-1.0), )) + self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vff( + (1.0 / pow(2.0, bits - 1.0), )) + self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff( + (pow(2, bits - 1.0), )) self.blocks_float_to_short_0 = blocks.float_to_short(1, 1) ################################################## # Connections ################################################## self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self, 0)) - self.connect((self.blocks_short_to_float_0, 0), (self.blocks_multiply_const_vxx_0_0, 0)) - self.connect((self.blocks_float_to_short_0, 0), (self.blocks_short_to_float_0, 0)) - self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_float_to_short_0, 0)) + self.connect((self.blocks_short_to_float_0, 0), + (self.blocks_multiply_const_vxx_0_0, 0)) + self.connect((self.blocks_float_to_short_0, 0), + (self.blocks_short_to_float_0, 0)) + self.connect((self.blocks_multiply_const_vxx_0, 0), + (self.blocks_float_to_short_0, 0)) self.connect((self, 0), (self.blocks_multiply_const_vxx_0, 0)) - -# QT sink close method reimplementation - def get_bits(self): return self.bits def set_bits(self, bits): self.bits = bits - self.blocks_multiply_const_vxx_0_0.set_k((1.0 / pow(2.0,self.bits-1.0), )) - self.blocks_multiply_const_vxx_0.set_k((pow(2,self.bits-1.0), )) - - + self.blocks_multiply_const_vxx_0_0.set_k( + (1.0 / pow(2.0, self.bits - 1.0), )) + self.blocks_multiply_const_vxx_0.set_k((pow(2, self.bits - 1.0), )) diff --git a/gr-digital/examples/berawgn.py b/gr-digital/examples/berawgn.py index 082b73d83f0..31ea8403b05 100644 --- a/gr-digital/examples/berawgn.py +++ b/gr-digital/examples/berawgn.py @@ -21,7 +21,6 @@ """ - import math import numpy from gnuradio import gr, digital @@ -45,20 +44,23 @@ N_BITS = 1e7 RAND_SEED = 42 + def berawgn(EbN0): """ Calculates theoretical bit error rate in AWGN (for BPSK and given Eb/N0) """ return 0.5 * erfc(math.sqrt(10**(float(EbN0) / 10))) + class BitErrors(gr.hier_block2): """ Two inputs: true and received bits. We compare them and add up the number of incorrect bits. Because integrate_ff() can only add up a certain number of values, the output is not a scalar, but a sequence of values, the sum of which is the BER. """ + def __init__(self, bits_per_byte): gr.hier_block2.__init__(self, "BitErrors", - gr.io_signature(2, 2, gr.sizeof_char), - gr.io_signature(1, 1, gr.sizeof_int)) + gr.io_signature(2, 2, gr.sizeof_char), + gr.io_signature(1, 1, gr.sizeof_int)) # Bit comparison comp = blocks.xor_bb() @@ -74,29 +76,32 @@ def __init__(self, bits_per_byte): self) self.connect((self, 1), (comp, 1)) + class BERAWGNSimu(gr.top_block): " This contains the simulation flow graph " + def __init__(self, EbN0): gr.top_block.__init__(self) self.const = digital.qpsk_constellation() # Source is N_BITS bits, non-repeated - data = list(map(int, numpy.random.randint(0, self.const.arity(), N_BITS / self.const.bits_per_symbol()))) - src = blocks.vector_source_b(data, False) - mod = digital.chunks_to_symbols_bc((self.const.points()), 1) - add = blocks.add_vcc() + data = list(map(int, numpy.random.randint( + 0, self.const.arity(), N_BITS / self.const.bits_per_symbol()))) + src = blocks.vector_source_b(data, False) + mod = digital.chunks_to_symbols_bc((self.const.points()), 1) + add = blocks.add_vcc() noise = analog.noise_source_c(analog.GR_GAUSSIAN, self.EbN0_to_noise_voltage(EbN0), RAND_SEED) demod = digital.constellation_decoder_cb(self.const.base()) - ber = BitErrors(self.const.bits_per_symbol()) - self.sink = blocks.vector_sink_f() + ber = BitErrors(self.const.bits_per_symbol()) + self.sink = blocks.vector_sink_f() self.connect(src, mod, add, demod, ber, self.sink) self.connect(noise, (add, 1)) self.connect(src, (ber, 1)) def EbN0_to_noise_voltage(self, EbN0): """ Converts Eb/N0 to a complex noise voltage (assuming unit symbol power) """ - return 1.0 / math.sqrt(self.const.bits_per_symbol( * 10**(float(EbN0) / 10))) + return 1.0 / math.sqrt(self.const.bits_per_symbol(* 10**(float(EbN0) / 10))) def simulate_ber(EbN0): @@ -106,16 +111,17 @@ def simulate_ber(EbN0): fg.run() return numpy.sum(fg.sink.data()) + if __name__ == "__main__": EbN0_min = 0 EbN0_max = 15 - EbN0_range = list(range(EbN0_min, EbN0_max+1)) - ber_theory = [berawgn(x) for x in EbN0_range] + EbN0_range = list(range(EbN0_min, EbN0_max + 1)) + ber_theory = [berawgn(x) for x in EbN0_range] print("Simulating...") - ber_simu = [simulate_ber(x) for x in EbN0_range] + ber_simu = [simulate_ber(x) for x in EbN0_range] f = pyplot.figure() - s = f.add_subplot(1,1,1) + s = f.add_subplot(1, 1, 1) s.semilogy(EbN0_range, ber_theory, 'g-.', label="Theoretical") s.semilogy(EbN0_range, ber_simu, 'b-o', label="Simulated") s.set_title('BER Simulation') diff --git a/gr-digital/examples/example_costas.py b/gr-digital/examples/example_costas.py index 1db32875782..b7185ba974a 100644 --- a/gr-digital/examples/example_costas.py +++ b/gr-digital/examples/example_costas.py @@ -24,6 +24,7 @@ print("Error: could not import pyplot (http://matplotlib.sourceforge.net/)") sys.exit(1) + class example_costas(gr.top_block): def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset): gr.top_block.__init__(self) @@ -31,8 +32,8 @@ def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset) rrc_taps = filter.firdes.root_raised_cosine( sps, sps, 1.0, rolloff, ntaps) - data = 2.0*numpy.random.randint(0, 2, N) - 1.0 - data = numpy.exp(1j*poffset) * data + data = 2.0 * numpy.random.randint(0, 2, N) - 1.0 + data = numpy.exp(1j * poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) @@ -45,28 +46,29 @@ def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset) self.connect(self.src, self.rrc, self.chn, self.cst, self.vsnk_cst) self.connect(self.rrc, self.vsnk_src) - self.connect((self.cst,1), self.vsnk_frq) + self.connect((self.cst, 1), self.vsnk_frq) + def main(): parser = ArgumentParser(conflict_handler="resolve") parser.add_argument("-N", "--nsamples", type=int, default=2000, - help="Set the number of samples to process [default=%(default)r]") + help="Set the number of samples to process [default=%(default)r]") parser.add_argument("-S", "--sps", type=int, default=4, - help="Set the samples per symbol [default=%(default)r]") + help="Set the samples per symbol [default=%(default)r]") parser.add_argument("-r", "--rolloff", type=eng_float, default=0.35, - help="Set the rolloff factor [default=%(default)r]") - parser.add_argument("-W", "--bandwidth", type=eng_float, default=2*numpy.pi/100.0, - help="Set the loop bandwidth [default=%(default)r]") + help="Set the rolloff factor [default=%(default)r]") + parser.add_argument("-W", "--bandwidth", type=eng_float, default=2 * numpy.pi / 100.0, + help="Set the loop bandwidth [default=%(default)r]") parser.add_argument("-n", "--ntaps", type=int, default=45, - help="Set the number of taps in the filters [default=%(default)r]") + help="Set the number of taps in the filters [default=%(default)r]") parser.add_argument("--noise", type=eng_float, default=0.0, - help="Set the simulation noise voltage [default=%(default)r]") + help="Set the simulation noise voltage [default=%(default)r]") parser.add_argument("-f", "--foffset", type=eng_float, default=0.0, - help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") + help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") parser.add_argument("-t", "--toffset", type=eng_float, default=1.0, - help="Set the simulation's timing offset [default=%(default)r]") + help="Set the simulation's timing offset [default=%(default)r]") parser.add_argument("-p", "--poffset", type=eng_float, default=0.707, - help="Set the simulation's phase offset [default=%(default)r]") + help="Set the simulation's phase offset [default=%(default)r]") args = parser.parse_args() # Adjust N for the interpolation by sps @@ -81,21 +83,21 @@ def main(): data_src = numpy.array(put.vsnk_src.data()) # Convert the FLL's LO frequency from rads/sec to Hz - data_frq = numpy.array(put.vsnk_frq.data()) / (2.0*numpy.pi) + data_frq = numpy.array(put.vsnk_frq.data()) / (2.0 * numpy.pi) # adjust this to align with the data. - data_cst = numpy.array(3*[0,]+list(put.vsnk_cst.data())) + data_cst = numpy.array(3 * [0, ] + list(put.vsnk_cst.data())) # Plot the Costas loop's LO frequency - f1 = pyplot.figure(1, figsize=(12,10), facecolor='w') - s1 = f1.add_subplot(2,2,1) + f1 = pyplot.figure(1, figsize=(12, 10), facecolor='w') + s1 = f1.add_subplot(2, 2, 1) s1.plot(data_frq) s1.set_title("Costas LO") s1.set_xlabel("Samples") s1.set_ylabel("Frequency (normalized Hz)") # Plot the IQ symbols - s3 = f1.add_subplot(2,2,2) + s3 = f1.add_subplot(2, 2, 2) s3.plot(data_src.real, data_src.imag, "o") s3.plot(data_cst.real, data_cst.imag, "rx") s3.set_title("IQ") @@ -105,7 +107,7 @@ def main(): s3.set_ylim([-2, 2]) # Plot the symbols in time - s4 = f1.add_subplot(2,2,3) + s4 = f1.add_subplot(2, 2, 3) s4.set_position([0.125, 0.05, 0.775, 0.4]) s4.plot(data_src.real, "o-") s4.plot(data_cst.real, "rx-") @@ -115,9 +117,9 @@ def main(): pyplot.show() + if __name__ == "__main__": try: main() except KeyboardInterrupt: pass - diff --git a/gr-digital/examples/example_fll.py b/gr-digital/examples/example_fll.py index 021a3c1f6fd..70b5bbd7497 100644 --- a/gr-digital/examples/example_fll.py +++ b/gr-digital/examples/example_fll.py @@ -24,6 +24,7 @@ print("Error: could not from matplotlib import pyplot (http://matplotlib.sourceforge.net/)") sys.exit(1) + class example_fll(gr.top_block): def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset): gr.top_block.__init__(self) @@ -31,8 +32,8 @@ def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset) rrc_taps = filter.firdes.root_raised_cosine( sps, sps, 1.0, rolloff, ntaps) - data = 2.0*numpy.random.randint(0, 2, N) - 1.0 - data = numpy.exp(1j*poffset) * data + data = 2.0 * numpy.random.randint(0, 2, N) - 1.0 + data = numpy.exp(1j * poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) @@ -47,30 +48,31 @@ def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset) self.connect(self.src, self.rrc, self.chn, self.fll, self.vsnk_fll) self.connect(self.rrc, self.vsnk_src) - self.connect((self.fll,1), self.vsnk_frq) - self.connect((self.fll,2), self.vsnk_phs) - self.connect((self.fll,3), self.vsnk_err) + self.connect((self.fll, 1), self.vsnk_frq) + self.connect((self.fll, 2), self.vsnk_phs) + self.connect((self.fll, 3), self.vsnk_err) + def main(): parser = ArgumentParser(conflict_handler="resolve") parser.add_argument("-N", "--nsamples", type=int, default=2000, - help="Set the number of samples to process [default=%(default)r]") + help="Set the number of samples to process [default=%(default)r]") parser.add_argument("-S", "--sps", type=int, default=4, - help="Set the samples per symbol [default=%(default)r]") + help="Set the samples per symbol [default=%(default)r]") parser.add_argument("-r", "--rolloff", type=eng_float, default=0.35, - help="Set the rolloff factor [default=%(default)r]") - parser.add_argument("-W", "--bandwidth", type=eng_float, default=2*numpy.pi/100.0, - help="Set the loop bandwidth [default=%(default)r]") + help="Set the rolloff factor [default=%(default)r]") + parser.add_argument("-W", "--bandwidth", type=eng_float, default=2 * numpy.pi / 100.0, + help="Set the loop bandwidth [default=%(default)r]") parser.add_argument("-n", "--ntaps", type=int, default=45, - help="Set the number of taps in the filters [default=%(default)r]") + help="Set the number of taps in the filters [default=%(default)r]") parser.add_argument("--noise", type=eng_float, default=0.0, - help="Set the simulation noise voltage [default=%(default)r]") + help="Set the simulation noise voltage [default=%(default)r]") parser.add_argument("-f", "--foffset", type=eng_float, default=0.2, - help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") + help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") parser.add_argument("-t", "--toffset", type=eng_float, default=1.0, - help="Set the simulation's timing offset [default=%(default)r]") + help="Set the simulation's timing offset [default=%(default)r]") parser.add_argument("-p", "--poffset", type=eng_float, default=0.0, - help="Set the simulation's phase offset [default=%(default)r]") + help="Set the simulation's phase offset [default=%(default)r]") args = parser.parse_args() # Adjust N for the interpolation by sps @@ -86,29 +88,29 @@ def main(): data_err = numpy.array(put.vsnk_err.data()) # Convert the FLL's LO frequency from rads/sec to Hz - data_frq = numpy.array(put.vsnk_frq.data()) / (2.0*numpy.pi) + data_frq = numpy.array(put.vsnk_frq.data()) / (2.0 * numpy.pi) # adjust this to align with the data. There are 2 filters of # ntaps long and the channel introduces another 4 sample delay. - data_fll = numpy.array(put.vsnk_fll.data()[2*args.ntaps-4:]) + data_fll = numpy.array(put.vsnk_fll.data()[2 * args.ntaps - 4:]) # Plot the FLL's LO frequency - f1 = pyplot.figure(1, figsize=(12,10)) - s1 = f1.add_subplot(2,2,1) + f1 = pyplot.figure(1, figsize=(12, 10)) + s1 = f1.add_subplot(2, 2, 1) s1.plot(data_frq) s1.set_title("FLL LO") s1.set_xlabel("Samples") s1.set_ylabel("Frequency (normalized Hz)") # Plot the FLL's error - s2 = f1.add_subplot(2,2,2) + s2 = f1.add_subplot(2, 2, 2) s2.plot(data_err) s2.set_title("FLL Error") s2.set_xlabel("Samples") s2.set_ylabel("FLL Loop error") # Plot the IQ symbols - s3 = f1.add_subplot(2,2,3) + s3 = f1.add_subplot(2, 2, 3) s3.plot(data_src.real, data_src.imag, "o") s3.plot(data_fll.real, data_fll.imag, "rx") s3.set_title("IQ") @@ -116,7 +118,7 @@ def main(): s3.set_ylabel("Imag part") # Plot the symbols in time - s4 = f1.add_subplot(2,2,4) + s4 = f1.add_subplot(2, 2, 4) s4.plot(data_src.real, "o-") s4.plot(data_fll.real, "rx-") s4.set_title("Symbols") @@ -125,9 +127,9 @@ def main(): pyplot.show() + if __name__ == "__main__": try: main() except KeyboardInterrupt: pass - diff --git a/gr-digital/examples/example_timing.py b/gr-digital/examples/example_timing.py index e2ff4a56496..f49576b2aa2 100644 --- a/gr-digital/examples/example_timing.py +++ b/gr-digital/examples/example_timing.py @@ -24,6 +24,7 @@ print("Error: could not from matplotlib import pyplot (http://matplotlib.sourceforge.net/)") sys.exit(1) + class example_timing(gr.top_block): def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset, mode=0): @@ -35,10 +36,10 @@ def __init__(self, N, sps, rolloff, ntaps, bw, noise, gain = bw nfilts = 32 rrc_taps_rx = filter.firdes.root_raised_cosine( - nfilts, sps*nfilts, 1.0, rolloff, ntaps*nfilts) + nfilts, sps * nfilts, 1.0, rolloff, ntaps * nfilts) - data = 2.0*numpy.random.randint(0, 2, N) - 1.0 - data = numpy.exp(1j*poffset) * data + data = 2.0 * numpy.random.randint(0, 2, N) - 1.0 + data = numpy.exp(1j * poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) @@ -47,25 +48,25 @@ def __init__(self, N, sps, rolloff, ntaps, bw, noise, if mode == 0: self.clk = digital.pfb_clock_sync_ccf(sps, gain, rrc_taps_rx, - nfilts, nfilts//2, 1) + nfilts, nfilts // 2, 1) self.taps = self.clk.taps() self.dtaps = self.clk.diff_taps() - self.delay = int(numpy.ceil(((len(rrc_taps)-1)//2 + - (len(self.taps[0])-1)//2 )//float(sps))) + 1 + self.delay = int(numpy.ceil(((len(rrc_taps) - 1) // 2 + + (len(self.taps[0]) - 1) // 2) // float(sps))) + 1 self.vsnk_err = blocks.vector_sink_f() self.vsnk_rat = blocks.vector_sink_f() self.vsnk_phs = blocks.vector_sink_f() - self.connect((self.clk,1), self.vsnk_err) - self.connect((self.clk,2), self.vsnk_rat) - self.connect((self.clk,3), self.vsnk_phs) + self.connect((self.clk, 1), self.vsnk_err) + self.connect((self.clk, 2), self.vsnk_rat) + self.connect((self.clk, 3), self.vsnk_phs) - else: # mode == 1 + else: # mode == 1 mu = 0.5 gain_mu = bw - gain_omega = 0.25*gain_mu*gain_mu + gain_omega = 0.25 * gain_mu * gain_mu omega_rel_lim = 0.02 self.clk = digital.clock_recovery_mm_cc(sps, gain_omega, mu, gain_mu, @@ -73,37 +74,38 @@ def __init__(self, N, sps, rolloff, ntaps, bw, noise, self.vsnk_err = blocks.vector_sink_f() - self.connect((self.clk,1), self.vsnk_err) + self.connect((self.clk, 1), self.vsnk_err) self.vsnk_src = blocks.vector_sink_c() self.vsnk_clk = blocks.vector_sink_c() - self.connect(self.src, self.rrc, self.chn, self.off, self.clk, self.vsnk_clk) + self.connect(self.src, self.rrc, self.chn, + self.off, self.clk, self.vsnk_clk) self.connect(self.src, self.vsnk_src) def main(): parser = ArgumentParser(conflict_handler="resolve") parser.add_argument("-N", "--nsamples", type=int, default=2000, - help="Set the number of samples to process [default=%(default)r]") + help="Set the number of samples to process [default=%(default)r]") parser.add_argument("-S", "--sps", type=int, default=4, - help="Set the samples per symbol [default=%(default)r]") + help="Set the samples per symbol [default=%(default)r]") parser.add_argument("-r", "--rolloff", type=eng_float, default=0.35, - help="Set the rolloff factor [default=%(default)r]") - parser.add_argument("-W", "--bandwidth", type=eng_float, default=2*numpy.pi/100.0, - help="Set the loop bandwidth (PFB) or gain (M&M) [default=%(default)r]") + help="Set the rolloff factor [default=%(default)r]") + parser.add_argument("-W", "--bandwidth", type=eng_float, default=2 * numpy.pi / 100.0, + help="Set the loop bandwidth (PFB) or gain (M&M) [default=%(default)r]") parser.add_argument("-n", "--ntaps", type=int, default=45, - help="Set the number of taps in the filters [default=%(default)r]") + help="Set the number of taps in the filters [default=%(default)r]") parser.add_argument("--noise", type=eng_float, default=0.0, - help="Set the simulation noise voltage [default=%(default)r]") + help="Set the simulation noise voltage [default=%(default)r]") parser.add_argument("-f", "--foffset", type=eng_float, default=0.0, - help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") + help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") parser.add_argument("-t", "--toffset", type=eng_float, default=1.0, - help="Set the simulation's timing offset [default=%(default)r]") + help="Set the simulation's timing offset [default=%(default)r]") parser.add_argument("-p", "--poffset", type=eng_float, default=0.0, - help="Set the simulation's phase offset [default=%(default)r]") + help="Set the simulation's phase offset [default=%(default)r]") parser.add_argument("-M", "--mode", type=int, default=0, - help="Set the recovery mode (0: polyphase, 1: M&M) [default=%(default)r]") + help="Set the recovery mode (0: polyphase, 1: M&M) [default=%(default)r]") args = parser.parse_args() # Adjust N for the interpolation by sps @@ -124,10 +126,10 @@ def main(): data_rat = numpy.array(put.vsnk_rat.data()[20:]) data_phs = numpy.array(put.vsnk_phs.data()[20:]) - f1 = pyplot.figure(1, figsize=(12,10), facecolor='w') + f1 = pyplot.figure(1, figsize=(12, 10), facecolor='w') # Plot the IQ symbols - s1 = f1.add_subplot(2,2,1) + s1 = f1.add_subplot(2, 2, 1) s1.plot(data_src.real, data_src.imag, "bo") s1.plot(data_clk.real, data_clk.imag, "ro") s1.set_title("IQ") @@ -139,7 +141,7 @@ def main(): # Plot the symbols in time delay = put.delay m = len(data_clk.real) - s2 = f1.add_subplot(2,2,2) + s2 = f1.add_subplot(2, 2, 2) s2.plot(data_src.real, "bs", markersize=10, label="Input") s2.plot(data_clk.real[delay:], "ro", label="Recovered") s2.set_title("Symbols") @@ -148,7 +150,7 @@ def main(): s2.legend() # Plot the clock recovery loop's error - s3 = f1.add_subplot(2,2,3) + s3 = f1.add_subplot(2, 2, 3) s3.plot(data_err, label="Error") s3.plot(data_rat, 'r', label="Update rate") s3.set_title("Clock Recovery Loop Error") @@ -158,26 +160,27 @@ def main(): s3.legend() # Plot the clock recovery loop's error - s4 = f1.add_subplot(2,2,4) + s4 = f1.add_subplot(2, 2, 4) s4.plot(data_phs) s4.set_title("Clock Recovery Loop Filter Phase") s4.set_xlabel("Samples") s4.set_ylabel("Filter Phase") - diff_taps = put.dtaps ntaps = len(diff_taps[0]) nfilts = len(diff_taps) - t = numpy.arange(0, ntaps*nfilts) + t = numpy.arange(0, ntaps * nfilts) - f3 = pyplot.figure(3, figsize=(12,10), facecolor='w') - s31 = f3.add_subplot(2,1,1) - s32 = f3.add_subplot(2,1,2) + f3 = pyplot.figure(3, figsize=(12, 10), facecolor='w') + s31 = f3.add_subplot(2, 1, 1) + s32 = f3.add_subplot(2, 1, 2) s31.set_title("Differential Filters") s32.set_title("FFT of Differential Filters") - for i,d in enumerate(diff_taps): - D = 20.0*numpy.log10(1e-20+abs(numpy.fft.fftshift(numpy.fft.fft(d, 10000)))) + for i, d in enumerate(diff_taps): + D = 20.0 * \ + numpy.log10( + 1e-20 + abs(numpy.fft.fftshift(numpy.fft.fft(d, 10000)))) s31.plot(t[i::nfilts].real, d, "-o") s32.plot(D) s32.set_ylim([-120, 10]) @@ -189,10 +192,10 @@ def main(): data_err = numpy.array(put.vsnk_err.data()[20:]) - f1 = pyplot.figure(1, figsize=(12,10), facecolor='w') + f1 = pyplot.figure(1, figsize=(12, 10), facecolor='w') # Plot the IQ symbols - s1 = f1.add_subplot(2,2,1) + s1 = f1.add_subplot(2, 2, 1) s1.plot(data_src.real, data_src.imag, "o") s1.plot(data_clk.real, data_clk.imag, "ro") s1.set_title("IQ") @@ -202,7 +205,7 @@ def main(): s1.set_ylim([-2, 2]) # Plot the symbols in time - s2 = f1.add_subplot(2,2,2) + s2 = f1.add_subplot(2, 2, 2) s2.plot(data_src.real, "bs", markersize=10, label="Input") s2.plot(data_clk.real, "ro", label="Recovered") s2.set_title("Symbols") @@ -211,7 +214,7 @@ def main(): s2.legend() # Plot the clock recovery loop's error - s3 = f1.add_subplot(2,2,3) + s3 = f1.add_subplot(2, 2, 3) s3.plot(data_err) s3.set_title("Clock Recovery Loop Error") s3.set_xlabel("Samples") @@ -219,6 +222,7 @@ def main(): pyplot.show() + if __name__ == "__main__": try: main() diff --git a/gr-digital/examples/gen_whitener.py b/gr-digital/examples/gen_whitener.py index a6261d021b6..67985971313 100644 --- a/gr-digital/examples/gen_whitener.py +++ b/gr-digital/examples/gen_whitener.py @@ -1,18 +1,19 @@ #!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. -# +# # This file is part of GNU Radio -# +# # SPDX-License-Identifier: GPL-3.0-or-later # -# +# from gnuradio import gr from gnuradio import blocks from argparse import ArgumentParser import sys + class my_graph(gr.top_block): def __init__(self): @@ -25,6 +26,7 @@ def __init__(self): self.dst = blocks.vector_sink_s() self.connect(src, head, self.dst) + if __name__ == '__main__': try: tb = my_graph() @@ -34,10 +36,9 @@ def __init__(self): for s in tb.dst.data(): f.write("%3d, " % (s & 0xff,)) f.write("%3d, " % ((s >> 8) & 0xff,)) - i = i+2 + i = i + 2 if i % 16 == 0: f.write('\n') except KeyboardInterrupt: pass - diff --git a/gr-digital/examples/narrowband/benchmark_add_channel.py b/gr-digital/examples/narrowband/benchmark_add_channel.py index 351aae29cdb..725138f85db 100644 --- a/gr-digital/examples/narrowband/benchmark_add_channel.py +++ b/gr-digital/examples/narrowband/benchmark_add_channel.py @@ -15,7 +15,10 @@ from gnuradio.eng_option import eng_option from optparse import OptionParser -import random, math, sys +import random +import math +import sys + class my_top_block(gr.top_block): def __init__(self, ifile, ofile, options): @@ -24,7 +27,7 @@ def __init__(self, ifile, ofile, options): SNR = 10.0**(options.snr / 10.0) frequency_offset = options.frequency_offset time_offset = options.time_offset - phase_offset = options.phase_offset*(math.pi / 180.0) + phase_offset = options.phase_offset * (math.pi / 180.0) # calculate noise voltage from SNR power_in_signal = abs(options.tx_amplitude)**2 @@ -35,9 +38,9 @@ def __init__(self, ifile, ofile, options): #self.throttle = blocks.throttle(gr.sizeof_gr_complex, options.sample_rate) self.channel = channels.channel_model(noise_voltage, frequency_offset, - time_offset, noise_seed=-random.randint(0,100000)) + time_offset, noise_seed=-random.randint(0, 100000)) self.phase = blocks.multiply_const_cc(complex(math.cos(phase_offset), - math.sin(phase_offset))) + math.sin(phase_offset))) self.snk = blocks.file_sink(gr.sizeof_gr_complex, ofile) self.connect(self.src, self.channel, self.phase, self.snk) @@ -50,7 +53,8 @@ def __init__(self, ifile, ofile, options): def main(): # Create Options Parser: usage = "benchmack_add_channel.py [options] " - parser = OptionParser (usage=usage, option_class=eng_option, conflict_handler="resolve") + parser = OptionParser( + usage=usage, option_class=eng_option, conflict_handler="resolve") parser.add_option("-n", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") parser.add_option("", "--seed", action="store_true", default=False, @@ -67,7 +71,7 @@ def main(): default=1.0, help="tell the simulator the signal amplitude [default=%default]") - (options, args) = parser.parse_args () + (options, args) = parser.parse_args() if len(args) != 2: parser.print_help(sys.stderr) @@ -86,6 +90,7 @@ def main(): tb.start() # start flow graph tb.wait() # wait for it to finish + if __name__ == '__main__': try: main() diff --git a/gr-digital/examples/narrowband/digital_bert_rx.py b/gr-digital/examples/narrowband/digital_bert_rx.py index e20b798ee2e..7b951c45693 100644 --- a/gr-digital/examples/narrowband/digital_bert_rx.py +++ b/gr-digital/examples/narrowband/digital_bert_rx.py @@ -13,7 +13,9 @@ from optparse import OptionParser from gnuradio.eng_option import eng_option import threading -import sys, time, math +import sys +import time +import math from gnuradio import digital from gnuradio import blocks @@ -23,6 +25,7 @@ n2s = eng_notation.num_to_str + class status_thread(threading.Thread): def __init__(self, tb): threading.Thread.__init__(self) @@ -34,14 +37,13 @@ def __init__(self, tb): def run(self): while not self.done: print("Freq. Offset: {0:5.0f} Hz Timing Offset: {1:10.1f} ppm Estimated SNR: {2:4.1f} dB BER: {3:g}".format( - tb.frequency_offset(), tb.timing_offset()*1e6, tb.snr(), tb.ber())) + tb.frequency_offset(), tb.timing_offset() * 1e6, tb.snr(), tb.ber())) try: time.sleep(1.0) except KeyboardInterrupt: self.done = True - class bert_receiver(gr.hier_block2): def __init__(self, bitrate, constellation, samples_per_symbol, @@ -50,7 +52,8 @@ def __init__(self, bitrate, verbose, log): gr.hier_block2.__init__(self, "bert_receive", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0, 0, 0)) # Output signature self._bitrate = bitrate @@ -70,7 +73,8 @@ def __init__(self, bitrate, self.connect(self._demod.time_recov, self._snr_probe) # Descramble BERT sequence. A channel error will create 3 incorrect bits - self._descrambler = digital.descrambler_bb(0x8A, 0x7F, 7) # CCSDS 7-bit descrambler + self._descrambler = digital.descrambler_bb( + 0x8A, 0x7F, 7) # CCSDS 7-bit descrambler # Measure BER by the density of 0s in the stream self._ber = digital.probe_density_b(1.0 / self._symbol_rate) @@ -78,7 +82,7 @@ def __init__(self, bitrate, self.connect(self, self._demod, self._descrambler, self._ber) def frequency_offset(self): - return self._demod.freq_recov.get_frequency()*self._sample_rate/(2*math.pi) + return self._demod.freq_recov.get_frequency() * self._sample_rate / (2 * math.pi) def timing_offset(self): return self._demod.time_recov.clock_rate() @@ -87,8 +91,7 @@ def snr(self): return self._snr_probe.snr() def ber(self): - return (1.0-self._ber.density()) / 3.0 - + return (1.0 - self._ber.density()) / 3.0 class rx_psk_block(gr.top_block): @@ -99,7 +102,8 @@ def __init__(self, demod, options): self._demodulator_class = demod # Get demod_kwargs - demod_kwargs = self._demodulator_class.extract_kwargs_from_options(options) + demod_kwargs = self._demodulator_class.extract_kwargs_from_options( + options) # demodulator self._demodulator = self._demodulator_class(**demod_kwargs) @@ -114,7 +118,8 @@ def __init__(self, demod, options): options.samples_per_symbol = self._source._sps elif(options.from_file is not None): - self._source = blocks.file_source(gr.sizeof_gr_complex, options.from_file) + self._source = blocks.file_source( + gr.sizeof_gr_complex, options.from_file) else: self._source = blocks.null_source(gr.sizeof_gr_complex) @@ -154,7 +159,7 @@ def timing_offset(self): def get_options(demods): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") - parser.add_option("","--from-file", default=None, + parser.add_option("", "--from-file", default=None, help="input file of samples to demod") parser.add_option("-m", "--modulation", type="choice", choices=list(demods.keys()), default='psk', @@ -165,10 +170,11 @@ def get_options(demods): parser.add_option("-S", "--samples-per-symbol", type="float", default=2, help="set samples/symbol [default=%default]") if not parser.has_option("--verbose"): - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) if not parser.has_option("--log"): parser.add_option("", "--log", action="store_true", default=False, - help="Log all parts of flow graph to files (CAUTION: lots of data)") + help="Log all parts of flow graph to files (CAUTION: lots of data)") uhd_receiver.add_options(parser) @@ -185,7 +191,7 @@ def get_options(demods): if __name__ == "__main__": - print ("""Warning: this example in its current shape is deprecated and + print("""Warning: this example in its current shape is deprecated and will be removed or fundamentally reworked in a coming GNU Radio release.""") demods = digital.modulation_utils.type_1_demods() diff --git a/gr-digital/examples/narrowband/digital_bert_tx.py b/gr-digital/examples/narrowband/digital_bert_tx.py index fe8ad0671fb..d6095342718 100644 --- a/gr-digital/examples/narrowband/digital_bert_tx.py +++ b/gr-digital/examples/narrowband/digital_bert_tx.py @@ -21,25 +21,30 @@ n2s = eng_notation.num_to_str + class bert_transmit(gr.hier_block2): def __init__(self, constellation, samples_per_symbol, differential, excess_bw, gray_coded, verbose, log): gr.hier_block2.__init__(self, "bert_transmit", - gr.io_signature(0, 0, 0), # Output signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Input signature + # Output signature + gr.io_signature(0, 0, 0), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Input signature # Create BERT data bit stream - self._bits = blocks.vector_source_b([1,], True) # Infinite stream of ones - self._scrambler = digital.scrambler_bb(0x8A, 0x7F, 7) # CCSDS 7-bit scrambler + self._bits = blocks.vector_source_b( + [1, ], True) # Infinite stream of ones + self._scrambler = digital.scrambler_bb( + 0x8A, 0x7F, 7) # CCSDS 7-bit scrambler self._mod = digital.generic_mod(constellation, differential, samples_per_symbol, gray_coded, excess_bw, verbose, log) - self._pack = blocks.unpacked_to_packed_bb(self._mod.bits_per_symbol(), gr.GR_MSB_FIRST) + self._pack = blocks.unpacked_to_packed_bb( + self._mod.bits_per_symbol(), gr.GR_MSB_FIRST) self.connect(self._bits, self._scrambler, self._pack, self._mod, self) @@ -66,11 +71,11 @@ def __init__(self, mod, options): options.samples_per_symbol = self._sink._sps elif(options.to_file is not None): - self._sink = blocks.file_sink(gr.sizeof_gr_complex, options.to_file) + self._sink = blocks.file_sink( + gr.sizeof_gr_complex, options.to_file) else: self._sink = blocks.null_sink(gr.sizeof_gr_complex) - self._transmitter = bert_transmit(self._modulator._constellation, options.samples_per_symbol, options.differential, @@ -95,10 +100,11 @@ def get_options(mods): help="Select modulation bit rate (default=%default)") parser.add_option("-S", "--samples-per-symbol", type="float", default=2, help="set samples/symbol [default=%default]") - parser.add_option("","--to-file", default=None, + parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") if not parser.has_option("--verbose"): - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) if not parser.has_option("--log"): parser.add_option("", "--log", action="store_true", default=False) @@ -114,8 +120,9 @@ def get_options(mods): return (options, args) + if __name__ == "__main__": - print ("""Warning: this example in its current shape is deprecated and + print("""Warning: this example in its current shape is deprecated and will be removed or fundamentally reworked in a coming GNU Radio release.""") mods = digital.modulation_utils.type_1_mods() diff --git a/gr-digital/examples/narrowband/uhd_interface.py b/gr-digital/examples/narrowband/uhd_interface.py index 54d152cd7cd..7a541296ee2 100644 --- a/gr-digital/examples/narrowband/uhd_interface.py +++ b/gr-digital/examples/narrowband/uhd_interface.py @@ -16,6 +16,7 @@ import sys + def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq @@ -30,14 +31,17 @@ def freq_callback(option, opt_str, value, parser): help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ") + class uhd_interface(object): def __init__(self, istx, args, sym_rate, sps, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None): if(istx): - self.u = uhd.usrp_sink(device_addr=args, stream_args=uhd.stream_args('fc32')) + self.u = uhd.usrp_sink( + device_addr=args, stream_args=uhd.stream_args('fc32')) else: - self.u = uhd.usrp_source(device_addr=args, stream_args=uhd.stream_args('fc32')) + self.u = uhd.usrp_source( + device_addr=args, stream_args=uhd.stream_args('fc32')) # Set clock source if(clock_source): @@ -52,7 +56,7 @@ def __init__(self, istx, args, sym_rate, sps, freq=None, lo_offset=None, self.u.set_antenna(antenna, 0) self._args = args - self._ant = antenna + self._ant = antenna self._spec = spec self._gain = self.set_gain(gain) self._lo_offset = lo_offset @@ -69,7 +73,7 @@ def set_sample_rate(self, sym_rate, req_sps): sps = actual_samp_rate / sym_rate if(sps < 2): - req_sps +=1 + req_sps += 1 else: actual_sps = sps break @@ -93,10 +97,10 @@ def set_gain(self, gain=None): if gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() - gain = float(g.start()+g.stop()) / 2 + gain = float(g.start() + g.stop()) / 2 print("\nNo gain specified.") print("Setting gain to %f (from [%f, %f])" % - (gain, g.start(), g.stop())) + (gain, g.start(), g.stop())) self.u.set_gain(gain, 0) return gain @@ -111,20 +115,21 @@ def set_freq(self, freq=None, lo_offset=None): return freq else: frange = self.u.get_freq_range() - sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % \ - (freq, frange.start(), frange.stop())) + sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % + (freq, frange.start(), frange.stop())) sys.exit(1) #-------------------------------------------------------------------# # TRANSMITTER #-------------------------------------------------------------------# + class uhd_transmitter(uhd_interface, gr.hier_block2): def __init__(self, args, sym_rate, sps, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_transmitter", - gr.io_signature(1,1,gr.sizeof_gr_complex), - gr.io_signature(0,0,0)) + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(0, 0, 0)) # Set up the UHD interface as a transmitter uhd_interface.__init__(self, True, args, sym_rate, sps, @@ -153,21 +158,23 @@ def add_options(parser): help="set transmit gain in dB (default is midpoint)") parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) def _print_verbage(self): """ Prints information about the UHD transmitter """ print("\nUHD Transmitter:") - print("Args: %s" % (self._args)) - print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) - print("LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset)) ) + print("Args: %s" % (self._args)) + print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) + print("LO Offset: %sHz" % + (eng_notation.num_to_str(self._lo_offset))) print("Gain: %f dB" % (self._gain)) print("Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate))) - print("Antenna: %s" % (self._ant)) - print("Subdev Spec: %s" % (self._spec)) - print("Clock Source: %s" % (self._clock_source)) + print("Antenna: %s" % (self._ant)) + print("Subdev Spec: %s" % (self._spec)) + print("Clock Source: %s" % (self._clock_source)) #-------------------------------------------------------------------# # RECEIVER @@ -178,8 +185,8 @@ class uhd_receiver(uhd_interface, gr.hier_block2): def __init__(self, args, sym_rate, sps, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_receiver", - gr.io_signature(0,0,0), - gr.io_signature(1,1,gr.sizeof_gr_complex)) + gr.io_signature(0, 0, 0), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Set up the UHD interface as a receiver uhd_interface.__init__(self, False, args, sym_rate, sps, @@ -209,19 +216,20 @@ def add_options(parser): parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") if not parser.has_option("--verbose"): - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) def _print_verbage(self): """ Prints information about the UHD transmitter """ print("\nUHD Receiver:") - print("UHD Args: %s" % (self._args)) - print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) - print("LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset)) ) + print("UHD Args: %s" % (self._args)) + print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) + print("LO Offset: %sHz" % + (eng_notation.num_to_str(self._lo_offset))) print("Gain: %f dB" % (self._gain)) print("Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate))) - print("Antenna: %s" % (self._ant)) - print("Spec: %s" % (self._spec)) - print("Clock Source: %s" % (self._clock_source)) - + print("Antenna: %s" % (self._ant)) + print("Spec: %s" % (self._spec)) + print("Clock Source: %s" % (self._clock_source)) diff --git a/gr-digital/examples/ofdm/benchmark_add_channel.py b/gr-digital/examples/ofdm/benchmark_add_channel.py index 6355bcc8289..fec315e8d70 100644 --- a/gr-digital/examples/ofdm/benchmark_add_channel.py +++ b/gr-digital/examples/ofdm/benchmark_add_channel.py @@ -15,7 +15,10 @@ from gnuradio.eng_option import eng_option from optparse import OptionParser -import random, math, sys +import random +import math +import sys + class my_top_block(gr.top_block): def __init__(self, ifile, ofile, options): @@ -23,7 +26,7 @@ def __init__(self, ifile, ofile, options): SNR = 10.0**(options.snr / 10.0) time_offset = options.time_offset - phase_offset = options.phase_offset*(math.pi / 180.0) + phase_offset = options.phase_offset * (math.pi / 180.0) # calculate noise voltage from SNR power_in_signal = abs(options.tx_amplitude)**2 @@ -37,9 +40,9 @@ def __init__(self, ifile, ofile, options): #self.throttle = blocks.throttle(gr.sizeof_gr_complex, options.sample_rate) self.channel = channels.channel_model(noise_voltage, frequency_offset, - time_offset, noise_seed=-random.randint(0,100000)) + time_offset, noise_seed=-random.randint(0, 100000)) self.phase = blocks.multiply_const_cc(complex(math.cos(phase_offset), - math.sin(phase_offset))) + math.sin(phase_offset))) self.snk = blocks.file_sink(gr.sizeof_gr_complex, ofile) self.connect(self.src, self.channel, self.phase, self.snk) @@ -52,7 +55,8 @@ def __init__(self, ifile, ofile, options): def main(): # Create Options Parser: usage = "benchmack_add_channel.py [options] " - parser = OptionParser (usage=usage, option_class=eng_option, conflict_handler="resolve") + parser = OptionParser( + usage=usage, option_class=eng_option, conflict_handler="resolve") parser.add_option("-n", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") parser.add_option("", "--seed", action="store_true", default=False, @@ -71,7 +75,7 @@ def main(): default=1.0, help="tell the simulator the signal amplitude [default=%default]") - (options, args) = parser.parse_args () + (options, args) = parser.parse_args() if len(args) != 2: parser.print_help(sys.stderr) @@ -94,6 +98,7 @@ def main(): tb.start() # start flow graph tb.wait() # wait for it to finish + if __name__ == '__main__': try: main() diff --git a/gr-digital/examples/ofdm/receive_path.py b/gr-digital/examples/ofdm/receive_path.py index 90b572a08f3..e46056c245e 100644 --- a/gr-digital/examples/ofdm/receive_path.py +++ b/gr-digital/examples/ofdm/receive_path.py @@ -19,6 +19,7 @@ # receive path # ///////////////////////////////////////////////////////////////////////////// + class receive_path(gr.hier_block2): def __init__(self, rx_callback, options): @@ -26,12 +27,13 @@ def __init__(self, rx_callback, options): gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0, 0, 0)) + # make a copy so we can destructively modify + options = copy.copy(options) - options = copy.copy(options) # make a copy so we can destructively modify - - self._verbose = options.verbose - self._log = options.log - self._rx_callback = rx_callback # this callback is fired when there's a packet available + self._verbose = options.verbose + self._log = options.log + # this callback is fired when there's a packet available + self._rx_callback = rx_callback # receiver self.ofdm_rx = digital.ofdm_demod(options, @@ -40,7 +42,7 @@ def __init__(self, rx_callback, options): # Carrier Sensing Blocks alpha = 0.001 thresh = 30 # in dB, will have to adjust - self.probe = analog.probe_avg_mag_sqrd_c(thresh,alpha) + self.probe = analog.probe_avg_mag_sqrd_c(thresh, alpha) self.connect(self, self.ofdm_rx) self.connect(self.ofdm_rx, self.probe) @@ -53,7 +55,7 @@ def carrier_sensed(self): """ Return True if we think carrier is present. """ - #return self.probe.level() > X + # return self.probe.level() > X return self.probe.unmuted() def carrier_threshold(self): @@ -79,7 +81,8 @@ def add_options(normal, expert): normal.add_option("-W", "--bandwidth", type="eng_float", default=500e3, help="set symbol bandwidth [default=%default]") - normal.add_option("-v", "--verbose", action="store_true", default=False) + normal.add_option("-v", "--verbose", + action="store_true", default=False) expert.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to files (CAUTION: lots of data)") diff --git a/gr-digital/examples/ofdm/transmit_path.py b/gr-digital/examples/ofdm/transmit_path.py index 0982bb688c9..83ac6a19a4a 100644 --- a/gr-digital/examples/ofdm/transmit_path.py +++ b/gr-digital/examples/ofdm/transmit_path.py @@ -20,6 +20,7 @@ # transmit path # ///////////////////////////////////////////////////////////////////////////// + class transmit_path(gr.hier_block2): def __init__(self, options): ''' @@ -30,10 +31,11 @@ def __init__(self, options): gr.io_signature(0, 0, 0), gr.io_signature(1, 1, gr.sizeof_gr_complex)) - options = copy.copy(options) # make a copy so we can destructively modify + # make a copy so we can destructively modify + options = copy.copy(options) - self._verbose = options.verbose # turn verbose mode on/off - self._tx_amplitude = options.tx_amplitude # digital amp sent to radio + self._verbose = options.verbose # turn verbose mode on/off + self._tx_amplitude = options.tx_amplitude # digital amp sent to radio self.ofdm_tx = digital.ofdm_mod(options, msgq_limit=4, @@ -87,4 +89,3 @@ def _print_verbage(self): Prints information about the transmit path """ print("Tx amplitude %s" % (self._tx_amplitude)) - diff --git a/gr-digital/examples/ofdm/uhd_interface.py b/gr-digital/examples/ofdm/uhd_interface.py index c3544732672..ca0f0e25989 100644 --- a/gr-digital/examples/ofdm/uhd_interface.py +++ b/gr-digital/examples/ofdm/uhd_interface.py @@ -16,6 +16,7 @@ import sys + def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq @@ -30,14 +31,17 @@ def freq_callback(option, opt_str, value, parser): help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ") + class uhd_interface(object): def __init__(self, istx, args, bandwidth, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None): if(istx): - self.u = uhd.usrp_sink(device_addr=args, stream_args=uhd.stream_args('fc32')) + self.u = uhd.usrp_sink( + device_addr=args, stream_args=uhd.stream_args('fc32')) else: - self.u = uhd.usrp_source(device_addr=args, stream_args=uhd.stream_args('fc32')) + self.u = uhd.usrp_source( + device_addr=args, stream_args=uhd.stream_args('fc32')) # Set clock source to external. if(clock_source): @@ -52,7 +56,7 @@ def __init__(self, istx, args, bandwidth, freq=None, lo_offset=None, self.u.set_antenna(antenna, 0) self._args = args - self._ant = antenna + self._ant = antenna self._spec = spec self._gain = self.set_gain(gain) self._lo_offset = lo_offset @@ -73,10 +77,10 @@ def set_gain(self, gain=None): if gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() - gain = float(g.start()+g.stop()) / 2 + gain = float(g.start() + g.stop()) / 2 print("\nNo gain specified.") print("Setting gain to %f (from [%f, %f])" % - (gain, g.start(), g.stop())) + (gain, g.start(), g.stop())) self.u.set_gain(gain, 0) return gain @@ -92,20 +96,21 @@ def set_freq(self, freq=None, lo_offset=None): return freq else: frange = self.u.get_freq_range() - sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % \ - (freq, frange.start(), frange.stop())) + sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % + (freq, frange.start(), frange.stop())) sys.exit(1) #-------------------------------------------------------------------# # TRANSMITTER #-------------------------------------------------------------------# + class uhd_transmitter(uhd_interface, gr.hier_block2): def __init__(self, args, bandwidth, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_transmitter", - gr.io_signature(1,1,gr.sizeof_gr_complex), - gr.io_signature(0,0,0)) + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(0, 0, 0)) # Set up the UHD interface as a transmitter uhd_interface.__init__(self, True, args, bandwidth, @@ -134,22 +139,23 @@ def add_options(parser): help="set transmit gain in dB (default is midpoint)") parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) def _print_verbage(self): """ Prints information about the UHD transmitter """ print("\nUHD Transmitter:") - print("UHD Args: %s" % (self._args)) - print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) - print("LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset))) + print("UHD Args: %s" % (self._args)) + print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) + print("LO Offset: %sHz" % + (eng_notation.num_to_str(self._lo_offset))) print("Gain: %f dB" % (self._gain)) print("Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate))) - print("Antenna: %s" % (self._ant)) - print("Subdev Sec: %s" % (self._spec)) - print("Clock Source: %s" % (self._clock_source)) - + print("Antenna: %s" % (self._ant)) + print("Subdev Sec: %s" % (self._spec)) + print("Clock Source: %s" % (self._clock_source)) #-------------------------------------------------------------------# @@ -161,8 +167,8 @@ class uhd_receiver(uhd_interface, gr.hier_block2): def __init__(self, args, bandwidth, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_receiver", - gr.io_signature(0,0,0), - gr.io_signature(1,1,gr.sizeof_gr_complex)) + gr.io_signature(0, 0, 0), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Set up the UHD interface as a receiver uhd_interface.__init__(self, False, args, bandwidth, @@ -192,19 +198,20 @@ def add_options(parser): parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") if not parser.has_option("--verbose"): - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) def _print_verbage(self): """ Prints information about the UHD transmitter """ print("\nUHD Receiver:") - print("UHD Args: %s" % (self._args)) - print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) - print("LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset))) + print("UHD Args: %s" % (self._args)) + print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) + print("LO Offset: %sHz" % + (eng_notation.num_to_str(self._lo_offset))) print("Gain: %f dB" % (self._gain)) print("Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate))) - print("Antenna: %s" % (self._ant)) - print("Subdev Sec: %s" % (self._spec)) - print("Clock Source: %s" % (self._clock_source)) - + print("Antenna: %s" % (self._ant)) + print("Subdev Sec: %s" % (self._spec)) + print("Clock Source: %s" % (self._clock_source)) diff --git a/gr-digital/examples/run_length.py b/gr-digital/examples/run_length.py index 0d9477012c6..8d84b605330 100644 --- a/gr-digital/examples/run_length.py +++ b/gr-digital/examples/run_length.py @@ -12,6 +12,7 @@ from optparse import OptionParser import sys + def main(): parser = OptionParser() parser.add_option("-f", "--file", default=None, @@ -33,7 +34,7 @@ def main(): for ch in f.read(): x = ord(ch) bytes = bytes + 1 - for i in range(7,-1,-1): + for i in range(7, -1, -1): bits = bits + 1 t = (x >> i) & 0x1 if t == current: @@ -42,29 +43,30 @@ def main(): if count > 0: if len(runs) < count: for j in range(count - len(runs)): - runs.append(0); - runs[count-1] = runs[count-1] + 1 + runs.append(0) + runs[count - 1] = runs[count - 1] + 1 - current = 1-current; + current = 1 - current count = 1 # Deal with last run at EOF if len(runs) < count and count > 0: for j in range(count - len(runs)): - runs.append(0); - runs[count-1] = runs[count-1] + 1 + runs.append(0) + runs[count - 1] = runs[count - 1] + 1 chk = 0 print("Bytes read: ", bytes) print("Bits read: ", bits) print() for i in range(len(runs)): - chk = chk + runs[i]*(i+1) - print("Runs of length", i+1, ":", runs[i]) + chk = chk + runs[i] * (i + 1) + print("Runs of length", i + 1, ":", runs[i]) print() print("Sum of runs:", chk, "bits") print() print("Maximum run length is", len(runs), "bits") + if __name__ == "__main__": main() diff --git a/gr-digital/examples/snr_estimators.py b/gr-digital/examples/snr_estimators.py index fbaf06a5abf..bc622bfd313 100644 --- a/gr-digital/examples/snr_estimators.py +++ b/gr-digital/examples/snr_estimators.py @@ -38,6 +38,7 @@ http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics ''' + def online_skewness(data): n = 0 mean = 0 @@ -46,52 +47,57 @@ def online_skewness(data): for n in range(len(data)): delta = data[n] - mean - delta_n = delta / (n+1) + delta_n = delta / (n + 1) term1 = delta * delta_n * n mean = mean + delta_n M3 = M3 + term1 * delta_n * (n - 1) - 3 * delta_n * M2 M2 = M2 + term1 - return scipy.sqrt(len(data))*M3 / scipy.power(M2, 3.0 / 2.0); + return scipy.sqrt(len(data)) * M3 / scipy.power(M2, 3.0 / 2.0) + def snr_est_simple(signal): s = scipy.mean(abs(signal)**2) - n = 2*scipy.var(abs(signal)) + n = 2 * scipy.var(abs(signal)) snr_rat = s / n - return 10.0*scipy.log10(snr_rat), snr_rat + return 10.0 * scipy.log10(snr_rat), snr_rat + def snr_est_skew(signal): y1 = scipy.mean(abs(signal)) y2 = scipy.mean(scipy.real(signal**2)) - y3 = (y1*y1 - y2) + y3 = (y1 * y1 - y2) y4 = online_skewness(signal.real) #y4 = stats.skew(abs(signal.real)) - skw = y4*y4 / (y2*y2*y2); - s = y1*y1 - n = 2*(y3 + skw*s) + skw = y4 * y4 / (y2 * y2 * y2) + s = y1 * y1 + n = 2 * (y3 + skw * s) snr_rat = s / n - return 10.0*scipy.log10(snr_rat), snr_rat + return 10.0 * scipy.log10(snr_rat), snr_rat + def snr_est_m2m4(signal): M2 = scipy.mean(abs(signal)**2) M4 = scipy.mean(abs(signal)**4) - snr_rat = scipy.sqrt(2*M2*M2 - M4) / (M2 - scipy.sqrt(2*M2*M2 - M4)) - return 10.0*scipy.log10(snr_rat), snr_rat + snr_rat = scipy.sqrt(2 * M2 * M2 - M4) / \ + (M2 - scipy.sqrt(2 * M2 * M2 - M4)) + return 10.0 * scipy.log10(snr_rat), snr_rat + def snr_est_svr(signal): N = len(signal) ssum = 0 msum = 0 for i in range(1, N): - ssum += (abs(signal[i])**2)*(abs(signal[i-1])**2) + ssum += (abs(signal[i])**2) * (abs(signal[i - 1])**2) msum += (abs(signal[i])**4) - savg = (1.0 / (float(N-1.0)))*ssum - mavg = (1.0 / (float(N-1.0)))*msum + savg = (1.0 / (float(N - 1.0))) * ssum + mavg = (1.0 / (float(N - 1.0))) * msum beta = savg / (mavg - savg) - snr_rat = ((beta - 1) + scipy.sqrt(beta*(beta-1))) - return 10.0*scipy.log10(snr_rat), snr_rat + snr_rat = ((beta - 1) + scipy.sqrt(beta * (beta - 1))) + return 10.0 * scipy.log10(snr_rat), snr_rat def main(): @@ -104,7 +110,6 @@ def main(): "m2m4": snr_est_m2m4, "svr": snr_est_svr} - parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=10000, help="Set the number of samples to process [default=%default]") @@ -118,13 +123,13 @@ def main(): choices=list(gr_estimators.keys()), default="simple", help="Estimator type {0} [default=%default]".format( list(gr_estimators.keys()))) - (options, args) = parser.parse_args () + (options, args) = parser.parse_args() N = options.nsamples xx = scipy.random.randn(N) xy = scipy.random.randn(N) - bits =2*scipy.complex64(scipy.random.randint(0, 2, N)) - 1 - #bits =(2*scipy.complex64(scipy.random.randint(0, 2, N)) - 1) + \ + bits = 2 * scipy.complex64(scipy.random.randint(0, 2, N)) - 1 + # bits =(2*scipy.complex64(scipy.random.randint(0, 2, N)) - 1) + \ # 1j*(2*scipy.complex64(scipy.random.randint(0, 2, N)) - 1) snr_known = list() @@ -134,7 +139,7 @@ def main(): # when to issue an SNR tag; can be ignored in this example. ntag = 10000 - n_cpx = xx + 1j*xy + n_cpx = xx + 1j * xy py_est = py_estimators[options.type] gr_est = gr_estimators[options.type] @@ -142,17 +147,17 @@ def main(): SNR_min = options.snr_min SNR_max = options.snr_max SNR_step = options.snr_step - SNR_dB = scipy.arange(SNR_min, SNR_max+SNR_step, SNR_step) + SNR_dB = scipy.arange(SNR_min, SNR_max + SNR_step, SNR_step) for snr in SNR_dB: SNR = 10.0**(snr / 10.0) - scale = scipy.sqrt(2*SNR) + scale = scipy.sqrt(2 * SNR) yy = bits + n_cpx / scale print("SNR: ", snr) Sknown = scipy.mean(yy**2) Nknown = scipy.var(n_cpx / scale) snr0 = Sknown / Nknown - snr0dB = 10.0*scipy.log10(snr0) + snr0dB = 10.0 * scipy.log10(snr0) snr_known.append(float(snr0dB)) snrdB, snr = py_est(yy) @@ -169,7 +174,7 @@ def main(): snr_gr.append(gr_snr.snr()) f1 = pyplot.figure(1) - s1 = f1.add_subplot(1,1,1) + s1 = f1.add_subplot(1, 1, 1) s1.plot(SNR_dB, snr_known, "k-o", linewidth=2, label="Known") s1.plot(SNR_dB, snr_python, "b-o", linewidth=2, label="Python") s1.plot(SNR_dB, snr_gr, "g-o", linewidth=2, label="GNU Radio") @@ -180,7 +185,7 @@ def main(): s1.legend() f2 = pyplot.figure(2) - s2 = f2.add_subplot(1,1,1) + s2 = f2.add_subplot(1, 1, 1) s2.plot(yy.real, yy.imag, 'o') pyplot.show() diff --git a/gr-digital/include/gnuradio/digital/constellation.h b/gr-digital/include/gnuradio/digital/constellation.h index 037075f2bb8..d6d39353d81 100644 --- a/gr-digital/include/gnuradio/digital/constellation.h +++ b/gr-digital/include/gnuradio/digital/constellation.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include namespace gr { @@ -113,7 +113,7 @@ class DIGITAL_API constellation : public std::enable_shared_from_this #include #include -#include + +#include + #include namespace gr { @@ -88,9 +90,9 @@ void constellation_receiver_cb_impl::handle_set_constellation( pmt::pmt_t constellation_pmt) { if (pmt::is_any(constellation_pmt)) { - std::any constellation_any = pmt::any_ref(constellation_pmt); + boost::any constellation_any = pmt::any_ref(constellation_pmt); constellation_sptr constellation = - std::any_cast(constellation_any); + boost::any_cast(constellation_any); set_constellation(constellation); } else { GR_LOG_ERROR(d_logger, "Received constellation that is not a PMT any; skipping."); diff --git a/gr-digital/python/digital/__init__.py b/gr-digital/python/digital/__init__.py index 64281eb2bb2..80de67055db 100644 --- a/gr-digital/python/digital/__init__.py +++ b/gr-digital/python/digital/__init__.py @@ -22,11 +22,7 @@ __path__.append(os.path.join(dirname, "bindings")) from .digital_python import * -from gnuradio import analog # just need analog for the enum -class gmskmod_bc(cpmmod_bc): - def __init__(self, samples_per_sym = 2, L = 4, beta = 0.3): - cpmmod_bc.__init__(self, analog.cpm.GAUSSIAN, 0.5, samples_per_sym, L, beta) - +from gnuradio import analog # just need analog for the enum from .psk import * from .qam import * from .qamlike import * @@ -42,4 +38,7 @@ def __init__(self, samples_per_sym = 2, L = 4, beta = 0.3): from .qam_constellations import * from .constellation_map_generator import * -from . import packet_utils + +class gmskmod_bc(cpmmod_bc): + def __init__(self, samples_per_sym=2, L=4, beta=0.3): + cpmmod_bc.__init__(self, analog.cpm.GAUSSIAN, 0.5, samples_per_sym, L, beta) diff --git a/gr-digital/python/digital/bindings/constellation_python.cc b/gr-digital/python/digital/bindings/constellation_python.cc index b9e28067c28..4172bc550f6 100644 --- a/gr-digital/python/digital/bindings/constellation_python.cc +++ b/gr-digital/python/digital/bindings/constellation_python.cc @@ -14,7 +14,7 @@ /* BINDTOOL_GEN_AUTOMATIC(0) */ /* BINDTOOL_USE_PYGCCXML(0) */ /* BINDTOOL_HEADER_FILE(constellation.h) */ -/* BINDTOOL_HEADER_FILE_HASH(0dd35633df785034ea38ce7065495486) */ +/* BINDTOOL_HEADER_FILE_HASH(096509fbce3ab57c42e63e4c4c15c6f6) */ /***********************************************************************************/ #include diff --git a/gr-digital/python/digital/bpsk.py b/gr-digital/python/digital/bpsk.py index 7d5b8cde7aa..e6d507e2f79 100644 --- a/gr-digital/python/digital/bpsk.py +++ b/gr-digital/python/digital/bpsk.py @@ -25,6 +25,7 @@ # BPSK constellation # ///////////////////////////////////////////////////////////////////////////// + def bpsk_constellation(): return digital_python.constellation_bpsk() @@ -32,6 +33,7 @@ def bpsk_constellation(): # DBPSK constellation # ///////////////////////////////////////////////////////////////////////////// + def dbpsk_constellation(): return digital_python.constellation_dbpsk() diff --git a/gr-digital/python/digital/constellation_map_generator.py b/gr-digital/python/digital/constellation_map_generator.py index e6e660392c7..e3d6f532fd9 100644 --- a/gr-digital/python/digital/constellation_map_generator.py +++ b/gr-digital/python/digital/constellation_map_generator.py @@ -35,7 +35,7 @@ def constellation_map_generator(basis_cpoints, basis_symbols, k, pi): symbols = list() for s_i in s: tmp = 0 - for i,p in enumerate(pi): + for i, p in enumerate(pi): bit = (s_i >> i) & 0x1 tmp |= bit << p symbols.append(tmp ^ k) diff --git a/gr-digital/python/digital/cpm.py b/gr-digital/python/digital/cpm.py index d21ae55a875..ca32fb70360 100644 --- a/gr-digital/python/digital/cpm.py +++ b/gr-digital/python/digital/cpm.py @@ -29,7 +29,7 @@ _def_bits_per_symbol = 1 _def_h_numerator = 1 _def_h_denominator = 2 -_def_cpm_type = 0 # 0=CPFSK, 1=GMSK, 2=RC, 3=GENERAL +_def_cpm_type = 0 # 0=CPFSK, 1=GMSK, 2=RC, 3=GENERAL _def_bt = 0.35 _def_symbols_per_pulse = 1 _def_generic_taps = numpy.empty(1) @@ -80,62 +80,69 @@ def __init__(self, log=_def_log): gr.hier_block2.__init__(self, "cpm_mod", - gr.io_signature(1, 1, gr.sizeof_char), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_char), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._samples_per_symbol = samples_per_symbol self._bits_per_symbol = bits_per_symbol self._h_numerator = h_numerator self._h_denominator = h_denominator self._cpm_type = cpm_type - self._bt=bt - if cpm_type == 0 or cpm_type == 2 or cpm_type == 3: # CPFSK, RC, Generic + self._bt = bt + if cpm_type == 0 or cpm_type == 2 or cpm_type == 3: # CPFSK, RC, Generic self._symbols_per_pulse = symbols_per_pulse - elif cpm_type == 1: # GMSK + elif cpm_type == 1: # GMSK self._symbols_per_pulse = 4 else: - raise TypeError("cpm_type must be an integer in {0,1,2,3}, is %r" % (cpm_type,)) + raise TypeError( + "cpm_type must be an integer in {0,1,2,3}, is %r" % (cpm_type,)) - self._generic_taps=numpy.array(generic_taps) + self._generic_taps = numpy.array(generic_taps) if samples_per_symbol < 2: - raise TypeError("samples_per_symbol must be >= 2, is %r" % (samples_per_symbol,)) + raise TypeError("samples_per_symbol must be >= 2, is %r" % + (samples_per_symbol,)) self.nsymbols = 2**bits_per_symbol - self.sym_alphabet = numpy.arange(-(self.nsymbols-1),self.nsymbols,2).tolist() - + self.sym_alphabet = numpy.arange(-(self.nsymbols - 1), + self.nsymbols, 2).tolist() self.ntaps = int(self._symbols_per_pulse * samples_per_symbol) sensitivity = 2 * pi * h_numerator / h_denominator / samples_per_symbol # Unpack Bytes into bits_per_symbol groups - self.B2s = blocks.packed_to_unpacked_bb(bits_per_symbol,gr.GR_MSB_FIRST) - + self.B2s = blocks.packed_to_unpacked_bb( + bits_per_symbol, gr.GR_MSB_FIRST) # Turn it into symmetric PAM data. - self.pam = digital_python.chunks_to_symbols_bf(self.sym_alphabet,1) + self.pam = digital_python.chunks_to_symbols_bf(self.sym_alphabet, 1) # Generate pulse (sum of taps = samples_per_symbol/2) - if cpm_type == 0: # CPFSK - self.taps= (1.0/self._symbols_per_pulse/2,) * self.ntaps - elif cpm_type == 1: # GMSK + if cpm_type == 0: # CPFSK + self.taps = (1.0 / self._symbols_per_pulse / 2,) * self.ntaps + elif cpm_type == 1: # GMSK gaussian_taps = filter.firdes.gaussian( 1.0 / 2, # gain samples_per_symbol, # symbol_rate bt, # bandwidth * symbol time self.ntaps # number of taps - ) + ) sqwave = (1,) * samples_per_symbol # rectangular window - self.taps = numpy.convolve(numpy.array(gaussian_taps),numpy.array(sqwave)) - elif cpm_type == 2: # Raised Cosine + self.taps = numpy.convolve(numpy.array( + gaussian_taps), numpy.array(sqwave)) + elif cpm_type == 2: # Raised Cosine # generalize it for arbitrary roll-off factor - self.taps = (1-numpy.cos(2*pi*numpy.arange(0 / self.ntaps/samples_per_symbol/self._symbols_per_pulse)),(2*self._symbols_per_pulse)) - elif cpm_type == 3: # Generic CPM + self.taps = (1 - numpy.cos(2 * pi * numpy.arange(0 / self.ntaps / + samples_per_symbol / self._symbols_per_pulse)), (2 * self._symbols_per_pulse)) + elif cpm_type == 3: # Generic CPM self.taps = generic_taps else: - raise TypeError("cpm_type must be an integer in {0,1,2,3}, is %r" % (cpm_type,)) + raise TypeError( + "cpm_type must be an integer in {0,1,2,3}, is %r" % (cpm_type,)) - self.filter = filter.pfb.arb_resampler_fff(samples_per_symbol, self.taps) + self.filter = filter.pfb.arb_resampler_fff( + samples_per_symbol, self.taps) # FM modulation self.fmmod = analog.frequency_modulator_fc(sensitivity) @@ -170,19 +177,17 @@ def bt(self): def symbols_per_pulse(self): return self._symbols_per_pulse - def _print_verbage(self): print("Samples per symbol = %d" % self._samples_per_symbol) print("Bits per symbol = %d" % self._bits_per_symbol) - print("h = " , self._h_numerator , " / " , self._h_denominator) - print("Symbol alphabet = " , self.sym_alphabet) + print("h = ", self._h_numerator, " / ", self._h_denominator) + print("Symbol alphabet = ", self.sym_alphabet) print("Symbols per pulse = %d" % self._symbols_per_pulse) - print("taps = " , self.taps) + print("taps = ", self.taps) print("CPM type = %d" % self._cpm_type) if self._cpm_type == 1: - print("Gaussian filter BT = %.2f" % self._bt) - + print("Gaussian filter BT = %.2f" % self._bt) def _setup_logging(self): print("Modulation logging turned on.") @@ -209,8 +214,7 @@ def extract_kwargs_from_options(options): Given command line options, create dictionary suitable for passing to __init__ """ return modulation_utils.extract_kwargs_from_options(cpm_mod.__init__, - ('self',), options) - + ('self',), options) # ///////////////////////////////////////////////////////////////////////////// @@ -219,7 +223,6 @@ def extract_kwargs_from_options(options): # # Not yet implemented # - # # Add these to the mod/demod registry # diff --git a/gr-digital/python/digital/generic_mod_demod.py b/gr-digital/python/digital/generic_mod_demod.py index a40a7fda5fc..2db9e4482a0 100644 --- a/gr-digital/python/digital/generic_mod_demod.py +++ b/gr-digital/python/digital/generic_mod_demod.py @@ -29,17 +29,18 @@ _def_truncate = False # Frequency correction -_def_freq_bw = 2*math.pi/100.0 +_def_freq_bw = 2 * math.pi / 100.0 # Symbol timing recovery -_def_timing_bw = 2*math.pi/100.0 +_def_timing_bw = 2 * math.pi / 100.0 _def_timing_max_dev = 1.5 # Fine frequency / Phase correction -_def_phase_bw = 2*math.pi/100.0 +_def_phase_bw = 2 * math.pi / 100.0 # Number of points in constellation _def_constellation_points = 16 # Whether differential coding is used. _def_differential = False + def add_common_options(parser): """ Sets options common to both modulator and demodulator. @@ -55,7 +56,7 @@ def add_common_options(parser): parser.add_option("", "--mod-code", type="choice", choices=mod_codes.codes, default=mod_codes.NO_CODE, help="Select modulation code from: %s [default=%%default]" - % (', '.join(mod_codes.codes),)) + % (', '.join(mod_codes.codes),)) parser.add_option("", "--excess-bw", type="float", default=_def_excess_bw, help="set RRC excess bandwidth factor [default=%default]") @@ -92,8 +93,9 @@ def __init__(self, constellation, truncate=_def_truncate): gr.hier_block2.__init__(self, "generic_mod", - gr.io_signature(1, 1, gr.sizeof_char), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_char), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._constellation = constellation self._samples_per_symbol = samples_per_symbol @@ -103,31 +105,36 @@ def __init__(self, constellation, self.pre_diff_code = pre_diff_code and self._constellation.apply_pre_diff_code() if self._samples_per_symbol < 2: - raise TypeError("sps must be >= 2, is %f" % self._samples_per_symbol) + raise TypeError("sps must be >= 2, is %f" % + self._samples_per_symbol) - arity = pow(2,self.bits_per_symbol()) + arity = pow(2, self.bits_per_symbol()) # turn bytes into k-bit vectors self.bytes2chunks = \ - blocks.packed_to_unpacked_bb(self.bits_per_symbol(), gr.GR_MSB_FIRST) + blocks.packed_to_unpacked_bb( + self.bits_per_symbol(), gr.GR_MSB_FIRST) if self.pre_diff_code: - self.symbol_mapper = digital.map_bb(self._constellation.pre_diff_code()) + self.symbol_mapper = digital.map_bb( + self._constellation.pre_diff_code()) if differential: self.diffenc = digital.diff_encoder_bb(arity) - self.chunks2symbols = digital.chunks_to_symbols_bc(self._constellation.points()) + self.chunks2symbols = digital.chunks_to_symbols_bc( + self._constellation.points()) # pulse shaping filter nfilts = 32 ntaps_per_filt = 11 - ntaps = nfilts * ntaps_per_filt * int(self._samples_per_symbol) # make nfilts filters of ntaps each + # make nfilts filters of ntaps each + ntaps = nfilts * ntaps_per_filt * int(self._samples_per_symbol) self.rrc_taps = filter.firdes.root_raised_cosine( nfilts, # gain nfilts, # sampling rate based on 32 filters in resampler 1.0, # symbol rate - self._excess_bw, # excess bandwidth (roll-off factor) + self._excess_bw, # excess bandwidth (roll-off factor) ntaps) self.rrc_filter = filter.pfb_arb_resampler_ccf(self._samples_per_symbol, self.rrc_taps) @@ -135,8 +142,10 @@ def __init__(self, constellation, # Remove the filter transient at the beginning of the transmission if truncate: fsps = float(self._samples_per_symbol) - len_filt_delay = int((ntaps_per_filt*fsps*fsps-fsps)/2.0) # Length of delay through rrc filter - self.skiphead = blocks.skiphead(gr.sizeof_gr_complex*1, len_filt_delay) + # Length of delay through rrc filter + len_filt_delay = int((ntaps_per_filt * fsps * fsps - fsps) / 2.0) + self.skiphead = blocks.skiphead( + gr.sizeof_gr_complex * 1, len_filt_delay) # Connect self._blocks = [self, self.bytes2chunks] @@ -145,7 +154,7 @@ def __init__(self, constellation, if differential: self._blocks.append(self.diffenc) self._blocks += [self.chunks2symbols, self.rrc_filter] - + if truncate: self._blocks.append(self.skiphead) self._blocks.append(self) @@ -157,7 +166,6 @@ def __init__(self, constellation, if log: self._setup_logging() - def samples_per_symbol(self): return self._samples_per_symbol @@ -176,8 +184,7 @@ def extract_kwargs_from_options(cls, options): Given command line options, create dictionary suitable for passing to __init__ """ return extract_kwargs_from_options_for_class(cls, options) - extract_kwargs_from_options=classmethod(extract_kwargs_from_options) - + extract_kwargs_from_options = classmethod(extract_kwargs_from_options) def _print_verbage(self): print("\nModulator:") @@ -239,7 +246,8 @@ def __init__(self, constellation, log=_def_log): gr.hier_block2.__init__(self, "generic_demod", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_char)) # Output signature self._constellation = constellation @@ -248,19 +256,20 @@ def __init__(self, constellation, self._phase_bw = phase_bw self._freq_bw = freq_bw self._timing_bw = timing_bw - self._timing_max_dev= _def_timing_max_dev + self._timing_max_dev = _def_timing_max_dev self._differential = differential if self._samples_per_symbol < 2: - raise TypeError("sps must be >= 2, is %d" % self._samples_per_symbol) + raise TypeError("sps must be >= 2, is %d" % + self._samples_per_symbol) # Only apply a predifferential coding if the constellation also supports it. self.pre_diff_code = pre_diff_code and self._constellation.apply_pre_diff_code() - arity = pow(2,self.bits_per_symbol()) + arity = pow(2, self.bits_per_symbol()) nfilts = 32 - ntaps = 11 * int(self._samples_per_symbol*nfilts) + ntaps = 11 * int(self._samples_per_symbol * nfilts) # Automatic gain control self.agc = analog.agc2_cc(0.6e-1, 1e-3, 1, 1) @@ -271,11 +280,11 @@ def __init__(self, constellation, fll_ntaps, self._freq_bw) # symbol timing recovery with RRC data filter - taps = filter.firdes.root_raised_cosine(nfilts, nfilts*self._samples_per_symbol, + taps = filter.firdes.root_raised_cosine(nfilts, nfilts * self._samples_per_symbol, 1.0, self._excess_bw, ntaps) self.time_recov = digital.pfb_clock_sync_ccf(self._samples_per_symbol, self._timing_bw, taps, - nfilts, nfilts//2, self._timing_max_dev) + nfilts, nfilts // 2, self._timing_max_dev) fmin = -0.25 fmax = 0.25 @@ -318,7 +327,7 @@ def bits_per_symbol(self): def _print_verbage(self): print("\nDemodulator:") - print("bits per symbol: %d" % self.bits_per_symbol()) + print("bits per symbol: %d" % self.bits_per_symbol()) print("RRC roll-off factor: %.2f" % self._excess_bw) print("FLL bandwidth: %.2e" % self._freq_bw) print("Timing bandwidth: %.2e" % self._timing_bw) @@ -381,7 +390,8 @@ def extract_kwargs_from_options(cls, options): Given command line options, create dictionary suitable for passing to __init__ """ return extract_kwargs_from_options_for_class(cls, options) - extract_kwargs_from_options=classmethod(extract_kwargs_from_options) + extract_kwargs_from_options = classmethod(extract_kwargs_from_options) + shared_demod_args = """ samples_per_symbol: samples per baud >= 2 (float) excess_bw: Root-raised cosine filter excess bandwidth (float) diff --git a/gr-digital/python/digital/gfsk.py b/gr-digital/python/digital/gfsk.py index 2cc8f69c974..63583cc1e0b 100644 --- a/gr-digital/python/digital/gfsk.py +++ b/gr-digital/python/digital/gfsk.py @@ -70,8 +70,9 @@ def __init__(self, do_unpack=_def_do_unpack): gr.hier_block2.__init__(self, "gfsk_mod", - gr.io_signature(1, 1, gr.sizeof_char), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_char), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature samples_per_symbol = int(samples_per_symbol) self._samples_per_symbol = samples_per_symbol @@ -79,12 +80,11 @@ def __init__(self, self._differential = False if not isinstance(samples_per_symbol, int) or samples_per_symbol < 2: - raise TypeError("samples_per_symbol must be an integer >= 2, is %r" % (samples_per_symbol,)) + raise TypeError( + "samples_per_symbol must be an integer >= 2, is %r" % (samples_per_symbol,)) ntaps = 4 * samples_per_symbol # up to 3 bits in filter at once - #sensitivity = (pi / 2) / samples_per_symbol # phase change per bit = pi / 2 - - + # sensitivity = (pi / 2) / samples_per_symbol # phase change per bit = pi / 2 # Turn it into NRZ data. #self.nrz = digital.bytes_to_syms() @@ -93,15 +93,17 @@ def __init__(self, # Form Gaussian filter # Generate Gaussian response (Needs to be convolved with window below). self.gaussian_taps = filter.firdes.gaussian( - 1.0, # gain - samples_per_symbol, # symbol_rate - bt, # bandwidth * symbol time - ntaps # number of taps - ) + 1.0, # gain + samples_per_symbol, # symbol_rate + bt, # bandwidth * symbol time + ntaps # number of taps + ) self.sqwave = (1,) * samples_per_symbol # rectangular window - self.taps = numpy.convolve(numpy.array(self.gaussian_taps),numpy.array(self.sqwave)) - self.gaussian_filter = filter.interp_fir_filter_fff(samples_per_symbol, self.taps) + self.taps = numpy.convolve(numpy.array( + self.gaussian_taps), numpy.array(self.sqwave)) + self.gaussian_filter = filter.interp_fir_filter_fff( + samples_per_symbol, self.taps) # FM modulation self.fmmod = analog.frequency_modulator_fc(sensitivity) @@ -118,22 +120,24 @@ def __init__(self, # Connect & Initialize base class if do_unpack: self.unpack = blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST) - self.connect(self, self.unpack, self.nrz, self.gaussian_filter, self.fmmod, self.amp, self) + self.connect(self, self.unpack, self.nrz, + self.gaussian_filter, self.fmmod, self.amp, self) else: - self.connect(self, self.nrz, self.gaussian_filter, self.fmmod, self.amp, self) + self.connect(self, self.nrz, self.gaussian_filter, + self.fmmod, self.amp, self) def samples_per_symbol(self): return self._samples_per_symbol @staticmethod - def bits_per_symbol(self=None): # staticmethod that's also callable on an instance + # staticmethod that's also callable on an instance + def bits_per_symbol(self=None): return 1 def _print_verbage(self): print("bits per symbol = %d" % self.bits_per_symbol()) print("Gaussian filter bt = %.2f" % self._bt) - def _setup_logging(self): print("Modulation logging turned on.") self.connect(self.nrz, @@ -197,7 +201,8 @@ def __init__(self, log=_def_log): gr.hier_block2.__init__(self, "gfsk_demod", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_char)) # Output signature self._samples_per_symbol = samples_per_symbol @@ -207,17 +212,20 @@ def __init__(self, self._differential = False if samples_per_symbol < 2: - raise TypeError("samples_per_symbol >= 2, is %f" % samples_per_symbol) + raise TypeError("samples_per_symbol >= 2, is %f" % + samples_per_symbol) - self._omega = samples_per_symbol*(1+self._freq_error) + self._omega = samples_per_symbol * (1 + self._freq_error) if not self._gain_mu: self._gain_mu = 0.175 - self._gain_omega = .25 * self._gain_mu * self._gain_mu # critically damped + self._gain_omega = .25 * self._gain_mu * \ + self._gain_mu # critically damped self._damping = 1.0 - self._loop_bw = -ln((self._gain_mu + self._gain_omega)/(-2.0) + 1) # critically damped + # critically damped + self._loop_bw = -ln((self._gain_mu + self._gain_omega) / (-2.0) + 1) self._max_dev = self._omega_relative_limit * self._samples_per_symbol # Demodulate FM @@ -227,16 +235,16 @@ def __init__(self, # the clock recovery block tracks the symbol clock and resamples as needed. # the output of the block is a stream of soft symbols (float) self.clock_recovery = self.digital_symbol_sync_xx_0 = digital.symbol_sync_ff(digital.TED_MUELLER_AND_MULLER, - self._omega, - self._loop_bw, - self._damping, - 1.0, # Expected TED gain - self._max_dev, - 1, # Output sps - digital.constellation_bpsk().base(), - digital.IR_MMSE_8TAP, - 128, - []) + self._omega, + self._loop_bw, + self._damping, + 1.0, # Expected TED gain + self._max_dev, + 1, # Output sps + digital.constellation_bpsk().base(), + digital.IR_MMSE_8TAP, + 128, + []) # slice the floats at 0, outputting 1 bit (the LSB of the output byte) per sample self.slicer = digital.binary_slicer_fb() @@ -248,7 +256,8 @@ def __init__(self, self._setup_logging() # Connect & Initialize base class - self.connect(self, self.fmdemod, self.clock_recovery, self.slicer, self) + self.connect(self, self.fmdemod, + self.clock_recovery, self.slicer, self) def samples_per_symbol(self): return self._samples_per_symbol @@ -262,18 +271,18 @@ def _print_verbage(self): print("Symbol Sync M&M omega = %f" % self._omega) print("Symbol Sync M&M gain mu = %f" % self._gain_mu) print("M&M clock recovery mu (Unused) = %f" % self._mu) - print("Symbol Sync M&M omega rel. limit = %f" % self._omega_relative_limit) + print("Symbol Sync M&M omega rel. limit = %f" % + self._omega_relative_limit) print("frequency error = %f" % self._freq_error) - def _setup_logging(self): print("Demodulation logging turned on.") self.connect(self.fmdemod, - blocks.file_sink(gr.sizeof_float, "fmdemod.dat")) + blocks.file_sink(gr.sizeof_float, "fmdemod.dat")) self.connect(self.clock_recovery, - blocks.file_sink(gr.sizeof_float, "clock_recovery.dat")) + blocks.file_sink(gr.sizeof_float, "clock_recovery.dat")) self.connect(self.slicer, - blocks.file_sink(gr.sizeof_char, "slicer.dat")) + blocks.file_sink(gr.sizeof_char, "slicer.dat")) @staticmethod def add_options(parser): diff --git a/gr-digital/python/digital/gmsk.py b/gr-digital/python/digital/gmsk.py index 68127119e61..106e588782b 100644 --- a/gr-digital/python/digital/gmsk.py +++ b/gr-digital/python/digital/gmsk.py @@ -68,8 +68,9 @@ def __init__(self, do_unpack=_def_do_unpack): gr.hier_block2.__init__(self, "gmsk_mod", - gr.io_signature(1, 1, gr.sizeof_char), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_char), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature samples_per_symbol = int(samples_per_symbol) self._samples_per_symbol = samples_per_symbol @@ -77,10 +78,13 @@ def __init__(self, self._differential = False if not isinstance(samples_per_symbol, int) or samples_per_symbol < 2: - raise TypeError("samples_per_symbol must be an integer >= 2, is %r" % (samples_per_symbol,)) + raise TypeError( + "samples_per_symbol must be an integer >= 2, is %r" % (samples_per_symbol,)) - ntaps = 4 * samples_per_symbol # up to 3 bits in filter at once - sensitivity = (pi / 2) / samples_per_symbol # phase change per bit = pi / 2 + # up to 3 bits in filter at once + ntaps = 4 * samples_per_symbol + # phase change per bit = pi / 2 + sensitivity = (pi / 2) / samples_per_symbol # Turn it into NRZ data. #self.nrz = digital.bytes_to_syms() @@ -89,15 +93,17 @@ def __init__(self, # Form Gaussian filter # Generate Gaussian response (Needs to be convolved with window below). self.gaussian_taps = filter.firdes.gaussian( - 1, # gain - samples_per_symbol, # symbol_rate - bt, # bandwidth * symbol time - ntaps # number of taps - ) + 1, # gain + samples_per_symbol, # symbol_rate + bt, # bandwidth * symbol time + ntaps # number of taps + ) self.sqwave = (1,) * samples_per_symbol # rectangular window - self.taps = numpy.convolve(numpy.array(self.gaussian_taps),numpy.array(self.sqwave)) - self.gaussian_filter = filter.interp_fir_filter_fff(samples_per_symbol, self.taps) + self.taps = numpy.convolve(numpy.array( + self.gaussian_taps), numpy.array(self.sqwave)) + self.gaussian_filter = filter.interp_fir_filter_fff( + samples_per_symbol, self.taps) # FM modulation self.fmmod = analog.frequency_modulator_fc(sensitivity) @@ -111,22 +117,24 @@ def __init__(self, # Connect & Initialize base class if do_unpack: self.unpack = blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST) - self.connect(self, self.unpack, self.nrz, self.gaussian_filter, self.fmmod, self) + self.connect(self, self.unpack, self.nrz, + self.gaussian_filter, self.fmmod, self) else: - self.connect(self, self.nrz, self.gaussian_filter, self.fmmod, self) + self.connect(self, self.nrz, self.gaussian_filter, + self.fmmod, self) def samples_per_symbol(self): return self._samples_per_symbol @staticmethod - def bits_per_symbol(self=None): # staticmethod that's also callable on an instance + # staticmethod that's also callable on an instance + def bits_per_symbol(self=None): return 1 def _print_verbage(self): print("bits per symbol = %d" % self.bits_per_symbol()) print("Gaussian filter bt = %.2f" % self._bt) - def _setup_logging(self): print("Modulation logging turned on.") self.connect(self.nrz, @@ -185,7 +193,8 @@ def __init__(self, log=_def_log): gr.hier_block2.__init__(self, "gmsk_demod", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_char)) # Output signature self._samples_per_symbol = samples_per_symbol @@ -195,17 +204,20 @@ def __init__(self, self._differential = False if samples_per_symbol < 2: - raise TypeError("samples_per_symbol >= 2, is %f" % samples_per_symbol) + raise TypeError("samples_per_symbol >= 2, is %f" % + samples_per_symbol) - self._omega = samples_per_symbol*(1+self._freq_error) + self._omega = samples_per_symbol * (1 + self._freq_error) if not self._gain_mu: self._gain_mu = 0.175 - self._gain_omega = .25 * self._gain_mu * self._gain_mu # critically damped + self._gain_omega = .25 * self._gain_mu * \ + self._gain_mu # critically damped self._damping = 1.0 - self._loop_bw = -ln((self._gain_mu + self._gain_omega)/(-2.0) + 1) # critically damped + # critically damped + self._loop_bw = -ln((self._gain_mu + self._gain_omega) / (-2.0) + 1) self._max_dev = self._omega_relative_limit * self._samples_per_symbol # Demodulate FM @@ -215,16 +227,16 @@ def __init__(self, # the clock recovery block tracks the symbol clock and resamples as needed. # the output of the block is a stream of soft symbols (float) self.clock_recovery = self.digital_symbol_sync_xx_0 = digital.symbol_sync_ff(digital.TED_MUELLER_AND_MULLER, - self._omega, - self._loop_bw, - self._damping, - 1.0, # Expected TED gain - self._max_dev, - 1, # Output sps - digital.constellation_bpsk().base(), - digital.IR_MMSE_8TAP, - 128, - []) + self._omega, + self._loop_bw, + self._damping, + 1.0, # Expected TED gain + self._max_dev, + 1, # Output sps + digital.constellation_bpsk().base(), + digital.IR_MMSE_8TAP, + 128, + []) # slice the floats at 0, outputting 1 bit (the LSB of the output byte) per sample self.slicer = digital.binary_slicer_fb() @@ -236,7 +248,8 @@ def __init__(self, self._setup_logging() # Connect & Initialize base class - self.connect(self, self.fmdemod, self.clock_recovery, self.slicer, self) + self.connect(self, self.fmdemod, + self.clock_recovery, self.slicer, self) def samples_per_symbol(self): return self._samples_per_symbol @@ -250,18 +263,18 @@ def _print_verbage(self): print("Symbol Sync M&M omega = %f" % self._omega) print("Symbol Sync M&M gain mu = %f" % self._gain_mu) print("M&M clock recovery mu (Unused) = %f" % self._mu) - print("Symbol Sync M&M omega rel. limit = %f" % self._omega_relative_limit) + print("Symbol Sync M&M omega rel. limit = %f" % + self._omega_relative_limit) print("frequency error = %f" % self._freq_error) - def _setup_logging(self): print("Demodulation logging turned on.") self.connect(self.fmdemod, - blocks.file_sink(gr.sizeof_float, "fmdemod.dat")) + blocks.file_sink(gr.sizeof_float, "fmdemod.dat")) self.connect(self.clock_recovery, - blocks.file_sink(gr.sizeof_float, "clock_recovery.dat")) + blocks.file_sink(gr.sizeof_float, "clock_recovery.dat")) self.connect(self.slicer, - blocks.file_sink(gr.sizeof_char, "slicer.dat")) + blocks.file_sink(gr.sizeof_char, "slicer.dat")) @staticmethod def add_options(parser): diff --git a/gr-digital/python/digital/modulation_utils.py b/gr-digital/python/digital/modulation_utils.py index 59809ae1d8c..1d57e1c9ba1 100644 --- a/gr-digital/python/digital/modulation_utils.py +++ b/gr-digital/python/digital/modulation_utils.py @@ -1,8 +1,8 @@ # # Copyright 2010 Free Software Foundation, Inc. -# +# # This file is part of GNU Radio -# +# # SPDX-License-Identifier: GPL-3.0-or-later # @@ -17,9 +17,11 @@ # Type 1 modulators accept a stream of bytes on their input and produce complex baseband output _type_1_modulators = {} + def type_1_mods(): return _type_1_modulators + def add_type_1_mod(name, mod_class): _type_1_modulators[name] = mod_class @@ -29,18 +31,23 @@ def add_type_1_mod(name, mod_class): # to resolve phase or polarity ambiguities. _type_1_demodulators = {} + def type_1_demods(): return _type_1_demodulators + def add_type_1_demod(name, demod_class): _type_1_demodulators[name] = demod_class + # Also record the constellation making functions of the modulations _type_1_constellations = {} + def type_1_constellations(): return _type_1_constellations + def add_type_1_constellation(name, constellation): _type_1_constellations[name] = constellation @@ -67,7 +74,7 @@ def extract_kwargs_from_options(function, excluded_args, options): excluded_args: function arguments that are NOT to be added to the dictionary (sequence of strings) options: result of command argument parsing (optparse.Values) """ - + # Try this in C++ ;) spec = inspect.getfullargspec(function) d = {} @@ -77,6 +84,7 @@ def extract_kwargs_from_options(function, excluded_args, options): d[kw] = getattr(options, kw) return d + def extract_kwargs_from_options_for_class(cls, options): """ Given command line options, create dictionary suitable for passing to __init__ diff --git a/gr-digital/python/digital/ofdm_txrx.py b/gr-digital/python/digital/ofdm_txrx.py index 9d083c5fe28..60109ceaaa4 100644 --- a/gr-digital/python/digital/ofdm_txrx.py +++ b/gr-digital/python/digital/ofdm_txrx.py @@ -31,15 +31,20 @@ _def_packet_length_tag_key = "packet_length" _def_packet_num_tag_key = "packet_num" # Data and pilot carriers are same as in 802.11a -_def_occupied_carriers = (list(range(-26, -21)) + list(range(-20, -7)) + list(range(-6, 0)) + list(range(1, 7)) + list(range(8, 21)) + list(range(22, 27)),) -_def_pilot_carriers=((-21, -7, 7, 21,),) +_def_occupied_carriers = (list(range(-26, -21)) + list(range(-20, -7)) + list( + range(-6, 0)) + list(range(1, 7)) + list(range(8, 21)) + list(range(22, 27)),) +_def_pilot_carriers = ((-21, -7, 7, 21,),) _pilot_sym_scramble_seq = ( - 1,1,1,1, -1,-1,-1,1, -1,-1,-1,-1, 1,1,-1,1, -1,-1,1,1, -1,1,1,-1, 1,1,1,1, 1,1,-1,1, - 1,1,-1,1, 1,-1,-1,1, 1,1,-1,1, -1,-1,-1,1, -1,1,-1,-1, 1,-1,-1,1, 1,1,1,1, -1,-1,1,1, - -1,-1,1,-1, 1,-1,1,1, -1,-1,-1,1, 1,-1,-1,-1, -1,1,-1,-1, 1,-1,1,1, 1,1,-1,1, -1,1,-1,1, - -1,-1,-1,-1, -1,1,-1,1, 1,-1,1,-1, 1,1,1,-1, -1,1,-1,-1, -1,1,1,1, -1,-1,-1,-1, -1,-1,-1 + 1, 1, 1, 1, -1, -1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, - + 1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, + 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, 1, - + 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, + -1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, -1, - + 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, 1, -1, 1, + -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, 1, -1, - + 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1 ) -_def_pilot_symbols= tuple([(x, x, x, -x) for x in _pilot_sym_scramble_seq]) +_def_pilot_symbols = tuple([(x, x, x, -x) for x in _pilot_sym_scramble_seq]) _seq_seed = 42 @@ -52,6 +57,7 @@ def _get_active_carriers(fft_len, occupied_carriers, pilot_carriers): active_carriers.append(carrier) return active_carriers + def _make_sync_word1(fft_len, occupied_carriers, pilot_carriers): """ Creates a random sync sequence for fine frequency offset and timing estimation. This is the first of typically two sync preamble symbols @@ -64,31 +70,37 @@ def _make_sync_word1(fft_len, occupied_carriers, pilot_carriers): Carrier 0 (DC carrier) is always zero. If used, carrier 1 is non-zero. This means the sync algorithm has to check on odd carriers! """ - active_carriers = _get_active_carriers(fft_len, occupied_carriers, pilot_carriers) + active_carriers = _get_active_carriers( + fft_len, occupied_carriers, pilot_carriers) numpy.random.seed(_seq_seed) bpsk = {0: numpy.sqrt(2), 1: -numpy.sqrt(2)} - sw1 = [bpsk[numpy.random.randint(2)] if x in active_carriers and x % 2 else 0 for x in range(fft_len)] + sw1 = [bpsk[numpy.random.randint( + 2)] if x in active_carriers and x % 2 else 0 for x in range(fft_len)] return numpy.fft.fftshift(sw1) + def _make_sync_word2(fft_len, occupied_carriers, pilot_carriers): """ Creates a random sync sequence for coarse frequency offset and channel estimation. This is the second of typically two sync preamble symbols for the Schmidl & Cox sync algorithm. Symbols are always BPSK symbols. """ - active_carriers = _get_active_carriers(fft_len, occupied_carriers, pilot_carriers) + active_carriers = _get_active_carriers( + fft_len, occupied_carriers, pilot_carriers) numpy.random.seed(_seq_seed) bpsk = {0: 1, 1: -1} - sw2 = [bpsk[numpy.random.randint(2)] if x in active_carriers else 0 for x in range(fft_len)] + sw2 = [bpsk[numpy.random.randint( + 2)] if x in active_carriers else 0 for x in range(fft_len)] sw2[0] = 0j return numpy.fft.fftshift(sw2) + def _get_constellation(bps): """ Returns a modulator block for a given number of bits per symbol """ constellation = { - 1: digital.constellation_bpsk(), - 2: digital.constellation_qpsk(), - 3: digital.constellation_8psk() + 1: digital.constellation_bpsk(), + 2: digital.constellation_qpsk(), + 3: digital.constellation_8psk() } try: return constellation[bps] @@ -96,6 +108,7 @@ def _get_constellation(bps): print('Modulation not supported.') exit(1) + class ofdm_tx(gr.hier_block2): """Hierarchical block for OFDM modulation. @@ -122,6 +135,7 @@ class ofdm_tx(gr.hier_block2): scramble_bits: Activates the scramblers (set this to True unless debugging) """ + def __init__(self, fft_len=_def_fft_len, cp_len=_def_cp_len, packet_length_tag_key=_def_packet_length_tag_key, occupied_carriers=_def_occupied_carriers, @@ -136,75 +150,82 @@ def __init__(self, fft_len=_def_fft_len, cp_len=_def_cp_len, scramble_bits=False ): gr.hier_block2.__init__(self, "ofdm_tx", - gr.io_signature(1, 1, gr.sizeof_char), - gr.io_signature(1, 1, gr.sizeof_gr_complex)) + gr.io_signature(1, 1, gr.sizeof_char), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) ### Param init / sanity check ######################################## - self.fft_len = fft_len - self.cp_len = cp_len + self.fft_len = fft_len + self.cp_len = cp_len self.packet_length_tag_key = packet_length_tag_key self.occupied_carriers = occupied_carriers - self.pilot_carriers = pilot_carriers - self.pilot_symbols = pilot_symbols - self.bps_header = bps_header - self.bps_payload = bps_payload + self.pilot_carriers = pilot_carriers + self.pilot_symbols = pilot_symbols + self.bps_header = bps_header + self.bps_payload = bps_payload self.sync_word1 = sync_word1 if sync_word1 is None: - self.sync_word1 = _make_sync_word1(fft_len, occupied_carriers, pilot_carriers) + self.sync_word1 = _make_sync_word1( + fft_len, occupied_carriers, pilot_carriers) else: if len(sync_word1) != self.fft_len: - raise ValueError("Length of sync sequence(s) must be FFT length.") - self.sync_words = [self.sync_word1,] + raise ValueError( + "Length of sync sequence(s) must be FFT length.") + self.sync_words = [self.sync_word1, ] if sync_word2 is None: - self.sync_word2 = _make_sync_word2(fft_len, occupied_carriers, pilot_carriers) + self.sync_word2 = _make_sync_word2( + fft_len, occupied_carriers, pilot_carriers) else: self.sync_word2 = sync_word2 if len(self.sync_word2): if len(self.sync_word2) != fft_len: - raise ValueError("Length of sync sequence(s) must be FFT length.") + raise ValueError( + "Length of sync sequence(s) must be FFT length.") self.sync_word2 = list(self.sync_word2) self.sync_words.append(self.sync_word2) if scramble_bits: self.scramble_seed = 0x7f else: - self.scramble_seed = 0x00 # We deactivate the scrambler by init'ing it with zeros + self.scramble_seed = 0x00 # We deactivate the scrambler by init'ing it with zeros ### Header modulation ################################################ crc = digital.crc32_bb(False, self.packet_length_tag_key) - header_constellation = _get_constellation(bps_header) - header_mod = digital.chunks_to_symbols_bc(header_constellation.points()) + header_constellation = _get_constellation(bps_header) + header_mod = digital.chunks_to_symbols_bc( + header_constellation.points()) formatter_object = digital.packet_header_ofdm( occupied_carriers=occupied_carriers, n_syms=1, bits_per_header_sym=self.bps_header, bits_per_payload_sym=self.bps_payload, scramble_header=scramble_bits ) - header_gen = digital.packet_headergenerator_bb(formatter_object.base(), self.packet_length_tag_key) + header_gen = digital.packet_headergenerator_bb( + formatter_object.base(), self.packet_length_tag_key) header_payload_mux = blocks.tagged_stream_mux( - itemsize=gr.sizeof_gr_complex*1, - lengthtagname=self.packet_length_tag_key, - tag_preserve_head_pos=1 # Head tags on the payload stream stay on the head + itemsize=gr.sizeof_gr_complex * 1, + lengthtagname=self.packet_length_tag_key, + tag_preserve_head_pos=1 # Head tags on the payload stream stay on the head ) self.connect( - self, - crc, - header_gen, - header_mod, - (header_payload_mux, 0) + self, + crc, + header_gen, + header_mod, + (header_payload_mux, 0) ) if debug_log: self.connect(header_gen, blocks.file_sink(1, 'tx-hdr.dat')) ### Payload modulation ############################################### payload_constellation = _get_constellation(bps_payload) - payload_mod = digital.chunks_to_symbols_bc(payload_constellation.points()) + payload_mod = digital.chunks_to_symbols_bc( + payload_constellation.points()) payload_scrambler = digital.additive_scrambler_bb( 0x8a, self.scramble_seed, 7, - 0, # Don't reset after fixed length (let the reset tag do that) - bits_per_byte=8, # This is before unpacking + 0, # Don't reset after fixed length (let the reset tag do that) + bits_per_byte=8, # This is before unpacking reset_tag_key=self.packet_length_tag_key ) payload_unpack = blocks.repack_bits_bb( - 8, # Unpack 8 bits per byte + 8, # Unpack 8 bits per byte bps_payload, self.packet_length_tag_key ) @@ -225,21 +246,24 @@ def __init__(self, fft_len=_def_fft_len, cp_len=_def_cp_len, len_tag_key=self.packet_length_tag_key ) ffter = fft.fft_vcc( - self.fft_len, - False, # Inverse FFT - (), # No window - True # Shift + self.fft_len, + False, # Inverse FFT + (), # No window + True # Shift ) cyclic_prefixer = digital.ofdm_cyclic_prefixer( self.fft_len, - self.fft_len+self.cp_len, + self.fft_len + self.cp_len, rolloff, self.packet_length_tag_key ) - self.connect(header_payload_mux, allocator, ffter, cyclic_prefixer, self) + self.connect(header_payload_mux, allocator, + ffter, cyclic_prefixer, self) if debug_log: - self.connect(allocator, blocks.file_sink(gr.sizeof_gr_complex * fft_len, 'tx-post-allocator.dat')) - self.connect(cyclic_prefixer, blocks.file_sink(gr.sizeof_gr_complex, 'tx-signal.dat')) + self.connect(allocator, blocks.file_sink( + gr.sizeof_gr_complex * fft_len, 'tx-post-allocator.dat')) + self.connect(cyclic_prefixer, blocks.file_sink( + gr.sizeof_gr_complex, 'tx-signal.dat')) class ofdm_rx(gr.hier_block2): @@ -265,6 +289,7 @@ class ofdm_rx(gr.hier_block2): | entirely. Also used for coarse frequency offset and | channel estimation. """ + def __init__(self, fft_len=_def_fft_len, cp_len=_def_cp_len, frame_length_tag_key=_def_frame_length_tag_key, packet_length_tag_key=_def_packet_length_tag_key, @@ -280,60 +305,69 @@ def __init__(self, fft_len=_def_fft_len, cp_len=_def_cp_len, scramble_bits=False ): gr.hier_block2.__init__(self, "ofdm_rx", - gr.io_signature(1, 1, gr.sizeof_gr_complex), - gr.io_signature(1, 1, gr.sizeof_char)) + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(1, 1, gr.sizeof_char)) ### Param init / sanity check ######################################## - self.fft_len = fft_len - self.cp_len = cp_len - self.frame_length_tag_key = frame_length_tag_key - self.packet_length_tag_key = packet_length_tag_key + self.fft_len = fft_len + self.cp_len = cp_len + self.frame_length_tag_key = frame_length_tag_key + self.packet_length_tag_key = packet_length_tag_key self.occupied_carriers = occupied_carriers - self.bps_header = bps_header - self.bps_payload = bps_payload + self.bps_header = bps_header + self.bps_payload = bps_payload n_sync_words = 1 if sync_word1 is None: - self.sync_word1 = _make_sync_word1(fft_len, occupied_carriers, pilot_carriers) + self.sync_word1 = _make_sync_word1( + fft_len, occupied_carriers, pilot_carriers) else: if len(sync_word1) != self.fft_len: - raise ValueError("Length of sync sequence(s) must be FFT length.") + raise ValueError( + "Length of sync sequence(s) must be FFT length.") self.sync_word1 = sync_word1 self.sync_word2 = () if sync_word2 is None: - self.sync_word2 = _make_sync_word2(fft_len, occupied_carriers, pilot_carriers) + self.sync_word2 = _make_sync_word2( + fft_len, occupied_carriers, pilot_carriers) n_sync_words = 2 elif len(sync_word2): if len(sync_word2) != fft_len: - raise ValueError("Length of sync sequence(s) must be FFT length.") + raise ValueError( + "Length of sync sequence(s) must be FFT length.") self.sync_word2 = sync_word2 n_sync_words = 2 if scramble_bits: self.scramble_seed = 0x7f else: - self.scramble_seed = 0x00 # We deactivate the scrambler by init'ing it with zeros + self.scramble_seed = 0x00 # We deactivate the scrambler by init'ing it with zeros ### Sync ############################################################ sync_detect = digital.ofdm_sync_sc_cfb(fft_len, cp_len) - delay = blocks.delay(gr.sizeof_gr_complex, fft_len+cp_len) + delay = blocks.delay(gr.sizeof_gr_complex, fft_len + cp_len) oscillator = analog.frequency_modulator_fc(-2.0 / fft_len) mixer = blocks.multiply_cc() hpd = digital.header_payload_demux( - n_sync_words+1, # Number of OFDM symbols before payload (sync + 1 sym header) + # Number of OFDM symbols before payload (sync + 1 sym header) + n_sync_words + 1, fft_len, cp_len, # FFT length, guard interval - frame_length_tag_key, # Frame length tag key + frame_length_tag_key, # Frame length tag key "", # We're not using trigger tags - True # One output item is one OFDM symbol (False would output complex scalars) + # One output item is one OFDM symbol (False would output complex scalars) + True ) self.connect(self, sync_detect) self.connect(self, delay, (mixer, 0), (hpd, 0)) self.connect((sync_detect, 0), oscillator, (mixer, 1)) self.connect((sync_detect, 1), (hpd, 1)) if debug_log: - self.connect((sync_detect, 0), blocks.file_sink(gr.sizeof_float, 'freq-offset.dat')) - self.connect((sync_detect, 1), blocks.file_sink(gr.sizeof_char, 'sync-detect.dat')) + self.connect((sync_detect, 0), blocks.file_sink( + gr.sizeof_float, 'freq-offset.dat')) + self.connect((sync_detect, 1), blocks.file_sink( + gr.sizeof_char, 'sync-detect.dat')) ### Header demodulation ############################################## - header_fft = fft.fft_vcc(self.fft_len, True, (), True) - chanest = digital.ofdm_chanest_vcvc(self.sync_word1, self.sync_word2, 1) + header_fft = fft.fft_vcc(self.fft_len, True, (), True) + chanest = digital.ofdm_chanest_vcvc( + self.sync_word1, self.sync_word2, 1) header_constellation = _get_constellation(bps_header) - header_equalizer = digital.ofdm_equalizer_simpledfe( + header_equalizer = digital.ofdm_equalizer_simpledfe( fft_len, header_constellation.base(), occupied_carriers, @@ -342,93 +376,108 @@ def __init__(self, fft_len=_def_fft_len, cp_len=_def_cp_len, symbols_skipped=0, ) header_eq = digital.ofdm_frame_equalizer_vcvc( - header_equalizer.base(), - cp_len, - self.frame_length_tag_key, - True, - 1 # Header is 1 symbol long + header_equalizer.base(), + cp_len, + self.frame_length_tag_key, + True, + 1 # Header is 1 symbol long ) header_serializer = digital.ofdm_serializer_vcc( - fft_len, occupied_carriers, - self.frame_length_tag_key + fft_len, occupied_carriers, + self.frame_length_tag_key ) - header_demod = digital.constellation_decoder_cb(header_constellation.base()) + header_demod = digital.constellation_decoder_cb( + header_constellation.base()) header_formatter = digital.packet_header_ofdm( - occupied_carriers, 1, - packet_length_tag_key, - frame_length_tag_key, - packet_num_tag_key, - bps_header, - bps_payload, - scramble_header=scramble_bits + occupied_carriers, 1, + packet_length_tag_key, + frame_length_tag_key, + packet_num_tag_key, + bps_header, + bps_payload, + scramble_header=scramble_bits ) - header_parser = digital.packet_headerparser_b(header_formatter.formatter()) + header_parser = digital.packet_headerparser_b( + header_formatter.formatter()) self.connect( - (hpd, 0), - header_fft, - chanest, - header_eq, - header_serializer, - header_demod, - header_parser + (hpd, 0), + header_fft, + chanest, + header_eq, + header_serializer, + header_demod, + header_parser ) self.msg_connect(header_parser, "header_data", hpd, "header_data") if debug_log: - self.connect((chanest, 1), blocks.file_sink(gr.sizeof_gr_complex * fft_len, 'channel-estimate.dat')) - self.connect((chanest, 0), blocks.file_sink(gr.sizeof_gr_complex * fft_len, 'post-hdr-chanest.dat')) - self.connect((chanest, 0), blocks.tag_debug(gr.sizeof_gr_complex * fft_len, 'post-hdr-chanest')) - self.connect(header_eq, blocks.file_sink(gr.sizeof_gr_complex * fft_len, 'post-hdr-eq.dat')) - self.connect(header_serializer, blocks.file_sink(gr.sizeof_gr_complex, 'post-hdr-serializer.dat')) + self.connect((chanest, 1), blocks.file_sink( + gr.sizeof_gr_complex * fft_len, 'channel-estimate.dat')) + self.connect((chanest, 0), blocks.file_sink( + gr.sizeof_gr_complex * fft_len, 'post-hdr-chanest.dat')) + self.connect((chanest, 0), blocks.tag_debug( + gr.sizeof_gr_complex * fft_len, 'post-hdr-chanest')) + self.connect(header_eq, blocks.file_sink( + gr.sizeof_gr_complex * fft_len, 'post-hdr-eq.dat')) + self.connect(header_serializer, blocks.file_sink( + gr.sizeof_gr_complex, 'post-hdr-serializer.dat')) ### Payload demod #################################################### payload_fft = fft.fft_vcc(self.fft_len, True, (), True) payload_constellation = _get_constellation(bps_payload) payload_equalizer = digital.ofdm_equalizer_simpledfe( - fft_len, - payload_constellation.base(), - occupied_carriers, - pilot_carriers, - pilot_symbols, - symbols_skipped=1, # (that was already in the header) - alpha=0.1 + fft_len, + payload_constellation.base(), + occupied_carriers, + pilot_carriers, + pilot_symbols, + symbols_skipped=1, # (that was already in the header) + alpha=0.1 ) payload_eq = digital.ofdm_frame_equalizer_vcvc( - payload_equalizer.base(), - cp_len, - self.frame_length_tag_key + payload_equalizer.base(), + cp_len, + self.frame_length_tag_key ) payload_serializer = digital.ofdm_serializer_vcc( - fft_len, occupied_carriers, - self.frame_length_tag_key, - self.packet_length_tag_key, - 1 # Skip 1 symbol (that was already in the header) + fft_len, occupied_carriers, + self.frame_length_tag_key, + self.packet_length_tag_key, + 1 # Skip 1 symbol (that was already in the header) ) - payload_demod = digital.constellation_decoder_cb(payload_constellation.base()) + payload_demod = digital.constellation_decoder_cb( + payload_constellation.base()) self.payload_descrambler = digital.additive_scrambler_bb( 0x8a, self.scramble_seed, 7, - 0, # Don't reset after fixed length - bits_per_byte=8, # This is after packing + 0, # Don't reset after fixed length + bits_per_byte=8, # This is after packing reset_tag_key=self.packet_length_tag_key ) - payload_pack = blocks.repack_bits_bb(bps_payload, 8, self.packet_length_tag_key, True) + payload_pack = blocks.repack_bits_bb( + bps_payload, 8, self.packet_length_tag_key, True) self.crc = digital.crc32_bb(True, self.packet_length_tag_key) self.connect( - (hpd, 1), - payload_fft, - payload_eq, - payload_serializer, - payload_demod, - payload_pack, - self.payload_descrambler, - self.crc, - self + (hpd, 1), + payload_fft, + payload_eq, + payload_serializer, + payload_demod, + payload_pack, + self.payload_descrambler, + self.crc, + self ) if debug_log: - self.connect((hpd, 1), blocks.tag_debug(gr.sizeof_gr_complex*fft_len, 'post-hpd')) - self.connect(payload_fft, blocks.file_sink(gr.sizeof_gr_complex*fft_len, 'post-payload-fft.dat')) - self.connect(payload_eq, blocks.file_sink(gr.sizeof_gr_complex*fft_len, 'post-payload-eq.dat')) - self.connect(payload_serializer, blocks.file_sink(gr.sizeof_gr_complex, 'post-payload-serializer.dat')) - self.connect(payload_demod, blocks.file_sink(1, 'post-payload-demod.dat')) - self.connect(payload_pack, blocks.file_sink(1, 'post-payload-pack.dat')) - self.connect(self.crc, blocks.file_sink(1, 'post-payload-crc.dat')) + self.connect((hpd, 1), blocks.tag_debug( + gr.sizeof_gr_complex * fft_len, 'post-hpd')) + self.connect(payload_fft, blocks.file_sink( + gr.sizeof_gr_complex * fft_len, 'post-payload-fft.dat')) + self.connect(payload_eq, blocks.file_sink( + gr.sizeof_gr_complex * fft_len, 'post-payload-eq.dat')) + self.connect(payload_serializer, blocks.file_sink( + gr.sizeof_gr_complex, 'post-payload-serializer.dat')) + self.connect(payload_demod, blocks.file_sink( + 1, 'post-payload-demod.dat')) + self.connect(payload_pack, blocks.file_sink( + 1, 'post-payload-pack.dat')) + self.connect(self.crc, blocks.file_sink(1, 'post-payload-crc.dat')) diff --git a/gr-digital/python/digital/psk.py b/gr-digital/python/digital/psk.py index b04d66f75f0..4866d54ede5 100644 --- a/gr-digital/python/digital/psk.py +++ b/gr-digital/python/digital/psk.py @@ -28,6 +28,7 @@ # Default use of differential encoding _def_differential = True + def create_encodings(mod_code, arity, differential): post_diff_code = None if mod_code not in mod_codes.codes: @@ -43,13 +44,15 @@ def create_encodings(mod_code, arity, differential): pre_diff_code = [] post_diff_code = None else: - raise ValueError('That modulation code is not implemented for this constellation.') + raise ValueError( + 'That modulation code is not implemented for this constellation.') return (pre_diff_code, post_diff_code) # ///////////////////////////////////////////////////////////////////////////// # PSK constellation # ///////////////////////////////////////////////////////////////////////////// + def psk_constellation(m=_def_constellation_points, mod_code=_def_mod_code, differential=_def_differential): """ @@ -57,8 +60,9 @@ def psk_constellation(m=_def_constellation_points, mod_code=_def_mod_code, """ k = log(m) / log(2.0) if (k != int(k)): - raise Exception('Number of constellation points must be a power of two.') - points = [exp(2*pi*(0+1j)*i/m) for i in range(0,m)] + raise Exception( + 'Number of constellation points must be a power of two.') + points = [exp(2 * pi * (0 + 1j) * i / m) for i in range(0, m)] pre_diff_code, post_diff_code = create_encodings(mod_code, m, differential) if post_diff_code is not None: inverse_post_diff_code = mod_codes.invert_code(post_diff_code) @@ -70,6 +74,7 @@ def psk_constellation(m=_def_constellation_points, mod_code=_def_mod_code, # PSK modulator # ///////////////////////////////////////////////////////////////////////////// + class psk_mod(generic_mod): """ Hierarchical block for RRC-filtered PSK modulation. @@ -95,14 +100,17 @@ def __init__(self, constellation_points=_def_constellation_points, mod_code=_def_mod_code, differential=_def_differential, *args, **kwargs): - constellation = psk_constellation(constellation_points, mod_code, differential) - super(psk_mod, self).__init__(constellation, differential, *args, **kwargs) + constellation = psk_constellation( + constellation_points, mod_code, differential) + super(psk_mod, self).__init__( + constellation, differential, *args, **kwargs) # ///////////////////////////////////////////////////////////////////////////// # PSK demodulator # # ///////////////////////////////////////////////////////////////////////////// + class psk_demod(generic_demod): """ @@ -120,12 +128,16 @@ class psk_demod(generic_demod): """ # See generic_mod for additional arguments __doc__ += shared_mod_args + def __init__(self, constellation_points=_def_constellation_points, mod_code=_def_mod_code, differential=_def_differential, *args, **kwargs): - constellation = psk_constellation(constellation_points, mod_code, differential) - super(psk_demod, self).__init__(constellation, differential, *args, **kwargs) + constellation = psk_constellation( + constellation_points, mod_code, differential) + super(psk_demod, self).__init__( + constellation, differential, *args, **kwargs) + # # Add these to the mod/demod registry diff --git a/gr-digital/python/digital/psk_constellations.py b/gr-digital/python/digital/psk_constellations.py index c3809e7adea..520eafebe2c 100644 --- a/gr-digital/python/digital/psk_constellations.py +++ b/gr-digital/python/digital/psk_constellations.py @@ -52,6 +52,7 @@ # BPSK Constellation Mappings + def psk_2_0x0(): ''' 0 | 1 @@ -59,9 +60,12 @@ def psk_2_0x0(): const_points = [-1, 1] symbols = [0, 1] return (const_points, symbols) + + psk_2 = psk_2_0x0 # Basic BPSK rotation psk_2_0 = psk_2 # First ID for BPSK rotations + def psk_2_0x1(): ''' 1 | 0 @@ -69,6 +73,8 @@ def psk_2_0x1(): const_points = [-1, 1] symbols = [1, 0] return (const_points, symbols) + + psk_2_1 = psk_2_0x1 @@ -81,18 +87,23 @@ def sd_psk_2_0x0(x, Es=1): 0 | 1 ''' x_re = x.real - dist = Es*numpy.sqrt(2) - return [dist*x_re,] + dist = Es * numpy.sqrt(2) + return [dist * x_re, ] + + sd_psk_2 = sd_psk_2_0x0 # Basic BPSK rotation sd_psk_2_0 = sd_psk_2 # First ID for BPSK rotations + def sd_psk_2_0x1(x, Es=1): ''' 1 | 0 ''' - x_re = [x.real,] - dist = Es*numpy.sqrt(2) - return -dist*x_re + x_re = [x.real, ] + dist = Es * numpy.sqrt(2) + return -dist * x_re + + sd_psk_2_1 = sd_psk_2_0x1 @@ -106,13 +117,16 @@ def psk_4_0x0_0_1(): | ------- | 00 | 01 ''' - const_points = [-1-1j, 1-1j, - -1+1j, 1+1j] + const_points = [-1 - 1j, 1 - 1j, + -1 + 1j, 1 + 1j] symbols = [0, 1, 2, 3] return (const_points, symbols) + + psk_4 = psk_4_0x0_0_1 psk_4_0 = psk_4 + def psk_4_0x1_0_1(): ''' | 11 | 10 @@ -122,8 +136,11 @@ def psk_4_0x1_0_1(): k = 0x1 pi = [0, 1] return constellation_map_generator(psk_4()[0], psk_4()[1], k, pi) + + psk_4_1 = psk_4_0x1_0_1 + def psk_4_0x2_0_1(): ''' | 00 | 01 @@ -133,8 +150,11 @@ def psk_4_0x2_0_1(): k = 0x2 pi = [0, 1] return constellation_map_generator(psk_4()[0], psk_4()[1], k, pi) + + psk_4_2 = psk_4_0x2_0_1 + def psk_4_0x3_0_1(): ''' | 01 | 00 @@ -144,8 +164,11 @@ def psk_4_0x3_0_1(): k = 0x3 pi = [0, 1] return constellation_map_generator(psk_4()[0], psk_4()[1], k, pi) + + psk_4_3 = psk_4_0x3_0_1 + def psk_4_0x0_1_0(): ''' | 01 | 11 @@ -155,8 +178,11 @@ def psk_4_0x0_1_0(): k = 0x0 pi = [1, 0] return constellation_map_generator(psk_4()[0], psk_4()[1], k, pi) + + psk_4_4 = psk_4_0x0_1_0 + def psk_4_0x1_1_0(): ''' | 00 | 10 @@ -166,8 +192,11 @@ def psk_4_0x1_1_0(): k = 0x1 pi = [1, 0] return constellation_map_generator(psk_4()[0], psk_4()[1], k, pi) + + psk_4_5 = psk_4_0x1_1_0 + def psk_4_0x2_1_0(): ''' | 11 | 01 @@ -177,8 +206,11 @@ def psk_4_0x2_1_0(): k = 0x2 pi = [1, 0] return constellation_map_generator(psk_4()[0], psk_4()[1], k, pi) + + psk_4_6 = psk_4_0x2_1_0 + def psk_4_0x3_1_0(): ''' | 10 | 00 @@ -188,9 +220,10 @@ def psk_4_0x3_1_0(): k = 0x3 pi = [1, 0] return constellation_map_generator(psk_4()[0], psk_4()[1], k, pi) -psk_4_7 = psk_4_0x3_1_0 +psk_4_7 = psk_4_0x3_1_0 + ############################################################ # QPSK Constellation Softbit LUT generators @@ -204,11 +237,14 @@ def sd_psk_4_0x0_0_1(x, Es=1): ''' x_re = x.real x_im = x.imag - dist = Es*numpy.sqrt(2) - return [dist*x_im, dist*x_re] + dist = Es * numpy.sqrt(2) + return [dist * x_im, dist * x_re] + + sd_psk_4 = sd_psk_4_0x0_0_1 sd_psk_4_0 = sd_psk_4 + def sd_psk_4_0x1_0_1(x, Es=1): ''' | 11 | 10 @@ -217,10 +253,13 @@ def sd_psk_4_0x1_0_1(x, Es=1): ''' x_re = x.real x_im = x.imag - dist = Es*numpy.sqrt(2) - return [dist*x_im, -dist*x_re] + dist = Es * numpy.sqrt(2) + return [dist * x_im, -dist * x_re] + + sd_psk_4_1 = sd_psk_4_0x1_0_1 + def sd_psk_4_0x2_0_1(x, Es=1): ''' | 00 | 01 @@ -229,10 +268,13 @@ def sd_psk_4_0x2_0_1(x, Es=1): ''' x_re = x.real x_im = x.imag - dist = Es*numpy.sqrt(2) - return [-dist*x_im, dist*x_re] + dist = Es * numpy.sqrt(2) + return [-dist * x_im, dist * x_re] + + sd_psk_4_2 = sd_psk_4_0x2_0_1 + def sd_psk_4_0x3_0_1(x, Es=1): ''' | 01 | 00 @@ -241,10 +283,13 @@ def sd_psk_4_0x3_0_1(x, Es=1): ''' x_re = x.real x_im = x.imag - dist = Es*numpy.sqrt(2) - return [-dist*x_im, -dist*x_re] + dist = Es * numpy.sqrt(2) + return [-dist * x_im, -dist * x_re] + + sd_psk_4_3 = sd_psk_4_0x3_0_1 + def sd_psk_4_0x0_1_0(x, Es=1): ''' | 01 | 11 @@ -253,10 +298,13 @@ def sd_psk_4_0x0_1_0(x, Es=1): ''' x_re = x.real x_im = x.imag - dist = Es*numpy.sqrt(2) - return [dist*x_re, dist*x_im] + dist = Es * numpy.sqrt(2) + return [dist * x_re, dist * x_im] + + sd_psk_4_4 = sd_psk_4_0x0_1_0 + def sd_psk_4_0x1_1_0(x, Es=1): ''' | 00 | 10 @@ -265,8 +313,10 @@ def sd_psk_4_0x1_1_0(x, Es=1): ''' x_re = x.real x_im = x.imag - dist = Es*numpy.sqrt(2) - return [dist*x_re, -dist*x_im] + dist = Es * numpy.sqrt(2) + return [dist * x_re, -dist * x_im] + + sd_psk_4_5 = sd_psk_4_0x1_1_0 @@ -278,10 +328,13 @@ def sd_psk_4_0x2_1_0(x, Es=1): ''' x_re = x.real x_im = x.imag - dist = Es*numpy.sqrt(2) - return [-dist*x_re, dist*x_im] + dist = Es * numpy.sqrt(2) + return [-dist * x_re, dist * x_im] + + sd_psk_4_6 = sd_psk_4_0x2_1_0 + def sd_psk_4_0x3_1_0(x, Es=1): ''' | 10 | 00 @@ -290,6 +343,8 @@ def sd_psk_4_0x3_1_0(x, Es=1): ''' x_re = x.real x_im = x.imag - dist = Es*numpy.sqrt(2) - return [-dist*x_re, -dist*x_im] + dist = Es * numpy.sqrt(2) + return [-dist * x_re, -dist * x_im] + + sd_psk_4_7 = sd_psk_4_0x3_1_0 diff --git a/gr-digital/python/digital/qa_burst_shaper.py b/gr-digital/python/digital/qa_burst_shaper.py index 40ac210ec23..b1fc7939245 100644 --- a/gr-digital/python/digital/qa_burst_shaper.py +++ b/gr-digital/python/digital/qa_burst_shaper.py @@ -85,7 +85,8 @@ def test_cc(self): -4.0 * np.ones(5, dtype=complex))) tags = (make_length_tag(0, length),) expected = np.concatenate((np.zeros(prepad, dtype=complex), window[0:5], - np.ones(length - len(window), dtype=complex), + np.ones(length - len(window), + dtype=complex), window[5:10], np.zeros(postpad, dtype=complex))) etag = make_length_tag(0, length + prepad + postpad) @@ -239,8 +240,10 @@ def test_consecutive_bursts(self): window = np.concatenate((-2.0 * np.ones(5), -4.0 * np.ones(5))) tags = (make_length_tag(0, length1), make_length_tag(length1, length2)) expected = np.concatenate((np.zeros(prepad), window[0:5], - np.ones(length1 - len(window)), window[5:10], - np.zeros(postpad + prepad), -1.0 * window[0:5], + np.ones(length1 - len(window) + ), window[5:10], + np.zeros(postpad + prepad), - + 1.0 * window[0:5], -1.0 * np.ones(length2 - len(window)), -1.0 * window[5:10], np.zeros(postpad))) etags = (make_length_tag(0, length1 + prepad + postpad), @@ -335,8 +338,10 @@ def test_tag_propagation(self): make_tag(tag4_offset, 'body', pmt.intern('tag4')), make_tag(tag5_offset, 'body', pmt.intern('tag5'))) expected = np.concatenate((np.zeros(prepad), window[0:5], - np.ones(length1 - len(window)), window[5:10], - np.zeros(postpad + prepad), -1.0 * window[0:5], + np.ones(length1 - len(window) + ), window[5:10], + np.zeros(postpad + prepad), - + 1.0 * window[0:5], -1.0 * np.ones(length2 - len(window)), -1.0 * window[5:10], np.zeros(postpad))) elentag1_offset = 0 diff --git a/gr-digital/python/digital/qa_constellation.py b/gr-digital/python/digital/qa_constellation.py index 7c9984405fd..7345f782a2c 100644 --- a/gr-digital/python/digital/qa_constellation.py +++ b/gr-digital/python/digital/qa_constellation.py @@ -230,7 +230,6 @@ def test_hard_decision(self): data[first:], msg=msg) - def test_soft_qpsk_gen(self): prec = 8 constel, code = digital.psk_4_0() diff --git a/gr-digital/python/digital/qa_constellation_encoder_bc.py b/gr-digital/python/digital/qa_constellation_encoder_bc.py index 2c6d587dac4..ef1991bf809 100644 --- a/gr-digital/python/digital/qa_constellation_encoder_bc.py +++ b/gr-digital/python/digital/qa_constellation_encoder_bc.py @@ -12,6 +12,7 @@ from gnuradio import gr, gr_unittest, digital, blocks import numpy as np + class test_constellation_encoder(gr_unittest.TestCase): def setUp(self): @@ -23,8 +24,8 @@ def tearDown(self): def test_constellation_encoder_bc_bpsk(self): cnst = digital.constellation_bpsk() - src_data = (1, 1, 0, 0, - 1, 0, 1) + src_data = (1, 1, 0, 0, + 1, 0, 1) const_map = [-1.0, 1.0] expected_result = [const_map[x] for x in src_data] @@ -43,8 +44,8 @@ def test_constellation_encoder_bc_bpsk(self): def test_constellation_encoder_bc_qpsk(self): cnst = digital.constellation_qpsk() - src_data = (3, 1, 0, 2, - 3, 2, 1) + src_data = (3, 1, 0, 2, + 3, 2, 1) expected_result = [cnst.points()[x] for x in src_data] src = blocks.vector_source_b(src_data) op = digital.constellation_encoder_bc(cnst.base()) @@ -59,7 +60,6 @@ def test_constellation_encoder_bc_qpsk(self): # print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result) - def test_constellation_encoder_bc_qpsk_random(self): cnst = digital.constellation_qpsk() src_data = np.random.randint(0, 4, size=20000) @@ -77,5 +77,6 @@ def test_constellation_encoder_bc_qpsk_random(self): # print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result) + if __name__ == '__main__': gr_unittest.run(test_constellation_encoder) diff --git a/gr-digital/python/digital/qa_decision_feedback_equalizer.py b/gr-digital/python/digital/qa_decision_feedback_equalizer.py index 1d4587a6f09..f915272e521 100755 --- a/gr-digital/python/digital/qa_decision_feedback_equalizer.py +++ b/gr-digital/python/digital/qa_decision_feedback_equalizer.py @@ -116,7 +116,7 @@ def transform(self, src_data, const, alg): 1, 1, alg, - True, + True, [], '') dst = blocks.vector_sink_c() diff --git a/gr-digital/python/digital/qa_glfsr_source.py b/gr-digital/python/digital/qa_glfsr_source.py index 7fde483ed3a..23382605c61 100644 --- a/gr-digital/python/digital/qa_glfsr_source.py +++ b/gr-digital/python/digital/qa_glfsr_source.py @@ -60,7 +60,7 @@ def test_004_degree_f(self): lambda: digital.glfsr_source_f(0)) self.assertRaises(RuntimeError, lambda: digital.glfsr_source_f(65)) - + def test_005_correlation_f(self): for degree in range( 1, 11): # Higher degrees take too long to correlate diff --git a/gr-digital/python/digital/qa_lfsr.py b/gr-digital/python/digital/qa_lfsr.py index e0db6a382bf..8caa0dbada1 100644 --- a/gr-digital/python/digital/qa_lfsr.py +++ b/gr-digital/python/digital/qa_lfsr.py @@ -14,6 +14,7 @@ from gnuradio import gr, gr_unittest, digital from gnuradio.digital.utils import lfsr_args + class test_lfsr(gr_unittest.TestCase): def setUp(self): @@ -33,19 +34,20 @@ def test_lfsr_001(self): self.assertFloatTuplesAlmostEqual(expected_result, result_data, 5) def test_lfsr_002(self): - l = digital.lfsr(*lfsr_args(0b1,5,3,0)) - result_data = [l.next_bit() for _ in range(2*(2**5-1))] - + l = digital.lfsr(*lfsr_args(0b1, 5, 3, 0)) + result_data = [l.next_bit() for _ in range(2 * (2**5 - 1))] + expected_result = [1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, - 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0]*2 + 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0] * 2 self.assertEqual(expected_result, result_data) - seq1 = [l.next_bit() for _ in range(2**5-1)] - seq2 = [l.next_bit() for _ in range(2**5-1)] - self.assertEqual(seq1,seq2) + seq1 = [l.next_bit() for _ in range(2**5 - 1)] + seq2 = [l.next_bit() for _ in range(2**5 - 1)] + self.assertEqual(seq1, seq2) + + res = (np.convolve(seq1, [1, 0, 1, 0, 0, 1]) % 2) + self.assertTrue(sum(res[5:-5]) == 0, "LRS not generated properly") - res = (np.convolve(seq1,[1,0,1,0,0,1])%2) - self.assertTrue(sum(res[5:-5])==0,"LRS not generated properly") if __name__ == '__main__': gr_unittest.run(test_lfsr) diff --git a/gr-digital/python/digital/qa_linear_equalizer.py b/gr-digital/python/digital/qa_linear_equalizer.py index 64fd84d2f3a..39fea0ef495 100755 --- a/gr-digital/python/digital/qa_linear_equalizer.py +++ b/gr-digital/python/digital/qa_linear_equalizer.py @@ -111,7 +111,7 @@ def transform(self, src_data, const, alg): 4, 1, alg, - True, + True, [], '') dst = blocks.vector_sink_c() diff --git a/gr-digital/python/digital/qa_ofdm_chanest_vcvc.py b/gr-digital/python/digital/qa_ofdm_chanest_vcvc.py index a1f8cef6e90..7d5f79781c3 100644 --- a/gr-digital/python/digital/qa_ofdm_chanest_vcvc.py +++ b/gr-digital/python/digital/qa_ofdm_chanest_vcvc.py @@ -303,7 +303,8 @@ def run_flow_graph(sync_sym1, sync_sym2, data_sym): for x in range(fft_len)] src = blocks.vector_source_c(tx_data, False, fft_len) chan = blocks.multiply_const_vcc(channel) - noise = blocks.vector_source_c(numpy.random.normal(0,wgn_amplitude,(len(tx_data),)), False, fft_len) + noise = blocks.vector_source_c(numpy.random.normal( + 0, wgn_amplitude, (len(tx_data),)), False, fft_len) add = blocks.add_cc(fft_len) chanest = digital.ofdm_chanest_vcvc(sync_sym1, sync_sym2, 1) sink = blocks.vector_sink_c(fft_len) @@ -325,7 +326,8 @@ def run_flow_graph(sync_sym1, sync_sym2, data_sym): shifted_carrier_mask = shift_tuple(carrier_mask, carr_offset) for i in range(fft_len): if shifted_carrier_mask[i] and channel_est[i]: - self.assertAlmostEqual(channel[i], channel_est[i], places=0) + self.assertAlmostEqual( + channel[i], channel_est[i], places=0) rx_sym_est[i] = (sink.data()[i] / channel_est[i]).real return carr_offset, list(shift_tuple(rx_sym_est, -carr_offset_hat)) bit_errors = 0 diff --git a/gr-digital/python/digital/qa_ofdm_sync_sc_cfb.py b/gr-digital/python/digital/qa_ofdm_sync_sc_cfb.py index 254479363ee..10b484e839f 100644 --- a/gr-digital/python/digital/qa_ofdm_sync_sc_cfb.py +++ b/gr-digital/python/digital/qa_ofdm_sync_sc_cfb.py @@ -106,7 +106,8 @@ def test_003_multiburst(self): for _ in range(n_bursts): gap = [0, ] * random.randint(0, 2 * fft_len) tx_signal += gap + \ - make_bpsk_burst(fft_len, cp_len, fft_len * random.randint(5, 23)) + make_bpsk_burst(fft_len, cp_len, fft_len * + random.randint(5, 23)) # Very loose definition of SNR here snr = 20 # dB sigma = 10**(-snr / 10) diff --git a/gr-digital/python/digital/qa_scrambler.py b/gr-digital/python/digital/qa_scrambler.py index 7d87f87b6c2..b350d9e1b7f 100644 --- a/gr-digital/python/digital/qa_scrambler.py +++ b/gr-digital/python/digital/qa_scrambler.py @@ -26,6 +26,7 @@ def additive_scramble_lfsr(mask, seed, reglen, bpb, data): out.append(d ^ scramble_word) return out + class test_scrambler(gr_unittest.TestCase): def setUp(self): @@ -34,33 +35,35 @@ def setUp(self): def tearDown(self): self.tb = None - def test_lfsr_002(self): - _a = lfsr_args(1,51,3,0) + _a = lfsr_args(1, 51, 3, 0) l = digital.lfsr(*_a) seq = [l.next_bit() for _ in range(2**10)] - reg = np.zeros(52,np.int8) - reg[::-1][(51,3,0),] = 1 - res = (np.convolve(seq,reg)%2) - self.assertTrue(sum(res[52:-52])==0,"LRS not generated properly") + reg = np.zeros(52, np.int8) + reg[::-1][(51, 3, 0), ] = 1 + res = (np.convolve(seq, reg) % 2) + self.assertTrue(sum(res[52:-52]) == 0, "LRS not generated properly") def test_scrambler_descrambler_001(self): - src_data = np.random.randint(0,2,500,dtype=np.int8) + src_data = np.random.randint(0, 2, 500, dtype=np.int8) src = blocks.vector_source_b(src_data, False) - scrambler = digital.scrambler_bb(*lfsr_args(0b1,7,2,0)) # p(x) = x^7 + x^2 + 1 - descrambler = digital.descrambler_bb(*lfsr_args(0b111,7,2,0)) # we can use any seed here, it is descrambling. + scrambler = digital.scrambler_bb( + *lfsr_args(0b1, 7, 2, 0)) # p(x) = x^7 + x^2 + 1 + # we can use any seed here, it is descrambling. + descrambler = digital.descrambler_bb(*lfsr_args(0b111, 7, 2, 0)) m_tap = blocks.vector_sink_b() dst = blocks.vector_sink_b() self.tb.connect(src, scrambler, descrambler, dst) self.tb.connect(scrambler, m_tap) self.tb.run() - self.assertEqual(src_data[:-7].tolist(), dst.data()[7:]) # skip garbage during synchronization - self.assertEqual(tuple(np.convolve(m_tap.data(),[1,0,0,0,0,1,0,1])%2)[7:-10], - tuple(src_data[:-10])) # manual descrambling test + # skip garbage during synchronization + self.assertEqual(src_data[:-7].tolist(), dst.data()[7:]) + self.assertEqual(tuple(np.convolve(m_tap.data(), [1, 0, 0, 0, 0, 1, 0, 1]) % 2)[7:-10], + tuple(src_data[:-10])) # manual descrambling test def test_scrambler_descrambler_002(self): - _a = lfsr_args(0b1,51,6,0) #p(x) = x^51+x^6+1 - src_data = np.random.randint(0,2,1000,dtype=np.int8) + _a = lfsr_args(0b1, 51, 6, 0) # p(x) = x^51+x^6+1 + src_data = np.random.randint(0, 2, 1000, dtype=np.int8) src = blocks.vector_source_b(src_data, False) scrambler = digital.scrambler_bb(*_a) m_tap = blocks.vector_sink_b() @@ -69,26 +72,29 @@ def test_scrambler_descrambler_002(self): self.tb.connect(src, scrambler, descrambler, dst) self.tb.connect(scrambler, m_tap) self.tb.run() - self.assertTrue(np.all(src_data[:-51]==dst.data()[51:])) # skip garbage during synchronization - reg = np.zeros(52,np.int8) - reg[::-1][(51,6,0),] = 1 - self.assertTrue(np.all( np.convolve(m_tap.data(),reg)[51:-60]%2 - == src_data[:-60])) # manual descrambling test + # skip garbage during synchronization + self.assertTrue(np.all(src_data[:-51] == dst.data()[51:])) + reg = np.zeros(52, np.int8) + reg[::-1][(51, 6, 0), ] = 1 + self.assertTrue(np.all(np.convolve(m_tap.data(), reg)[51:-60] % 2 == + src_data[:-60])) # manual descrambling test def test_scrambler_descrambler_003(self): - src_data = np.random.randint(0,2,1000,dtype=np.int8) + src_data = np.random.randint(0, 2, 1000, dtype=np.int8) src = blocks.vector_source_b(src_data, False) - scrambler = digital.scrambler_bb(*lfsr_args(1,12,10,3,2,0)) # this is the product of the other two - descrambler1 = digital.descrambler_bb(*lfsr_args(1,5,3,0)) - descrambler2 = digital.descrambler_bb(*lfsr_args(1,7,2,0)) + # this is the product of the other two + scrambler = digital.scrambler_bb(*lfsr_args(1, 12, 10, 3, 2, 0)) + descrambler1 = digital.descrambler_bb(*lfsr_args(1, 5, 3, 0)) + descrambler2 = digital.descrambler_bb(*lfsr_args(1, 7, 2, 0)) dst = blocks.vector_sink_b() self.tb.connect(src, scrambler, descrambler1, descrambler2, dst) self.tb.run() - self.assertTrue(np.all(src_data[:-12]==dst.data()[12:])) # skip garbage during synchronization + # skip garbage during synchronization + self.assertTrue(np.all(src_data[:-12] == dst.data()[12:])) def test_additive_scrambler_001(self): - _a = lfsr_args(1,51,3,0) #i p(x) = x^51+x^3+1, seed 0x1 - src_data = np.random.randint(0,2,1000,dtype=np.int8).tolist() + _a = lfsr_args(1, 51, 3, 0) # i p(x) = x^51+x^3+1, seed 0x1 + src_data = np.random.randint(0, 2, 1000, dtype=np.int8).tolist() src = blocks.vector_source_b(src_data, False) scrambler = digital.additive_scrambler_bb(*_a) descrambler = digital.additive_scrambler_bb(*_a) @@ -98,18 +104,18 @@ def test_additive_scrambler_001(self): self.assertEqual(tuple(src_data), tuple(dst.data())) def test_additive_scrambler_002(self): - _a = lfsr_args(1,51,3,0) #i p(x) = x^51+x^3+1, seed 0x1 - src_data = [1,]*1000 + _a = lfsr_args(1, 51, 3, 0) # i p(x) = x^51+x^3+1, seed 0x1 + src_data = [1, ] * 1000 src = blocks.vector_source_b(src_data, False) scrambler = digital.additive_scrambler_bb(*_a) dst = blocks.vector_sink_b() self.tb.connect(src, scrambler, dst) self.tb.run() - reg = np.zeros(52,np.int8) - reg[::-1][(51,3,0),] = 1 - res = (np.convolve(dst.data(),reg)%2)[52:-52] - self.assertEqual(len(res), sum(res)) # when convolved with mask, - # after sync, only 1's would be returned. + reg = np.zeros(52, np.int8) + reg[::-1][(51, 3, 0), ] = 1 + res = (np.convolve(dst.data(), reg) % 2)[52:-52] + self.assertEqual(len(res), sum(res)) # when convolved with mask, + # after sync, only 1's would be returned. def test_scrambler_descrambler(self): src_data = [1, ] * 1000 diff --git a/gr-digital/python/digital/qam.py b/gr-digital/python/digital/qam.py index d74866b946c..6e8951ef1e5 100644 --- a/gr-digital/python/digital/qam.py +++ b/gr-digital/python/digital/qam.py @@ -243,8 +243,8 @@ def large_ampls_to_corners_mapping(side, points, width): # use the center point. c = ((real_x - side / 2.0 + 0.5) * width + (imag_x - side / 2.0 + 0.5) * width * 1j) - if (real_x >= extra_layers and real_x < side - extra_layers - and imag_x >= extra_layers and imag_x < side - extra_layers): + if (real_x >= extra_layers and real_x < side - extra_layers and + imag_x >= extra_layers and imag_x < side - extra_layers): # This is not an edge row/column. Find closest point. index = find_closest_point(c, points) else: diff --git a/gr-digital/python/digital/qpsk.py b/gr-digital/python/digital/qpsk.py index db97d31fc3c..22587948fc9 100644 --- a/gr-digital/python/digital/qpsk.py +++ b/gr-digital/python/digital/qpsk.py @@ -27,23 +27,28 @@ # QPSK constellation # ///////////////////////////////////////////////////////////////////////////// + def qpsk_constellation(mod_code=_def_mod_code): """ Creates a QPSK constellation. """ if mod_code != mod_codes.GRAY_CODE: - raise ValueError("This QPSK mod/demod works only for gray-coded constellations.") + raise ValueError( + "This QPSK mod/demod works only for gray-coded constellations.") return digital.constellation_qpsk() # ///////////////////////////////////////////////////////////////////////////// # DQPSK constellation # ///////////////////////////////////////////////////////////////////////////// + def dqpsk_constellation(mod_code=_def_mod_code): if mod_code != mod_codes.GRAY_CODE: - raise ValueError("The DQPSK constellation is only generated for gray_coding. But it can be used for non-grayed coded modulation if one doesn't use the pre-differential code.") + raise ValueError( + "The DQPSK constellation is only generated for gray_coding. But it can be used for non-grayed coded modulation if one doesn't use the pre-differential code.") return digital.constellation_dqpsk() + # # Add these to the mod/demod registry # diff --git a/gr-digital/python/digital/soft_dec_lut_gen.py b/gr-digital/python/digital/soft_dec_lut_gen.py index 898af5320d8..13c50251a59 100644 --- a/gr-digital/python/digital/soft_dec_lut_gen.py +++ b/gr-digital/python/digital/soft_dec_lut_gen.py @@ -11,6 +11,7 @@ import numpy + def soft_dec_table_generator(soft_dec_gen, prec, Es=1): ''' | Builds a LUT that is a list of tuples. The tuple represents the @@ -71,7 +72,7 @@ def soft_dec_table_generator(soft_dec_gen, prec, Es=1): ''' npts = int(2.0**prec) - maxd = Es*numpy.sqrt(2.0)/2.0 + maxd = Es * numpy.sqrt(2.0) / 2.0 yrng = numpy.linspace(-maxd, maxd, npts) xrng = numpy.linspace(-maxd, maxd, npts) @@ -83,6 +84,7 @@ def soft_dec_table_generator(soft_dec_gen, prec, Es=1): table.append(decs) return table + def soft_dec_table(constel, symbols, prec, npwr=1): ''' Similar in nature to soft_dec_table_generator above. Instead, this @@ -120,6 +122,7 @@ def soft_dec_table(constel, symbols, prec, npwr=1): table.append(decs) return table + def calc_soft_dec_from_table(sample, table, prec, Es=1.0): ''' Takes in a complex sample and converts it from the coordinates @@ -144,25 +147,26 @@ def calc_soft_dec_from_table(sample, table, prec, Es=1.0): constellation. ''' lut_scale = 2.0**prec - maxd = Es*numpy.sqrt(2.0)/2.0 - scale = (lut_scale) / (2.0*maxd) + maxd = Es * numpy.sqrt(2.0) / 2.0 + scale = (lut_scale) / (2.0 * maxd) - alpha = 0.99 # to keep index within bounds + alpha = 0.99 # to keep index within bounds xre = sample.real xim = sample.imag - xre = ((maxd + min(alpha*maxd, max(-alpha*maxd, xre))) * scale) - xim = ((maxd + min(alpha*maxd, max(-alpha*maxd, xim))) * scale) - index = int(xre) + lut_scale*int(xim) + xre = ((maxd + min(alpha * maxd, max(-alpha * maxd, xre))) * scale) + xim = ((maxd + min(alpha * maxd, max(-alpha * maxd, xim))) * scale) + index = int(xre) + lut_scale * int(xim) max_index = lut_scale**2 while(index >= max_index): - index -= lut_scale; + index -= lut_scale while(index < 0): - index += lut_scale; + index += lut_scale return table[int(index)] + def calc_soft_dec(sample, constel, symbols, npwr=1): ''' This function takes in any consteallation and symbol symbol set @@ -186,8 +190,8 @@ def calc_soft_dec(sample, constel, symbols, npwr=1): M = len(constel) k = int(numpy.log2(M)) - tmp = 2*k*[0] - s = k*[0] + tmp = 2 * k * [0] + s = k * [0] for i in range(M): # Calculate the distance between the sample and the current @@ -200,21 +204,21 @@ def calc_soft_dec(sample, constel, symbols, npwr=1): for j in range(k): # Get the bit at the jth index - mask = 1<> j # If the bit is a 0, add to the probability of a zero if(bit == 0): - tmp[2*j+0] += d + tmp[2 * j + 0] += d # else, add to the probability of a one else: - tmp[2*j+1] += d + tmp[2 * j + 1] += d # Calculate the log-likelihood ratio for all bits based on the # probability of ones (tmp[2*i+1]) over the probability of a zero # (tmp[2*i+0]). for i in range(k): - s[k-1-i] = (numpy.log(tmp[2*i+1]) - numpy.log(tmp[2*i+0])) + s[k - 1 - i] = (numpy.log(tmp[2 * i + 1]) - numpy.log(tmp[2 * i + 0])) return s @@ -225,19 +229,19 @@ def show_table(table): pp = "" subi = 1 subj = 0 - for i in reversed(list(range(prec+1))): - if(i == prec//2): - pp += "-----" + prec*((nbits*8)+3)*"-" + "\n" + for i in reversed(list(range(prec + 1))): + if(i == prec // 2): + pp += "-----" + prec * ((nbits * 8) + 3) * "-" + "\n" subi = 0 continue - for j in range(prec+1): - if(j == prec//2): + for j in range(prec + 1): + if(j == prec // 2): pp += "| " subj = 1 else: - item = table[prec*(i-subi) + (j-subj)] + item = table[prec * (i - subi) + (j - subj)] pp += "( " - for t in range(nbits-1, -1, -1): + for t in range(nbits - 1, -1, -1): pp += "{0: .4f} ".format(item[t]) pp += ") " pp += "\n" diff --git a/gr-digital/python/digital/test_soft_decisions.py b/gr-digital/python/digital/test_soft_decisions.py index 59b6edc0321..33501035731 100644 --- a/gr-digital/python/digital/test_soft_decisions.py +++ b/gr-digital/python/digital/test_soft_decisions.py @@ -9,13 +9,15 @@ # -import numpy, sys +import numpy +import sys from matplotlib import pyplot from gnuradio import digital from .soft_dec_lut_gen import soft_dec_table, calc_soft_dec_from_table, calc_soft_dec from .psk_constellations import psk_4_0, psk_4_1, psk_4_2, psk_4_3, psk_4_4, psk_4_5, psk_4_6, psk_4_7, sd_psk_4_0, sd_psk_4_1, sd_psk_4_2, sd_psk_4_3, sd_psk_4_4, sd_psk_4_5, sd_psk_4_6, sd_psk_4_7 from .qam_constellations import qam_16_0, sd_qam_16_0 + def test_qpsk(i, sample, prec): qpsk_const_list = [psk_4_0, psk_4_1, psk_4_2, psk_4_3, psk_4_4, psk_4_5, psk_4_6, psk_4_7] @@ -33,7 +35,8 @@ def test_qpsk(i, sample, prec): # Get max energy/symbol in constellation constel = c.points() - Es = max([numpy.sqrt(constel_i.real**2 + constel_i.imag**2) for constel_i in constel]) + Es = max([numpy.sqrt(constel_i.real**2 + constel_i.imag**2) + for constel_i in constel]) #table = soft_dec_table_generator(qpsk_lut_gen, prec, Es) table = soft_dec_table(constel, code, prec) @@ -50,6 +53,7 @@ def test_qpsk(i, sample, prec): return (y_python_gen_calc, y_python_table, y_python_raw_calc, y_cpp_table, y_cpp_raw_calc, constel, code, c) + def test_qam16(i, sample, prec): sample = sample / 1 qam_const_list = [qam_16_0, ] @@ -71,7 +75,7 @@ def test_qam16(i, sample, prec): #table = soft_dec_table_generator(qam_lut_gen, prec, Es) table = soft_dec_table(constel, code, prec, 1) - #c.gen_soft_dec_lut(prec) + # c.gen_soft_dec_lut(prec) c.set_soft_dec_lut(table, prec) y_python_gen_calc = qam_lut_gen(sample, Es) @@ -83,14 +87,15 @@ def test_qam16(i, sample, prec): return (y_python_gen_calc, y_python_table, y_python_raw_calc, y_cpp_table, y_cpp_raw_calc, constel, code, c) + if __name__ == "__main__": index = 0 prec = 8 - x_re = 2*numpy.random.random()-1 - x_im = 2*numpy.random.random()-1 - x = x_re + x_im*1j + x_re = 2 * numpy.random.random() - 1 + x_im = 2 * numpy.random.random() - 1 + x = x_re + x_im * 1j #x = -1 + -0.j if 1: @@ -112,14 +117,14 @@ def test_qam16(i, sample, prec): print("C++ Raw calc: ", (y_cpp_raw_calc)) fig = pyplot.figure(1) - sp1 = fig.add_subplot(1,1,1) + sp1 = fig.add_subplot(1, 1, 1) sp1.plot([c.real for c in constel], [c.imag for c in constel], 'bo') sp1.plot(x.real, x.imag, 'ro') sp1.set_xlim([-1.5, 1.5]) sp1.set_ylim([-1.5, 1.5]) fill = int(numpy.log2(len(constel))) - for i,c in enumerate(constel): - sp1.text(1.2*c.real, 1.2*c.imag, bin(code[i])[2:].zfill(fill), + for i, c in enumerate(constel): + sp1.text(1.2 * c.real, 1.2 * c.imag, bin(code[i])[2:].zfill(fill), ha='center', va='center', size=18) pyplot.show() diff --git a/gr-digital/python/digital/utils/__init__.py b/gr-digital/python/digital/utils/__init__.py index 0d5aae0b79e..f3a8390af8c 100644 --- a/gr-digital/python/digital/utils/__init__.py +++ b/gr-digital/python/digital/utils/__init__.py @@ -1,11 +1,11 @@ #!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. -# +# # This file is part of GNU Radio -# +# # SPDX-License-Identifier: GPL-3.0-or-later # -# +# from .lfsr import lfsr_args diff --git a/gr-digital/python/digital/utils/alignment.py b/gr-digital/python/digital/utils/alignment.py index f0541dea567..531c39830e2 100644 --- a/gr-digital/python/digital/utils/alignment.py +++ b/gr-digital/python/digital/utils/alignment.py @@ -1,12 +1,12 @@ #!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. -# +# # This file is part of GNU Radio -# +# # SPDX-License-Identifier: GPL-3.0-or-later # -# +# """ This module contains functions for aligning sequences. @@ -41,6 +41,7 @@ # The maximum number of samples to take from two sequences to check alignment. def_num_samples = 1000 + def compare_sequences(d1, d2, offset, sample_indices=None): """ Takes two binary sequences and an offset and returns the number of @@ -49,7 +50,7 @@ def compare_sequences(d1, d2, offset, sample_indices=None): offset -- offset of d2 relative to d1 sample_indices -- a list of indices to use for the comparison """ - max_index = min(len(d1), len(d2)+offset) + max_index = min(len(d1), len(d2) + offset) if sample_indices is None: sample_indices = list(range(0, max_index)) correct = 0 @@ -57,11 +58,12 @@ def compare_sequences(d1, d2, offset, sample_indices=None): for i in sample_indices: if i >= max_index: break - if d1[i] == d2[i-offset]: + if d1[i] == d2[i - offset]: correct += 1 total += 1 return (correct, total) + def random_sample(size, num_samples=def_num_samples, seed=None): """ Returns a set of random integers between 0 and (size-1). @@ -76,12 +78,13 @@ def random_sample(size, num_samples=def_num_samples, seed=None): num_samples = num_samples / 2 indices = set([]) while len(indices) < num_samples: - index = rndm.randint(0, size-1) + index = rndm.randint(0, size - 1) indices.add(index) indices = list(indices) indices.sort() return indices + def align_sequences(d1, d2, num_samples=def_num_samples, max_offset=def_max_offset, @@ -113,7 +116,7 @@ def align_sequences(d1, d2, int_range = [item for items in zip(pos_range, neg_range) for item in items] for offset in int_range: correct, compared = compare_sequences(d1, d2, offset, indices) - frac_correct = 1.0*correct/compared + frac_correct = 1.0 * correct / compared if frac_correct > max_frac_correct: max_frac_correct = frac_correct best_offset = offset @@ -122,8 +125,8 @@ def align_sequences(d1, d2, if frac_correct > correct_cutoff: break return max_frac_correct, best_compared, best_offset, indices - + + if __name__ == "__main__": import doctest doctest.testmod() - diff --git a/gr-digital/python/digital/utils/gray_code.py b/gr-digital/python/digital/utils/gray_code.py index e045e9a4ac6..de8ffbc93c5 100644 --- a/gr-digital/python/digital/utils/gray_code.py +++ b/gr-digital/python/digital/utils/gray_code.py @@ -41,14 +41,14 @@ def generate_new_gray_code(self, length): else: # if not we take advantage of the symmetry of all but the last bit # around a power of two. - result = self.gcs[2*self.lp2-1-self.i] + self.lp2 + result = self.gcs[2 * self.lp2 - 1 - self.i] + self.lp2 self.gcs.append(result) self.i += 1 if self.i == self.np2: self.lp2 = self.i - self.np2 = self.i*2 + self.np2 = self.i * 2 + _gray_code_generator = GrayCodeGenerator() gray_code = _gray_code_generator.get_gray_code - diff --git a/gr-digital/python/digital/utils/lfsr.py b/gr-digital/python/digital/utils/lfsr.py index 2b8a47cb764..44f62f0c7a9 100644 --- a/gr-digital/python/digital/utils/lfsr.py +++ b/gr-digital/python/digital/utils/lfsr.py @@ -1,12 +1,12 @@ #!/usr/bin/env python # # Copyright 2020 Free Software Foundation, Inc. -# +# # This file is part of GNU Radio -# +# # SPDX-License-Identifier: GPL-3.0-or-later # -# +# def lfsr_args(seed, *exp): """ @@ -18,4 +18,4 @@ def lfsr_args(seed, *exp): Creates an lfsr object with seed 0b11001, mask 0b1000011, K=6 """ from functools import reduce - return reduce(int.__xor__, map(lambda x:2**x, exp)), seed, max(exp)-1 + return reduce(int.__xor__, map(lambda x: 2**x, exp)), seed, max(exp) - 1 diff --git a/gr-digital/python/digital/utils/mod_codes.py b/gr-digital/python/digital/utils/mod_codes.py index bafb85e18b1..f0ac9f1fb52 100644 --- a/gr-digital/python/digital/utils/mod_codes.py +++ b/gr-digital/python/digital/utils/mod_codes.py @@ -1,12 +1,12 @@ #!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. -# +# # This file is part of GNU Radio -# +# # SPDX-License-Identifier: GPL-3.0-or-later # -# +# # Constants used to represent what coding to use. GRAY_CODE = 'gray' @@ -15,6 +15,7 @@ codes = (GRAY_CODE, SET_PARTITION_CODE, NO_CODE) + def invert_code(code): c = enumerate(code) ic = [(b, a) for (a, b) in c] diff --git a/gr-digital/python/digital/utils/tagged_streams.py b/gr-digital/python/digital/utils/tagged_streams.py index 49c10589817..9876519bd05 100644 --- a/gr-digital/python/digital/utils/tagged_streams.py +++ b/gr-digital/python/digital/utils/tagged_streams.py @@ -13,6 +13,7 @@ from gnuradio import gr import pmt + def make_lengthtags(lengths, offsets, tagname='length', vlen=1): tags = [] assert(len(offsets) == len(lengths)) @@ -24,26 +25,31 @@ def make_lengthtags(lengths, offsets, tagname='length', vlen=1): tags.append(tag) return tags + def string_to_vector(string): v = [] for s in string: v.append(ord(s)) return v + def strings_to_vectors(strings, lengthtagname): vs = [string_to_vector(string) for string in strings] return packets_to_vectors(vs, lengthtagname) + def vector_to_string(v): s = [] for d in v: s.append(chr(d)) return ''.join(s) + def vectors_to_strings(data, tags, lengthtagname): packets = vectors_to_packets(data, tags, lengthtagname) return [vector_to_string(packet) for packet in packets] + def count_bursts(data, tags, lengthtagname, vlen=1): lengthtags = [t for t in tags if pmt.symbol_to_string(t.key) == lengthtagname] @@ -53,7 +59,7 @@ def count_bursts(data, tags, lengthtagname, vlen=1): raise ValueError( "More than one tags with key {0} with the same offset={1}." .format(lengthtagname, tag.offset)) - lengths[tag.offset] = pmt.to_long(tag.value)*vlen + lengths[tag.offset] = pmt.to_long(tag.value) * vlen in_burst = False in_packet = False packet_length = None @@ -62,7 +68,8 @@ def count_bursts(data, tags, lengthtagname, vlen=1): for pos in range(len(data)): if pos in lengths: if in_packet: - print("Got tag at pos {0} current packet_pos is {1}".format(pos, packet_pos)) + print("Got tag at pos {0} current packet_pos is {1}".format( + pos, packet_pos)) raise Exception("Received packet tag while in packet.") packet_pos = -1 packet_length = lengths[pos] @@ -74,11 +81,12 @@ def count_bursts(data, tags, lengthtagname, vlen=1): in_burst = False if in_packet: packet_pos += 1 - if packet_pos == packet_length-1: + if packet_pos == packet_length - 1: in_packet = False packet_pos = None return burst_count + def vectors_to_packets(data, tags, lengthtagname, vlen=1): lengthtags = [t for t in tags if pmt.symbol_to_string(t.key) == lengthtagname] @@ -88,7 +96,7 @@ def vectors_to_packets(data, tags, lengthtagname, vlen=1): raise ValueError( "More than one tags with key {0} with the same offset={1}." .format(lengthtagname, tag.offset)) - lengths[tag.offset] = pmt.to_long(tag.value)*vlen + lengths[tag.offset] = pmt.to_long(tag.value) * vlen if 0 not in lengths: raise ValueError("There is no tag with key {0} and an offset of 0" .format(lengthtagname)) @@ -102,12 +110,13 @@ def vectors_to_packets(data, tags, lengthtagname, vlen=1): length = lengths[pos] if length == 0: raise ValueError("Packets cannot have zero length.") - if pos+length > len(data): + if pos + length > len(data): raise ValueError("The final packet is incomplete.") - packets.append(data[pos: pos+length]) + packets.append(data[pos: pos + length]) pos += length return packets + def packets_to_vectors(packets, lengthtagname, vlen=1): tags = [] data = [] diff --git a/gr-dtv/examples/atsc_ctrlport_monitor.py b/gr-dtv/examples/atsc_ctrlport_monitor.py index e6d6c8e19db..2d3f452f7ba 100644 --- a/gr-dtv/examples/atsc_ctrlport_monitor.py +++ b/gr-dtv/examples/atsc_ctrlport_monitor.py @@ -6,15 +6,15 @@ # -import sys -import matplotlib -matplotlib.use("QT4Agg") -import matplotlib.pyplot as plt -import matplotlib.animation as animation +import numpy from gnuradio.ctrlport.GNURadioControlPortClient import ( GNURadioControlPortClient, TTransportException, ) -import numpy +import matplotlib.animation as animation +import matplotlib.pyplot as plt +import sys +import matplotlib +matplotlib.use("QT4Agg") """ If a host is running the ATSC receiver chain with ControlPort @@ -26,6 +26,7 @@ and displays the frequency response. """ + class atsc_ctrlport_monitor(object): def __init__(self, host, port): argv = [None, host, port] @@ -33,31 +34,31 @@ def __init__(self, host, port): self.radio = radiosys.client print(self.radio) - vt_init_key = 'dtv_atsc_viterbi_decoder0::decoder_metrics' data = self.radio.getKnobs([vt_init_key])[vt_init_key] init_metric = numpy.mean(data.value) - self._viterbi_metric = 100*[init_metric,] + self._viterbi_metric = 100 * [init_metric, ] table_col_labels = ('Num Packets', 'Error Rate', 'Packet Error Rate', 'Viterbi Metric', 'SNR') - self._fig = plt.figure(1, figsize=(12,12), facecolor='w') - self._sp0 = self._fig.add_subplot(4,1,1) - self._sp1 = self._fig.add_subplot(4,1,2) - self._sp2 = self._fig.add_subplot(4,1,3) + self._fig = plt.figure(1, figsize=(12, 12), facecolor='w') + self._sp0 = self._fig.add_subplot(4, 1, 1) + self._sp1 = self._fig.add_subplot(4, 1, 2) + self._sp2 = self._fig.add_subplot(4, 1, 3) self._plot_taps = self._sp0.plot([], [], 'k', linewidth=2) - self._plot_psd = self._sp1.plot([], [], 'k', linewidth=2) - self._plot_data = self._sp2.plot([], [], 'ok', linewidth=2, markersize=4, alpha=0.05) + self._plot_psd = self._sp1.plot([], [], 'k', linewidth=2) + self._plot_data = self._sp2.plot( + [], [], 'ok', linewidth=2, markersize=4, alpha=0.05) - self._ax2 = self._fig.add_subplot(4,1,4) - self._table = self._ax2.table(cellText=[len(table_col_labels)*['0']], + self._ax2 = self._fig.add_subplot(4, 1, 4) + self._table = self._ax2.table(cellText=[len(table_col_labels) * ['0']], colLabels=table_col_labels, loc='center') self._ax2.axis('off') cells = self._table.properties()['child_artists'] for c in cells: - c.set_lw(0.1) # set's line width + c.set_lw(0.1) # set's line width c.set_ls('solid') c.set_height(0.2) @@ -104,7 +105,7 @@ def update_data(self, x, taps, psd, syms, table): fs = 6.25e6 freq = numpy.linspace(-fs / 2, fs / 2, 10000) H = numpy.fft.fftshift(numpy.fft.fft(eqdata.value, 10000)) - HdB = 20.0*numpy.log10(abs(H)) + HdB = 20.0 * numpy.log10(abs(H)) psd.set_ydata(HdB) psd.set_xdata(freq) self._sp1.set_xlim(0, fs / 2) @@ -114,24 +115,27 @@ def update_data(self, x, taps, psd, syms, table): nsyms = len(symdata.value) syms.set_ydata(symdata.value) - syms.set_xdata(nsyms*[0,]) + syms.set_xdata(nsyms * [0, ]) self._sp2.set_xlim([-1, 1]) self._sp2.set_ylim([-10, 10]) per = float(rs_num_bad_packets.value) / float(rs_num_packets.value) - ber = float(rs_num_errors_corrected.value) / float(187*rs_num_packets.value) + ber = float(rs_num_errors_corrected.value) / \ + float(187 * rs_num_packets.value) - table._cells[(1,0)]._text.set_text("{0}".format(rs_num_packets.value)) - table._cells[(1,1)]._text.set_text("{0:.2g}".format(ber)) - table._cells[(1,2)]._text.set_text("{0:.2g}".format(per)) - table._cells[(1,3)]._text.set_text("{0:.1f}".format(numpy.mean(self._viterbi_metric))) - table._cells[(1,4)]._text.set_text("{0:.4f}".format(snr_est.value[0])) + table._cells[(1, 0)]._text.set_text("{0}".format(rs_num_packets.value)) + table._cells[(1, 1)]._text.set_text("{0:.2g}".format(ber)) + table._cells[(1, 2)]._text.set_text("{0:.2g}".format(per)) + table._cells[(1, 3)]._text.set_text( + "{0:.1f}".format(numpy.mean(self._viterbi_metric))) + table._cells[(1, 4)]._text.set_text("{0:.4f}".format(snr_est.value[0])) return (taps, psd, syms, table) def init_function(self): return self._plot_taps + self._plot_psd + self._plot_data + if __name__ == "__main__": host = sys.argv[1] port = sys.argv[2] diff --git a/gr-dtv/python/dtv/atsc_rx.py b/gr-dtv/python/dtv/atsc_rx.py index 88efa89a59f..dd7002c4d09 100644 --- a/gr-dtv/python/dtv/atsc_rx.py +++ b/gr-dtv/python/dtv/atsc_rx.py @@ -22,17 +22,19 @@ from gnuradio import gr, filter, analog from .atsc_rx_filter import * + class atsc_rx(gr.hier_block2): def __init__(self, input_rate, sps): gr.hier_block2.__init__(self, "atsc_rx", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_char)) # Output signature # ATSC receiver filter/interpolator rx_filt = atsc_rx_filter(input_rate, sps) # Lock on to pilot tone, shift to DC, then discard Q channel - output_rate = ATSC_SYMBOL_RATE*sps + output_rate = ATSC_SYMBOL_RATE * sps pll = dtv.atsc_fpll(output_rate) # Remove pilot tone now at DC @@ -67,15 +69,15 @@ def __init__(self, input_rate, sps): # Connect pipeline self.connect(self, rx_filt, pll, dcr, agc, btl, fsc) - self.connect((fsc,0),(equ,0)) - self.connect((fsc,1),(equ,1)) - self.connect((equ,0),(vit,0)) - self.connect((equ,1),(vit,1)) - self.connect((vit,0),(dei,0)) - self.connect((vit,1),(dei,1)) - self.connect((dei,0),(rsd,0)) - self.connect((dei,1),(rsd,1)) - self.connect((rsd,0),(der,0)) - self.connect((rsd,1),(der,1)) - self.connect((der,0),(dep,0)) - self.connect((dep,0),(self,0)) + self.connect((fsc, 0), (equ, 0)) + self.connect((fsc, 1), (equ, 1)) + self.connect((equ, 0), (vit, 0)) + self.connect((equ, 1), (vit, 1)) + self.connect((vit, 0), (dei, 0)) + self.connect((vit, 1), (dei, 1)) + self.connect((dei, 0), (rsd, 0)) + self.connect((dei, 1), (rsd, 1)) + self.connect((rsd, 0), (der, 0)) + self.connect((rsd, 1), (der, 1)) + self.connect((der, 0), (dep, 0)) + self.connect((dep, 0), (self, 0)) diff --git a/gr-dtv/python/dtv/atsc_rx_filter.py b/gr-dtv/python/dtv/atsc_rx_filter.py index cd463f2746f..6e701112a1d 100644 --- a/gr-dtv/python/dtv/atsc_rx_filter.py +++ b/gr-dtv/python/dtv/atsc_rx_filter.py @@ -23,26 +23,29 @@ from . import dtv_python as dtv # FIXME move these into separate constants module -ATSC_CHANNEL_BW = 6.0e6 -ATSC_SYMBOL_RATE = 4.5e6/286*684 # ~10.76 Mbaud -ATSC_RRC_SYMS = 8 # filter kernel extends over 2N+1 symbols +ATSC_CHANNEL_BW = 6.0e6 +ATSC_SYMBOL_RATE = 4.5e6 / 286 * 684 # ~10.76 Mbaud +ATSC_RRC_SYMS = 8 # filter kernel extends over 2N+1 symbols + class atsc_rx_filter(gr.hier_block2): def __init__(self, input_rate, sps): gr.hier_block2.__init__(self, "atsc_rx_filter", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature # Create matched RX filter with RRC response for fractional # interpolator. nfilts = 16 - output_rate = ATSC_SYMBOL_RATE*sps # Desired oversampled sample rate - filter_rate = input_rate*nfilts - symbol_rate = ATSC_SYMBOL_RATE / 2.0 # One-sided bandwidth of sideband - excess_bw = 0.1152 #1.0-(0.5*ATSC_SYMBOL_RATE/ATSC_CHANNEL_BW) # ~10.3% - ntaps = int((2*ATSC_RRC_SYMS+1)*sps*nfilts) + output_rate = ATSC_SYMBOL_RATE * sps # Desired oversampled sample rate + filter_rate = input_rate * nfilts + symbol_rate = ATSC_SYMBOL_RATE / 2.0 # One-sided bandwidth of sideband + # 1.0-(0.5*ATSC_SYMBOL_RATE/ATSC_CHANNEL_BW) # ~10.3% + excess_bw = 0.1152 + ntaps = int((2 * ATSC_RRC_SYMS + 1) * sps * nfilts) interp = output_rate / input_rate - gain = nfilts*symbol_rate/filter_rate + gain = nfilts * symbol_rate / filter_rate rrc_taps = filter.firdes.root_raised_cosine(gain, # Filter gain filter_rate, # PFB filter prototype rate symbol_rate, # ATSC symbol rate diff --git a/gr-fec/lib/generic_decoder.cc b/gr-fec/lib/generic_decoder.cc index 0ce9cef7516..1ef597d277d 100644 --- a/gr-fec/lib/generic_decoder.cc +++ b/gr-fec/lib/generic_decoder.cc @@ -14,6 +14,8 @@ #include +#include + namespace gr { namespace fec { @@ -21,8 +23,7 @@ generic_decoder::generic_decoder(std::string name) { d_name = name; my_id = base_unique_id++; - - GR_LOG_ASSIGN_CONFIGURED_LOGPTR(d_logger, alias()); + d_logger = std::make_shared(alias()); } generic_decoder::~generic_decoder() {} diff --git a/gr-fec/lib/generic_encoder.cc b/gr-fec/lib/generic_encoder.cc index 66c3713286e..659a0fc0905 100644 --- a/gr-fec/lib/generic_encoder.cc +++ b/gr-fec/lib/generic_encoder.cc @@ -14,6 +14,7 @@ #include #include +#include namespace gr { namespace fec { @@ -22,8 +23,7 @@ generic_encoder::generic_encoder(std::string name) { d_name = name; my_id = base_unique_id++; - - GR_LOG_ASSIGN_CONFIGURED_LOGPTR(d_logger, alias()); + d_logger = std::make_shared(alias()); } generic_encoder::~generic_encoder() {} diff --git a/gr-fec/python/fec/LDPC/Generate_LDPC_matrix.py b/gr-fec/python/fec/LDPC/Generate_LDPC_matrix.py index 4e0c622e151..b745815d33e 100644 --- a/gr-fec/python/fec/LDPC/Generate_LDPC_matrix.py +++ b/gr-fec/python/fec/LDPC/Generate_LDPC_matrix.py @@ -41,7 +41,7 @@ p = 3 # column weight q = 5 # row weight -parity_check_matrix = LDPC_matrix(n_p_q = [n, p, q]) +parity_check_matrix = LDPC_matrix(n_p_q=[n, p, q]) # Richardson and Urbanke's preprocessing method requires a full rank # matrix to start. The matrices generated by the diff --git a/gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py b/gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py index 9563d66afbc..7d5e00536ba 100644 --- a/gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py +++ b/gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py @@ -21,698 +21,700 @@ # verbose = 1 ####################################################### def read_alist_file(filename): - """ - This function reads in an alist file and creates the - corresponding parity check matrix H. The format of alist - files is described at: - http://www.inference.phy.cam.ac.uk/mackay/codes/alist.html - """ - - with open(filename, 'r') as myfile: - data = myfile.readlines() - numCols, numRows = parse_alist_header(data[0]) - H = zeros((numRows, numCols)) - # The locations of 1s starts in the 5th line of the file - for lineNumber in np.arange(4, 4 + numCols): - indices = data[lineNumber].split() - for index in indices: - H[int(index) - 1, lineNumber - 4] = 1 - # The subsequent lines in the file list the indices for where - # the 1s are in the rows, but this is redundant - # information. - - return H + """ + This function reads in an alist file and creates the + corresponding parity check matrix H. The format of alist + files is described at: + http://www.inference.phy.cam.ac.uk/mackay/codes/alist.html + """ + + with open(filename, 'r') as myfile: + data = myfile.readlines() + numCols, numRows = parse_alist_header(data[0]) + H = zeros((numRows, numCols)) + # The locations of 1s starts in the 5th line of the file + for lineNumber in np.arange(4, 4 + numCols): + indices = data[lineNumber].split() + for index in indices: + H[int(index) - 1, lineNumber - 4] = 1 + # The subsequent lines in the file list the indices for where + # the 1s are in the rows, but this is redundant + # information. + + return H def parse_alist_header(header): - size = header.split() - return int(size[0]), int(size[1]) + size = header.split() + return int(size[0]), int(size[1]) def write_alist_file(filename, H, verbose=0): - """ - This function writes an alist file for the parity check - matrix. The format of alist files is described at: - http://www.inference.phy.cam.ac.uk/mackay/codes/alist.html - """ - with open(filename, 'w') as myfile: - - numRows = H.shape[0] - numCols = H.shape[1] - - tempstring = repr(numCols) + ' ' + repr(numRows) + '\n' - myfile.write(tempstring) - - tempstring1 = '' - tempstring2 = '' - maxRowWeight = 0 - for rowNum in np.arange(numRows): - nonzeros = array(H[rowNum, :].nonzero()) - rowWeight = nonzeros.shape[1] - if rowWeight > maxRowWeight: - maxRowWeight = rowWeight - tempstring1 = tempstring1 + repr(rowWeight) + ' ' - for tempArray in nonzeros: - for index in tempArray: - tempstring2 = tempstring2 + repr(index + 1) + ' ' - tempstring2 = tempstring2 + '\n' - tempstring1 = tempstring1 + '\n' - - tempstring3 = '' - tempstring4 = '' - maxColWeight = 0 - for colNum in np.arange(numCols): - nonzeros = array(H[:, colNum].nonzero()) - colWeight = nonzeros.shape[1] - if colWeight > maxColWeight: - maxColWeight = colWeight - tempstring3 = tempstring3 + repr(colWeight) + ' ' - for tempArray in nonzeros: - for index in tempArray: - tempstring4 = tempstring4 + repr(index + 1) + ' ' - tempstring4 = tempstring4 + '\n' - tempstring3 = tempstring3 + '\n' - - tempstring = repr(maxColWeight) + ' ' + repr(maxRowWeight) + '\n' - # write out max column and row weights - myfile.write(tempstring) - # write out all of the column weights - myfile.write(tempstring3) - # write out all of the row weights - myfile.write(tempstring1) - # write out the nonzero indices for each column - myfile.write(tempstring4) - # write out the nonzero indices for each row - myfile.write(tempstring2) + """ + This function writes an alist file for the parity check + matrix. The format of alist files is described at: + http://www.inference.phy.cam.ac.uk/mackay/codes/alist.html + """ + with open(filename, 'w') as myfile: + + numRows = H.shape[0] + numCols = H.shape[1] + + tempstring = repr(numCols) + ' ' + repr(numRows) + '\n' + myfile.write(tempstring) + + tempstring1 = '' + tempstring2 = '' + maxRowWeight = 0 + for rowNum in np.arange(numRows): + nonzeros = array(H[rowNum, :].nonzero()) + rowWeight = nonzeros.shape[1] + if rowWeight > maxRowWeight: + maxRowWeight = rowWeight + tempstring1 = tempstring1 + repr(rowWeight) + ' ' + for tempArray in nonzeros: + for index in tempArray: + tempstring2 = tempstring2 + repr(index + 1) + ' ' + tempstring2 = tempstring2 + '\n' + tempstring1 = tempstring1 + '\n' + + tempstring3 = '' + tempstring4 = '' + maxColWeight = 0 + for colNum in np.arange(numCols): + nonzeros = array(H[:, colNum].nonzero()) + colWeight = nonzeros.shape[1] + if colWeight > maxColWeight: + maxColWeight = colWeight + tempstring3 = tempstring3 + repr(colWeight) + ' ' + for tempArray in nonzeros: + for index in tempArray: + tempstring4 = tempstring4 + repr(index + 1) + ' ' + tempstring4 = tempstring4 + '\n' + tempstring3 = tempstring3 + '\n' + + tempstring = repr(maxColWeight) + ' ' + repr(maxRowWeight) + '\n' + # write out max column and row weights + myfile.write(tempstring) + # write out all of the column weights + myfile.write(tempstring3) + # write out all of the row weights + myfile.write(tempstring1) + # write out the nonzero indices for each column + myfile.write(tempstring4) + # write out the nonzero indices for each row + myfile.write(tempstring2) class LDPC_matrix(object): - """ Class for a LDPC parity check matrix """ - - def __init__(self, alist_filename=None, - n_p_q=None, - H_matrix=None): - if (alist_filename != None): - self.H = read_alist_file(alist_filename) - elif (n_p_q != None): - self.H = self.regular_LDPC_code_contructor(n_p_q) - elif (H_matrix != None): - self.H = H_matrix - else: - print('Error: provide either an alist filename, ', end='') - print('parameters for constructing regular LDPC parity, ', end='') - print('check matrix, or a numpy array.') + """ Class for a LDPC parity check matrix """ + + def __init__(self, alist_filename=None, + n_p_q=None, + H_matrix=None): + if (alist_filename != None): + self.H = read_alist_file(alist_filename) + elif (n_p_q != None): + self.H = self.regular_LDPC_code_contructor(n_p_q) + elif (H_matrix != None): + self.H = H_matrix + else: + print('Error: provide either an alist filename, ', end='') + print('parameters for constructing regular LDPC parity, ', end='') + print('check matrix, or a numpy array.') + + self.rank = linalg.matrix_rank(self.H) + self.numRows = self.H.shape[0] + self.n = self.H.shape[1] + self.k = self.n - self.numRows + + def regular_LDPC_code_contructor(self, n_p_q): + """ + This function constructs a LDPC parity check matrix + H. The algorithm follows Gallager's approach where we create + p submatrices and stack them together. Reference: Turbo + Coding for Satellite and Wireless Communications, section + 9,3. + + Note: the matrices computed from this algorithm will never + have full rank. (Reference Gallager's Dissertation.) They + will have rank = (number of rows - p + 1). To convert it + to full rank, use the function get_full_rank_H_matrix + """ + + n = n_p_q[0] # codeword length + p = n_p_q[1] # column weight + q = n_p_q[2] # row weight + # TODO: There should probably be other guidelines for n/p/q, + # but I have not found any specifics in the literature.... + + # For this algorithm, n/p must be an integer, because the + # number of rows in each submatrix must be a whole number. + ratioTest = (n * 1.0) / q + if ratioTest % 1 != 0: + print('\nError in regular_LDPC_code_contructor: The ', end='') + print('ratio of inputs n/q must be a whole number.\n') + return + + # First submatrix first: + m = (n * p) / q # number of rows in H matrix + submatrix1 = zeros((m / p, n)) + for row in np.arange(m / p): + range1 = row * q + range2 = (row + 1) * q + submatrix1[row, range1:range2] = 1 + H = submatrix1 + + # Create the other submatrices and vertically stack them on. + submatrixNum = 2 + newColumnOrder = np.arange(n) + while submatrixNum <= p: + submatrix = zeros((m / p, n)) + shuffle(newColumnOrder) + + for columnNum in np.arange(n): + submatrix[:, columnNum] = \ + submatrix1[:, newColumnOrder[columnNum]] + + H = vstack((H, submatrix)) + submatrixNum = submatrixNum + 1 + + # Double check the row weight and column weights. + size = H.shape + rows = size[0] + cols = size[1] + + # Check the row weights. + for rowNum in np.arange(rows): + nonzeros = array(H[rowNum, :].nonzero()) + if nonzeros.shape[1] != q: + print('Row', rowNum, 'has incorrect weight!') + return + + # Check the column weights + for columnNum in np.arange(cols): + nonzeros = array(H[:, columnNum].nonzero()) + if nonzeros.shape[1] != p: + print('Row', columnNum, 'has incorrect weight!') + return + + return H - self.rank = linalg.matrix_rank(self.H) - self.numRows = self.H.shape[0] - self.n = self.H.shape[1] - self.k = self.n - self.numRows - def regular_LDPC_code_contructor(self, n_p_q): +def greedy_upper_triangulation(H, verbose=0): """ - This function constructs a LDPC parity check matrix - H. The algorithm follows Gallager's approach where we create - p submatrices and stack them together. Reference: Turbo - Coding for Satellite and Wireless Communications, section - 9,3. - - Note: the matrices computed from this algorithm will never - have full rank. (Reference Gallager's Dissertation.) They - will have rank = (number of rows - p + 1). To convert it - to full rank, use the function get_full_rank_H_matrix + This function performs row/column permutations to bring + H into approximate upper triangular form via greedy + upper triangulation method outlined in Modern Coding + Theory Appendix 1, Section A.2 """ - - n = n_p_q[0] # codeword length - p = n_p_q[1] # column weight - q = n_p_q[2] # row weight - # TODO: There should probably be other guidelines for n/p/q, - # but I have not found any specifics in the literature.... - - # For this algorithm, n/p must be an integer, because the - # number of rows in each submatrix must be a whole number. - ratioTest = (n * 1.0) / q - if ratioTest % 1 != 0: - print('\nError in regular_LDPC_code_contructor: The ', end='') - print('ratio of inputs n/q must be a whole number.\n') - return - - # First submatrix first: - m = (n * p) / q # number of rows in H matrix - submatrix1 = zeros((m / p, n)) - for row in np.arange(m / p): - range1 = row * q - range2 = (row + 1) * q - submatrix1[row, range1:range2] = 1 - H = submatrix1 - - # Create the other submatrices and vertically stack them on. - submatrixNum = 2 - newColumnOrder = np.arange(n) - while submatrixNum <= p: - submatrix = zeros((m / p, n)) - shuffle(newColumnOrder) - - for columnNum in np.arange(n): - submatrix[:, columnNum] = \ - submatrix1[:, newColumnOrder[columnNum]] - - H = vstack((H, submatrix)) - submatrixNum = submatrixNum + 1 - - # Double check the row weight and column weights. - size = H.shape - rows = size[0] - cols = size[1] - - # Check the row weights. - for rowNum in np.arange(rows): - nonzeros = array(H[rowNum, :].nonzero()) - if nonzeros.shape[1] != q: - print('Row', rowNum, 'has incorrect weight!') - return - - # Check the column weights - for columnNum in np.arange(cols): - nonzeros = array(H[:, columnNum].nonzero()) - if nonzeros.shape[1] != p: - print('Row', columnNum, 'has incorrect weight!') + H_t = H.copy() + + # Per email from Dr. Urbanke, author of this textbook, this + # algorithm requires H to be full rank + if linalg.matrix_rank(H_t) != H_t.shape[0]: + print('Rank of H:', linalg.matrix_rank(tempArray)) + print('H has', H_t.shape[0], 'rows') + print('Error: H must be full rank.') return - return H - + size = H_t.shape + n = size[1] + k = n - size[0] + g = t = 0 + + while t != (n - k - g): + H_residual = H_t[t:n - k - g, t:n] + size = H_residual.shape + numRows = size[0] + numCols = size[1] + + minResidualDegrees = zeros((1, numCols), dtype=int) + + for colNum in np.arange(numCols): + nonZeroElements = array(H_residual[:, colNum].nonzero()) + minResidualDegrees[0, colNum] = nonZeroElements.shape[1] + + # Find the minimum nonzero residual degree + nonZeroElementIndices = minResidualDegrees.nonzero() + nonZeroElements = minResidualDegrees[nonZeroElementIndices[0], + nonZeroElementIndices[1]] + minimumResidualDegree = nonZeroElements.min() + + # Get indices of all of the columns in H_t that have degree + # equal to the min positive residual degree, then pick a + # random column c. + indices = (minResidualDegrees == minimumResidualDegree) \ + .nonzero()[1] + indices = indices + t + if indices.shape[0] == 1: + columnC = indices[0] + else: + randomIndex = randint(0, indices.shape[0], (1, 1))[0][0] + columnC = indices[randomIndex] -def greedy_upper_triangulation(H, verbose=0): - """ - This function performs row/column permutations to bring - H into approximate upper triangular form via greedy - upper triangulation method outlined in Modern Coding - Theory Appendix 1, Section A.2 - """ - H_t = H.copy() - - # Per email from Dr. Urbanke, author of this textbook, this - # algorithm requires H to be full rank - if linalg.matrix_rank(H_t) != H_t.shape[0]: - print('Rank of H:', linalg.matrix_rank(tempArray)) - print('H has', H_t.shape[0], 'rows') - print('Error: H must be full rank.') - return - - size = H_t.shape - n = size[1] - k = n - size[0] - g = t = 0 - - while t != (n - k - g): - H_residual = H_t[t:n - k - g, t:n] - size = H_residual.shape - numRows = size[0] - numCols = size[1] - - minResidualDegrees = zeros((1, numCols), dtype=int) - - for colNum in np.arange(numCols): - nonZeroElements = array(H_residual[:, colNum].nonzero()) - minResidualDegrees[0, colNum] = nonZeroElements.shape[1] - - # Find the minimum nonzero residual degree - nonZeroElementIndices = minResidualDegrees.nonzero() - nonZeroElements = minResidualDegrees[nonZeroElementIndices[0], - nonZeroElementIndices[1]] - minimumResidualDegree = nonZeroElements.min() - - # Get indices of all of the columns in H_t that have degree - # equal to the min positive residual degree, then pick a - # random column c. - indices = (minResidualDegrees == minimumResidualDegree) \ - .nonzero()[1] - indices = indices + t - if indices.shape[0] == 1: - columnC = indices[0] - else: - randomIndex = randint(0, indices.shape[0], (1, 1))[0][0] - columnC = indices[randomIndex] - - Htemp = H_t.copy() - - if minimumResidualDegree == 1: - # This is the 'extend' case - rowThatContainsNonZero = H_residual[:, columnC - t].nonzero()[0][0] - - # Swap column c with column t. (Book says t+1 but we - # index from 0, not 1.) - Htemp[:, columnC] = H_t[:, t] - Htemp[:, t] = H_t[:, columnC] - H_t = Htemp.copy() - Htemp = H_t.copy() - # Swap row r with row t. (Book says t+1 but we index from - # 0, not 1.) - Htemp[rowThatContainsNonZero + t, :] = H_t[t, :] - Htemp[t, :] = H_t[rowThatContainsNonZero + t, :] - H_t = Htemp.copy() - Htemp = H_t.copy() - else: - # This is the 'choose' case. - rowsThatContainNonZeros = H_residual[:, columnC - t] \ - .nonzero()[0] - - # Swap column c with column t. (Book says t+1 but we - # index from 0, not 1.) - Htemp[:, columnC] = H_t[:, t] - Htemp[:, t] = H_t[:, columnC] - H_t = Htemp.copy() - Htemp = H_t.copy() - - # Swap row r1 with row t - r1 = rowsThatContainNonZeros[0] - Htemp[r1 + t, :] = H_t[t, :] - Htemp[t, :] = H_t[r1 + t, :] - numRowsLeft = rowsThatContainNonZeros.shape[0] - 1 - H_t = Htemp.copy() - Htemp = H_t.copy() - - # Move the other rows that contain nonZero entries to the - # bottom of the matrix. We can't just swap them, - # otherwise we will be pulling up rows that we pushed - # down before. So, use a rotation method. - for index in np.arange(1, numRowsLeft + 1): - rowInH_residual = rowsThatContainNonZeros[index] - rowInH_t = rowInH_residual + t - index + 1 - m = n - k - # Move the row with the nonzero element to the - # bottom; don't update H_t. - Htemp[m - 1, :] = H_t[rowInH_t, :] - # Now rotate the bottom rows up. - sub_index = 1 - while sub_index < (m - rowInH_t): - Htemp[m - sub_index - 1, :] = H_t[m - sub_index, :] - sub_index = sub_index + 1 - H_t = Htemp.copy() Htemp = H_t.copy() - # Save temp H as new H_t. - H_t = Htemp.copy() - Htemp = H_t.copy() - g = g + (minimumResidualDegree - 1) - - t = t + 1 - - if g == 0: - if verbose: - print('Error: gap is 0.') - return - - # We need to ensure phi is nonsingular. - T = H_t[0:t, 0:t] - E = H_t[t:t + g, 0:t] - A = H_t[0:t, t:t + g] - C = H_t[t:t + g, t:t + g] - D = H_t[t:t + g, t + g:n] - - invTmod2array = inv_mod2(T) - temp1 = dot(E, invTmod2array) % 2 - temp2 = dot(temp1, A) % 2 - phi = (C - temp2) % 2 - if phi.any(): - try: - # Try to take the inverse of phi. - invPhi = inv_mod2(phi) - except linalg.linalg.LinAlgError: - # Phi is singular - if verbose > 1: - print('Initial phi is singular') - else: - # Phi is nonsingular, so we need to use this version of H. - if verbose > 1: - print('Initial phi is nonsingular') - return [H_t, g, t] - else: - if verbose: - print('Initial phi is all zeros:\n', phi) + if minimumResidualDegree == 1: + # This is the 'extend' case + rowThatContainsNonZero = H_residual[:, columnC - t].nonzero()[0][0] + + # Swap column c with column t. (Book says t+1 but we + # index from 0, not 1.) + Htemp[:, columnC] = H_t[:, t] + Htemp[:, t] = H_t[:, columnC] + H_t = Htemp.copy() + Htemp = H_t.copy() + # Swap row r with row t. (Book says t+1 but we index from + # 0, not 1.) + Htemp[rowThatContainsNonZero + t, :] = H_t[t, :] + Htemp[t, :] = H_t[rowThatContainsNonZero + t, :] + H_t = Htemp.copy() + Htemp = H_t.copy() + else: + # This is the 'choose' case. + rowsThatContainNonZeros = H_residual[:, columnC - t] \ + .nonzero()[0] + + # Swap column c with column t. (Book says t+1 but we + # index from 0, not 1.) + Htemp[:, columnC] = H_t[:, t] + Htemp[:, t] = H_t[:, columnC] + H_t = Htemp.copy() + Htemp = H_t.copy() + + # Swap row r1 with row t + r1 = rowsThatContainNonZeros[0] + Htemp[r1 + t, :] = H_t[t, :] + Htemp[t, :] = H_t[r1 + t, :] + numRowsLeft = rowsThatContainNonZeros.shape[0] - 1 + H_t = Htemp.copy() + Htemp = H_t.copy() + + # Move the other rows that contain nonZero entries to the + # bottom of the matrix. We can't just swap them, + # otherwise we will be pulling up rows that we pushed + # down before. So, use a rotation method. + for index in np.arange(1, numRowsLeft + 1): + rowInH_residual = rowsThatContainNonZeros[index] + rowInH_t = rowInH_residual + t - index + 1 + m = n - k + # Move the row with the nonzero element to the + # bottom; don't update H_t. + Htemp[m - 1, :] = H_t[rowInH_t, :] + # Now rotate the bottom rows up. + sub_index = 1 + while sub_index < (m - rowInH_t): + Htemp[m - sub_index - 1, :] = H_t[m - sub_index, :] + sub_index = sub_index + 1 + H_t = Htemp.copy() + Htemp = H_t.copy() + + # Save temp H as new H_t. + H_t = Htemp.copy() + Htemp = H_t.copy() + g = g + (minimumResidualDegree - 1) + + t = t + 1 + + if g == 0: + if verbose: + print('Error: gap is 0.') + return - # If the C and D submatrices are all zeros, there is no point in - # shuffling them around in an attempt to find a good phi. - if not (C.any() or D.any()): - if verbose: - print('C and D are all zeros. There is no hope in', ) - print('finding a nonsingular phi matrix. ') - return - - # We can't look at every row/column permutation possibility - # because there would be (n-t)! column shuffles and g! row - # shuffles. g has gotten up to 12 in tests, so 12! would still - # take quite some time. Instead, we will just pick an arbitrary - # number of max iterations to perform, then break. - maxIterations = 300 - iterationCount = 0 - columnsToShuffle = np.arange(t, n) - rowsToShuffle = np.arange(t, t + g) - - while iterationCount < maxIterations: - if verbose > 1: - print('iterationCount:', iterationCount) - tempH = H_t.copy() - - shuffle(columnsToShuffle) - shuffle(rowsToShuffle) - index = 0 - for newDestinationColumnNumber in np.arange(t, n): - oldColumnNumber = columnsToShuffle[index] - tempH[:, newDestinationColumnNumber] = \ - H_t[:, oldColumnNumber] - index += 1 - - tempH2 = tempH.copy() - index = 0 - for newDesinationRowNumber in np.arange(t, t + g): - oldRowNumber = rowsToShuffle[index] - tempH[newDesinationRowNumber, :] = tempH2[oldRowNumber, :] - index += 1 - - # Now test this new H matrix. - H_t = tempH.copy() + # We need to ensure phi is nonsingular. T = H_t[0:t, 0:t] E = H_t[t:t + g, 0:t] A = H_t[0:t, t:t + g] C = H_t[t:t + g, t:t + g] + D = H_t[t:t + g, t + g:n] + invTmod2array = inv_mod2(T) temp1 = dot(E, invTmod2array) % 2 temp2 = dot(temp1, A) % 2 phi = (C - temp2) % 2 if phi.any(): - try: - # Try to take the inverse of phi. - invPhi = inv_mod2(phi) - except linalg.linalg.LinAlgError: - # Phi is singular - if verbose > 1: - print('Phi is still singular') - else: - # Phi is nonsingular, so we're done. - if verbose: - print('Found a nonsingular phi on', ) - print('iterationCount = ', iterationCount) - return [H_t, g, t] + try: + # Try to take the inverse of phi. + invPhi = inv_mod2(phi) + except linalg.linalg.LinAlgError: + # Phi is singular + if verbose > 1: + print('Initial phi is singular') + else: + # Phi is nonsingular, so we need to use this version of H. + if verbose > 1: + print('Initial phi is nonsingular') + return [H_t, g, t] else: - if verbose > 1: - print('phi is all zeros') - - iterationCount += 1 - - # If we've reached this point, then we haven't found a - # version of H that has a nonsingular phi. - if verbose: - print('--- Error: nonsingular phi matrix not found.') + if verbose: + print('Initial phi is all zeros:\n', phi) + # If the C and D submatrices are all zeros, there is no point in + # shuffling them around in an attempt to find a good phi. + if not (C.any() or D.any()): + if verbose: + print('C and D are all zeros. There is no hope in', ) + print('finding a nonsingular phi matrix. ') + return -def inv_mod2(squareMatrix, verbose=0): - """ - Calculates the mod 2 inverse of a matrix. - """ - A = squareMatrix.copy() - t = A.shape[0] - - # Special case for one element array [1] - if A.size == 1 and A[0] == 1: - return array([1]) - - Ainverse = inv(A) - B = det(A) * Ainverse - C = B % 2 - - # Encountered lots of rounding errors with this function. - # Previously tried floor, C.astype(int), and casting with (int) - # and none of that works correctly, so doing it the tedious way. - - test = dot(A, C) % 2 - tempTest = zeros_like(test) - for colNum in np.arange(test.shape[1]): - for rowNum in np.arange(test.shape[0]): - value = test[rowNum, colNum] - if (abs(1 - value)) < 0.01: - # this is a 1 - tempTest[rowNum, colNum] = 1 - elif (abs(2 - value)) < 0.01: - # there shouldn't be any 2s after B % 2, but I'm - # seeing them! - tempTest[rowNum, colNum] = 0 - elif (abs(0 - value)) < 0.01: - # this is a 0 - tempTest[rowNum, colNum] = 0 - else: + # We can't look at every row/column permutation possibility + # because there would be (n-t)! column shuffles and g! row + # shuffles. g has gotten up to 12 in tests, so 12! would still + # take quite some time. Instead, we will just pick an arbitrary + # number of max iterations to perform, then break. + maxIterations = 300 + iterationCount = 0 + columnsToShuffle = np.arange(t, n) + rowsToShuffle = np.arange(t, t + g) + + while iterationCount < maxIterations: if verbose > 1: - print('In inv_mod2. Rounding error on this', ) - print('value? Mod 2 has already been done.', ) - print('value:', value) + print('iterationCount:', iterationCount) + tempH = H_t.copy() + + shuffle(columnsToShuffle) + shuffle(rowsToShuffle) + index = 0 + for newDestinationColumnNumber in np.arange(t, n): + oldColumnNumber = columnsToShuffle[index] + tempH[:, newDestinationColumnNumber] = \ + H_t[:, oldColumnNumber] + index += 1 + + tempH2 = tempH.copy() + index = 0 + for newDesinationRowNumber in np.arange(t, t + g): + oldRowNumber = rowsToShuffle[index] + tempH[newDesinationRowNumber, :] = tempH2[oldRowNumber, :] + index += 1 + + # Now test this new H matrix. + H_t = tempH.copy() + T = H_t[0:t, 0:t] + E = H_t[t:t + g, 0:t] + A = H_t[0:t, t:t + g] + C = H_t[t:t + g, t:t + g] + invTmod2array = inv_mod2(T) + temp1 = dot(E, invTmod2array) % 2 + temp2 = dot(temp1, A) % 2 + phi = (C - temp2) % 2 + if phi.any(): + try: + # Try to take the inverse of phi. + invPhi = inv_mod2(phi) + except linalg.linalg.LinAlgError: + # Phi is singular + if verbose > 1: + print('Phi is still singular') + else: + # Phi is nonsingular, so we're done. + if verbose: + print('Found a nonsingular phi on', ) + print('iterationCount = ', iterationCount) + return [H_t, g, t] + else: + if verbose > 1: + print('phi is all zeros') + + iterationCount += 1 + + # If we've reached this point, then we haven't found a + # version of H that has a nonsingular phi. + if verbose: + print('--- Error: nonsingular phi matrix not found.') - test = tempTest.copy() - if (test - eye(t, t) % 2).any(): - if verbose: - print('Error in inv_mod2: did not find inverse.') - # TODO is this the most appropriate error to raise? - raise linalg.linalg.LinAlgError - else: - return C +def inv_mod2(squareMatrix, verbose=0): + """ + Calculates the mod 2 inverse of a matrix. + """ + A = squareMatrix.copy() + t = A.shape[0] + + # Special case for one element array [1] + if A.size == 1 and A[0] == 1: + return array([1]) + + Ainverse = inv(A) + B = det(A) * Ainverse + C = B % 2 + + # Encountered lots of rounding errors with this function. + # Previously tried floor, C.astype(int), and casting with (int) + # and none of that works correctly, so doing it the tedious way. + + test = dot(A, C) % 2 + tempTest = zeros_like(test) + for colNum in np.arange(test.shape[1]): + for rowNum in np.arange(test.shape[0]): + value = test[rowNum, colNum] + if (abs(1 - value)) < 0.01: + # this is a 1 + tempTest[rowNum, colNum] = 1 + elif (abs(2 - value)) < 0.01: + # there shouldn't be any 2s after B % 2, but I'm + # seeing them! + tempTest[rowNum, colNum] = 0 + elif (abs(0 - value)) < 0.01: + # this is a 0 + tempTest[rowNum, colNum] = 0 + else: + if verbose > 1: + print('In inv_mod2. Rounding error on this', ) + print('value? Mod 2 has already been done.', ) + print('value:', value) + + test = tempTest.copy() + + if (test - eye(t, t) % 2).any(): + if verbose: + print('Error in inv_mod2: did not find inverse.') + # TODO is this the most appropriate error to raise? + raise linalg.linalg.LinAlgError + else: + return C def swap_columns(a, b, arrayIn): - """ - Swaps two columns in a matrix. - """ - arrayOut = arrayIn.copy() - arrayOut[:, a] = arrayIn[:, b] - arrayOut[:, b] = arrayIn[:, a] - return arrayOut + """ + Swaps two columns in a matrix. + """ + arrayOut = arrayIn.copy() + arrayOut[:, a] = arrayIn[:, b] + arrayOut[:, b] = arrayIn[:, a] + return arrayOut def move_row_to_bottom(i, arrayIn): - """" - Moves a specified row (just one) to the bottom of the matrix, - then rotates the rows at the bottom up. - - For example, if we had a matrix with 5 rows, and we wanted to - push row 2 to the bottom, then the resulting row order would be: - 1,3,4,5,2 - """ - arrayOut = arrayIn.copy() - numRows = arrayOut.shape[0] - # Push the specified row to the bottom. - arrayOut[numRows - 1] = arrayIn[i, :] - # Now rotate the bottom rows up. - index = 2 - while (numRows - index) >= i: - arrayOut[numRows - index, :] = arrayIn[numRows - index + 1] - index = index + 1 - return arrayOut + """" + Moves a specified row (just one) to the bottom of the matrix, + then rotates the rows at the bottom up. + + For example, if we had a matrix with 5 rows, and we wanted to + push row 2 to the bottom, then the resulting row order would be: + 1,3,4,5,2 + """ + arrayOut = arrayIn.copy() + numRows = arrayOut.shape[0] + # Push the specified row to the bottom. + arrayOut[numRows - 1] = arrayIn[i, :] + # Now rotate the bottom rows up. + index = 2 + while (numRows - index) >= i: + arrayOut[numRows - index, :] = arrayIn[numRows - index + 1] + index = index + 1 + return arrayOut def get_full_rank_H_matrix(H, verbose=False): - """ - This function accepts a parity check matrix H and, if it is not - already full rank, will determine which rows are dependent and - remove them. The updated matrix will be returned. - """ - tempArray = H.copy() - if linalg.matrix_rank(tempArray) == tempArray.shape[0]: - if verbose: - print('Returning H; it is already full rank.') - return tempArray + """ + This function accepts a parity check matrix H and, if it is not + already full rank, will determine which rows are dependent and + remove them. The updated matrix will be returned. + """ + tempArray = H.copy() + if linalg.matrix_rank(tempArray) == tempArray.shape[0]: + if verbose: + print('Returning H; it is already full rank.') + return tempArray + + numRows = tempArray.shape[0] + numColumns = tempArray.shape[1] + limit = numRows + rank = 0 + i = 0 - numRows = tempArray.shape[0] - numColumns = tempArray.shape[1] - limit = numRows - rank = 0 - i = 0 + # Create an array to save the column permutations. + columnOrder = np.arange(numColumns).reshape(1, numColumns) - # Create an array to save the column permutations. - columnOrder = np.arange(numColumns).reshape(1, numColumns) + # Create an array to save the row permutations. We just need + # this to know which dependent rows to delete. + rowOrder = np.arange(numRows).reshape(numRows, 1) - # Create an array to save the row permutations. We just need - # this to know which dependent rows to delete. - rowOrder = np.arange(numRows).reshape(numRows, 1) + while i < limit: + if verbose: + print('In get_full_rank_H_matrix; i:', i) + # Flag indicating that the row contains a non-zero entry + found = False + for j in np.arange(i, numColumns): + if tempArray[i, j] == 1: + # Encountered a non-zero entry at (i, j) + found = True + # Increment rank by 1 + rank = rank + 1 + # Make the entry at (i,i) be 1 + tempArray = swap_columns(j, i, tempArray) + # Keep track of the column swapping + columnOrder = swap_columns(j, i, columnOrder) + break + if found == True: + for k in np.arange(0, numRows): + if k == i: + continue + # Checking for 1's + if tempArray[k, i] == 1: + # Add row i to row k + tempArray[k, :] = tempArray[k, :] + tempArray[i, :] + # Addition is mod2 + tempArray = tempArray.copy() % 2 + # All the entries above & below (i, i) are now 0 + i = i + 1 + if found == False: + # Push the row of 0s to the bottom, and move the bottom + # rows up (sort of a rotation thing). + tempArray = move_row_to_bottom(i, tempArray) + # Decrease limit since we just found a row of 0s + limit -= 1 + # Keep track of row swapping + rowOrder = move_row_to_bottom(i, rowOrder) + + # Don't need the dependent rows + finalRowOrder = rowOrder[0:i] + + # Reorder H, per the permutations taken above . + # First, put rows in order, omitting the dependent rows. + newNumberOfRowsForH = finalRowOrder.shape[0] + newH = zeros((newNumberOfRowsForH, numColumns)) + for index in np.arange(newNumberOfRowsForH): + newH[index, :] = H[finalRowOrder[index], :] + + # Next, put the columns in order. + tempHarray = newH.copy() + for index in np.arange(numColumns): + newH[:, index] = tempHarray[:, columnOrder[0, index]] - while i < limit: if verbose: - print('In get_full_rank_H_matrix; i:', i) - # Flag indicating that the row contains a non-zero entry - found = False - for j in np.arange(i, numColumns): - if tempArray[i, j] == 1: - # Encountered a non-zero entry at (i, j) - found = True - # Increment rank by 1 - rank = rank + 1 - # Make the entry at (i,i) be 1 - tempArray = swap_columns(j, i, tempArray) - # Keep track of the column swapping - columnOrder = swap_columns(j, i, columnOrder) - break - if found == True: - for k in np.arange(0, numRows): - if k == i: continue - # Checking for 1's - if tempArray[k, i] == 1: - # Add row i to row k - tempArray[k, :] = tempArray[k, :] + tempArray[i, :] - # Addition is mod2 - tempArray = tempArray.copy() % 2 - # All the entries above & below (i, i) are now 0 - i = i + 1 - if found == False: - # Push the row of 0s to the bottom, and move the bottom - # rows up (sort of a rotation thing). - tempArray = move_row_to_bottom(i, tempArray) - # Decrease limit since we just found a row of 0s - limit -= 1 - # Keep track of row swapping - rowOrder = move_row_to_bottom(i, rowOrder) - - # Don't need the dependent rows - finalRowOrder = rowOrder[0:i] - - # Reorder H, per the permutations taken above . - # First, put rows in order, omitting the dependent rows. - newNumberOfRowsForH = finalRowOrder.shape[0] - newH = zeros((newNumberOfRowsForH, numColumns)) - for index in np.arange(newNumberOfRowsForH): - newH[index, :] = H[finalRowOrder[index], :] - - # Next, put the columns in order. - tempHarray = newH.copy() - for index in np.arange(numColumns): - newH[:, index] = tempHarray[:, columnOrder[0, index]] - - if verbose: - print('original H.shape:', H.shape) - print('newH.shape:', newH.shape) - - return newH + print('original H.shape:', H.shape) + print('newH.shape:', newH.shape) + + return newH def get_best_matrix(H, numIterations=100, verbose=0): - """ - This function will run the Greedy Upper Triangulation algorithm - for numIterations times, looking for the lowest possible gap. - The submatrices returned are those needed for real-time encoding. - """ - - hadFirstJoy = 0 - index = 1 - while index <= numIterations: - if verbose: - print('--- In get_best_matrix, iteration:', index) - index += 1 - try: - ret = greedy_upper_triangulation(H, verbose) - except ValueError as e: - if verbose > 1: - print('greedy_upper_triangulation error: ', e) + """ + This function will run the Greedy Upper Triangulation algorithm + for numIterations times, looking for the lowest possible gap. + The submatrices returned are those needed for real-time encoding. + """ + + hadFirstJoy = 0 + index = 1 + while index <= numIterations: + if verbose: + print('--- In get_best_matrix, iteration:', index) + index += 1 + try: + ret = greedy_upper_triangulation(H, verbose) + except ValueError as e: + if verbose > 1: + print('greedy_upper_triangulation error: ', e) + else: + if ret: + [betterH, gap, t] = ret + else: + continue + + if not hadFirstJoy: + hadFirstJoy = 1 + bestGap = gap + bestH = betterH.copy() + bestT = t + elif gap < bestGap: + bestGap = gap + bestH = betterH.copy() + bestT = t + + if hadFirstJoy: + return [bestH, bestGap] else: - if ret: - [betterH, gap, t] = ret - else: - continue - - if not hadFirstJoy: - hadFirstJoy = 1 - bestGap = gap - bestH = betterH.copy() - bestT = t - elif gap < bestGap: - bestGap = gap - bestH = betterH.copy() - bestT = t - - if hadFirstJoy: - return [bestH, bestGap] - else: - if verbose: - print('Error: Could not find appropriate H form', ) - print('for encoding.') - return + if verbose: + print('Error: Could not find appropriate H form', ) + print('for encoding.') + return def getSystematicGmatrix(GenMatrix): - """ - This function finds the systematic form of the generator - matrix GenMatrix. This form is G = [I P] where I is an identity - matrix and P is the parity submatrix. If the GenMatrix matrix - provided is not full rank, then dependent rows will be deleted. - - This function does not convert parity check (H) matrices to the - generator matrix format. Use the function getSystematicGmatrixFromH - for that purpose. - """ - tempArray = GenMatrix.copy() - numRows = tempArray.shape[0] - numColumns = tempArray.shape[1] - limit = numRows - rank = 0 - i = 0 - while i < limit: - # Flag indicating that the row contains a non-zero entry - found = False - for j in np.arange(i, numColumns): - if tempArray[i, j] == 1: - # Encountered a non-zero entry at (i, j) - found = True - # Increment rank by 1 - rank = rank + 1 - # make the entry at (i,i) be 1 - tempArray = swap_columns(j, i, tempArray) - break - if found == True: - for k in np.arange(0, numRows): - if k == i: continue - # Checking for 1's - if tempArray[k, i] == 1: - # add row i to row k - tempArray[k, :] = tempArray[k, :] + tempArray[i, :] - # Addition is mod2 - tempArray = tempArray.copy() % 2 - # All the entries above & below (i, i) are now 0 - i = i + 1 - if found == False: - # push the row of 0s to the bottom, and move the bottom - # rows up (sort of a rotation thing) - tempArray = move_row_to_bottom(i, tempArray) - # decrease limit since we just found a row of 0s - limit -= 1 - # the rows below i are the dependent rows, which we discard - G = tempArray[0:i, :] - return G + """ + This function finds the systematic form of the generator + matrix GenMatrix. This form is G = [I P] where I is an identity + matrix and P is the parity submatrix. If the GenMatrix matrix + provided is not full rank, then dependent rows will be deleted. + + This function does not convert parity check (H) matrices to the + generator matrix format. Use the function getSystematicGmatrixFromH + for that purpose. + """ + tempArray = GenMatrix.copy() + numRows = tempArray.shape[0] + numColumns = tempArray.shape[1] + limit = numRows + rank = 0 + i = 0 + while i < limit: + # Flag indicating that the row contains a non-zero entry + found = False + for j in np.arange(i, numColumns): + if tempArray[i, j] == 1: + # Encountered a non-zero entry at (i, j) + found = True + # Increment rank by 1 + rank = rank + 1 + # make the entry at (i,i) be 1 + tempArray = swap_columns(j, i, tempArray) + break + if found == True: + for k in np.arange(0, numRows): + if k == i: + continue + # Checking for 1's + if tempArray[k, i] == 1: + # add row i to row k + tempArray[k, :] = tempArray[k, :] + tempArray[i, :] + # Addition is mod2 + tempArray = tempArray.copy() % 2 + # All the entries above & below (i, i) are now 0 + i = i + 1 + if found == False: + # push the row of 0s to the bottom, and move the bottom + # rows up (sort of a rotation thing) + tempArray = move_row_to_bottom(i, tempArray) + # decrease limit since we just found a row of 0s + limit -= 1 + # the rows below i are the dependent rows, which we discard + G = tempArray[0:i, :] + return G def getSystematicGmatrixFromH(H, verbose=False): - """ - If given a parity check matrix H, this function returns a - generator matrix G in the systematic form: G = [I P] - where: I is an identity matrix, size k x k - P is the parity submatrix, size k x (n-k) - If the H matrix provided is not full rank, then dependent rows - will be deleted first. - """ - if verbose: - print('received H with size: ', H.shape) - - # First, put the H matrix into the form H = [I|m] where: - # I is (n-k) x (n-k) identity matrix - # m is (n-k) x k - # This part is just copying the algorithm from getSystematicGmatrix - tempArray = getSystematicGmatrix(H) - - # Next, swap I and m columns so the matrix takes the forms [m|I]. - n = H.shape[1] - k = n - H.shape[0] - I_temp = tempArray[:, 0:(n - k)] - m = tempArray[:, (n - k):n] - newH = concatenate((m, I_temp), axis=1) - - # Now the submatrix m is the transpose of the parity submatrix, - # i.e. H is in the form H = [P'|I]. So G is just [I|P] - k = m.shape[1] - G = concatenate((identity(k), m.T), axis=1) - if verbose: - print('returning G with size: ', G.shape) - return G + """ + If given a parity check matrix H, this function returns a + generator matrix G in the systematic form: G = [I P] + where: I is an identity matrix, size k x k + P is the parity submatrix, size k x (n-k) + If the H matrix provided is not full rank, then dependent rows + will be deleted first. + """ + if verbose: + print('received H with size: ', H.shape) + + # First, put the H matrix into the form H = [I|m] where: + # I is (n-k) x (n-k) identity matrix + # m is (n-k) x k + # This part is just copying the algorithm from getSystematicGmatrix + tempArray = getSystematicGmatrix(H) + + # Next, swap I and m columns so the matrix takes the forms [m|I]. + n = H.shape[1] + k = n - H.shape[0] + I_temp = tempArray[:, 0:(n - k)] + m = tempArray[:, (n - k):n] + newH = concatenate((m, I_temp), axis=1) + + # Now the submatrix m is the transpose of the parity submatrix, + # i.e. H is in the form H = [P'|I]. So G is just [I|P] + k = m.shape[1] + G = concatenate((identity(k), m.T), axis=1) + if verbose: + print('returning G with size: ', G.shape) + return G diff --git a/gr-fec/python/fec/__init__.py b/gr-fec/python/fec/__init__.py index 83b906ad064..d3788e47f5e 100644 --- a/gr-fec/python/fec/__init__.py +++ b/gr-fec/python/fec/__init__.py @@ -20,6 +20,19 @@ __path__.append(os.path.join(dirname, "bindings")) from .fec_python import * +from .bercurve_generator import bercurve_generator +from .fec_test import fec_test +from .extended_tagged_decoder import extended_tagged_decoder +from .extended_tagged_encoder import extended_tagged_encoder +from .extended_async_encoder import extended_async_encoder +from .capillary_threaded_encoder import capillary_threaded_encoder +from .capillary_threaded_decoder import capillary_threaded_decoder +from .threaded_decoder import threaded_decoder +from .threaded_encoder import threaded_encoder +from .extended_decoder import extended_decoder +from .extended_encoder import extended_encoder +from .bitflip import * + # Pybind cannot bind constructors to make functions that return a different type # Remap make functions to __init__ here @@ -74,23 +87,8 @@ ldpc_gen_mtrx_encoder_make = code.ldpc_gen_mtrx_encoder.make ldpc_bit_flip_decoder = code.ldpc_bit_flip_decoder except AttributeError: - pass + pass polar_decoder_sc = code.polar_decoder_sc polar_decoder_sc_list = code.polar_decoder_sc_list polar_decoder_sc_systematic = code.polar_decoder_sc_systematic - -from .bitflip import * -from .extended_encoder import extended_encoder -from .extended_decoder import extended_decoder -from .threaded_encoder import threaded_encoder -from .threaded_decoder import threaded_decoder -from .capillary_threaded_decoder import capillary_threaded_decoder -from .capillary_threaded_encoder import capillary_threaded_encoder -from .extended_async_encoder import extended_async_encoder -from .extended_tagged_encoder import extended_tagged_encoder -from .extended_tagged_decoder import extended_tagged_decoder - - -from .fec_test import fec_test -from .bercurve_generator import bercurve_generator diff --git a/gr-fec/python/fec/_qa_helper.py b/gr-fec/python/fec/_qa_helper.py index 00a60156843..1eef05d9760 100644 --- a/gr-fec/python/fec/_qa_helper.py +++ b/gr-fec/python/fec/_qa_helper.py @@ -9,7 +9,6 @@ # - import numpy from gnuradio import gr, blocks @@ -23,9 +22,9 @@ class map_bb(gr.sync_block): def __init__(self, bitmap): gr.sync_block.__init__( self, - name = "map_bb", - in_sig = [numpy.int8], - out_sig = [numpy.int8]) + name="map_bb", + in_sig=[numpy.int8], + out_sig=[numpy.int8]) self.bitmap = bitmap def work(self, input_items, output_items): @@ -45,11 +44,13 @@ def __init__(self, data_size, enc, dec, threading): self.data_size = data_size self.threading = threading - self.ext_encoder = extended_encoder(enc, threading=self.threading, puncpat=self.puncpat) + self.ext_encoder = extended_encoder( + enc, threading=self.threading, puncpat=self.puncpat) self.ext_decoder = extended_decoder(dec, threading=self.threading, ann=None, puncpat=self.puncpat, integration_period=10000) - self.src = blocks.vector_source_b(data_size*[0, 1, 2, 3, 5, 7, 9, 13, 15, 25, 31, 45, 63, 95, 127], False) + self.src = blocks.vector_source_b( + data_size * [0, 1, 2, 3, 5, 7, 9, 13, 15, 25, 31, 45, 63, 95, 127], False) self.unpack = blocks.unpack_k_bits_bb(8) self.map = map_bb([-1, 1]) self.to_float = blocks.char_to_float(1) @@ -62,18 +63,19 @@ def __init__(self, data_size, enc, dec, threading): self.connect(self.unpack, self.snk_input) self.connect(self.ext_decoder, self.snk_output) + if __name__ == '__main__': frame_size = 30 - enc = fec.dummy_encoder_make(frame_size*8) + enc = fec.dummy_encoder_make(frame_size * 8) #enc = fec.repetition_encoder_make(frame_size*8, 3) - dec = fec.dummy_decoder.make(frame_size*8) + dec = fec.dummy_decoder.make(frame_size * 8) - tb = _qa_helper(10*frame_size, enc, dec, None) + tb = _qa_helper(10 * frame_size, enc, dec, None) tb.run() errs = 0 - for i,o in zip(tb.snk_input.data(), tb.snk_output.data()): - if i-o != 0: + for i, o in zip(tb.snk_input.data(), tb.snk_output.data()): + if i - o != 0: errs += 1 if errs == 0: diff --git a/gr-fec/python/fec/bercurve_generator.py b/gr-fec/python/fec/bercurve_generator.py index 3536c45d528..3d556cf7a1d 100644 --- a/gr-fec/python/fec/bercurve_generator.py +++ b/gr-fec/python/fec/bercurve_generator.py @@ -13,6 +13,7 @@ from .fec_test import fec_test + class bercurve_generator(gr.hier_block2): def __init__(self, encoder_list, decoder_list, esno=numpy.arange(0.0, 3.0, .25), @@ -20,7 +21,7 @@ def __init__(self, encoder_list, decoder_list, esno=numpy.arange(0.0, 3.0, .25), gr.hier_block2.__init__( self, "ber_curve_generator", gr.io_signature(0, 0, 0), - gr.io_signature(len(esno) * 2, len(esno) * 2, gr.sizeof_char*1)) + gr.io_signature(len(esno) * 2, len(esno) * 2, gr.sizeof_char * 1)) self.esno = esno self.samp_rate = samp_rate @@ -28,8 +29,9 @@ def __init__(self, encoder_list, decoder_list, esno=numpy.arange(0.0, 3.0, .25), self.decoder_list = decoder_list self.puncpat = puncpat - self.random_gen_b_0 = blocks.vector_source_b(list(map(int, numpy.random.randint(0, 256, 100000))), True) - self.deinterleave = blocks.deinterleave(gr.sizeof_char*1) + self.random_gen_b_0 = blocks.vector_source_b( + list(map(int, numpy.random.randint(0, 256, 100000))), True) + self.deinterleave = blocks.deinterleave(gr.sizeof_char * 1) self.connect(self.random_gen_b_0, self.deinterleave) self.ber_generators = [] @@ -47,12 +49,12 @@ def __init__(self, encoder_list, decoder_list, esno=numpy.arange(0.0, 3.0, .25), threading=threading, puncpat=puncpat, seed=seed) - self.ber_generators.append(ber_generator_temp); + self.ber_generators.append(ber_generator_temp) for i in range(0, len(esno)): self.connect((self.deinterleave, i), (self.ber_generators[i])) - self.connect((self.ber_generators[i], 0), (self, i*2)); - self.connect((self.ber_generators[i], 1), (self, i*2 + 1)); + self.connect((self.ber_generators[i], 0), (self, i * 2)) + self.connect((self.ber_generators[i], 1), (self, i * 2 + 1)) def get_esno(self): return self.esno diff --git a/gr-fec/python/fec/bitflip.py b/gr-fec/python/fec/bitflip.py index edd841ef14e..a482152e547 100644 --- a/gr-fec/python/fec/bitflip.py +++ b/gr-fec/python/fec/bitflip.py @@ -9,63 +9,64 @@ # - - def bitreverse(mint): - res = 0; + res = 0 while mint != 0: - res = res << 1; - res += mint & 1; - mint = mint >> 1; - return res; + res = res << 1 + res += mint & 1 + mint = mint >> 1 + return res + + +const_lut = [2] +specinvert_lut = [[0, 2, 1, 3]] -const_lut = [2]; -specinvert_lut = [[0, 2, 1, 3]]; def bitflip(mint, bitflip_lut, index, csize): - res = 0; - cnt = 0; - mask = (1 << const_lut[index]) - 1; + res = 0 + cnt = 0 + mask = (1 << const_lut[index]) - 1 while (cnt < csize): - res += (bitflip_lut[(mint >> cnt) & (mask)]) << cnt; - cnt += const_lut[index]; - return res; + res += (bitflip_lut[(mint >> cnt) & (mask)]) << cnt + cnt += const_lut[index] + return res def read_bitlist(bitlist): - res = 0; + res = 0 for i in range(len(bitlist)): if int(bitlist[i]) == 1: - res += 1 << (len(bitlist) - i - 1); - return res; + res += 1 << (len(bitlist) - i - 1) + return res def read_big_bitlist(bitlist): ret = [] for j in range(0, len(bitlist) / 64): - res = 0; + res = 0 for i in range(0, 64): - if int(bitlist[j*64+i]) == 1: - res += 1 << (64 - i - 1); - ret.append(res); - res = 0; - j = 0; - for i in range(len(bitlist)%64): - if int(bitlist[len(ret)*64+i]) == 1: - res += 1 << (64 - j - 1); - j += 1; - ret.append(res); - return ret; + if int(bitlist[j * 64 + i]) == 1: + res += 1 << (64 - i - 1) + ret.append(res) + res = 0 + j = 0 + for i in range(len(bitlist) % 64): + if int(bitlist[len(ret) * 64 + i]) == 1: + res += 1 << (64 - j - 1) + j += 1 + ret.append(res) + return ret + def generate_symmetries(symlist): retlist = [] if len(symlist) == 1: for i in range(len(symlist[0])): - retlist.append(symlist[0][i:] + symlist[0][0:i]); - invlist = symlist[0]; + retlist.append(symlist[0][i:] + symlist[0][0:i]) + invlist = symlist[0] for i in range(1, len(symlist[0]) / 2): - invlist[i] = symlist[0][i + len(symlist[0]) / 2]; - invlist[i + len(symlist[0]) / 2] = symlist[0][i]; + invlist[i] = symlist[0][i + len(symlist[0]) / 2] + invlist[i + len(symlist[0]) / 2] = symlist[0][i] for i in range(len(symlist[0])): - retlist.append(symlist[0][i:] + symlist[0][0:i]); - return retlist; + retlist.append(symlist[0][i:] + symlist[0][0:i]) + return retlist diff --git a/gr-fec/python/fec/capillary_threaded_decoder.py b/gr-fec/python/fec/capillary_threaded_decoder.py index 71d968eb99a..7a800098cd4 100644 --- a/gr-fec/python/fec/capillary_threaded_decoder.py +++ b/gr-fec/python/fec/capillary_threaded_decoder.py @@ -19,14 +19,15 @@ class capillary_threaded_decoder(gr.hier_block2): def __init__(self, decoder_list_0, input_size, output_size): gr.hier_block2.__init__( self, "Capillary Threaded Decoder", - gr.io_signature(1, 1, input_size*1), - gr.io_signature(1, 1, output_size*1)) + gr.io_signature(1, 1, input_size * 1), + gr.io_signature(1, 1, output_size * 1)) self.decoder_list_0 = decoder_list_0 check = math.log10(len(self.decoder_list_0)) / math.log10(2.0) if(abs(check - int(check)) > 0): - gr.log.info("fec.capillary_threaded_decoder: number of decoders must be a power of 2.") + gr.log.info( + "fec.capillary_threaded_decoder: number of decoders must be a power of 2.") raise AttributeError self.deinterleaves_0 = [] @@ -37,7 +38,8 @@ def __init__(self, decoder_list_0, input_size, output_size): self.generic_decoders_0 = [] for i in range(len(decoder_list_0)): - self.generic_decoders_0.append(fec.decoder(decoder_list_0[i], input_size, output_size)) + self.generic_decoders_0.append(fec.decoder( + decoder_list_0[i], input_size, output_size)) self.interleaves_0 = [] for i in range(int(math.log(len(decoder_list_0), 2))): @@ -49,15 +51,19 @@ def __init__(self, decoder_list_0, input_size, output_size): branchcount = 1 for i in range(int(math.log(len(decoder_list_0), 2)) - 1): for j in range(int(math.pow(2, i))): - self.connect((self.deinterleaves_0[rootcount], 0), (self.deinterleaves_0[branchcount], 0)) - self.connect((self.deinterleaves_0[rootcount], 1), (self.deinterleaves_0[branchcount + 1], 0)) + self.connect( + (self.deinterleaves_0[rootcount], 0), (self.deinterleaves_0[branchcount], 0)) + self.connect( + (self.deinterleaves_0[rootcount], 1), (self.deinterleaves_0[branchcount + 1], 0)) rootcount += 1 branchcount += 2 codercount = 0 for i in range(len(decoder_list_0) // 2): - self.connect((self.deinterleaves_0[rootcount], 0), (self.generic_decoders_0[codercount], 0)) - self.connect((self.deinterleaves_0[rootcount], 1), (self.generic_decoders_0[codercount + 1], 0)) + self.connect( + (self.deinterleaves_0[rootcount], 0), (self.generic_decoders_0[codercount], 0)) + self.connect( + (self.deinterleaves_0[rootcount], 1), (self.generic_decoders_0[codercount + 1], 0)) rootcount += 1 codercount += 2 @@ -65,15 +71,19 @@ def __init__(self, decoder_list_0, input_size, output_size): branchcount = 1 for i in range(int(math.log(len(decoder_list_0), 2)) - 1): for j in range(int(math.pow(2, i))): - self.connect((self.interleaves_0[branchcount], 0), (self.interleaves_0[rootcount], 0)) - self.connect((self.interleaves_0[branchcount + 1], 0), (self.interleaves_0[rootcount], 1)) + self.connect( + (self.interleaves_0[branchcount], 0), (self.interleaves_0[rootcount], 0)) + self.connect( + (self.interleaves_0[branchcount + 1], 0), (self.interleaves_0[rootcount], 1)) rootcount += 1 branchcount += 2 codercount = 0 for i in range(len(decoder_list_0) // 2): - self.connect((self.generic_decoders_0[codercount], 0), (self.interleaves_0[rootcount], 0)) - self.connect((self.generic_decoders_0[codercount + 1], 0), (self.interleaves_0[rootcount], 1)) + self.connect( + (self.generic_decoders_0[codercount], 0), (self.interleaves_0[rootcount], 0)) + self.connect( + (self.generic_decoders_0[codercount + 1], 0), (self.interleaves_0[rootcount], 1)) rootcount += 1 codercount += 2 diff --git a/gr-fec/python/fec/capillary_threaded_encoder.py b/gr-fec/python/fec/capillary_threaded_encoder.py index c8ed970bbc0..abd7a61b49d 100644 --- a/gr-fec/python/fec/capillary_threaded_encoder.py +++ b/gr-fec/python/fec/capillary_threaded_encoder.py @@ -25,59 +25,66 @@ def __init__(self, encoder_list_0, input_size=gr.sizeof_char, output_size=gr.siz check = math.log10(len(self.encoder_list_0)) / math.log10(2.0) if(abs(check - int(check)) > 0.0): - gr.log.info("fec.capillary_threaded_encoder: number of encoders must be a power of 2.") + gr.log.info( + "fec.capillary_threaded_encoder: number of encoders must be a power of 2.") raise AttributeError - self.deinterleaves_0 = []; + self.deinterleaves_0 = [] for i in range(int(math.log(len(encoder_list_0), 2))): for j in range(int(math.pow(2, i))): self.deinterleaves_0.append(blocks.deinterleave(input_size, fec.get_encoder_input_size(encoder_list_0[0]))) - self.generic_encoders_0 = []; + self.generic_encoders_0 = [] for i in range(len(encoder_list_0)): self.generic_encoders_0.append(fec.encoder(encoder_list_0[i], input_size, output_size)) - self.interleaves_0 = []; + self.interleaves_0 = [] for i in range(int(math.log(len(encoder_list_0), 2))): for j in range(int(math.pow(2, i))): self.interleaves_0.append(blocks.interleave(output_size, fec.get_encoder_output_size(encoder_list_0[0]))) - rootcount = 0; - branchcount = 1; + rootcount = 0 + branchcount = 1 for i in range(int(math.log(len(encoder_list_0), 2)) - 1): for j in range(int(math.pow(2, i))): - self.connect((self.deinterleaves_0[rootcount], 0), (self.deinterleaves_0[branchcount], 0)) - self.connect((self.deinterleaves_0[rootcount], 1), (self.deinterleaves_0[branchcount + 1], 0)) - rootcount += 1; - branchcount += 2; - - codercount = 0; + self.connect( + (self.deinterleaves_0[rootcount], 0), (self.deinterleaves_0[branchcount], 0)) + self.connect( + (self.deinterleaves_0[rootcount], 1), (self.deinterleaves_0[branchcount + 1], 0)) + rootcount += 1 + branchcount += 2 + + codercount = 0 for i in range(len(encoder_list_0) // 2): - self.connect((self.deinterleaves_0[rootcount], 0), (self.generic_encoders_0[codercount], 0)) - self.connect((self.deinterleaves_0[rootcount], 1), (self.generic_encoders_0[codercount + 1], 0)) - rootcount += 1; - codercount += 2; - - - rootcount = 0; - branchcount = 1; + self.connect( + (self.deinterleaves_0[rootcount], 0), (self.generic_encoders_0[codercount], 0)) + self.connect( + (self.deinterleaves_0[rootcount], 1), (self.generic_encoders_0[codercount + 1], 0)) + rootcount += 1 + codercount += 2 + + rootcount = 0 + branchcount = 1 for i in range(int(math.log(len(encoder_list_0), 2)) - 1): for j in range(int(math.pow(2, i))): - self.connect((self.interleaves_0[branchcount], 0), (self.interleaves_0[rootcount], 0)) - self.connect((self.interleaves_0[branchcount + 1], 0), (self.interleaves_0[rootcount], 1)) - rootcount += 1; - branchcount += 2; - - - codercount = 0; + self.connect( + (self.interleaves_0[branchcount], 0), (self.interleaves_0[rootcount], 0)) + self.connect( + (self.interleaves_0[branchcount + 1], 0), (self.interleaves_0[rootcount], 1)) + rootcount += 1 + branchcount += 2 + + codercount = 0 for i in range(len(encoder_list_0) // 2): - self.connect((self.generic_encoders_0[codercount], 0), (self.interleaves_0[rootcount], 0)) - self.connect((self.generic_encoders_0[codercount + 1], 0), (self.interleaves_0[rootcount], 1)) - rootcount += 1; - codercount += 2; + self.connect( + (self.generic_encoders_0[codercount], 0), (self.interleaves_0[rootcount], 0)) + self.connect( + (self.generic_encoders_0[codercount + 1], 0), (self.interleaves_0[rootcount], 1)) + rootcount += 1 + codercount += 2 if((len(self.encoder_list_0)) > 1): self.connect((self, 0), (self.deinterleaves_0[0], 0)) diff --git a/gr-fec/python/fec/extended_async_encoder.py b/gr-fec/python/fec/extended_async_encoder.py index 0a130ff4bfa..434b86615ee 100644 --- a/gr-fec/python/fec/extended_async_encoder.py +++ b/gr-fec/python/fec/extended_async_encoder.py @@ -27,14 +27,15 @@ def __init__(self, encoder_obj_list, puncpat=None): self.message_port_register_hier_in('in') self.message_port_register_hier_out('out') - self.puncpat=puncpat + self.puncpat = puncpat # If it's a list of encoders, take the first one, unless it's # a list of lists of encoders. if(type(encoder_obj_list) == list): # This block doesn't handle parallelism of > 1 if(type(encoder_obj_list[0]) == list): - gr.log.info("fec.extended_encoder: Parallelism must be 0 or 1.") + gr.log.info( + "fec.extended_encoder: Parallelism must be 0 or 1.") raise AttributeError encoder_obj = encoder_obj_list[0] @@ -46,14 +47,14 @@ def __init__(self, encoder_obj_list, puncpat=None): self.encoder = fec.async_encoder(encoder_obj) #self.puncture = None - #if self.puncpat != '11': + # if self.puncpat != '11': # self.puncture = fec.puncture_bb(len(puncpat), read_bitlist(puncpat), 0) self.msg_connect(weakref.proxy(self), "in", self.encoder, "in") - #if(self.puncture): + # if(self.puncture): # self.msg_connect(self.encoder, "out", self.puncture, "in") # self.msg_connect(self.puncture, "out", weakref.proxy(self), "out") - #else: + # else: # self.msg_connect(self.encoder, "out", weakref.proxy(self), "out") self.msg_connect(self.encoder, "out", weakref.proxy(self), "out") diff --git a/gr-fec/python/fec/extended_decoder.py b/gr-fec/python/fec/extended_decoder.py index 94098249819..648d03503cc 100644 --- a/gr-fec/python/fec/extended_decoder.py +++ b/gr-fec/python/fec/extended_decoder.py @@ -101,19 +101,22 @@ def __init__( # anything going through the annihilator needs shifted, uchar vals if ( - fec.get_decoder_input_conversion(decoder_obj_list[0]) == "uchar" - or fec.get_decoder_input_conversion(decoder_obj_list[0]) == "packed_bits" + fec.get_decoder_input_conversion(decoder_obj_list[0]) == "uchar" or + fec.get_decoder_input_conversion( + decoder_obj_list[0]) == "packed_bits" ): self.blocks.append(blocks.multiply_const_ff(48.0)) if fec.get_shift(decoder_obj_list[0]) != 0.0: - self.blocks.append(blocks.add_const_ff(fec.get_shift(decoder_obj_list[0]))) + self.blocks.append(blocks.add_const_ff( + fec.get_shift(decoder_obj_list[0]))) elif fec.get_decoder_input_conversion(decoder_obj_list[0]) == "packed_bits": self.blocks.append(blocks.add_const_ff(128.0)) if ( - fec.get_decoder_input_conversion(decoder_obj_list[0]) == "uchar" - or fec.get_decoder_input_conversion(decoder_obj_list[0]) == "packed_bits" + fec.get_decoder_input_conversion(decoder_obj_list[0]) == "uchar" or + fec.get_decoder_input_conversion( + decoder_obj_list[0]) == "packed_bits" ): self.blocks.append(blocks.float_to_uchar()) @@ -134,9 +137,9 @@ def __init__( if 1.0 / self.ann.count("1") >= i: synd_garble = self.garbletable[i] print( - "using syndrom garble threshold " - + str(synd_garble) - + "for conv_bit_corr_bb" + "using syndrom garble threshold " + + str(synd_garble) + + "for conv_bit_corr_bb" ) print("ceiling: .0335 data garble rate") self.blocks.append( @@ -196,7 +199,8 @@ def __init__( ) if fec.get_decoder_output_conversion(decoder_obj_list[0]) == "unpack": - self.blocks.append(blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST)) + self.blocks.append( + blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST)) self.connect((self, 0), (self.blocks[0], 0)) self.connect((self.blocks[-1], 0), (self, 0)) diff --git a/gr-fec/python/fec/extended_encoder.py b/gr-fec/python/fec/extended_encoder.py index fbcbeb1be14..1324f052c75 100644 --- a/gr-fec/python/fec/extended_encoder.py +++ b/gr-fec/python/fec/extended_encoder.py @@ -23,8 +23,8 @@ def __init__(self, encoder_obj_list, threading, puncpat=None): gr.io_signature(1, 1, gr.sizeof_char), gr.io_signature(1, 1, gr.sizeof_char)) - self.blocks=[] - self.puncpat=puncpat + self.blocks = [] + self.puncpat = puncpat if (type(encoder_obj_list) == list): if (type(encoder_obj_list[0]) == list): @@ -32,7 +32,7 @@ def __init__(self, encoder_obj_list, threading, puncpat=None): raise AttributeError else: # If it has parallelism of 0, force it into a list of 1 - encoder_obj_list = [encoder_obj_list,] + encoder_obj_list = [encoder_obj_list, ] if fec.get_encoder_input_conversion(encoder_obj_list[0]) == "pack": self.blocks.append(blocks.pack_k_bits_bb(8)) @@ -51,17 +51,19 @@ def __init__(self, encoder_obj_list, threading, puncpat=None): gr.sizeof_char)) if fec.get_encoder_output_conversion(encoder_obj_list[0]) == "packed_bits": - self.blocks.append(blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST)) + self.blocks.append( + blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST)) if self.puncpat != '11': - self.blocks.append(fec.puncture_bb(len(puncpat), read_bitlist(puncpat), 0)) + self.blocks.append(fec.puncture_bb( + len(puncpat), read_bitlist(puncpat), 0)) # Connect the input to the encoder and the output to the # puncture if used or the encoder if not. - self.connect((self, 0), (self.blocks[0], 0)); - self.connect((self.blocks[-1], 0), (self, 0)); + self.connect((self, 0), (self.blocks[0], 0)) + self.connect((self.blocks[-1], 0), (self, 0)) # If using the puncture block, add it into the flowgraph after # the encoder. for i in range(len(self.blocks) - 1): - self.connect((self.blocks[i], 0), (self.blocks[i+1], 0)); + self.connect((self.blocks[i], 0), (self.blocks[i + 1], 0)) diff --git a/gr-fec/python/fec/extended_tagged_decoder.py b/gr-fec/python/fec/extended_tagged_decoder.py index 0489d738aee..cda601db430 100644 --- a/gr-fec/python/fec/extended_tagged_decoder.py +++ b/gr-fec/python/fec/extended_tagged_decoder.py @@ -91,7 +91,8 @@ def __init__( # We could just grab encoder [0][0], but we don't want to encourage # this. if isinstance(decoder_obj_list[0], list): - gr.log.info("fec.extended_tagged_decoder: Parallelism must be 1.") + gr.log.info( + "fec.extended_tagged_decoder: Parallelism must be 1.") raise AttributeError decoder_obj = decoder_obj_list[0] @@ -110,8 +111,8 @@ def __init__( # anything going through the annihilator needs shifted, uchar vals if ( - fec.get_decoder_input_conversion(decoder_obj) == "uchar" - or fec.get_decoder_input_conversion(decoder_obj) == "packed_bits" + fec.get_decoder_input_conversion(decoder_obj) == "uchar" or + fec.get_decoder_input_conversion(decoder_obj) == "packed_bits" ): self.blocks.append(blocks.multiply_const_ff(48.0)) @@ -121,8 +122,8 @@ def __init__( self.blocks.append(blocks.add_const_ff(128.0)) if ( - fec.get_decoder_input_conversion(decoder_obj) == "uchar" - or fec.get_decoder_input_conversion(decoder_obj) == "packed_bits" + fec.get_decoder_input_conversion(decoder_obj) == "uchar" or + fec.get_decoder_input_conversion(decoder_obj) == "packed_bits" ): self.blocks.append(blocks.float_to_uchar()) @@ -143,9 +144,9 @@ def __init__( if 1.0 / self.ann.count("1") >= i: synd_garble = self.garbletable[i] print( - "using syndrom garble threshold " - + str(synd_garble) - + "for conv_bit_corr_bb" + "using syndrom garble threshold " + + str(synd_garble) + + "for conv_bit_corr_bb" ) print("ceiling: .0335 data garble rate") self.blocks.append( @@ -191,7 +192,8 @@ def __init__( ) if fec.get_decoder_output_conversion(decoder_obj) == "unpack": - self.blocks.append(blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST)) + self.blocks.append( + blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST)) self.connect((self, 0), (self.blocks[0], 0)) self.connect((self.blocks[-1], 0), (self, 0)) diff --git a/gr-fec/python/fec/extended_tagged_encoder.py b/gr-fec/python/fec/extended_tagged_encoder.py index 8519436f83c..c1ea7fb680d 100644 --- a/gr-fec/python/fec/extended_tagged_encoder.py +++ b/gr-fec/python/fec/extended_tagged_encoder.py @@ -9,7 +9,6 @@ # - from gnuradio import gr, blocks from . import fec_python as fec @@ -23,8 +22,8 @@ def __init__(self, encoder_obj_list, puncpat=None, lentagname=None, mtu=1500): gr.io_signature(1, 1, gr.sizeof_char), gr.io_signature(1, 1, gr.sizeof_char)) - self.blocks=[] - self.puncpat=puncpat + self.blocks = [] + self.puncpat = puncpat # If it's a list of encoders, take the first one, unless it's # a list of lists of encoders. @@ -32,7 +31,8 @@ def __init__(self, encoder_obj_list, puncpat=None, lentagname=None, mtu=1500): # This block doesn't handle parallelism of > 1 # We could just grab encoder [0][0], but we don't want to encourage this. if(type(encoder_obj_list[0]) == list): - gr.log.info("fec.extended_tagged_encoder: Parallelism must be 0 or 1.") + gr.log.info( + "fec.extended_tagged_encoder: Parallelism must be 0 or 1.") raise AttributeError encoder_obj = encoder_obj_list[0] @@ -61,14 +61,15 @@ def __init__(self, encoder_obj_list, puncpat=None, lentagname=None, mtu=1500): lentagname, mtu)) if self.puncpat != '11': - self.blocks.append(fec.puncture_bb(len(puncpat), read_bitlist(puncpat), 0)) + self.blocks.append(fec.puncture_bb( + len(puncpat), read_bitlist(puncpat), 0)) # Connect the input to the encoder and the output to the # puncture if used or the encoder if not. - self.connect((self, 0), (self.blocks[0], 0)); - self.connect((self.blocks[-1], 0), (self, 0)); + self.connect((self, 0), (self.blocks[0], 0)) + self.connect((self.blocks[-1], 0), (self, 0)) # If using the puncture block, add it into the flowgraph after # the encoder. for i in range(len(self.blocks) - 1): - self.connect((self.blocks[i], 0), (self.blocks[i+1], 0)); + self.connect((self.blocks[i], 0), (self.blocks[i + 1], 0)) diff --git a/gr-fec/python/fec/fec_test.py b/gr-fec/python/fec/fec_test.py index 264abf4e3ca..db38a3b93d7 100644 --- a/gr-fec/python/fec/fec_test.py +++ b/gr-fec/python/fec/fec_test.py @@ -21,14 +21,15 @@ from .extended_encoder import extended_encoder from .extended_decoder import extended_decoder + class fec_test(gr.hier_block2): def __init__(self, generic_encoder=0, generic_decoder=0, esno=0, samp_rate=3200000, threading="capillary", puncpat='11', seed=0): gr.hier_block2.__init__(self, "fec_test", - gr.io_signature(1, 1, gr.sizeof_char*1), - gr.io_signature(2, 2, gr.sizeof_char*1)) + gr.io_signature(1, 1, gr.sizeof_char * 1), + gr.io_signature(2, 2, gr.sizeof_char * 1)) self.generic_encoder = generic_encoder self.generic_decoder = generic_decoder @@ -52,7 +53,7 @@ def __init__(self, generic_encoder=0, generic_decoder=0, esno=0, ann=None, puncpat=puncpat, integration_period=10000, rotator=None) - noise = math.sqrt((10.0**(-esno / 10.0))/2.0) + noise = math.sqrt((10.0**(-esno / 10.0)) / 2.0) #self.fastnoise = analog.fastnoise_source_f(analog.GR_GAUSSIAN, noise, seed, 8192) self.fastnoise = analog.noise_source_f(analog.GR_GAUSSIAN, noise, seed) self.addnoise = blocks.add_ff(1) @@ -68,12 +69,11 @@ def __init__(self, generic_encoder=0, generic_decoder=0, esno=0, self.connect(self.encoder, self.map_bb) self.connect(self.map_bb, self.b2f) self.connect(self.b2f, (self.addnoise, 0)) - self.connect(self.fastnoise, (self.addnoise,1)) + self.connect(self.fastnoise, (self.addnoise, 1)) self.connect(self.addnoise, self.decoder) self.connect(self.decoder, self.pack8) self.connect(self.pack8, (self, 0)) - def get_generic_encoder(self): return self.generic_encoder diff --git a/gr-fec/python/fec/polar/__init__.py b/gr-fec/python/fec/polar/__init__.py index ce4e5063349..26698752c85 100644 --- a/gr-fec/python/fec/polar/__init__.py +++ b/gr-fec/python/fec/polar/__init__.py @@ -17,19 +17,25 @@ CHANNEL_TYPE_AWGN = 'AWGN' CHANNEL_TYPE_BEC = 'BEC' + def get_z_params(is_prototype, channel, block_size, design_snr, mu): - print('POLAR code channel construction called with parameters channel={0}, blocksize={1}, design SNR={2}, mu={3}'.format(channel, block_size, design_snr, mu)) + print('POLAR code channel construction called with parameters channel={0}, blocksize={1}, design SNR={2}, mu={3}'.format( + channel, block_size, design_snr, mu)) if not (channel == 'AWGN' or channel == 'BEC'): - raise ValueError("channel is {0}, but only BEC and AWGN are supported!".format(channel)) + raise ValueError( + "channel is {0}, but only BEC and AWGN are supported!".format(channel)) if not is_power_of_two(block_size): - raise ValueError("block size={0} is not a power of 2!".format(block_size)) + raise ValueError( + "block size={0} is not a power of 2!".format(block_size)) if design_snr < -1.5917: - raise ValueError("design SNR={0} < -1.5917. MUST be greater!".format(design_snr)) + raise ValueError( + "design SNR={0} < -1.5917. MUST be greater!".format(design_snr)) if not mu > 0: raise ValueError("mu={0} < 1. MUST be > 1!".format(mu)) if not is_prototype and channel == 'AWGN': z_params = cc.load_z_parameters(block_size, design_snr, mu) - print('Read Z-parameter file: {0}'.format(cc.default_dir() + cc.generate_filename(block_size, design_snr, mu))) + print('Read Z-parameter file: {0}'.format(cc.default_dir() + + cc.generate_filename(block_size, design_snr, mu))) return z_params return bhattacharyya_bounds(design_snr, block_size) @@ -48,5 +54,5 @@ def load_frozen_bits_info(is_prototype, channel, block_size, num_info_bits, desi 'design_snr': design_snr, 'channel': channel, 'mu': mu, - } + } return data_set diff --git a/gr-fec/python/fec/polar/channel_construction.py b/gr-fec/python/fec/polar/channel_construction.py index 2ec78679a5d..643bfb7609a 100644 --- a/gr-fec/python/fec/polar/channel_construction.py +++ b/gr-fec/python/fec/polar/channel_construction.py @@ -69,7 +69,8 @@ def frozen_bit_positions(block_size, info_size, design_snr=0.0): def generate_filename(block_size, design_snr, mu): filename = "polar_code_z_parameters_N" + str(int(block_size)) - filename += "_SNR" + str(float(design_snr)) + "_MU" + str(int(mu)) + ".polar" + filename += "_SNR" + str(float(design_snr)) + \ + "_MU" + str(int(mu)) + ".polar" return filename diff --git a/gr-fec/python/fec/polar/channel_construction_awgn.py b/gr-fec/python/fec/polar/channel_construction_awgn.py index 667c17b8fcd..5a90262007a 100644 --- a/gr-fec/python/fec/polar/channel_construction_awgn.py +++ b/gr-fec/python/fec/polar/channel_construction_awgn.py @@ -95,9 +95,9 @@ def discretize_awgn(mu, design_snr): def instant_capacity_delta_callable(): return ( - lambda a, b: -1.0 * (a + b) * np.log2((a + b) / 2) - + a * np.log2(a) - + b * np.log2(b) + lambda a, b: -1.0 * (a + b) * np.log2((a + b) / 2) + + a * np.log2(a) + + b * np.log2(b) ) @@ -114,16 +114,19 @@ def quantize_to_size(tpm, mu): print("WARNING: This channel gets too small!") # lambda works on vectors just fine. Use Numpy vector awesomeness. - delta_i_vec = calculate_delta_I(tpm[0, 0:-1], tpm[1, 0:-1], tpm[0, 1:], tpm[1, 1:]) + delta_i_vec = calculate_delta_I( + tpm[0, 0:-1], tpm[1, 0:-1], tpm[0, 1:], tpm[1, 1:]) for i in range(L - mu): d = np.argmin(delta_i_vec) ap = tpm[0, d] + tpm[0, d + 1] bp = tpm[1, d] + tpm[1, d + 1] if d > 0: - delta_i_vec[d - 1] = calculate_delta_I(tpm[0, d - 1], tpm[1, d - 1], ap, bp) + delta_i_vec[d - + 1] = calculate_delta_I(tpm[0, d - 1], tpm[1, d - 1], ap, bp) if d < delta_i_vec.size - 1: - delta_i_vec[d + 1] = calculate_delta_I(ap, bp, tpm[0, d + 1], tpm[1, d + 1]) + delta_i_vec[d + + 1] = calculate_delta_I(ap, bp, tpm[0, d + 1], tpm[1, d + 1]) delta_i_vec = np.delete(delta_i_vec, d) tpm = np.delete(tpm, d, axis=1) tpm[0, d] = ap @@ -174,7 +177,8 @@ def tal_vardy_tpm_algorithm(block_size, design_snr, mu): def merge_lr_based(q, mu): lrs = q[0] / q[1] - vals, indices, inv_indices = np.unique(lrs, return_index=True, return_inverse=True) + vals, indices, inv_indices = np.unique( + lrs, return_index=True, return_inverse=True) # compare [1] (20). Ordering of representatives according to LRs. temp = np.zeros((2, len(indices)), dtype=float) if vals.size < mu: diff --git a/gr-fec/python/fec/polar/channel_construction_bec.py b/gr-fec/python/fec/polar/channel_construction_bec.py index dd0f386d813..edbfbacf453 100644 --- a/gr-fec/python/fec/polar/channel_construction_bec.py +++ b/gr-fec/python/fec/polar/channel_construction_bec.py @@ -41,7 +41,7 @@ def calc_one_recursion(iw0): def calculate_bec_channel_capacities_loop(initial_channel, block_power): - # compare [0, Arikan] eq. 6 + # compare [0, Arikan] eq. 6 iw = np.array([initial_channel, ], dtype=float) for i in range(block_power): iw = calc_one_recursion(iw) @@ -136,7 +136,7 @@ def plot_channel_capacities(capacity, save_file=None): def plot_average_channel_distance(save_file=None): - eta = 0.5 # design_snr_to_bec_eta(-1.5917) + eta = 0.5 # design_snr_to_bec_eta(-1.5917) powers = np.arange(4, 26) try: @@ -219,5 +219,6 @@ def main(): # plot_average_channel_distance() calculate_bec_channel_z_parameters(eta, block_size) + if __name__ == '__main__': main() diff --git a/gr-fec/python/fec/polar/common.py b/gr-fec/python/fec/polar/common.py index e60cc911f28..178544464af 100644 --- a/gr-fec/python/fec/polar/common.py +++ b/gr-fec/python/fec/polar/common.py @@ -46,7 +46,8 @@ def __init__(self, n, k, frozen_bit_position, frozenbits=None): self.K = k self.frozenbits = frozenbits self.frozen_bit_position = frozen_bit_position - self.info_bit_position = np.delete(np.arange(self.N), self.frozen_bit_position) + self.info_bit_position = np.delete( + np.arange(self.N), self.frozen_bit_position) def _insert_frozen_bits(self, u): prototype = np.empty(self.N, dtype=int) diff --git a/gr-fec/python/fec/polar/decoder.py b/gr-fec/python/fec/polar/decoder.py index 8cbda510172..d245f06e40e 100644 --- a/gr-fec/python/fec/polar/decoder.py +++ b/gr-fec/python/fec/polar/decoder.py @@ -19,8 +19,10 @@ class PolarDecoder(PolarCommon): def __init__(self, n, k, frozen_bit_position, frozenbits=None): PolarCommon.__init__(self, n, k, frozen_bit_position, frozenbits) - self.error_probability = 0.1 # this is kind of a dummy value. usually chosen individually. - self.lrs = ((1 - self.error_probability) / self.error_probability, self.error_probability / (1 - self.error_probability)) + # this is kind of a dummy value. usually chosen individually. + self.error_probability = 0.1 + self.lrs = ((1 - self.error_probability) / self.error_probability, + self.error_probability / (1 - self.error_probability)) self.llrs = np.log(self.lrs) def _llr_bit(self, bit): @@ -77,8 +79,8 @@ def _get_odd_indices_values(self, u_hat): def _calculate_lrs(self, y, u): ue = self._get_even_indices_values(u) uo = self._get_odd_indices_values(u) - ya = y[0:y.size//2] - yb = y[(y.size//2):] + ya = y[0:y.size // 2] + yb = y[(y.size // 2):] la = self._lr_decision_element(ya, (ue + uo) % 2) lb = self._lr_decision_element(yb, ue) return la, lb @@ -140,7 +142,8 @@ def _lr_sc_decoder_efficient(self, y): for i in range(self.N): graph[i][self.power] = self._llr_bit(y[i]) decode_order = self._vector_bit_reversed(np.arange(self.N), self.power) - decode_order = np.delete(decode_order, np.where(decode_order >= self.N // 2)) + decode_order = np.delete( + decode_order, np.where(decode_order >= self.N // 2)) u = np.array([], dtype=int) for pos in decode_order: graph = self._butterfly(pos, 0, graph, u) @@ -171,7 +174,8 @@ def _butterfly(self, bf_entry_row, stage, graph, u): # activate right side butterflies u_even = self._get_even_indices_values(u) u_odd = self._get_odd_indices_values(u) - graph = self._butterfly(bf_entry_row, stage + 1, graph, (u_even + u_odd) % 2) + graph = self._butterfly(bf_entry_row, stage + 1, + graph, (u_even + u_odd) % 2) lower_right = bf_entry_row + self.N // (2 ** (stage + 1)) graph = self._butterfly(lower_right, stage + 1, graph, u_even) @@ -182,7 +186,8 @@ def _butterfly(self, bf_entry_row, stage, graph, u): def decode(self, data, is_packed=False): if not len(data) == self.N: - raise ValueError("len(data)={0} is not equal to n={1}!".format(len(data), self.N)) + raise ValueError( + "len(data)={0} is not equal to n={1}!".format(len(data), self.N)) if is_packed: data = np.unpackbits(data) data = self._lr_sc_decoder_efficient(data) @@ -192,12 +197,14 @@ def decode(self, data, is_packed=False): return data def _extract_info_bits_reversed(self, y): - info_bit_positions_reversed = self._vector_bit_reversed(self.info_bit_position, self.power) + info_bit_positions_reversed = self._vector_bit_reversed( + self.info_bit_position, self.power) return y[info_bit_positions_reversed] def decode_systematic(self, data): if not len(data) == self.N: - raise ValueError("len(data)={0} is not equal to n={1}!".format(len(data), self.N)) + raise ValueError( + "len(data)={0} is not equal to n={1}!".format(len(data), self.N)) # data = self._reverse_bits(data) data = self._lr_sc_decoder_efficient(data) data = self._encode_natural_order(data) diff --git a/gr-fec/python/fec/polar/encoder.py b/gr-fec/python/fec/polar/encoder.py index d6279b1af57..273d6cc9cf3 100644 --- a/gr-fec/python/fec/polar/encoder.py +++ b/gr-fec/python/fec/polar/encoder.py @@ -32,7 +32,8 @@ def _encode_matrix(self, data): def encode(self, data, is_packed=False): if not len(data) == self.K: - raise ValueError("len(data)={0} is not equal to k={1}!".format(len(data), self.K)) + raise ValueError( + "len(data)={0} is not equal to k={1}!".format(len(data), self.K)) if is_packed: data = np.unpackbits(data) if np.max(data) > 1 or np.min(data) < 0: @@ -45,7 +46,8 @@ def encode(self, data, is_packed=False): def encode_systematic(self, data): if not len(data) == self.K: - raise ValueError("len(data)={0} is not equal to k={1}!".format(len(data), self.K)) + raise ValueError( + "len(data)={0} is not equal to k={1}!".format(len(data), self.K)) if np.max(data) > 1 or np.min(data) < 0: raise ValueError("can only encode bits!") @@ -102,7 +104,7 @@ def test_encoder_impls(): # frozenbits = np.zeros(n - k) # frozenbitposition8 = np.array((0, 1, 2, 4), dtype=int) # keep it! frozenbitposition = np.array((0, 1, 2, 3, 4, 5, 8, 9), dtype=int) - encoder = PolarEncoder(n, k, frozenbitposition) #, frozenbits) + encoder = PolarEncoder(n, k, frozenbitposition) # , frozenbits) print('result:', compare_results(encoder, ntests, k)) print('Test rate-1 encoder/decoder chain results') diff --git a/gr-fec/python/fec/polar/helper_functions.py b/gr-fec/python/fec/polar/helper_functions.py index 357bccd5b20..bcddfb83c99 100644 --- a/gr-fec/python/fec/polar/helper_functions.py +++ b/gr-fec/python/fec/polar/helper_functions.py @@ -8,7 +8,8 @@ import numpy as np -import time, sys +import time +import sys import copy @@ -125,8 +126,8 @@ def show_progress_bar(ndone, ntotal): percentage = 100. * fract ndone_chars = int(nchars * fract) nundone_chars = nchars - ndone_chars - sys.stdout.write('\r[{0}{1}] {2:5.2f}% ({3} / {4})'.format('=' * ndone_chars, ' ' * nundone_chars, percentage, ndone, ntotal)) - + sys.stdout.write('\r[{0}{1}] {2:5.2f}% ({3} / {4})'.format('=' * + ndone_chars, ' ' * nundone_chars, percentage, ndone, ntotal)) def mutual_information(w): @@ -173,7 +174,6 @@ def main(): n = 6 m = 2 ** n - pos = np.arange(m) rev_pos = bit_reverse_vector(pos, n) print(pos) @@ -190,6 +190,5 @@ def main(): print(a) - if __name__ == '__main__': main() diff --git a/gr-fec/python/fec/polar/polar_channel_construction b/gr-fec/python/fec/polar/polar_channel_construction index 8ea5753d488..6f1879acf78 100644 --- a/gr-fec/python/fec/polar/polar_channel_construction +++ b/gr-fec/python/fec/polar/polar_channel_construction @@ -18,14 +18,14 @@ def setup_parser(): override this and call the parent function. """ parser = ArgumentParser() parser.add_argument("-c", "--channel", choices=('BEC', 'AWGN'), - help="specify channel, currently BEC or AWGN (default='BEC')", - default='BEC') + help="specify channel, currently BEC or AWGN (default='BEC')", + default='BEC') parser.add_argument("-b", "--blocksize", type=int, dest="block_size", - help="specify block size of polar code (default=16)", default=16) + help="specify block size of polar code (default=16)", default=16) parser.add_argument("-s", "--design-snr", type=float, dest="design_snr", - help="specify design SNR of polar code (default=0.0)", default=0.0) + help="specify design SNR of polar code (default=0.0)", default=0.0) parser.add_argument("-k", "--mu", type=int, - help="specify block size of polar code (default=2)", default=2) + help="specify block size of polar code (default=2)", default=2) return parser @@ -37,7 +37,7 @@ def main(): args = parser.parse_args() z_params = cc.get_z_params(False, args.channel, args.block_size, - args.design_snr, args.mu) + args.design_snr, args.mu) print(z_params) diff --git a/gr-fec/python/fec/polar/testbed.py b/gr-fec/python/fec/polar/testbed.py index 4e1b40a7f79..7ce9f57bb08 100644 --- a/gr-fec/python/fec/polar/testbed.py +++ b/gr-fec/python/fec/polar/testbed.py @@ -52,7 +52,8 @@ def is_equal(first, second): result = first == second for i in range(len(result)): print( - "{0:4}: {1:2} == {2:1} = {3}".format(i, first[i], second[i], result[i]) + "{0:4}: {1:2} == {2:1} = {3}".format( + i, first[i], second[i], result[i]) ) return False return True @@ -132,7 +133,8 @@ def channel_analysis(): channel_counter = np.load(filename) print(np.min(channel_counter), np.max(channel_counter)) channel_counter[0] = np.min(channel_counter) - good_indices = find_good_indices(channel_counter, channel_counter.size // 2) + good_indices = find_good_indices( + channel_counter, channel_counter.size // 2) info_bit_positions = np.where(good_indices > 0) print(info_bit_positions) frozen_bit_positions = np.delete( @@ -303,7 +305,8 @@ def find_decoder_subframes(frozen_mask): print("--------------------------") ll = l sub_t = sub_mask[i] - print("{0:4} lock {1:4} value: {2} in sub {3}".format(i, 2 ** (l + 1), v, t)) + print("{0:4} lock {1:4} value: {2} in sub {3}".format( + i, 2 ** (l + 1), v, t)) def systematic_encoder_decoder_chain_test(): diff --git a/gr-fec/python/fec/qa_fecapi_dummy.py b/gr-fec/python/fec/qa_fecapi_dummy.py index fa1abdf7896..065d3ed6d2d 100644 --- a/gr-fec/python/fec/qa_fecapi_dummy.py +++ b/gr-fec/python/fec/qa_fecapi_dummy.py @@ -26,7 +26,7 @@ def setUp(self): def tearDown(self): self.tb = None - + def test_parallelism0_00(self): frame_size = 30 enc = fec.dummy_encoder_make(frame_size * 8) @@ -52,7 +52,7 @@ def test_parallelism0_01(self): data_in = self.test.snk_input.data() data_out = self.test.snk_output.data() - + self.assertSequenceEqualGR(data_in, data_out) def test_parallelism0_02(self): @@ -66,7 +66,7 @@ def test_parallelism0_02(self): data_in = self.test.snk_input.data() data_out = self.test.snk_output.data() - + self.assertSequenceEqualGR(data_in, data_out) def test_parallelism1_00(self): @@ -113,7 +113,7 @@ def test_parallelism1_02(self): self.tb.run() data_in = self.test.snk_input.data() data_out = self.test.snk_output.data() - + self.assertSequenceEqualGR(data_in, data_out) def test_parallelism1_03(self): diff --git a/gr-fec/python/fec/threaded_decoder.py b/gr-fec/python/fec/threaded_decoder.py index b5444a0a924..a5785377984 100644 --- a/gr-fec/python/fec/threaded_decoder.py +++ b/gr-fec/python/fec/threaded_decoder.py @@ -16,8 +16,8 @@ class threaded_decoder(gr.hier_block2): def __init__(self, decoder_list_0, input_size, output_size): gr.hier_block2.__init__( self, "Threaded Decoder", - gr.io_signature(1, 1, input_size*1), - gr.io_signature(1, 1, output_size*1)) + gr.io_signature(1, 1, input_size * 1), + gr.io_signature(1, 1, output_size * 1)) self.decoder_list_0 = decoder_list_0 @@ -33,11 +33,12 @@ def __init__(self, decoder_list_0, input_size, output_size): fec.get_decoder_output_size(decoder_list_0[0])) for i in range(len(decoder_list_0)): - self.connect((self.deinterleave_0, i), (self.generic_decoders_0[i], 0)) + self.connect((self.deinterleave_0, i), + (self.generic_decoders_0[i], 0)) for i in range(len(decoder_list_0)): - self.connect((self.generic_decoders_0[i], 0), (self.interleave_0, i)) - + self.connect( + (self.generic_decoders_0[i], 0), (self.interleave_0, i)) self.connect((self, 0), (self.deinterleave_0, 0)) self.connect((self.interleave_0, 0), (self, 0)) diff --git a/gr-fec/python/fec/threaded_encoder.py b/gr-fec/python/fec/threaded_encoder.py index 94ae01df218..b933f60402a 100644 --- a/gr-fec/python/fec/threaded_encoder.py +++ b/gr-fec/python/fec/threaded_encoder.py @@ -17,27 +17,29 @@ class threaded_encoder(gr.hier_block2): def __init__(self, encoder_list_0, input_size, output_size): gr.hier_block2.__init__( self, "Threaded Encoder", - gr.io_signature(1, 1, input_size*1), - gr.io_signature(1, 1, output_size*1)) + gr.io_signature(1, 1, input_size * 1), + gr.io_signature(1, 1, output_size * 1)) self.encoder_list_0 = encoder_list_0 self.fec_deinterleave_0 = blocks.deinterleave(input_size, fec.get_encoder_input_size(encoder_list_0[0])) - self.generic_encoders_0 = []; + self.generic_encoders_0 = [] for i in range(len(encoder_list_0)): self.generic_encoders_0.append(fec.encoder(encoder_list_0[i], input_size, output_size)) self.fec_interleave_0 = blocks.interleave(output_size, - fec.get_encoder_output_size(encoder_list_0[0])) + fec.get_encoder_output_size(encoder_list_0[0])) for i in range(len(encoder_list_0)): - self.connect((self.fec_deinterleave_0, i), (self.generic_encoders_0[i], 0)) + self.connect((self.fec_deinterleave_0, i), + (self.generic_encoders_0[i], 0)) for i in range(len(encoder_list_0)): - self.connect((self.generic_encoders_0[i], 0), (self.fec_interleave_0, i)) + self.connect( + (self.generic_encoders_0[i], 0), (self.fec_interleave_0, i)) self.connect((self, 0), (self.fec_deinterleave_0, 0)) self.connect((self.fec_interleave_0, 0), (self, 0)) diff --git a/gr-fft/python/fft/__init__.py b/gr-fft/python/fft/__init__.py index bb370a333ac..7e12455c99c 100644 --- a/gr-fft/python/fft/__init__.py +++ b/gr-fft/python/fft/__init__.py @@ -22,4 +22,4 @@ from .fft_python import * from .fft_vcc import fft_vcc -from .fft_vfc import fft_vfc \ No newline at end of file +from .fft_vfc import fft_vfc diff --git a/gr-fft/python/fft/logpwrfft.py b/gr-fft/python/fft/logpwrfft.py index 82f852e1903..f82fa06a8eb 100644 --- a/gr-fft/python/fft/logpwrfft.py +++ b/gr-fft/python/fft/logpwrfft.py @@ -9,7 +9,8 @@ from gnuradio import gr from gnuradio import blocks -import sys, math +import sys +import math from . import fft_python as fft from . import fft_vfc, fft_vcc @@ -21,6 +22,7 @@ sys.stderr.write('fft.logpwrfft required gr-filter.\n') sys.exit(1) + class _logpwrfft_base(gr.hier_block2): """ Create a log10(abs(fft)) stream chain, with real or complex input. @@ -42,24 +44,28 @@ def __init__(self, sample_rate, fft_size, ref_scale, frame_rate, avg_alpha, aver shift: shift zero-frequency component to center of spectrum """ gr.hier_block2.__init__(self, self._name, - gr.io_signature(1, 1, self._item_size), # Input signature - gr.io_signature(1, 1, gr.sizeof_float*fft_size)) # Output signature + # Input signature + gr.io_signature(1, 1, self._item_size), + gr.io_signature(1, 1, gr.sizeof_float * fft_size)) # Output signature self._sd = blocks.stream_to_vector_decimator(item_size=self._item_size, sample_rate=sample_rate, vec_rate=frame_rate, vec_len=fft_size) - if win is None: win = window.blackmanharris + if win is None: + win = window.blackmanharris fft_window = win(fft_size) fft = self._fft_block[0](fft_size, True, fft_window, shift=shift) - window_power = sum([x*x for x in fft_window]) + window_power = sum([x * x for x in fft_window]) c2magsq = blocks.complex_to_mag_squared(fft_size) self._avg = filter.single_pole_iir_filter_ff(1.0, fft_size) self._log = blocks.nlog10_ff(10, fft_size, - -20*math.log10(fft_size) # Adjust for number of bins - -10*math.log10(float(window_power) / fft_size) # Adjust for windowing loss - -20*math.log10(float(ref_scale) / 2)) # Adjust for reference scale + # Adjust for number of bins + -20 * math.log10(fft_size) - + # Adjust for windowing loss + 10 * math.log10(float(window_power) / fft_size) - + 20 * math.log10(float(ref_scale) / 2)) # Adjust for reference scale self.connect(self, self._sd, fft, c2magsq, self._avg, self._log, self) self._average = average @@ -147,18 +153,20 @@ def avg_alpha(self): """ return self._avg_alpha + class logpwrfft_f(_logpwrfft_base): - """ - Create an fft block chain, with real input. - """ - _name = "logpwrfft_f" - _item_size = gr.sizeof_float - _fft_block = (fft_vfc, ) + """ + Create an fft block chain, with real input. + """ + _name = "logpwrfft_f" + _item_size = gr.sizeof_float + _fft_block = (fft_vfc, ) + class logpwrfft_c(_logpwrfft_base): - """ - Create an fft block chain, with complex input. - """ - _name = "logpwrfft_c" - _item_size = gr.sizeof_gr_complex - _fft_block = (fft_vcc, ) + """ + Create an fft block chain, with complex input. + """ + _name = "logpwrfft_c" + _item_size = gr.sizeof_gr_complex + _fft_block = (fft_vcc, ) diff --git a/gr-filter/examples/benchmark_filters.py b/gr-filter/examples/benchmark_filters.py index f4470651052..2cecc57f71e 100644 --- a/gr-filter/examples/benchmark_filters.py +++ b/gr-filter/examples/benchmark_filters.py @@ -15,13 +15,15 @@ from gnuradio import blocks, filter from gnuradio.eng_arg import eng_float, intx + def make_random_complex_tuple(L): result = [] for x in range(L): - result.append(complex(random.uniform(-1000,1000), - random.uniform(-1000,1000))) + result.append(complex(random.uniform(-1000, 1000), + random.uniform(-1000, 1000))) return tuple(result) + def benchmark(name, creator, dec, ntaps, total_test_size, block_size): block_size = 32768 @@ -37,12 +39,14 @@ def benchmark(name, creator, dec, ntaps, total_test_size, block_size): stop = time.time() delta = stop - start print("%16s: taps: %4d input: %4g, time: %6.3f taps/sec: %10.4g" % ( - name, ntaps, total_test_size, delta, ntaps*total_test_size/delta)) + name, ntaps, total_test_size, delta, ntaps * total_test_size / delta)) + def main(): parser = ArgumentParser() parser.add_argument("-n", "--ntaps", type=int, default=256) - parser.add_argument("-t", "--total-input-size", type=eng_float, default=40e6) + parser.add_argument("-t", "--total-input-size", + type=eng_float, default=40e6) parser.add_argument("-b", "--block-size", type=intx, default=50000) parser.add_argument("-d", "--decimation", type=int, default=1) args = parser.parse_args() @@ -52,5 +56,6 @@ def main(): benchmark("filter.fft_filter_ccc", filter.fft_filter_ccc, args.decimation, args.ntaps, args.total_input_size, args.block_size) + if __name__ == '__main__': main() diff --git a/gr-filter/examples/channelize.py b/gr-filter/examples/channelize.py index 4d92bdce3f8..83e85bc9c15 100644 --- a/gr-filter/examples/channelize.py +++ b/gr-filter/examples/channelize.py @@ -12,7 +12,8 @@ from gnuradio import blocks from gnuradio import filter from gnuradio.fft import window -import sys, time +import sys +import time import numpy try: @@ -25,9 +26,11 @@ import pylab from pylab import mlab except ImportError: - sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") + sys.stderr.write( + "Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) + class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) @@ -35,7 +38,7 @@ def __init__(self): self._N = 2000000 # number of samples to use self._fs = 1000 # initial sampling rate self._M = M = 9 # Number of channels to channelize - self._ifs = M*self._fs # initial sampling rate + self._ifs = M * self._fs # initial sampling rate # Create a set of taps for the PFB channelizer self._taps = filter.firdes.low_pass_2(1, self._ifs, 475.50, 50, @@ -55,9 +58,10 @@ def __init__(self): self.add = blocks.add_cc() freqs = [-70, -50, -30, -10, 10, 20, 40, 60, 80] for i in range(len(freqs)): - f = freqs[i] + (M / 2-M+i+1)*self._fs - self.signals.append(analog.sig_source_c(self._ifs, analog.GR_SIN_WAVE, f, 1)) - self.connect(self.signals[i], (self.add,i)) + f = freqs[i] + (M / 2 - M + i + 1) * self._fs + self.signals.append(analog.sig_source_c( + self._ifs, analog.GR_SIN_WAVE, f, 1)) + self.connect(self.signals[i], (self.add, i)) self.head = blocks.head(gr.sizeof_gr_complex, self._N) @@ -72,7 +76,7 @@ def __init__(self): self.connect(self.add, self.snk_i) # Use this to play with the channel mapping - #self.pfb.set_channel_map([5,6,7,8,0,1,2,3,4]) + # self.pfb.set_channel_map([5,6,7,8,0,1,2,3,4]) # Create a vector sink for each of M output channels of the filter and connect it self.snks = list() @@ -91,9 +95,9 @@ def main(): print("Run time: %f" % (tend - tstart)) if 1: - fig_in = pylab.figure(1, figsize=(16,9), facecolor="w") - fig1 = pylab.figure(2, figsize=(16,9), facecolor="w") - fig2 = pylab.figure(3, figsize=(16,9), facecolor="w") + fig_in = pylab.figure(1, figsize=(16, 9), facecolor="w") + fig1 = pylab.figure(2, figsize=(16, 9), facecolor="w") + fig2 = pylab.figure(3, figsize=(16, 9), facecolor="w") Ns = 1000 Ne = 10000 @@ -106,22 +110,21 @@ def main(): d = tb.snk_i.data()[Ns:Ne] spin_f = fig_in.add_subplot(2, 1, 1) - X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, - window = lambda d: d*winfunc(fftlen), - scale_by_freq=True) - X_in = 10.0*numpy.log10(abs(X)) + X, freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, + window=lambda d: d * winfunc(fftlen), + scale_by_freq=True) + X_in = 10.0 * numpy.log10(abs(X)) f_in = numpy.arange(-fs / 2.0, fs / 2.0, fs / float(X_in.size)) pin_f = spin_f.plot(f_in, X_in, "b") - spin_f.set_xlim([min(f_in), max(f_in)+1]) + spin_f.set_xlim([min(f_in), max(f_in) + 1]) spin_f.set_ylim([-200.0, 50.0]) spin_f.set_title("Input Signal", weight="bold") spin_f.set_xlabel("Frequency (Hz)") spin_f.set_ylabel("Power (dBW)") - Ts = 1.0 / fs - Tmax = len(d)*Ts + Tmax = len(d) * Ts t_in = numpy.arange(0, Tmax, Ts) x_in = numpy.array(d) @@ -141,21 +144,21 @@ def main(): # time signals on Figure 3 fs_o = tb._fs Ts_o = 1.0 / fs_o - Tmax_o = len(d)*Ts_o + Tmax_o = len(d) * Ts_o for i in range(len(tb.snks)): # remove issues with the transients at the beginning # also remove some corruption at the end of the stream # this is a bug, probably due to the corner cases d = tb.snks[i].data()[Ns:Ne] - sp1_f = fig1.add_subplot(Nrows, Ncols, 1+i) - X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs_o, - window = lambda d: d*winfunc(fftlen), - scale_by_freq=True) - X_o = 10.0*numpy.log10(abs(X)) + sp1_f = fig1.add_subplot(Nrows, Ncols, 1 + i) + X, freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs_o, + window=lambda d: d * winfunc(fftlen), + scale_by_freq=True) + X_o = 10.0 * numpy.log10(abs(X)) f_o = numpy.arange(-fs_o / 2.0, fs_o / 2.0, fs_o / float(X_o.size)) p2_f = sp1_f.plot(f_o, X_o, "b") - sp1_f.set_xlim([min(f_o), max(f_o)+1]) + sp1_f.set_xlim([min(f_o), max(f_o) + 1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title(("Channel %d" % i), weight="bold") @@ -164,10 +167,10 @@ def main(): x_o = numpy.array(d) t_o = numpy.arange(0, Tmax_o, Ts_o) - sp2_o = fig2.add_subplot(Nrows, Ncols, 1+i) + sp2_o = fig2.add_subplot(Nrows, Ncols, 1 + i) p2_o = sp2_o.plot(t_o, x_o.real, "b") p2_o = sp2_o.plot(t_o, x_o.imag, "r") - sp2_o.set_xlim([min(t_o), max(t_o)+1]) + sp2_o.set_xlim([min(t_o), max(t_o) + 1]) sp2_o.set_ylim([-2, 2]) sp2_o.set_title(("Channel %d" % i), weight="bold") @@ -182,4 +185,3 @@ def main(): main() except KeyboardInterrupt: pass - diff --git a/gr-filter/examples/chirp_channelize.py b/gr-filter/examples/chirp_channelize.py index 03efcf873f5..d37e35cb8d3 100644 --- a/gr-filter/examples/chirp_channelize.py +++ b/gr-filter/examples/chirp_channelize.py @@ -12,7 +12,8 @@ from gnuradio import blocks from gnuradio import filter from gnuradio.fft import window -import sys, time +import sys +import time import numpy try: @@ -25,9 +26,11 @@ import pylab from pylab import mlab except ImportError: - sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") + sys.stderr.write( + "Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) + class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) @@ -49,7 +52,8 @@ def __init__(self): repeated = True if(repeated): - self.vco_input = analog.sig_source_f(self._fs, analog.GR_SIN_WAVE, 0.25, 110) + self.vco_input = analog.sig_source_f( + self._fs, analog.GR_SIN_WAVE, 0.25, 110) else: amp = 100 data = numpy.arange(0, amp, amp / float(self._N)) @@ -90,10 +94,10 @@ def main(): print("Run time: %f" % (tend - tstart)) if 1: - fig_in = pylab.figure(1, figsize=(16,9), facecolor="w") - fig1 = pylab.figure(2, figsize=(16,9), facecolor="w") - fig2 = pylab.figure(3, figsize=(16,9), facecolor="w") - fig3 = pylab.figure(4, figsize=(16,9), facecolor="w") + fig_in = pylab.figure(1, figsize=(16, 9), facecolor="w") + fig1 = pylab.figure(2, figsize=(16, 9), facecolor="w") + fig2 = pylab.figure(3, figsize=(16, 9), facecolor="w") + fig3 = pylab.figure(4, figsize=(16, 9), facecolor="w") Ns = 650 Ne = 20000 @@ -106,22 +110,21 @@ def main(): d = tb.snk_i.data()[Ns:Ne] spin_f = fig_in.add_subplot(2, 1, 1) - X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, - window = lambda d: d*winfunc(fftlen), - scale_by_freq=True) - X_in = 10.0*numpy.log10(abs(numpy.fft.fftshift(X))) + X, freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, + window=lambda d: d * winfunc(fftlen), + scale_by_freq=True) + X_in = 10.0 * numpy.log10(abs(numpy.fft.fftshift(X))) f_in = numpy.arange(-fs / 2.0, fs / 2.0, fs / float(X_in.size)) pin_f = spin_f.plot(f_in, X_in, "b") - spin_f.set_xlim([min(f_in), max(f_in)+1]) + spin_f.set_xlim([min(f_in), max(f_in) + 1]) spin_f.set_ylim([-200.0, 50.0]) spin_f.set_title("Input Signal", weight="bold") spin_f.set_xlabel("Frequency (Hz)") spin_f.set_ylabel("Power (dBW)") - Ts = 1.0 / fs - Tmax = len(d)*Ts + Tmax = len(d) * Ts t_in = numpy.arange(0, Tmax, Ts) x_in = numpy.array(d) @@ -141,21 +144,21 @@ def main(): # time signals on Figure 3 fs_o = tb._fs / tb._M Ts_o = 1.0 / fs_o - Tmax_o = len(d)*Ts_o + Tmax_o = len(d) * Ts_o for i in range(len(tb.snks)): # remove issues with the transients at the beginning # also remove some corruption at the end of the stream # this is a bug, probably due to the corner cases d = tb.snks[i].data()[Ns:Ne] - sp1_f = fig1.add_subplot(Nrows, Ncols, 1+i) - X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs_o, - window = lambda d: d*winfunc(fftlen), - scale_by_freq=True) - X_o = 10.0*numpy.log10(abs(X)) + sp1_f = fig1.add_subplot(Nrows, Ncols, 1 + i) + X, freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs_o, + window=lambda d: d * winfunc(fftlen), + scale_by_freq=True) + X_o = 10.0 * numpy.log10(abs(X)) f_o = freq p2_f = sp1_f.plot(f_o, X_o, "b") - sp1_f.set_xlim([min(f_o), max(f_o)+1]) + sp1_f.set_xlim([min(f_o), max(f_o) + 1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title(("Channel %d" % i), weight="bold") @@ -164,20 +167,19 @@ def main(): x_o = numpy.array(d) t_o = numpy.arange(0, Tmax_o, Ts_o) - sp2_o = fig2.add_subplot(Nrows, Ncols, 1+i) + sp2_o = fig2.add_subplot(Nrows, Ncols, 1 + i) p2_o = sp2_o.plot(t_o, x_o.real, "b") p2_o = sp2_o.plot(t_o, x_o.imag, "r") - sp2_o.set_xlim([min(t_o), max(t_o)+1]) + sp2_o.set_xlim([min(t_o), max(t_o) + 1]) sp2_o.set_ylim([-2, 2]) sp2_o.set_title(("Channel %d" % i), weight="bold") sp2_o.set_xlabel("Time (s)") sp2_o.set_ylabel("Amplitude") - - sp3 = fig3.add_subplot(1,1,1) + sp3 = fig3.add_subplot(1, 1, 1) p3 = sp3.plot(t_o, x_o.real) - sp3.set_xlim([min(t_o), max(t_o)+1]) + sp3.set_xlim([min(t_o), max(t_o) + 1]) sp3.set_ylim([-2, 2]) sp3.set_title("All Channels") @@ -192,4 +194,3 @@ def main(): main() except KeyboardInterrupt: pass - diff --git a/gr-filter/examples/decimate.py b/gr-filter/examples/decimate.py index 8e2f3c7c365..f291e51eb4b 100644 --- a/gr-filter/examples/decimate.py +++ b/gr-filter/examples/decimate.py @@ -12,7 +12,8 @@ from gnuradio import blocks from gnuradio import filter from gnuradio.fft import window -import sys, time +import sys +import time import numpy try: @@ -26,9 +27,11 @@ from matplotlib import pyplot from matplotlib import pyplot as mlab except ImportError: - sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") + sys.stderr.write( + "Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) + class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) @@ -56,8 +59,9 @@ def __init__(self): self.add = blocks.add_cc() freqs = [10, 20, 2040] for i in range(len(freqs)): - self.signals.append(analog.sig_source_c(self._fs, analog.GR_SIN_WAVE, freqs[i], 1)) - self.connect(self.signals[i], (self.add,i)) + self.signals.append(analog.sig_source_c( + self._fs, analog.GR_SIN_WAVE, freqs[i], 1)) + self.connect(self.signals[i], (self.add, i)) self.head = blocks.head(gr.sizeof_gr_complex, self._N) @@ -87,8 +91,8 @@ def main(): print("Run time: %f" % (tend - tstart)) if 1: - fig1 = pyplot.figure(1, figsize=(16,9)) - fig2 = pyplot.figure(2, figsize=(16,9)) + fig1 = pyplot.figure(1, figsize=(16, 9)) + fig2 = pyplot.figure(2, figsize=(16, 9)) Ns = 10000 Ne = 10000 @@ -99,16 +103,16 @@ def main(): # Plot the input to the decimator - d = tb.snk_i.data()[Ns:Ns+Ne] + d = tb.snk_i.data()[Ns:Ns + Ne] sp1_f = fig1.add_subplot(2, 1, 1) - X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, - window = lambda d: d*winfunc(fftlen), - scale_by_freq=True) - X_in = 10.0*numpy.log10(abs(numpy.fft.fftshift(X))) + X, freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, + window=lambda d: d * winfunc(fftlen), + scale_by_freq=True) + X_in = 10.0 * numpy.log10(abs(numpy.fft.fftshift(X))) f_in = numpy.arange(-fs / 2.0, fs / 2.0, fs / float(X_in.size)) p1_f = sp1_f.plot(f_in, X_in, "b") - sp1_f.set_xlim([min(f_in), max(f_in)+1]) + sp1_f.set_xlim([min(f_in), max(f_in) + 1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title("Input Signal", weight="bold") @@ -116,40 +120,38 @@ def main(): sp1_f.set_ylabel("Power (dBW)") Ts = 1.0 / fs - Tmax = len(d)*Ts + Tmax = len(d) * Ts t_in = numpy.arange(0, Tmax, Ts) x_in = numpy.array(d) sp1_t = fig1.add_subplot(2, 1, 2) p1_t = sp1_t.plot(t_in, x_in.real, "b") p1_t = sp1_t.plot(t_in, x_in.imag, "r") - sp1_t.set_ylim([-tb._decim*1.1, tb._decim*1.1]) + sp1_t.set_ylim([-tb._decim * 1.1, tb._decim * 1.1]) sp1_t.set_xlabel("Time (s)") sp1_t.set_ylabel("Amplitude") - # Plot the output of the decimator fs_o = tb._fs / tb._decim sp2_f = fig2.add_subplot(2, 1, 1) - d = tb.snk.data()[Ns:Ns+Ne] - X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs_o, - window = lambda d: d*winfunc(fftlen), - scale_by_freq=True) - X_o = 10.0*numpy.log10(abs(numpy.fft.fftshift(X))) + d = tb.snk.data()[Ns:Ns + Ne] + X, freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs_o, + window=lambda d: d * winfunc(fftlen), + scale_by_freq=True) + X_o = 10.0 * numpy.log10(abs(numpy.fft.fftshift(X))) f_o = numpy.arange(-fs_o / 2.0, fs_o / 2.0, fs_o / float(X_o.size)) p2_f = sp2_f.plot(f_o, X_o, "b") - sp2_f.set_xlim([min(f_o), max(f_o)+1]) + sp2_f.set_xlim([min(f_o), max(f_o) + 1]) sp2_f.set_ylim([-200.0, 50.0]) sp2_f.set_title("PFB Decimated Signal", weight="bold") sp2_f.set_xlabel("Frequency (Hz)") sp2_f.set_ylabel("Power (dBW)") - Ts_o = 1.0 / fs_o - Tmax_o = len(d)*Ts_o + Tmax_o = len(d) * Ts_o x_o = numpy.array(d) t_o = numpy.arange(0, Tmax_o, Ts_o) @@ -169,4 +171,3 @@ def main(): main() except KeyboardInterrupt: pass - diff --git a/gr-filter/examples/fft_filter_ccc.py b/gr-filter/examples/fft_filter_ccc.py index afdc0f3127f..c9a8353af23 100644 --- a/gr-filter/examples/fft_filter_ccc.py +++ b/gr-filter/examples/fft_filter_ccc.py @@ -23,6 +23,7 @@ print("Error: could not from matplotlib import pyplot (http://matplotlib.sourceforge.net/)") sys.exit(1) + class example_fft_filter_ccc(gr.top_block): def __init__(self, N, fs, bw0, bw1, tw, atten, D): gr.top_block.__init__(self) @@ -39,7 +40,7 @@ def __init__(self, N, fs, bw0, bw1, tw, atten, D): self._tw, self._at) print("Num. Taps: ", len(taps)) - self.src = analog.noise_source_c(analog.GR_GAUSSIAN, 1) + self.src = analog.noise_source_c(analog.GR_GAUSSIAN, 1) self.head = blocks.head(gr.sizeof_gr_complex, self._nsamps) self.filt0 = filter.fft_filter_ccc(self._decim, taps) @@ -50,22 +51,23 @@ def __init__(self, N, fs, bw0, bw1, tw, atten, D): self.connect(self.src, self.head, self.vsnk_src) self.connect(self.head, self.filt0, self.vsnk_out) + def main(): parser = ArgumentParser(conflict_handler="resolve") parser.add_argument("-N", "--nsamples", type=int, default=10000, - help="Number of samples to process [default=%(default)r]") + help="Number of samples to process [default=%(default)r]") parser.add_argument("-s", "--samplerate", type=eng_float, default=8000, - help="System sample rate [default=%(default)r]") + help="System sample rate [default=%(default)r]") parser.add_argument("-S", "--start-pass", type=eng_float, default=1000, - help="Start of Passband [default=%(default)r]") + help="Start of Passband [default=%(default)r]") parser.add_argument("-E", "--end-pass", type=eng_float, default=2000, - help="End of Passband [default=%(default)r]") + help="End of Passband [default=%(default)r]") parser.add_argument("-T", "--transition", type=eng_float, default=100, - help="Transition band [default=%(default)r]") + help="Transition band [default=%(default)r]") parser.add_argument("-A", "--attenuation", type=eng_float, default=80, - help="Stopband attenuation [default=%(default)r]") + help="Stopband attenuation [default=%(default)r]") parser.add_argument("-D", "--decimation", type=int, default=1, - help="Decmation factor [default=%(default)r]") + help="Decmation factor [default=%(default)r]") args = parser.parse_args() put = example_fft_filter_ccc(args.nsamples, @@ -82,23 +84,23 @@ def main(): # Plot the signals PSDs nfft = 1024 - f1 = pyplot.figure(1, figsize=(12,10)) - s1 = f1.add_subplot(1,1,1) + f1 = pyplot.figure(1, figsize=(12, 10)) + s1 = f1.add_subplot(1, 1, 1) s1.psd(data_src, NFFT=nfft, noverlap=nfft / 4, Fs=args.samplerate) s1.psd(data_snk, NFFT=nfft, noverlap=nfft / 4, Fs=args.samplerate) - f2 = pyplot.figure(2, figsize=(12,10)) - s2 = f2.add_subplot(1,1,1) + f2 = pyplot.figure(2, figsize=(12, 10)) + s2 = f2.add_subplot(1, 1, 1) s2.plot(data_src) s2.plot(data_snk.real, 'g') pyplot.show() + if __name__ == "__main__": try: main() except KeyboardInterrupt: pass - diff --git a/gr-filter/examples/fir_filter_ccc.py b/gr-filter/examples/fir_filter_ccc.py index 7e43735bb11..26ee561982c 100644 --- a/gr-filter/examples/fir_filter_ccc.py +++ b/gr-filter/examples/fir_filter_ccc.py @@ -23,6 +23,7 @@ print("Error: could not from matplotlib import pyplot (http://matplotlib.sourceforge.net/)") sys.exit(1) + class example_fir_filter_ccc(gr.top_block): def __init__(self, N, fs, bw, tw, atten, D): gr.top_block.__init__(self) @@ -33,10 +34,11 @@ def __init__(self, N, fs, bw, tw, atten, D): self._tw = tw self._at = atten self._decim = D - taps = filter.firdes.low_pass_2(1, self._fs, self._bw, self._tw, self._at) + taps = filter.firdes.low_pass_2( + 1, self._fs, self._bw, self._tw, self._at) print("Num. Taps: ", len(taps)) - self.src = analog.noise_source_c(analog.GR_GAUSSIAN, 1) + self.src = analog.noise_source_c(analog.GR_GAUSSIAN, 1) self.head = blocks.head(gr.sizeof_gr_complex, self._nsamps) self.filt0 = filter.fir_filter_ccc(self._decim, taps) @@ -47,20 +49,21 @@ def __init__(self, N, fs, bw, tw, atten, D): self.connect(self.src, self.head, self.vsnk_src) self.connect(self.head, self.filt0, self.vsnk_out) + def main(): parser = ArgumentParser(conflict_handler="resolve") parser.add_argument("-N", "--nsamples", type=int, default=10000, - help="Number of samples to process [default=%(default)r]") + help="Number of samples to process [default=%(default)r]") parser.add_argument("-s", "--samplerate", type=eng_float, default=8000, - help="System sample rate [default=%(default)r]") + help="System sample rate [default=%(default)r]") parser.add_argument("-B", "--bandwidth", type=eng_float, default=1000, - help="Filter bandwidth [default=%(default)r]") + help="Filter bandwidth [default=%(default)r]") parser.add_argument("-T", "--transition", type=eng_float, default=100, - help="Transition band [default=%(default)r]") + help="Transition band [default=%(default)r]") parser.add_argument("-A", "--attenuation", type=eng_float, default=80, - help="Stopband attenuation [default=%(default)r]") + help="Stopband attenuation [default=%(default)r]") parser.add_argument("-D", "--decimation", type=int, default=1, - help="Decmation factor [default=%(default)r]") + help="Decmation factor [default=%(default)r]") args = parser.parse_args() put = example_fir_filter_ccc(args.nsamples, @@ -76,23 +79,23 @@ def main(): # Plot the signals PSDs nfft = 1024 - f1 = pyplot.figure(1, figsize=(12,10)) - s1 = f1.add_subplot(1,1,1) + f1 = pyplot.figure(1, figsize=(12, 10)) + s1 = f1.add_subplot(1, 1, 1) s1.psd(data_src, NFFT=nfft, noverlap=nfft / 4, Fs=args.samplerate) s1.psd(data_snk, NFFT=nfft, noverlap=nfft / 4, Fs=args.samplerate) - f2 = pyplot.figure(2, figsize=(12,10)) - s2 = f2.add_subplot(1,1,1) + f2 = pyplot.figure(2, figsize=(12, 10)) + s2 = f2.add_subplot(1, 1, 1) s2.plot(data_src) s2.plot(data_snk.real, 'g') pyplot.show() + if __name__ == "__main__": try: main() except KeyboardInterrupt: pass - diff --git a/gr-filter/examples/fir_filter_fff.py b/gr-filter/examples/fir_filter_fff.py index f634c44cf23..74c41b1ec7f 100644 --- a/gr-filter/examples/fir_filter_fff.py +++ b/gr-filter/examples/fir_filter_fff.py @@ -23,6 +23,7 @@ print("Error: could not from matplotlib import pyplot (http://matplotlib.sourceforge.net/)") sys.exit(1) + class example_fir_filter_fff(gr.top_block): def __init__(self, N, fs, bw, tw, atten, D): gr.top_block.__init__(self) @@ -33,10 +34,11 @@ def __init__(self, N, fs, bw, tw, atten, D): self._tw = tw self._at = atten self._decim = D - taps = filter.firdes.low_pass_2(1, self._fs, self._bw, self._tw, self._at) + taps = filter.firdes.low_pass_2( + 1, self._fs, self._bw, self._tw, self._at) print("Num. Taps: ", len(taps)) - self.src = analog.noise_source_f(analog.GR_GAUSSIAN, 1) + self.src = analog.noise_source_f(analog.GR_GAUSSIAN, 1) self.head = blocks.head(gr.sizeof_float, self._nsamps) self.filt0 = filter.fir_filter_fff(self._decim, taps) @@ -47,20 +49,21 @@ def __init__(self, N, fs, bw, tw, atten, D): self.connect(self.src, self.head, self.vsnk_src) self.connect(self.head, self.filt0, self.vsnk_out) + def main(): parser = ArgumentParser(conflict_handler="resolve") parser.add_argument("-N", "--nsamples", type=int, default=10000, - help="Number of samples to process [default=%(default)r]") + help="Number of samples to process [default=%(default)r]") parser.add_argument("-s", "--samplerate", type=eng_float, default=8000, - help="System sample rate [default=%(default)r]") + help="System sample rate [default=%(default)r]") parser.add_argument("-B", "--bandwidth", type=eng_float, default=1000, - help="Filter bandwidth [default=%(default)r]") + help="Filter bandwidth [default=%(default)r]") parser.add_argument("-T", "--transition", type=eng_float, default=100, - help="Transition band [default=%(default)r]") + help="Transition band [default=%(default)r]") parser.add_argument("-A", "--attenuation", type=eng_float, default=80, - help="Stopband attenuation [default=%(default)r]") + help="Stopband attenuation [default=%(default)r]") parser.add_argument("-D", "--decimation", type=int, default=1, - help="Decmation factor [default=%(default)r]") + help="Decmation factor [default=%(default)r]") args = parser.parse_args() put = example_fir_filter_fff(args.nsamples, @@ -76,23 +79,23 @@ def main(): # Plot the signals PSDs nfft = 1024 - f1 = pyplot.figure(1, figsize=(12,10)) - s1 = f1.add_subplot(1,1,1) + f1 = pyplot.figure(1, figsize=(12, 10)) + s1 = f1.add_subplot(1, 1, 1) s1.psd(data_src, NFFT=nfft, noverlap=nfft / 4, Fs=args.samplerate) s1.psd(data_snk, NFFT=nfft, noverlap=nfft / 4, Fs=args.samplerate) - f2 = pyplot.figure(2, figsize=(12,10)) - s2 = f2.add_subplot(1,1,1) + f2 = pyplot.figure(2, figsize=(12, 10)) + s2 = f2.add_subplot(1, 1, 1) s2.plot(data_src) s2.plot(data_snk.real, 'g') pyplot.show() + if __name__ == "__main__": try: main() except KeyboardInterrupt: pass - diff --git a/gr-filter/examples/gr_filtdes_callback.py b/gr-filter/examples/gr_filtdes_callback.py index d27943174ef..371f337d4da 100644 --- a/gr-filter/examples/gr_filtdes_callback.py +++ b/gr-filter/examples/gr_filtdes_callback.py @@ -23,14 +23,17 @@ launch function returns gr_filter_design mainwindow object when callback is not None ''' + + def print_params(filtobj): print("Filter Count:", filtobj.get_filtercount()) print("Filter type:", filtobj.get_restype()) print("Filter params", filtobj.get_params()) print("Filter Coefficients", filtobj.get_taps()) + app = Qt.QApplication(sys.argv) -#launch function returns gr_filter_design mainwindow object +# launch function returns gr_filter_design mainwindow object main_win = filter_design.launch(sys.argv, print_params) main_win.show() app.exec_() diff --git a/gr-filter/examples/gr_filtdes_live_upd.py b/gr-filter/examples/gr_filtdes_live_upd.py index 3b1fd1e1c6e..182b7535ae1 100644 --- a/gr-filter/examples/gr_filtdes_live_upd.py +++ b/gr-filter/examples/gr_filtdes_live_upd.py @@ -41,6 +41,7 @@ sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) + class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) @@ -53,24 +54,24 @@ def __init__(self): self.qapp = QtGui.QApplication(sys.argv) - self.filt_taps = [1,] + self.filt_taps = [1, ] src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) - src = blocks.add_cc() + src = blocks.add_cc() channel = channels.channel_model(0.01) self.filt = filter.fft_filter_ccc(1, self.filt_taps) - thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) + thr = blocks.throttle(gr.sizeof_gr_complex, 100 * npts) self.snk1 = qtgui.freq_sink_c(npts, window.WIN_BLACKMAN_hARRIS, 0, Rs, "Complex Freq Example", 1) - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, channel, thr, self.filt, (self.snk1, 0)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, channel, thr, self.filt, (self.snk1, 0)) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtGui.QWidget @@ -82,12 +83,11 @@ def update_filter(self, filtobj): print("Filter params", filtobj.get_params()) self.filt.set_taps(filtobj.get_taps()) + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() mw = filter_design.launch(sys.argv, tb.update_filter) mw.show() tb.qapp.exec_() tb.stop() - - diff --git a/gr-filter/examples/gr_filtdes_restrict.py b/gr-filter/examples/gr_filtdes_restrict.py index e707895717d..7c734cbaf8a 100644 --- a/gr-filter/examples/gr_filtdes_restrict.py +++ b/gr-filter/examples/gr_filtdes_restrict.py @@ -22,13 +22,16 @@ Function called when "design" button is pressed or pole-zero plot is changed ''' + + def print_params(filtobj): print("Filter Count:", filtobj.get_filtercount()) print("Filter type:", filtobj.get_restype()) print("Filter params", filtobj.get_params()) print("Filter Coefficients", filtobj.get_taps()) + app = Qt.QApplication(sys.argv) -main_win = filter_design.launch(sys.argv, callback = print_params, restype = "iir") +main_win = filter_design.launch(sys.argv, callback=print_params, restype="iir") main_win.show() app.exec_() diff --git a/gr-filter/examples/interpolate.py b/gr-filter/examples/interpolate.py index 8674566e258..5f6f1a5f5c0 100644 --- a/gr-filter/examples/interpolate.py +++ b/gr-filter/examples/interpolate.py @@ -12,7 +12,8 @@ from gnuradio import blocks from gnuradio import filter from gnuradio.fft import window -import sys, time +import sys +import time import numpy try: @@ -25,9 +26,11 @@ import pylab from pylab import mlab except ImportError: - sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") + sys.stderr.write( + "Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) + class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) @@ -44,8 +47,8 @@ def __init__(self): # Create a set of taps for the PFB interpolator # This is based on the post-interpolation sample rate self._taps = filter.firdes.low_pass_2(self._interp, - self._interp*self._fs, - freq2+50, 50, + self._interp * self._fs, + freq2 + 50, 50, attenuation_dB=120, window=window.WIN_BLACKMAN_hARRIS) @@ -56,8 +59,8 @@ def __init__(self): # internally as an interpolator. flt_size = 32 self._taps2 = filter.firdes.low_pass_2(flt_size, - flt_size*self._fs, - freq2+50, 150, + flt_size * self._fs, + freq2 + 50, 150, attenuation_dB=120, window=window.WIN_BLACKMAN_hARRIS) @@ -68,8 +71,10 @@ def __init__(self): print("Taps per channel: ", tpc) # Create a couple of signals at different frequencies - self.signal1 = analog.sig_source_c(self._fs, analog.GR_SIN_WAVE, freq1, 0.5) - self.signal2 = analog.sig_source_c(self._fs, analog.GR_SIN_WAVE, freq2, 0.5) + self.signal1 = analog.sig_source_c( + self._fs, analog.GR_SIN_WAVE, freq1, 0.5) + self.signal2 = analog.sig_source_c( + self._fs, analog.GR_SIN_WAVE, freq2, 0.5) self.signal = blocks.add_cc() self.head = blocks.head(gr.sizeof_gr_complex, self._N) @@ -78,15 +83,16 @@ def __init__(self): self.pfb = filter.pfb.interpolator_ccf(self._interp, self._taps) # Construct the PFB arbitrary resampler filter - self.pfb_ar = filter.pfb.arb_resampler_ccf(self._ainterp, self._taps2, flt_size) + self.pfb_ar = filter.pfb.arb_resampler_ccf( + self._ainterp, self._taps2, flt_size) self.snk_i = blocks.vector_sink_c() - #self.pfb_ar.pfb.print_taps() - #self.pfb.pfb.print_taps() + # self.pfb_ar.pfb.print_taps() + # self.pfb.pfb.print_taps() # Connect the blocks - self.connect(self.signal1, self.head, (self.signal,0)) - self.connect(self.signal2, (self.signal,1)) + self.connect(self.signal1, self.head, (self.signal, 0)) + self.connect(self.signal2, (self.signal, 1)) self.connect(self.signal, self.pfb) self.connect(self.signal, self.pfb_ar) self.connect(self.signal, self.snk_i) @@ -106,11 +112,10 @@ def main(): tend = time.time() print("Run time: %f" % (tend - tstart)) - if 1: - fig1 = pylab.figure(1, figsize=(12,10), facecolor="w") - fig2 = pylab.figure(2, figsize=(12,10), facecolor="w") - fig3 = pylab.figure(3, figsize=(12,10), facecolor="w") + fig1 = pylab.figure(1, figsize=(12, 10), facecolor="w") + fig2 = pylab.figure(2, figsize=(12, 10), facecolor="w") + fig3 = pylab.figure(3, figsize=(12, 10), facecolor="w") Ns = 10000 Ne = 10000 @@ -121,25 +126,24 @@ def main(): # Plot input signal fs = tb._fs - d = tb.snk_i.data()[Ns:Ns+Ne] + d = tb.snk_i.data()[Ns:Ns + Ne] sp1_f = fig1.add_subplot(2, 1, 1) - X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, - window = lambda d: d*winfunc(fftlen), - scale_by_freq=True) - X_in = 10.0*numpy.log10(abs(numpy.fft.fftshift(X))) + X, freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, + window=lambda d: d * winfunc(fftlen), + scale_by_freq=True) + X_in = 10.0 * numpy.log10(abs(numpy.fft.fftshift(X))) f_in = numpy.arange(-fs / 2.0, fs / 2.0, fs / float(X_in.size)) p1_f = sp1_f.plot(f_in, X_in, "b") - sp1_f.set_xlim([min(f_in), max(f_in)+1]) + sp1_f.set_xlim([min(f_in), max(f_in) + 1]) sp1_f.set_ylim([-200.0, 50.0]) - sp1_f.set_title("Input Signal", weight="bold") sp1_f.set_xlabel("Frequency (Hz)") sp1_f.set_ylabel("Power (dBW)") Ts = 1.0 / fs - Tmax = len(d)*Ts + Tmax = len(d) * Ts t_in = numpy.arange(0, Tmax, Ts) x_in = numpy.array(d) @@ -152,19 +156,19 @@ def main(): sp1_t.set_xlabel("Time (s)") sp1_t.set_ylabel("Amplitude") - # Plot output of PFB interpolator - fs_int = tb._fs*tb._interp + fs_int = tb._fs * tb._interp sp2_f = fig2.add_subplot(2, 1, 1) - d = tb.snk1.data()[Ns:Ns+(tb._interp*Ne)] - X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, - window = lambda d: d*winfunc(fftlen), - scale_by_freq=True) - X_o = 10.0*numpy.log10(abs(numpy.fft.fftshift(X))) - f_o = numpy.arange(-fs_int / 2.0, fs_int / 2.0, fs_int / float(X_o.size)) + d = tb.snk1.data()[Ns:Ns + (tb._interp * Ne)] + X, freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, + window=lambda d: d * winfunc(fftlen), + scale_by_freq=True) + X_o = 10.0 * numpy.log10(abs(numpy.fft.fftshift(X))) + f_o = numpy.arange(-fs_int / 2.0, fs_int / 2.0, + fs_int / float(X_o.size)) p2_f = sp2_f.plot(f_o, X_o, "b") - sp2_f.set_xlim([min(f_o), max(f_o)+1]) + sp2_f.set_xlim([min(f_o), max(f_o) + 1]) sp2_f.set_ylim([-200.0, 50.0]) sp2_f.set_title("Output Signal from PFB Interpolator", weight="bold") @@ -172,7 +176,7 @@ def main(): sp2_f.set_ylabel("Power (dBW)") Ts_int = 1.0 / fs_int - Tmax = len(d)*Ts_int + Tmax = len(d) * Ts_int t_o = numpy.arange(0, Tmax, Ts_int) x_o1 = numpy.array(d) @@ -185,27 +189,28 @@ def main(): sp2_t.set_xlabel("Time (s)") sp2_t.set_ylabel("Amplitude") - # Plot output of PFB arbitrary resampler fs_aint = tb._fs * tb._ainterp sp3_f = fig3.add_subplot(2, 1, 1) - d = tb.snk2.data()[Ns:Ns+(tb._interp*Ne)] - X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, - window = lambda d: d*winfunc(fftlen), - scale_by_freq=True) - X_o = 10.0*numpy.log10(abs(numpy.fft.fftshift(X))) - f_o = numpy.arange(-fs_aint / 2.0, fs_aint / 2.0, fs_aint / float(X_o.size)) + d = tb.snk2.data()[Ns:Ns + (tb._interp * Ne)] + X, freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen / 4, Fs=fs, + window=lambda d: d * winfunc(fftlen), + scale_by_freq=True) + X_o = 10.0 * numpy.log10(abs(numpy.fft.fftshift(X))) + f_o = numpy.arange(-fs_aint / 2.0, fs_aint / 2.0, + fs_aint / float(X_o.size)) p3_f = sp3_f.plot(f_o, X_o, "b") - sp3_f.set_xlim([min(f_o), max(f_o)+1]) + sp3_f.set_xlim([min(f_o), max(f_o) + 1]) sp3_f.set_ylim([-200.0, 50.0]) - sp3_f.set_title("Output Signal from PFB Arbitrary Resampler", weight="bold") + sp3_f.set_title( + "Output Signal from PFB Arbitrary Resampler", weight="bold") sp3_f.set_xlabel("Frequency (Hz)") sp3_f.set_ylabel("Power (dBW)") Ts_aint = 1.0 / fs_aint - Tmax = len(d)*Ts_aint + Tmax = len(d) * Ts_aint t_o = numpy.arange(0, Tmax, Ts_aint) x_o2 = numpy.array(d) @@ -215,7 +220,8 @@ def main(): #p3_f = sp3_f.plot(t_o, x_o2.imag, "r-o") sp3_f.set_ylim([-2.5, 2.5]) - sp3_f.set_title("Output Signal from PFB Arbitrary Resampler", weight="bold") + sp3_f.set_title( + "Output Signal from PFB Arbitrary Resampler", weight="bold") sp3_f.set_xlabel("Time (s)") sp3_f.set_ylabel("Amplitude") @@ -227,4 +233,3 @@ def main(): main() except KeyboardInterrupt: pass - diff --git a/gr-filter/examples/reconstruction.py b/gr-filter/examples/reconstruction.py index a484d6a27a1..2a34f9e33fb 100644 --- a/gr-filter/examples/reconstruction.py +++ b/gr-filter/examples/reconstruction.py @@ -29,11 +29,12 @@ fftlen = 8192 + def main(): N = 10000 fs = 2000.0 Ts = 1.0 / fs - t = numpy.arange(0, N*Ts, Ts) + t = numpy.arange(0, N * Ts, Ts) # When playing with the number of channels, be careful about the filter # specs and the channel map of the synthesizer set below. @@ -42,19 +43,18 @@ def main(): # Build the filter(s) bw = 1000 tb = 400 - proto_taps = filter.firdes.low_pass_2(1, nchans*fs, + proto_taps = filter.firdes.low_pass_2(1, nchans * fs, bw, tb, 80, window.WIN_BLACKMAN_hARRIS) print("Filter length: ", len(proto_taps)) - # Create a modulated signal npwr = 0.01 data = numpy.random.randint(0, 256, N) rrc_taps = filter.firdes.root_raised_cosine(1, 2, 1, 0.35, 41) src = blocks.vector_source_b(data.astype(numpy.uint8).tolist(), False) - mod = digital.bpsk_mod(samples_per_symbol=2) + mod = digital.psk_mod(samples_per_symbol=2) chan = channels.channel_model(npwr) rrc = filter.fft_filter_ccc(1, rrc_taps) @@ -62,7 +62,7 @@ def main(): channelizer = filter.pfb.channelizer_ccf(nchans, proto_taps, 2) # Put the pieces back together again - syn_taps = [nchans*t for t in proto_taps] + syn_taps = [nchans * t for t in proto_taps] synthesizer = filter.pfb_synthesizer_ccf(nchans, syn_taps, True) src_snk = blocks.vector_sink_c() snk = blocks.vector_sink_c() @@ -70,7 +70,7 @@ def main(): # Remap the location of the channels # Can be done in synth or channelizer (watch out for rotattions in # the channelizer) - synthesizer.set_channel_map([ 0, 1, 2, 3, 4, + synthesizer.set_channel_map([0, 1, 2, 3, 4, 15, 16, 17, 18, 19]) tb = gr.top_block() @@ -79,34 +79,33 @@ def main(): vsnk = [] for i in range(nchans): - tb.connect((channelizer,i), (synthesizer, i)) + tb.connect((channelizer, i), (synthesizer, i)) vsnk.append(blocks.vector_sink_c()) - tb.connect((channelizer,i), vsnk[i]) + tb.connect((channelizer, i), vsnk[i]) tb.connect(synthesizer, snk) tb.run() - sin = numpy.array(src_snk.data()[1000:]) + sin = numpy.array(src_snk.data()[1000:]) sout = numpy.array(snk.data()[1000:]) - # Plot original signal - fs_in = nchans*fs - f1 = pyplot.figure(1, figsize=(16,12), facecolor='w') - s11 = f1.add_subplot(2,2,1) + fs_in = nchans * fs + f1 = pyplot.figure(1, figsize=(16, 12), facecolor='w') + s11 = f1.add_subplot(2, 2, 1) s11.psd(sin, NFFT=fftlen, Fs=fs_in) s11.set_title("PSD of Original Signal") s11.set_ylim([-200, -20]) - s12 = f1.add_subplot(2,2,2) + s12 = f1.add_subplot(2, 2, 2) s12.plot(sin.real[1000:1500], "o-b") s12.plot(sin.imag[1000:1500], "o-r") s12.set_title("Original Signal in Time") start = 1 - skip = 2 - s13 = f1.add_subplot(2,2,3) + skip = 2 + s13 = f1.add_subplot(2, 2, 3) s13.plot(sin.real[start::skip], sin.imag[start::skip], "o") s13.set_title("Constellation") s13.set_xlim([-2, 2]) @@ -116,29 +115,29 @@ def main(): nrows = int(numpy.sqrt(nchans)) ncols = int(numpy.ceil(float(nchans) / float(nrows))) - f2 = pyplot.figure(2, figsize=(16,12), facecolor='w') + f2 = pyplot.figure(2, figsize=(16, 12), facecolor='w') for n in range(nchans): - s = f2.add_subplot(nrows, ncols, n+1) + s = f2.add_subplot(nrows, ncols, n + 1) s.psd(vsnk[n].data(), NFFT=fftlen, Fs=fs_in) s.set_title("Channel {0}".format(n)) s.set_ylim([-200, -20]) # Plot reconstructed signal - fs_out = 2*nchans*fs - f3 = pyplot.figure(3, figsize=(16,12), facecolor='w') - s31 = f3.add_subplot(2,2,1) + fs_out = 2 * nchans * fs + f3 = pyplot.figure(3, figsize=(16, 12), facecolor='w') + s31 = f3.add_subplot(2, 2, 1) s31.psd(sout, NFFT=fftlen, Fs=fs_out) s31.set_title("PSD of Reconstructed Signal") s31.set_ylim([-200, -20]) - s32 = f3.add_subplot(2,2,2) + s32 = f3.add_subplot(2, 2, 2) s32.plot(sout.real[1000:1500], "o-b") s32.plot(sout.imag[1000:1500], "o-r") s32.set_title("Reconstructed Signal in Time") start = 0 - skip = 4 - s33 = f3.add_subplot(2,2,3) + skip = 4 + s33 = f3.add_subplot(2, 2, 3) s33.plot(sout.real[start::skip], sout.imag[start::skip], "o") s33.set_title("Constellation") s33.set_xlim([-2, 2]) @@ -152,4 +151,3 @@ def main(): main() except KeyboardInterrupt: pass - diff --git a/gr-filter/examples/resampler.py b/gr-filter/examples/resampler.py index 0208bac188d..282eaa1286f 100644 --- a/gr-filter/examples/resampler.py +++ b/gr-filter/examples/resampler.py @@ -23,15 +23,17 @@ try: from matplotlib import pyplot except ImportError: - sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") + sys.stderr.write( + "Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) + class mytb(gr.top_block): def __init__(self, fs_in, fs_out, fc, N=10000): gr.top_block.__init__(self) rerate = float(fs_out) / float(fs_in) - print("Resampling from %f to %f by %f " %(fs_in, fs_out, rerate)) + print("Resampling from %f to %f by %f " % (fs_in, fs_out, rerate)) # Creating our own taps taps = filter.firdes.low_pass_2(32, 32, 0.25, 0.1, 80) @@ -59,6 +61,7 @@ def __init__(self, fs_in, fs_out, fc, N=10000): self.connect(self.head, self.resamp_0, self.snk_0) self.connect(self.head, self.resamp_1, self.snk_1) + def main(): fs_in = 8000 fs_out = 20000 @@ -68,22 +71,21 @@ def main(): tb = mytb(fs_in, fs_out, fc, N) tb.run() - # Plot PSD of signals nfftsize = 2048 - fig1 = pyplot.figure(1, figsize=(10,10), facecolor="w") - sp1 = fig1.add_subplot(2,1,1) + fig1 = pyplot.figure(1, figsize=(10, 10), facecolor="w") + sp1 = fig1.add_subplot(2, 1, 1) sp1.psd(tb.snk_in.data(), NFFT=nfftsize, - noverlap=nfftsize / 4, Fs = fs_in) + noverlap=nfftsize / 4, Fs=fs_in) sp1.set_title(("Input Signal at f_s=%.2f kHz" % (fs_in / 1000.0))) sp1.set_xlim([-fs_in / 2, fs_in / 2]) - sp2 = fig1.add_subplot(2,1,2) + sp2 = fig1.add_subplot(2, 1, 2) sp2.psd(tb.snk_0.data(), NFFT=nfftsize, - noverlap=nfftsize / 4, Fs = fs_out, + noverlap=nfftsize / 4, Fs=fs_out, label="With our filter") sp2.psd(tb.snk_1.data(), NFFT=nfftsize, - noverlap=nfftsize / 4, Fs = fs_out, + noverlap=nfftsize / 4, Fs=fs_out, label="With auto-generated filter") sp2.set_title(("Output Signals at f_s=%.2f kHz" % (fs_out / 1000.0))) sp2.set_xlim([-fs_out / 2, fs_out / 2]) @@ -92,16 +94,16 @@ def main(): # Plot signals in time Ts_in = 1.0 / fs_in Ts_out = 1.0 / fs_out - t_in = numpy.arange(0, len(tb.snk_in.data())*Ts_in, Ts_in) - t_out = numpy.arange(0, len(tb.snk_0.data())*Ts_out, Ts_out) + t_in = numpy.arange(0, len(tb.snk_in.data()) * Ts_in, Ts_in) + t_out = numpy.arange(0, len(tb.snk_0.data()) * Ts_out, Ts_out) - fig2 = pyplot.figure(2, figsize=(10,10), facecolor="w") - sp21 = fig2.add_subplot(2,1,1) + fig2 = pyplot.figure(2, figsize=(10, 10), facecolor="w") + sp21 = fig2.add_subplot(2, 1, 1) sp21.plot(t_in, tb.snk_in.data()) sp21.set_title(("Input Signal at f_s=%.2f kHz" % (fs_in / 1000.0))) sp21.set_xlim([t_in[100], t_in[200]]) - sp22 = fig2.add_subplot(2,1,2) + sp22 = fig2.add_subplot(2, 1, 2) sp22.plot(t_out, tb.snk_0.data(), label="With our filter") sp22.plot(t_out, tb.snk_1.data(), @@ -113,6 +115,6 @@ def main(): pyplot.show() + if __name__ == "__main__": main() - diff --git a/gr-filter/examples/synth_filter.py b/gr-filter/examples/synth_filter.py index 2e8509feead..8c4f6e13ba4 100644 --- a/gr-filter/examples/synth_filter.py +++ b/gr-filter/examples/synth_filter.py @@ -23,9 +23,11 @@ try: from matplotlib import pyplot except ImportError: - sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") + sys.stderr.write( + "Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) + def main(): N = 1000000 fs = 8000 @@ -39,7 +41,7 @@ def main(): sigs.append(s) taps = filter.firdes.low_pass_2(len(freqs), fs, - fs/float(nchans)/2, 100, 100) + fs / float(nchans) / 2, 100, 100) print("Num. Taps = %d (taps per filter = %d)" % (len(taps), len(taps) / nchans)) filtbank = filter.pfb_synthesizer_ccf(nchans, taps) @@ -50,26 +52,27 @@ def main(): tb = gr.top_block() tb.connect(filtbank, head, snk) - for i,si in enumerate(sigs): + for i, si in enumerate(sigs): tb.connect(si, (filtbank, i)) tb.run() if 1: f1 = pyplot.figure(1) - s1 = f1.add_subplot(1,1,1) + s1 = f1.add_subplot(1, 1, 1) s1.plot(snk.data()[1000:]) fftlen = 2048 f2 = pyplot.figure(2) - s2 = f2.add_subplot(1,1,1) + s2 = f2.add_subplot(1, 1, 1) winfunc = numpy.blackman s2.psd(snk.data()[10000:], NFFT=fftlen, - Fs = nchans*fs, + Fs=nchans * fs, noverlap=fftlen / 4, - window = lambda d: d*winfunc(fftlen)) + window=lambda d: d * winfunc(fftlen)) pyplot.show() + if __name__ == "__main__": main() diff --git a/gr-filter/examples/synth_to_chan.py b/gr-filter/examples/synth_to_chan.py index 9a64e14ebf2..450197e09e8 100644 --- a/gr-filter/examples/synth_to_chan.py +++ b/gr-filter/examples/synth_to_chan.py @@ -23,9 +23,11 @@ try: from matplotlib import pyplot except ImportError: - sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") + sys.stderr.write( + "Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) + def main(): N = 1000000 fs = 8000 @@ -37,14 +39,17 @@ def main(): fmtx = list() for fi in freqs: s = analog.sig_source_f(fs, analog.GR_SIN_WAVE, fi, 1) - fm = analog.nbfm_tx(fs, 4*fs, max_dev=10000, tau=75e-6, fh=0.925*(4*fs)/2.0) + fm = analog.nbfm_tx(fs, 4 * fs, max_dev=10000, + tau=75e-6, fh=0.925 * (4 * fs) / 2.0) sigs.append(s) fmtx.append(fm) - syntaps = filter.firdes.low_pass_2(len(freqs), fs, fs/float(nchans)/2, 100, 100) + syntaps = filter.firdes.low_pass_2( + len(freqs), fs, fs / float(nchans) / 2, 100, 100) print("Synthesis Num. Taps = %d (taps per filter = %d)" % (len(syntaps), len(syntaps) / nchans)) - chtaps = filter.firdes.low_pass_2(len(freqs), fs, fs/float(nchans)/2, 100, 100) + chtaps = filter.firdes.low_pass_2( + len(freqs), fs, fs / float(nchans) / 2, 100, 100) print("Channelizer Num. Taps = %d (taps per filter = %d)" % (len(chtaps), len(chtaps) / nchans)) filtbank = filter.pfb_synthesizer_ccf(nchans, syntaps) @@ -58,13 +63,13 @@ def main(): tb = gr.top_block() - tb.connect(noise, (addnoise,0)) + tb.connect(noise, (addnoise, 0)) tb.connect(filtbank, head, (addnoise, 1)) tb.connect(addnoise, channelizer) tb.connect(addnoise, snk_synth) snk = list() - for i,si in enumerate(sigs): + for i, si in enumerate(sigs): tb.connect(si, fmtx[i], (filtbank, i)) for i in range(nchans): @@ -78,8 +83,8 @@ def main(): data = snk[channel].data()[1000:] f1 = pyplot.figure(1) - s1 = f1.add_subplot(1,1,1) - s1.plot(data[10000:10200] ) + s1 = f1.add_subplot(1, 1, 1) + s1.plot(data[10000:10200]) s1.set_title(("Output Signal from Channel %d" % channel)) fftlen = 2048 @@ -87,22 +92,23 @@ def main(): #winfunc = numpy.hamming f2 = pyplot.figure(2) - s2 = f2.add_subplot(1,1,1) + s2 = f2.add_subplot(1, 1, 1) s2.psd(data, NFFT=fftlen, - Fs = nchans*fs, + Fs=nchans * fs, noverlap=fftlen / 4, - window = lambda d: d*winfunc(fftlen)) + window=lambda d: d * winfunc(fftlen)) s2.set_title(("Output PSD from Channel %d" % channel)) f3 = pyplot.figure(3) - s3 = f3.add_subplot(1,1,1) + s3 = f3.add_subplot(1, 1, 1) s3.psd(snk_synth.data()[1000:], NFFT=fftlen, - Fs = nchans*fs, + Fs=nchans * fs, noverlap=fftlen / 4, - window = lambda d: d*winfunc(fftlen)) + window=lambda d: d * winfunc(fftlen)) s3.set_title("Output of Synthesis Filter") pyplot.show() + if __name__ == "__main__": main() diff --git a/gr-filter/python/filter/design/api_object.py b/gr-filter/python/filter/design/api_object.py index 2ba7afa7f50..cfcbdfcb3d3 100644 --- a/gr-filter/python/filter/design/api_object.py +++ b/gr-filter/python/filter/design/api_object.py @@ -12,15 +12,17 @@ class ApiObject(object): return multiple filter parameters in future e.g Cascaded Filters ''' - def __init__(self, filtcount = 1): + + def __init__(self, filtcount=1): self.filtercount = filtcount self.restype = [''] * self.filtercount - self.params = [''] * self.filtercount - self.taps = [''] * self.filtercount + self.params = [''] * self.filtercount + self.taps = [''] * self.filtercount ''' Updates params dictionary for the given filter number ''' + def update_params(self, params, filtno): if (filtno <= self.filtercount): self.params[filtno - 1] = params @@ -28,16 +30,17 @@ def update_params(self, params, filtno): ''' Updates filter type for the given filter number ''' + def update_filttype(self, filttype, filtno): if (filtno <= self.filtercount): self.filttype[filtno - 1] = filttype - ''' updates taps for the given filter number. taps will contain a list of coefficients in the case of fir design and (b,a) tuple in the case of iir design ''' + def update_taps(self, taps, filtno): if (filtno <= self.filtercount): self.taps[filtno - 1] = taps @@ -45,6 +48,7 @@ def update_taps(self, taps, filtno): ''' updates all of them in a single call ''' + def update_all(self, filttype, params, taps, filtno): if (filtno <= self.filtercount): self.taps[filtno - 1] = taps diff --git a/gr-filter/python/filter/design/filter_design.py b/gr-filter/python/filter/design/filter_design.py index 19ba6d5e871..fc3f69f9f7c 100644 --- a/gr-filter/python/filter/design/filter_design.py +++ b/gr-filter/python/filter/design/filter_design.py @@ -19,48 +19,56 @@ try: import numpy as np except ImportError: - raise SystemExit('Please install NumPy to run this script (https://www.np.org/)') + raise SystemExit( + 'Please install NumPy to run this script (https://www.np.org/)') try: import numpy.fft as fft_detail except ImportError: raise SystemExit('Could not import fft implementation of numpy') - + try: from numpy import poly1d except ImportError: - raise SystemExit('Please install NumPy to run this script (https://www.np.org)') + raise SystemExit( + 'Please install NumPy to run this script (https://www.np.org)') try: from scipy import signal except ImportError: - raise SystemExit('Please install SciPy to run this script (https://www.scipy.org)') + raise SystemExit( + 'Please install SciPy to run this script (https://www.scipy.org)') try: from PyQt5 import Qt, QtCore, QtWidgets except ImportError: - raise SystemExit('Please install PyQt5 to run this script (https://www.riverbankcomputing.com/software/pyqt/download5)') + raise SystemExit( + 'Please install PyQt5 to run this script (https://www.riverbankcomputing.com/software/pyqt/download5)') try: import pyqtgraph as pg except ImportError: - raise SystemExit('Please install pyqtgraph to run this script (http://www.pyqtgraph.org)') + raise SystemExit( + 'Please install pyqtgraph to run this script (http://www.pyqtgraph.org)') try: from gnuradio.filter.pyqt_filter_stacked import Ui_MainWindow except ImportError: - raise SystemExit('Could not import from pyqt_filter_stacked. Please build with "pyuic5 pyqt_filter_stacked.ui -o pyqt_filter_stacked.py"') + raise SystemExit( + 'Could not import from pyqt_filter_stacked. Please build with "pyuic5 pyqt_filter_stacked.ui -o pyqt_filter_stacked.py"') try: from gnuradio.filter.banditems import * except ImportError: - raise SystemExit('Could not import from banditems. Please check whether banditems.py is in the library path') + raise SystemExit( + 'Could not import from banditems. Please check whether banditems.py is in the library path') try: from gnuradio.filter.polezero_plot import * except ImportError: - raise SystemExit('Could not import from polezero_plot. Please check whether polezero_plot.py is in the library path') + raise SystemExit( + 'Could not import from polezero_plot. Please check whether polezero_plot.py is in the library path') # Behavior is not quite working on 3.8 - TODO # try: @@ -71,12 +79,14 @@ try: from gnuradio.filter.api_object import * except ImportError: - raise SystemExit('Could not import from api_object. Please check whether api_object.py is in the library path') + raise SystemExit( + 'Could not import from api_object. Please check whether api_object.py is in the library path') try: from gnuradio.filter.fir_design import * except ImportError: - raise SystemExit('Could not import from fir_design. Please check whether fir_design.py is in the library path') + raise SystemExit( + 'Could not import from fir_design. Please check whether fir_design.py is in the library path') try: _fromUtf8 = QtCore.QString.fromUtf8 @@ -84,6 +94,8 @@ def _fromUtf8(s): return s # Gnuradio Filter design tool main window + + class gr_plot_filter(QtGui.QMainWindow): def __init__(self, options, callback=None, restype=""): QtGui.QWidget.__init__(self, None) @@ -91,9 +103,12 @@ def __init__(self, options, callback=None, restype=""): self.callback = callback # Set Global pyqtgraph options - pg.setConfigOption('foreground', 'k') # Default foreground color for text, lines, axes, etc. - pg.setConfigOption('background', None) # Default background for GraphicsView. - pg.setConfigOptions(antialias=True) # Draw lines with smooth edges at the cost of reduced performance. + # Default foreground color for text, lines, axes, etc. + pg.setConfigOption('foreground', 'k') + # Default background for GraphicsView. + pg.setConfigOption('background', None) + # Draw lines with smooth edges at the cost of reduced performance. + pg.setConfigOptions(antialias=True) self.gui.setupUi(self) @@ -111,11 +126,16 @@ def __init__(self, options, callback=None, restype=""): self.gui.action_save.setEnabled(False) self.gui.action_open.triggered.connect(self.action_open_dialog) - self.gui.filterTypeComboBox.currentIndexChanged['const QString&'].connect(self.changed_filter_type) - self.gui.iirfilterBandComboBox.currentIndexChanged['const QString&'].connect(self.changed_iirfilter_band) - self.gui.filterDesignTypeComboBox.currentIndexChanged['const QString&'].connect(self.changed_filter_design_type) - self.gui.fselectComboBox.currentIndexChanged['const QString&'].connect(self.changed_fselect) - self.gui.iirfilterTypeComboBox.currentIndexChanged['const QString&'].connect(self.set_order) + self.gui.filterTypeComboBox.currentIndexChanged['const QString&'].connect( + self.changed_filter_type) + self.gui.iirfilterBandComboBox.currentIndexChanged['const QString&'].connect( + self.changed_iirfilter_band) + self.gui.filterDesignTypeComboBox.currentIndexChanged['const QString&'].connect( + self.changed_filter_design_type) + self.gui.fselectComboBox.currentIndexChanged['const QString&'].connect( + self.changed_fselect) + self.gui.iirfilterTypeComboBox.currentIndexChanged['const QString&'].connect( + self.set_order) self.gui.designButton.released.connect(self.design) @@ -127,11 +147,14 @@ def __init__(self, options, callback=None, restype=""): self.gui.actionSpec_Widget.triggered.connect(self.action_spec_widget) - self.gui.actionResponse_Widget.triggered.connect(self.action_response_widget) + self.gui.actionResponse_Widget.triggered.connect( + self.action_response_widget) - self.gui.actionDesign_Widget.triggered.connect(self.action_design_widget) + self.gui.actionDesign_Widget.triggered.connect( + self.action_design_widget) - self.gui.actionMagnitude_Response.triggered.connect(self.set_actmagresponse) + self.gui.actionMagnitude_Response.triggered.connect( + self.set_actmagresponse) self.gui.actionGrid_2.triggered.connect(self.set_actgrid) @@ -139,7 +162,8 @@ def __init__(self, options, callback=None, restype=""): self.gui.actionGroup_Delay.triggered.connect(self.set_actgdelay) - self.gui.actionFilter_Coefficients.triggered.connect(self.set_actfcoeff) + self.gui.actionFilter_Coefficients.triggered.connect( + self.set_actfcoeff) self.gui.actionBand_Diagram.triggered.connect(self.set_actband) @@ -212,9 +236,9 @@ def __init__(self, options, callback=None, restype=""): self.gui.checkStep.stateChanged['int'].connect(self.set_stepres) self.gridenable = False - self.mfoverlay = False - self.mtoverlay = False - self.iir = False + self.mfoverlay = False + self.mtoverlay = False + self.iir = False self.mfmagresponse = True self.mfphaseresponse = False @@ -225,7 +249,6 @@ def __init__(self, options, callback=None, restype=""): self.mtstep = False self.mtimpulse = False - self.gui.designButton.setShortcut(QtCore.Qt.Key_Return) self.taps = [] @@ -269,13 +292,12 @@ def __init__(self, options, callback=None, restype=""): self.plots['PDELAY'] = self.gui.pdelayPlot # for i in self.plots: - # self.plots[i] = pg.PlotWidget(enableMenu=False, viewBox=CustomViewBox()) - # self.plots[i].plotItem.vb = CustomViewBox() - + # self.plots[i] = pg.PlotWidget(enableMenu=False, viewBox=CustomViewBox()) + # self.plots[i].plotItem.vb = CustomViewBox() + self.mplots['mFREQ'] = self.gui.mfreqPlot self.mplots['mTIME'] = self.gui.mtimePlot - # for i in self.mplots: # self.mplots[i] = pg.PlotWidget(enableMenu=False, viewBox=CustomViewBox()) @@ -291,32 +313,48 @@ def __init__(self, options, callback=None, restype=""): # self.gui.mtimeTab.layout().addWidget(self.mplots['mTIME']) # Set Axis Labels. - self.labelstyle11b = {'font-family': 'Helvetica', 'font-size': '11pt', 'font-weight': 'bold'} + self.labelstyle11b = {'font-family': 'Helvetica', + 'font-size': '11pt', 'font-weight': 'bold'} - self.plots['FREQ'].setLabel('bottom', 'Frequency', units='Hz', **self.labelstyle11b) - self.plots['FREQ'].setLabel('left', 'Magnitude', units='dB', **self.labelstyle11b) + self.plots['FREQ'].setLabel( + 'bottom', 'Frequency', units='Hz', **self.labelstyle11b) + self.plots['FREQ'].setLabel( + 'left', 'Magnitude', units='dB', **self.labelstyle11b) - self.plots['TIME'].setLabel('bottom', 'Tap number', **self.labelstyle11b) + self.plots['TIME'].setLabel( + 'bottom', 'Tap number', **self.labelstyle11b) self.plots['TIME'].setLabel('left', 'Amplitude', **self.labelstyle11b) - self.plots['PHASE'].setLabel('bottom', 'Frequency', units='Hz', **self.labelstyle11b) - self.plots['PHASE'].setLabel('left', 'Phase', units='Radians', **self.labelstyle11b) + self.plots['PHASE'].setLabel( + 'bottom', 'Frequency', units='Hz', **self.labelstyle11b) + self.plots['PHASE'].setLabel( + 'left', 'Phase', units='Radians', **self.labelstyle11b) - self.plots['GROUP'].setLabel('bottom', 'Frequency', units='Hz', **self.labelstyle11b) - self.plots['GROUP'].setLabel('left', 'Delay', units='seconds', **self.labelstyle11b) + self.plots['GROUP'].setLabel( + 'bottom', 'Frequency', units='Hz', **self.labelstyle11b) + self.plots['GROUP'].setLabel( + 'left', 'Delay', units='seconds', **self.labelstyle11b) - self.plots['IMPRES'].setLabel('bottom', 'n', units='Samples', **self.labelstyle11b) - self.plots['IMPRES'].setLabel('left', 'Amplitude', **self.labelstyle11b) + self.plots['IMPRES'].setLabel( + 'bottom', 'n', units='Samples', **self.labelstyle11b) + self.plots['IMPRES'].setLabel( + 'left', 'Amplitude', **self.labelstyle11b) - self.plots['STEPRES'].setLabel('bottom', 'n', units='Samples', **self.labelstyle11b) - self.plots['STEPRES'].setLabel('left', 'Amplitude', **self.labelstyle11b) + self.plots['STEPRES'].setLabel( + 'bottom', 'n', units='Samples', **self.labelstyle11b) + self.plots['STEPRES'].setLabel( + 'left', 'Amplitude', **self.labelstyle11b) - self.plots['PDELAY'].setLabel('bottom', 'Frequency', units='Hz', **self.labelstyle11b) - self.plots['PDELAY'].setLabel('left', 'Phase Delay', units='Radians', **self.labelstyle11b) + self.plots['PDELAY'].setLabel( + 'bottom', 'Frequency', units='Hz', **self.labelstyle11b) + self.plots['PDELAY'].setLabel( + 'left', 'Phase Delay', units='Radians', **self.labelstyle11b) - self.labelstyle9b = {'font-family': 'Helvetica', 'font-size': '9pt', 'font-weight': 'bold'} + self.labelstyle9b = {'font-family': 'Helvetica', + 'font-size': '9pt', 'font-weight': 'bold'} - self.mplots['mTIME'].setLabel('bottom', 'n', units='Samples/taps', **self.labelstyle9b) + self.mplots['mTIME'].setLabel( + 'bottom', 'n', units='Samples/taps', **self.labelstyle9b) self.mplots['mTIME'].setLabel('left', 'Amplitude', **self.labelstyle9b) # Set up axes. @@ -336,9 +374,12 @@ def __init__(self, options, callback=None, restype=""): self.rcurve = self.plots['TIME'].plot(title="Real") self.icurve = self.plots['TIME'].plot(title="Imag") self.mtimecurve = self.mplots['mTIME'].plot(title="PSD") - self.mtimecurve_stems = self.mplots['mTIME'].plot(connect='pairs', name='Stems') - self.mtimecurve_i_stems = self.mplots['mTIME'].plot(connect='pairs', name='Stems') - self.mtimecurve_i = self.mplots['mTIME'].plot(title="Impulse Response Imag") + self.mtimecurve_stems = self.mplots['mTIME'].plot( + connect='pairs', name='Stems') + self.mtimecurve_i_stems = self.mplots['mTIME'].plot( + connect='pairs', name='Stems') + self.mtimecurve_i = self.mplots['mTIME'].plot( + title="Impulse Response Imag") self.plots['FREQ'].enableAutoRange(enable=True) self.freqcurve = self.plots['FREQ'].plot(title="PSD") @@ -348,38 +389,45 @@ def __init__(self, options, callback=None, restype=""): self.mfreqcurve = self.primary_freq_overlay.plot(title="PSD") self.secondary_freq_overlay_vb = CustomViewBox() self.primary_freq_overlay.scene().addItem(self.secondary_freq_overlay_vb) - self.primary_freq_overlay.getAxis('right').linkToView(self.secondary_freq_overlay_vb) + self.primary_freq_overlay.getAxis('right').linkToView( + self.secondary_freq_overlay_vb) self.mfreqcurve2 = pg.PlotCurveItem() # self.secondary_freq_overlay_vb.setGeometry(self.primary_freq_overlay.plotItem.vb.sceneBoundingRect()) self.secondary_freq_overlay_vb.setXLink(self.primary_freq_overlay) self.secondary_freq_overlay_vb.addItem(self.mfreqcurve2) - self.primary_freq_overlay.plotItem.vb.sigResized.connect(self.updateViews) + self.primary_freq_overlay.plotItem.vb.sigResized.connect( + self.updateViews) self.phasecurve = self.plots['PHASE'].plot(title="Phase") self.groupcurve = self.plots['GROUP'].plot(title="Group Delay") - self.imprescurve_stems = self.plots['IMPRES'].plot(connect='pairs', name='Stems') + self.imprescurve_stems = self.plots['IMPRES'].plot( + connect='pairs', name='Stems') self.imprescurve = self.plots['IMPRES'].plot(title="Impulse Response") - self.imprescurve_i_stems = self.plots['IMPRES'].plot(connect='pairs', name='Stems') + self.imprescurve_i_stems = self.plots['IMPRES'].plot( + connect='pairs', name='Stems') - self.imprescurve_i = self.plots['IMPRES'].plot(title="Impulse Response Imag") + self.imprescurve_i = self.plots['IMPRES'].plot( + title="Impulse Response Imag") - self.steprescurve_stems = self.plots['STEPRES'].plot(connect='pairs', name='Stems') + self.steprescurve_stems = self.plots['STEPRES'].plot( + connect='pairs', name='Stems') self.steprescurve = self.plots['STEPRES'].plot(title="Step Response") - self.steprescurve_i_stems = self.plots['STEPRES'].plot(connect='pairs', name='Stems') + self.steprescurve_i_stems = self.plots['STEPRES'].plot( + connect='pairs', name='Stems') - self.steprescurve_i = self.plots['STEPRES'].plot(title="Step Response Imag") + self.steprescurve_i = self.plots['STEPRES'].plot( + title="Step Response Imag") self.pdelaycurve = self.plots['PDELAY'].plot(title="Phase Delay") # Disable Ideal Band for now # self.idbanditems = IdealBandItems() - self.set_defaultpen() @@ -397,7 +445,7 @@ def __init__(self, options, callback=None, restype=""): # Populate the Band-diagram scene. self.scene = QtGui.QGraphicsScene() - self.scene.setSceneRect(0,0,250,250) + self.scene.setSceneRect(0, 0, 250, 250) lightback = QtGui.qRgb(0xf8, 0xf8, 0xff) backbrush = Qt.QBrush(Qt.QColor(lightback)) self.scene.setBackgroundBrush(backbrush) @@ -488,15 +536,13 @@ def __init__(self, options, callback=None, restype=""): self.gui.nTapsEdit.setText("0") - self.filterWindows = {"Hamming Window" : fft.window.WIN_HAMMING, - "Hann Window" : fft.window.WIN_HANN, - "Blackman Window" : fft.window.WIN_BLACKMAN, - "Rectangular Window" : fft.window.WIN_RECTANGULAR, - "Kaiser Window" : fft.window.WIN_KAISER, - "Blackman-harris Window" : fft.window.WIN_BLACKMAN_hARRIS} - self.EQUIRIPPLE_FILT = 6 # const for equiripple filter window types. - - + self.filterWindows = {"Hamming Window": fft.window.WIN_HAMMING, + "Hann Window": fft.window.WIN_HANN, + "Blackman Window": fft.window.WIN_BLACKMAN, + "Rectangular Window": fft.window.WIN_RECTANGULAR, + "Kaiser Window": fft.window.WIN_KAISER, + "Blackman-harris Window": fft.window.WIN_BLACKMAN_hARRIS} + self.EQUIRIPPLE_FILT = 6 # const for equiripple filter window types. # Disable functionality that is not quite working in 3.8 self.gui.checkKeepcur.setEnabled(False) @@ -506,7 +552,8 @@ def __init__(self, options, callback=None, restype=""): def updateViews(self): # for linking overlay graphs on GridView freq plots - self.secondary_freq_overlay_vb.setGeometry(self.primary_freq_overlay.plotItem.vb.sceneBoundingRect()) + self.secondary_freq_overlay_vb.setGeometry( + self.primary_freq_overlay.plotItem.vb.sceneBoundingRect()) # Set up curve pens, lines, and symbols. def set_defaultpen(self): @@ -584,7 +631,6 @@ def set_defaultpen(self): self.mtimecurve_i.setSymbolBrush(Qt.QBrush(Qt.Qt.gray)) self.mtimecurve_i.setSymbolSize(8) - def changed_fselect(self, ftype): if(ftype == "FIR"): self.gui.iirfilterTypeComboBox.hide() @@ -594,7 +640,8 @@ def changed_fselect(self, ftype): self.gui.globalParamsBox.show() self.gui.filterTypeComboBox.show() self.gui.filterTypeWidget.setCurrentWidget(self.gui.firlpfPage) - self.gui.tabGroup.addTab(self.gui.timeTab, _fromUtf8("Filter Taps")) + self.gui.tabGroup.addTab( + self.gui.timeTab, _fromUtf8("Filter Taps")) self.gui.mttapsPush.setEnabled(True) self.gui.addpolePush.setEnabled(False) self.gui.maddpolePush.setEnabled(False) @@ -606,54 +653,61 @@ def changed_fselect(self, ftype): self.gui.adComboBox.show() self.gui.iirfilterBandComboBox.show() self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirlpfPage) - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.timeTab)) + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.timeTab)) self.gui.mttapsPush.setEnabled(False) self.gui.addpolePush.setEnabled(True) self.gui.maddpolePush.setEnabled(True) -#self.design() +# self.design() def set_order(self, ftype): if(ftype == "Bessel"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) - self.changed_iirfilter_band(self.gui.iirfilterBandComboBox.currentText()) + self.changed_iirfilter_band( + self.gui.iirfilterBandComboBox.currentText()) else: - self.changed_iirfilter_band(self.gui.iirfilterBandComboBox.currentText()) + self.changed_iirfilter_band( + self.gui.iirfilterBandComboBox.currentText()) -#self.design() +# self.design() def changed_iirfilter_band(self, ftype): iirftype = self.gui.iirfilterTypeComboBox.currentText() if(ftype == "Low Pass"): if(iirftype == "Bessel"): - self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) + self.gui.filterTypeWidget.setCurrentWidget( + self.gui.iirbesselPage) self.gui.iirbesselcritLabel2.hide() self.gui.iirbesselcritEdit2.hide() else: self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirlpfPage) elif(ftype == "Band Pass"): if(iirftype == "Bessel"): - self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) + self.gui.filterTypeWidget.setCurrentWidget( + self.gui.iirbesselPage) self.gui.iirbesselcritLabel2.show() self.gui.iirbesselcritEdit2.show() else: self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbpfPage) elif(ftype == "Band Stop"): if(iirftype == "Bessel"): - self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) + self.gui.filterTypeWidget.setCurrentWidget( + self.gui.iirbesselPage) self.gui.iirbesselcritLabel2.show() self.gui.iirbesselcritEdit2.show() else: self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbsfPage) elif(ftype == "High Pass"): if(iirftype == "Bessel"): - self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) + self.gui.filterTypeWidget.setCurrentWidget( + self.gui.iirbesselPage) self.gui.iirbesselcritLabel2.hide() self.gui.iirbesselcritEdit2.hide() else: self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirhpfPage) -#self.design() +# self.design() def changed_filter_type(self, ftype): if(ftype == "Low Pass"): @@ -683,7 +737,7 @@ def changed_filter_type(self, ftype): elif(ftype == "Half Band"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.firhbPage) -#self.design() +# self.design() def changed_filter_design_type(self, design): if(design == "Equiripple"): @@ -691,7 +745,7 @@ def changed_filter_design_type(self, design): else: self.set_windowed() -#self.design() +# self.design() def set_equiripple(self): # Stop sending the signal for this function. @@ -746,7 +800,7 @@ def set_windowed(self): items = self.gui.filterTypeComboBox.count() for i in range(items): self.gui.filterTypeComboBox.removeItem(0) - + self.gui.filterTypeComboBox.addItems(self.firFilters) # If the last filter type was valid for this window type, @@ -762,9 +816,9 @@ def set_windowed(self): def design(self): ret = True - fs,r = getfloat(self.gui.sampleRateEdit.text()) + fs, r = getfloat(self.gui.sampleRateEdit.text()) ret = r and ret - gain,r = getfloat(self.gui.filterGainEdit.text()) + gain, r = getfloat(self.gui.filterGainEdit.text()) ret = r and ret winstr = self.gui.filterDesignTypeComboBox.currentText() @@ -772,7 +826,7 @@ def design(self): fsel = self.gui.fselectComboBox.currentText() if (fsel == "FIR"): - self.b, self.a = [],[] + self.b, self.a = [], [] if(ret): self.design_fir(ftype, fs, gain, winstr) elif (fsel.startswith("IIR")): @@ -791,25 +845,25 @@ def design_fir(self, ftype, fs, gain, winstr): self.cpicker.set_iir(False) self.cpicker2.set_iir(False) if(winstr == "Equiripple"): - designer = {"Low Pass" : design_opt_lpf, - "Band Pass" : design_opt_bpf, - "Complex Band Pass" : design_opt_cbpf, - "Band Notch" : design_opt_bnf, - "Half Band" : design_opt_hb, - "High Pass" : design_opt_hpf} - taps,params,r = designer[ftype](fs, gain, self) - - else: - designer = {"Low Pass" : design_win_lpf, - "Band Pass" : design_win_bpf, - "Complex Band Pass" : design_win_cbpf, - "Band Notch" : design_win_bnf, - "High Pass" : design_win_hpf, - "Half Band" : design_win_hb, - "Root Raised Cosine" : design_win_rrc, - "Gaussian" : design_win_gaus} + designer = {"Low Pass": design_opt_lpf, + "Band Pass": design_opt_bpf, + "Complex Band Pass": design_opt_cbpf, + "Band Notch": design_opt_bnf, + "Half Band": design_opt_hb, + "High Pass": design_opt_hpf} + taps, params, r = designer[ftype](fs, gain, self) + + else: + designer = {"Low Pass": design_win_lpf, + "Band Pass": design_win_bpf, + "Complex Band Pass": design_win_cbpf, + "Band Notch": design_win_bnf, + "High Pass": design_win_hpf, + "Half Band": design_win_hb, + "Root Raised Cosine": design_win_rrc, + "Gaussian": design_win_gaus} wintype = int(self.filterWindows[winstr]) - taps,params,r = designer[ftype](fs, gain, wintype, self) + taps, params, r = designer[ftype](fs, gain, wintype, self) if(r): if self.gridview: self.params = params @@ -818,7 +872,7 @@ def design_fir(self, ftype, fs, gain, winstr): self.set_mttaps() self.gui.nTapsEdit.setText(str(self.taps.size)) else: - self.draw_plots(taps,params) + self.draw_plots(taps, params) zeros = self.get_zeros() poles = self.get_poles() self.gui.pzPlot.insertZeros(zeros) @@ -847,46 +901,49 @@ def design_iir(self): self.cpicker.set_iir(True) self.cpicker2.set_iir(True) - iirft = {"Elliptic" : 'ellip', - "Butterworth" : 'butter', - "Chebyshev-1" : 'cheby1', - "Chebyshev-2" : 'cheby2', - "Bessel" : 'bessel' } + iirft = {"Elliptic": 'ellip', + "Butterworth": 'butter', + "Chebyshev-1": 'cheby1', + "Chebyshev-2": 'cheby2', + "Bessel": 'bessel'} - sanalog = {"Analog (rad/second)" : 1, - "Digital (normalized 0-1)" : 0 } + sanalog = {"Analog (rad/second)": 1, + "Digital (normalized 0-1)": 0} - paramtype = { 1 : "analog", - 0 : "digital" } + paramtype = {1: "analog", + 0: "digital"} iirabbr = { - "Low Pass" : "lpf", - "High Pass" : "hpf", - "Band Pass" : "bpf", - "Band Stop" : "bnf" } - - iirboxes = {"Low Pass" : [float(self.gui.iirendofLpfPassBandEdit.text()), - float(self.gui.iirstartofLpfStopBandEdit.text()), - float(self.gui.iirLpfPassBandAttenEdit.text()), - float(self.gui.iirLpfStopBandRippleEdit.text())], - - "High Pass" : [float(self.gui.iirstartofHpfPassBandEdit.text()), - float(self.gui.iirendofHpfStopBandEdit.text()), - float(self.gui.iirHpfPassBandAttenEdit.text()), - float(self.gui.iirHpfStopBandRippleEdit.text())], - - "Band Pass" : [float(self.gui.iirstartofBpfPassBandEdit.text()), - float(self.gui.iirendofBpfPassBandEdit.text()), - float(self.gui.iirendofBpfStopBandEdit1.text()), - float(self.gui.iirstartofBpfStopBandEdit2.text()), - float(self.gui.iirBpfPassBandAttenEdit.text()), - float(self.gui.iirBpfStopBandRippleEdit.text())], - - "Band Stop" : [float(self.gui.iirendofBsfPassBandEdit1.text()), - float(self.gui.iirstartofBsfPassBandEdit2.text()), - float(self.gui.iirstartofBsfStopBandEdit.text()), - float(self.gui.iirendofBsfStopBandEdit.text()), - float(self.gui.iirBsfPassBandAttenEdit.text()), - float(self.gui.iirBsfStopBandRippleEdit.text())] } + "Low Pass": "lpf", + "High Pass": "hpf", + "Band Pass": "bpf", + "Band Stop": "bnf"} + + iirboxes = {"Low Pass": [float(self.gui.iirendofLpfPassBandEdit.text()), + float(self.gui.iirstartofLpfStopBandEdit.text()), + float(self.gui.iirLpfPassBandAttenEdit.text()), + float(self.gui.iirLpfStopBandRippleEdit.text())], + + "High Pass": [float(self.gui.iirstartofHpfPassBandEdit.text()), + float(self.gui.iirendofHpfStopBandEdit.text()), + float(self.gui.iirHpfPassBandAttenEdit.text()), + float(self.gui.iirHpfStopBandRippleEdit.text())], + + "Band Pass": [float(self.gui.iirstartofBpfPassBandEdit.text()), + float(self.gui.iirendofBpfPassBandEdit.text()), + float(self.gui.iirendofBpfStopBandEdit1.text()), + float( + self.gui.iirstartofBpfStopBandEdit2.text()), + float(self.gui.iirBpfPassBandAttenEdit.text()), + float(self.gui.iirBpfStopBandRippleEdit.text())], + + "Band Stop": [float(self.gui.iirendofBsfPassBandEdit1.text()), + float( + self.gui.iirstartofBsfPassBandEdit2.text()), + float( + self.gui.iirstartofBsfStopBandEdit.text()), + float(self.gui.iirendofBsfStopBandEdit.text()), + float(self.gui.iirBsfPassBandAttenEdit.text()), + float(self.gui.iirBsfStopBandRippleEdit.text())]} # Remove Ideal band-diagrams if IIR. # self.set_drawideal() @@ -894,7 +951,7 @@ def design_iir(self): params.append(iirboxes[iirbtype][i]) if len(iirboxes[iirbtype]) == 6: - params = [params[:2],params[2:4],params[4],params[5]] + params = [params[:2], params[2:4], params[4], params[5]] if(iirftype == "Bessel"): if iirbtype == "Low Pass" or iirbtype == "High Pass": @@ -946,12 +1003,12 @@ def design_iir(self): self.callback(retobj) # IIR Filter design plot updates. - def iir_plot_all(self,z,p,k): - self.b,self.a = signal.zpk2tf(z,p,k) - w,h = signal.freqz(self.b,self.a) - self.fftdB = 20 * np.log10 (abs(h)) + def iir_plot_all(self, z, p, k): + self.b, self.a = signal.zpk2tf(z, p, k) + w, h = signal.freqz(self.b, self.a) + self.fftdB = 20 * np.log10(abs(h)) self.freq = w / max(w) - self.fftDeg = np.unwrap(np.arctan2(np.imag(h),np.real(h))) + self.fftDeg = np.unwrap(np.arctan2(np.imag(h), np.real(h))) self.groupDelay = -np.diff(self.fftDeg) self.phaseDelay = -self.fftDeg[1:] / self.freq[1:] if self.gridview: @@ -965,9 +1022,8 @@ def iir_plot_all(self,z,p,k): self.update_step_curves() self.update_imp_curves() - def nfft_edit_changed(self, nfft): - infft,r = getint(nfft) + infft, r = getint(nfft) if(r and (infft != self.nfftpts)): self.nfftpts = infft self.update_freq_curves() @@ -987,7 +1043,7 @@ def get_fft(self, fs, taps, Npts): self.freq = np.linspace(start=0, stop=fs, num=Npts, endpoint=False) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") - self.fftdB = 20.0*np.log10(abs(fftpts)) + self.fftdB = 20.0 * np.log10(abs(fftpts)) if any(self.fftdB == float('-inf')): sys.stderr.write('Filter design failed (taking log10 of 0).\n') self.fftdB = np.zeros([len(fftpts)]) @@ -1008,33 +1064,30 @@ def update_time_curves(self): self.icurve.setData(np.arange(ntaps), self.taps.imag) else: self.rcurve.setData(np.arange(ntaps), self.taps) - self.icurve.setData([],[]); + self.icurve.setData([], []) if self.mttaps: if(type(self.taps[0]) == scipy.complex128): self.mtimecurve_stems.setData(np.repeat(np.arange(ntaps), 2), - np.dstack((np.zeros(self.taps.real.shape[0], dtype=int), - self.taps.real)).flatten()) + np.dstack((np.zeros(self.taps.real.shape[0], dtype=int), + self.taps.real)).flatten()) self.mtimecurve.setData(np.arange(ntaps), self.taps.real) - self.mtimecurve_i_stems.setData(np.repeat(np.arange(ntaps), 2), np.dstack((np.zeros(self.taps.imag.shape[0], dtype=int), - self.taps.imag)).flatten()) + self.taps.imag)).flatten()) self.mtimecurve_i.setData(np.arange(ntaps), self.taps.imag) else: self.mtimecurve.setData(np.arange(ntaps), self.taps) self.mtimecurve_stems.setData(np.repeat(np.arange(ntaps), 2), - np.dstack((np.zeros(self.taps.shape[0], dtype=int), - self.taps)).flatten()) - - self.mtimecurve_i_stems.setData([],[]) - self.mtimecurve_i.setData([],[]) - + np.dstack((np.zeros(self.taps.shape[0], dtype=int), + self.taps)).flatten()) + self.mtimecurve_i_stems.setData([], []) + self.mtimecurve_i.setData([], []) # Configure plots. if self.mtoverlay: @@ -1055,7 +1108,7 @@ def update_step_curves(self): # Set Data. if self.iir: - stepres = self.step_response(self.b,self.a) + stepres = self.step_response(self.b, self.a) ntaps = 50 else: stepres = self.step_response(self.taps) @@ -1067,7 +1120,6 @@ def update_step_curves(self): self.steprescurve.setData(np.arange(ntaps), stepres.real) - self.steprescurve_i_stems.setData(np.repeat(np.arange(ntaps), 2), np.dstack((np.zeros(stepres.imag.shape[0], dtype=int), stepres.imag)).flatten()) @@ -1079,31 +1131,30 @@ def update_step_curves(self): stepres)).flatten()) self.steprescurve.setData(np.arange(ntaps), stepres) - self.steprescurve_i_stems.setData([],[]) - self.steprescurve_i.setData([],[]) + self.steprescurve_i_stems.setData([], []) + self.steprescurve_i.setData([], []) if self.mtstep: if(type(stepres[0]) == np.complex128): self.mtimecurve_stems.setData(np.repeat(np.arange(ntaps), 2), - np.dstack((np.zeros(stepres.real.shape[0], dtype=int), - stepres.real)).flatten()) + np.dstack((np.zeros(stepres.real.shape[0], dtype=int), + stepres.real)).flatten()) self.mtimecurve.setData(np.arange(ntaps), stepres.real) - self.mtimecurve_i_stems.setData(np.repeat(np.arange(ntaps), 2), np.dstack((np.zeros(stepres.imag.shape[0], dtype=int), - stepres.imag)).flatten()) + stepres.imag)).flatten()) self.mtimecurve_i.setData(np.arange(ntaps), stepres.imag) else: self.mtimecurve_stems.setData(np.repeat(np.arange(ntaps), 2), - np.dstack((np.zeros(stepres.shape[0], dtype=int), - stepres)).flatten()) + np.dstack((np.zeros(stepres.shape[0], dtype=int), + stepres)).flatten()) self.mtimecurve.setData(np.arange(ntaps), stepres) - self.mtimecurve_i_stems.setData([],[]) - self.mtimecurve_i.setData([],[]) + self.mtimecurve_i_stems.setData([], []) + self.mtimecurve_i.setData([], []) # Configure plots. if self.mtoverlay: @@ -1136,7 +1187,6 @@ def update_imp_curves(self): self.imprescurve.setData(np.arange(ntaps), impres.real) - self.imprescurve_i_stems.setData(np.repeat(np.arange(ntaps), 2), np.dstack((np.zeros(impres.imag.shape[0], dtype=int), impres.imag)).flatten()) @@ -1150,25 +1200,24 @@ def update_imp_curves(self): if self.mtimpulse: if(type(impres[0]) == np.complex128): self.mtimecurve_stems.setData(np.repeat(np.arange(ntaps), 2), - np.dstack((np.zeros(impres.real.shape[0], dtype=int), - impres.real)).flatten()) + np.dstack((np.zeros(impres.real.shape[0], dtype=int), + impres.real)).flatten()) self.mtimecurve.setData(np.arange(ntaps), impres.real) - self.mtimecurve_i_stems.setData(np.repeat(np.arange(ntaps), 2), np.dstack((np.zeros(impres.imag.shape[0], dtype=int), - impres.imag)).flatten()) + impres.imag)).flatten()) self.mtimecurve_i.setData(np.arange(ntaps), impres.imag) else: self.mtimecurve_stems.setData(np.repeat(np.arange(ntaps), 2), - np.dstack((np.zeros(impres.shape[0], dtype=int), - impres)).flatten()) + np.dstack((np.zeros(impres.shape[0], dtype=int), + impres)).flatten()) self.mtimecurve.setData(np.arange(ntaps), impres) - self.mtimecurve_i_stems.setData([],[]) - self.mtimecurve_i.setData([],[]) + self.mtimecurve_i_stems.setData([], []) + self.mtimecurve_i.setData([], []) # Configure plots. if self.mtoverlay: @@ -1196,11 +1245,11 @@ def plot_secondary(self): self.mfphasedelay = True self.update_pdelay_curves(True) - self.mplots['mFREQ'].showAxis('right', True) + self.mplots['mFREQ'].showAxis('right', True) else: self.mplots['mFREQ'].setMouseEnabled(x=False, y=False) - self.mplots['mFREQ'].showAxis('right', False) - self.mfreqcurve2.setData([],[]) + self.mplots['mFREQ'].showAxis('right', False) + self.mfreqcurve2.setData([], []) def update_freq_curves(self, secondary=False): npts = len(self.fftdB) @@ -1210,28 +1259,29 @@ def update_freq_curves(self, secondary=False): # Set Data. if self.iir: - self.freqcurve.setData(self.freq[:npts-1], self.fftdB[:npts-1]) + self.freqcurve.setData(self.freq[:npts - 1], self.fftdB[:npts - 1]) else: - self.freqcurve.setData(self.freq[:int(npts//2)], self.fftdB[:int(npts//2)]) + self.freqcurve.setData( + self.freq[:int(npts // 2)], self.fftdB[:int(npts // 2)]) if self.mfmagresponse: curve = self.mfreqcurve - if secondary: + if secondary: curve = self.mfreqcurve2 if self.iir: - curve.setData(self.freq[:npts-1], self.fftdB[:npts-1]) + curve.setData(self.freq[:npts - 1], self.fftdB[:npts - 1]) else: - curve.setData(self.freq[:int(npts//2)], self.fftdB[:int(npts//2)]) - + curve.setData(self.freq[:int(npts // 2)], + self.fftdB[:int(npts // 2)]) # Set axes to new scales. # Set plot limits and reset axis zoom. if self.iir: - xmax = self.freq[npts-1] + xmax = self.freq[npts - 1] else: - xmax = self.freq[npts//2] + xmax = self.freq[npts // 2] xmin = self.freq[0] @@ -1239,15 +1289,16 @@ def update_freq_curves(self, secondary=False): self.plot_auto_limit(self.mplots['mFREQ'], xMin=xmin, xMax=xmax) if secondary: - self.mplots['mFREQ'].setLabel('right', 'Magnitude', units='dB', **self.labelstyle9b) + self.mplots['mFREQ'].setLabel( + 'right', 'Magnitude', units='dB', **self.labelstyle9b) else: - self.mplots['mFREQ'].setLabel('left', 'Magnitude', units='dB', **self.labelstyle9b) + self.mplots['mFREQ'].setLabel( + 'left', 'Magnitude', units='dB', **self.labelstyle9b) if not secondary: self.plot_secondary() self.last_mfreq_plot = 'freq' - def update_phase_curves(self, secondary=False): npts = len(self.fftDeg) @@ -1256,27 +1307,28 @@ def update_phase_curves(self, secondary=False): # Set Data. if self.iir: - self.phasecurve.setData(self.freq[:npts-1], self.fftDeg[:npts-1]) + self.phasecurve.setData( + self.freq[:npts - 1], self.fftDeg[:npts - 1]) else: - self.phasecurve.setData(self.freq[:int(npts//2)], self.fftDeg[:int(npts//2)]) + self.phasecurve.setData( + self.freq[:int(npts // 2)], self.fftDeg[:int(npts // 2)]) if self.mfphaseresponse: curve = self.mfreqcurve - if secondary: + if secondary: curve = self.mfreqcurve2 if self.iir: - curve.setData(self.freq[:npts-1], self.fftDeg[:npts-1]) + curve.setData(self.freq[:npts - 1], self.fftDeg[:npts - 1]) else: - curve.setData(self.freq[:int(npts//2)], self.fftDeg[:int(npts//2)]) - - + curve.setData(self.freq[:int(npts // 2)], + self.fftDeg[:int(npts // 2)]) # Set plot limits and reset axis zoom. if self.iir: - xmax = self.freq[npts-1] + xmax = self.freq[npts - 1] else: - xmax = self.freq[npts//2] + xmax = self.freq[npts // 2] xmin = self.freq[0] @@ -1285,10 +1337,11 @@ def update_phase_curves(self, secondary=False): # Set Axis title. if secondary: - self.mplots['mFREQ'].setLabel('right', 'Phase', units='Radians', **self.labelstyle9b) + self.mplots['mFREQ'].setLabel( + 'right', 'Phase', units='Radians', **self.labelstyle9b) else: - self.mplots['mFREQ'].setLabel('left', 'Phase', units='Radians', **self.labelstyle9b) - + self.mplots['mFREQ'].setLabel( + 'left', 'Phase', units='Radians', **self.labelstyle9b) if not secondary: self.plot_secondary() @@ -1302,20 +1355,22 @@ def update_group_curves(self, secondary=False): # Set Data. if self.iir: - self.groupcurve.setData(self.freq[:npts-1], self.groupDelay[:npts-1]) + self.groupcurve.setData( + self.freq[:npts - 1], self.groupDelay[:npts - 1]) else: - self.groupcurve.setData(self.freq[:int(npts//2)], self.groupDelay[:int(npts//2)]) + self.groupcurve.setData( + self.freq[:int(npts // 2)], self.groupDelay[:int(npts // 2)]) if self.mfgroupdelay: curve = self.mfreqcurve - if secondary: + if secondary: curve = self.mfreqcurve2 if self.iir: - curve.setData(self.freq[:npts-1], self.groupDelay[:npts-1]) + curve.setData(self.freq[:npts - 1], self.groupDelay[:npts - 1]) else: - curve.setData(self.freq[:int(npts//2)], self.groupDelay[:int(npts//2)]) - + curve.setData(self.freq[:int(npts // 2)], + self.groupDelay[:int(npts // 2)]) # Configure plots. if self.mtoverlay: @@ -1326,9 +1381,9 @@ def update_group_curves(self, secondary=False): # Set plot limits and reset axis zoom. if self.iir: - xmax = self.freq[npts-1] + xmax = self.freq[npts - 1] else: - xmax = self.freq[npts//2] + xmax = self.freq[npts // 2] xmin = self.freq[0] @@ -1337,11 +1392,11 @@ def update_group_curves(self, secondary=False): # Set Axis title. if secondary: - self.mplots['mFREQ'].setLabel('right', 'Delay', units='seconds', **self.labelstyle9b) + self.mplots['mFREQ'].setLabel( + 'right', 'Delay', units='seconds', **self.labelstyle9b) else: - self.mplots['mFREQ'].setLabel('left', 'Delay', units='seconds', **self.labelstyle9b) - - + self.mplots['mFREQ'].setLabel( + 'left', 'Delay', units='seconds', **self.labelstyle9b) if not secondary: self.plot_secondary() @@ -1355,25 +1410,27 @@ def update_pdelay_curves(self, secondary=False): # Set Data. if self.iir: - self.pdelaycurve.setData(self.freq[:npts-1], self.phaseDelay[:npts-1]) + self.pdelaycurve.setData( + self.freq[:npts - 1], self.phaseDelay[:npts - 1]) else: - self.pdelaycurve.setData(self.freq[:int(npts//2)], self.phaseDelay[:int(npts//2)]) - + self.pdelaycurve.setData( + self.freq[:int(npts // 2)], self.phaseDelay[:int(npts // 2)]) + if self.mfphasedelay: curve = self.mfreqcurve - if secondary: + if secondary: curve = self.mfreqcurve2 if self.iir: - curve.setData(self.freq[:npts-1], self.phaseDelay[:npts-1]) + curve.setData(self.freq[:npts - 1], self.phaseDelay[:npts - 1]) else: - curve.setData(self.freq[:int(npts//2)], self.phaseDelay[:int(npts//2)]) - + curve.setData(self.freq[:int(npts // 2)], + self.phaseDelay[:int(npts // 2)]) # Set plot limits and reset axis zoom. if self.iir: - xmax = self.freq[npts-1] + xmax = self.freq[npts - 1] else: - xmax = self.freq[npts//2] + xmax = self.freq[npts // 2] xmin = self.freq[0] @@ -1382,9 +1439,11 @@ def update_pdelay_curves(self, secondary=False): # Set Axis title. if secondary: - self.mplots['mFREQ'].setLabel('right', 'Phase Delay', **self.labelstyle9b) + self.mplots['mFREQ'].setLabel( + 'right', 'Phase Delay', **self.labelstyle9b) else: - self.mplots['mFREQ'].setLabel('left', 'Phase Delay', **self.labelstyle9b) + self.mplots['mFREQ'].setLabel( + 'left', 'Phase Delay', **self.labelstyle9b) if not secondary: self.plot_secondary() @@ -1429,7 +1488,7 @@ def action_design_widget(self): # Saves and attach the plots for comparison. def set_bufferplots(self): - if (self.gui.checkKeepcur.checkState() == 0 ): + if (self.gui.checkKeepcur.checkState() == 0): # Detach and delete all plots if unchecked. for c in self.bufferplots: c.detach() @@ -1443,7 +1502,7 @@ def set_bufferplots(self): for item in page.children(): if isinstance(item, Qwt.QwtPlot): # Change colours as both plots overlay. - colours = [QtCore.Qt.darkYellow,QtCore.Qt.black] + colours = [QtCore.Qt.darkYellow, QtCore.Qt.black] for c in item.itemList(): if isinstance(c, Qwt.QwtPlotCurve): dup = Qwt.QwtPlotCurve() @@ -1455,7 +1514,8 @@ def set_bufferplots(self): del colours[0] dup.setPen(dpen) dup.setSymbol(dsym) - dup.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) + dup.setRenderHint( + Qwt.QwtPlotItem.RenderAntialiased) dup.setData([c.x(i) for i in range(c.dataSize())], [c.y(i) for i in range(c.dataSize())]) self.bufferplots.append(dup) @@ -1480,7 +1540,7 @@ def set_grid(self): self.plots[i].showGrid(x=True, y=True) def set_actgrid(self): - if (self.gui.actionGrid_2.isChecked() == 0 ): + if (self.gui.actionGrid_2.isChecked() == 0): self.gridenable = False for i in self.plots: @@ -1498,31 +1558,35 @@ def set_actgrid(self): self.plots[i].showGrid(x=True, y=True) def set_magresponse(self): - if (self.gui.checkMagres.checkState() == 0 ): + if (self.gui.checkMagres.checkState() == 0): self.magres = False - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.freqTab)) + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.freqTab)) else: self.magres = True - self.gui.tabGroup.addTab(self.gui.freqTab, _fromUtf8("Magnitude Response")) + self.gui.tabGroup.addTab( + self.gui.freqTab, _fromUtf8("Magnitude Response")) self.update_freq_curves() def set_actmagresponse(self): - if (self.gui.actionMagnitude_Response.isChecked() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.freqTab)) + if (self.gui.actionMagnitude_Response.isChecked() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.freqTab)) else: - self.gui.tabGroup.addTab(self.gui.freqTab, _fromUtf8("Magnitude Response")) + self.gui.tabGroup.addTab( + self.gui.freqTab, _fromUtf8("Magnitude Response")) self.update_freq_curves() def set_switchview(self): - if (self.gui.actionGridview.isChecked() == 0 ): + if (self.gui.actionGridview.isChecked() == 0): self.gridview = 0 self.set_defaultpen() self.set_actgrid() self.gui.stackedWindows.setCurrentIndex(0) if self.iir: - self.iir_plot_all(self.z,self.p,self.k) + self.iir_plot_all(self.z, self.p, self.k) else: - self.draw_plots(self.taps,self.params) + self.draw_plots(self.taps, self.params) else: self.gridview = 1 self.set_actgrid() @@ -1532,7 +1596,7 @@ def set_switchview(self): # self.set_drawideal() def set_plotselect(self): - if (self.gui.actionPlot_select.isChecked() == 0 ): + if (self.gui.actionPlot_select.isChecked() == 0): self.gui.mfgroupBox.hide() self.gui.mtgroupBox.hide() self.gui.pzgroupBox.hide() @@ -1568,7 +1632,6 @@ def set_mfmagresponse(self): self.mfgroupdelay = False self.mfphaseresponse = False - self.update_freq_curves() def set_mfphaseresponse(self): @@ -1608,13 +1671,13 @@ def set_mfphasedelay(self): self.update_pdelay_curves() - def ifinlist(self,a,dlist): + def ifinlist(self, a, dlist): for d in dlist: - if self.compare_instances(a,d): + if self.compare_instances(a, d): return True return False - def compare_instances(self,a,b): + def compare_instances(self, a, b): if a is b: return True else: @@ -1624,17 +1687,17 @@ def detach_firstattached(self, plot): items = plot.itemList() plot.enableAxis(Qwt.QwtPlot.yRight) if len(items) > 2: - yaxis=items[0].yAxis() + yaxis = items[0].yAxis() items[2].setPen(items[0].pen()) items[2].setYAxis(yaxis) items[0].detach() else: items[1].setYAxis(Qwt.QwtPlot.yRight) if plot is self.mplots['mFREQ']: - items[1].setPen(QtGui.QPen(QtCore.Qt.red, 1, QtCore.Qt.SolidLine)) + items[1].setPen(QtGui.QPen( + QtCore.Qt.red, 1, QtCore.Qt.SolidLine)) self.set_actgrid() - def update_fft(self, taps, params): self.params = params self.taps = np.array(taps) @@ -1692,63 +1755,77 @@ def set_mtimpulse(self): self.mttaps = False self.mtstep = False - self.update_imp_curves() - def set_gdelay(self): - if (self.gui.checkGdelay.checkState() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.groupTab)) + if (self.gui.checkGdelay.checkState() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.groupTab)) else: - self.gui.tabGroup.addTab(self.gui.groupTab, _fromUtf8("Group Delay")) + self.gui.tabGroup.addTab( + self.gui.groupTab, _fromUtf8("Group Delay")) self.update_freq_curves() def set_actgdelay(self): - if (self.gui.actionGroup_Delay.isChecked() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.groupTab)) + if (self.gui.actionGroup_Delay.isChecked() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.groupTab)) else: - self.gui.tabGroup.addTab(self.gui.groupTab, _fromUtf8("Group Delay")) + self.gui.tabGroup.addTab( + self.gui.groupTab, _fromUtf8("Group Delay")) self.update_freq_curves() def set_phase(self): - if (self.gui.checkPhase.checkState() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.phaseTab)) + if (self.gui.checkPhase.checkState() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.phaseTab)) else: - self.gui.tabGroup.addTab(self.gui.phaseTab, _fromUtf8("Phase Response")) + self.gui.tabGroup.addTab( + self.gui.phaseTab, _fromUtf8("Phase Response")) self.update_freq_curves() def set_actphase(self): - if (self.gui.actionPhase_Respone.isChecked() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.phaseTab)) + if (self.gui.actionPhase_Respone.isChecked() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.phaseTab)) else: - self.gui.tabGroup.addTab(self.gui.phaseTab, _fromUtf8("Phase Response")) + self.gui.tabGroup.addTab( + self.gui.phaseTab, _fromUtf8("Phase Response")) self.update_freq_curves() def set_fcoeff(self): - if (self.gui.checkFcoeff.checkState() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.fcTab)) + if (self.gui.checkFcoeff.checkState() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.fcTab)) else: - self.gui.tabGroup.addTab(self.gui.fcTab, _fromUtf8("Filter Coefficients")) + self.gui.tabGroup.addTab( + self.gui.fcTab, _fromUtf8("Filter Coefficients")) self.update_fcoeff() def set_actfcoeff(self): - if (self.gui.actionFilter_Coefficients.isChecked() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.fcTab)) + if (self.gui.actionFilter_Coefficients.isChecked() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.fcTab)) else: - self.gui.tabGroup.addTab(self.gui.fcTab, _fromUtf8("Filter Coefficients")) + self.gui.tabGroup.addTab( + self.gui.fcTab, _fromUtf8("Filter Coefficients")) self.update_fcoeff() def set_band(self): - if (self.gui.checkBand.checkState() == 0 ): - self.gui.filterspecView.removeTab(self.gui.filterspecView.indexOf(self.gui.bandDiagram)) + if (self.gui.checkBand.checkState() == 0): + self.gui.filterspecView.removeTab( + self.gui.filterspecView.indexOf(self.gui.bandDiagram)) else: - self.gui.filterspecView.addTab(self.gui.bandDiagram, _fromUtf8("Band Diagram")) + self.gui.filterspecView.addTab( + self.gui.bandDiagram, _fromUtf8("Band Diagram")) def set_actband(self): - if (self.gui.actionBand_Diagram.isChecked() == 0 ): - self.gui.filterspecView.removeTab(self.gui.filterspecView.indexOf(self.gui.bandDiagram)) + if (self.gui.actionBand_Diagram.isChecked() == 0): + self.gui.filterspecView.removeTab( + self.gui.filterspecView.indexOf(self.gui.bandDiagram)) else: - self.gui.filterspecView.addTab(self.gui.bandDiagram, _fromUtf8("Band Diagram")) + self.gui.filterspecView.addTab( + self.gui.bandDiagram, _fromUtf8("Band Diagram")) # def set_drawideal(self): # fsel = self.gui.fselectComboBox.currentText() @@ -1766,54 +1843,70 @@ def set_actband(self): # plot.replot() def set_pzplot(self): - if (self.gui.checkPzplot.checkState() == 0 ): - self.gui.filterspecView.removeTab(self.gui.filterspecView.indexOf(self.gui.poleZero)) + if (self.gui.checkPzplot.checkState() == 0): + self.gui.filterspecView.removeTab( + self.gui.filterspecView.indexOf(self.gui.poleZero)) else: - self.gui.filterspecView.addTab(self.gui.poleZero, _fromUtf8("Pole-Zero Plot")) + self.gui.filterspecView.addTab( + self.gui.poleZero, _fromUtf8("Pole-Zero Plot")) def set_actpzplot(self): - if (self.gui.actionPole_Zero_Plot_2.isChecked() == 0 ): - self.gui.filterspecView.removeTab(self.gui.filterspecView.indexOf(self.gui.poleZero)) + if (self.gui.actionPole_Zero_Plot_2.isChecked() == 0): + self.gui.filterspecView.removeTab( + self.gui.filterspecView.indexOf(self.gui.poleZero)) else: - self.gui.filterspecView.addTab(self.gui.poleZero, _fromUtf8("Pole-Zero Plot")) + self.gui.filterspecView.addTab( + self.gui.poleZero, _fromUtf8("Pole-Zero Plot")) def set_pdelay(self): - if (self.gui.checkPzplot.checkState() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.pdelayTab)) + if (self.gui.checkPzplot.checkState() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.pdelayTab)) else: - self.gui.tabGroup.addTab(self.gui.pdelayTab, _fromUtf8("Phase Delay")) + self.gui.tabGroup.addTab( + self.gui.pdelayTab, _fromUtf8("Phase Delay")) def set_actpdelay(self): - if (self.gui.actionPhase_Delay.isChecked() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.pdelayTab)) + if (self.gui.actionPhase_Delay.isChecked() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.pdelayTab)) else: - self.gui.tabGroup.addTab(self.gui.pdelayTab, _fromUtf8("Phase Delay")) + self.gui.tabGroup.addTab( + self.gui.pdelayTab, _fromUtf8("Phase Delay")) def set_impres(self): - if (self.gui.checkImpulse.checkState() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.impresTab)) + if (self.gui.checkImpulse.checkState() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.impresTab)) else: - self.gui.tabGroup.addTab(self.gui.impresTab, _fromUtf8("Impulse Response")) + self.gui.tabGroup.addTab( + self.gui.impresTab, _fromUtf8("Impulse Response")) def set_actimpres(self): - if (self.gui.actionImpulse_Response.isChecked() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.impresTab)) + if (self.gui.actionImpulse_Response.isChecked() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.impresTab)) else: - self.gui.tabGroup.addTab(self.gui.impresTab, _fromUtf8("Impulse Response")) + self.gui.tabGroup.addTab( + self.gui.impresTab, _fromUtf8("Impulse Response")) def set_stepres(self): - if (self.gui.checkStep.checkState() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.stepresTab)) + if (self.gui.checkStep.checkState() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.stepresTab)) else: - self.gui.tabGroup.addTab(self.gui.stepresTab, _fromUtf8("Step Response")) + self.gui.tabGroup.addTab( + self.gui.stepresTab, _fromUtf8("Step Response")) def set_actstepres(self): - if (self.gui.actionStep_Response.isChecked() == 0 ): - self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.stepresTab)) + if (self.gui.actionStep_Response.isChecked() == 0): + self.gui.tabGroup.removeTab( + self.gui.tabGroup.indexOf(self.gui.stepresTab)) else: - self.gui.tabGroup.addTab(self.gui.stepresTab, _fromUtf8("Step Response")) + self.gui.tabGroup.addTab( + self.gui.stepresTab, _fromUtf8("Step Response")) - def populate_bandview(self,fitems): + def populate_bandview(self, fitems): for item in fitems: if (item.isWidgetType()): self.scene.addWidget(item) @@ -1824,34 +1917,34 @@ def remove_bandview(self): for item in list(self.scene.items()): self.scene.removeItem(item) - def set_fatten(self,atten): + def set_fatten(self, atten): ftype = self.gui.filterTypeComboBox.currentText() if (ftype == "Low Pass"): - boxatten,r = getfloat(self.gui.lpfStopBandAttenEdit.text()) - self.gui.lpfStopBandAttenEdit.setText(str(atten+boxatten)) + boxatten, r = getfloat(self.gui.lpfStopBandAttenEdit.text()) + self.gui.lpfStopBandAttenEdit.setText(str(atten + boxatten)) if ftype == "High Pass": - boxatten,r = getfloat(self.gui.hpfStopBandAttenEdit.text()) - self.gui.hpfStopBandAttenEdit.setText(str(atten+boxatten)) + boxatten, r = getfloat(self.gui.hpfStopBandAttenEdit.text()) + self.gui.hpfStopBandAttenEdit.setText(str(atten + boxatten)) if ftype == "Band Pass": - boxatten,r = getfloat(self.gui.bpfStopBandAttenEdit.text()) - self.gui.bpfStopBandAttenEdit.setText(str(atten+boxatten)) + boxatten, r = getfloat(self.gui.bpfStopBandAttenEdit.text()) + self.gui.bpfStopBandAttenEdit.setText(str(atten + boxatten)) if ftype == "Band Notch": - boxatten,r = getfloat(self.gui.bnfStopBandAttenEdit.text()) - self.gui.bnfStopBandAttenEdit.setText(str(atten+boxatten)) + boxatten, r = getfloat(self.gui.bnfStopBandAttenEdit.text()) + self.gui.bnfStopBandAttenEdit.setText(str(atten + boxatten)) if ftype == "Complex Band Pass": - boxatten,r = getfloat(self.gui.bpfStopBandAttenEdit.text()) - self.gui.bpfStopBandAttenEdit.setText(str(atten+boxatten)) + boxatten, r = getfloat(self.gui.bpfStopBandAttenEdit.text()) + self.gui.bpfStopBandAttenEdit.setText(str(atten + boxatten)) def set_curvetaps(self, zeros_poles): zr, pl = zeros_poles if self.iir: self.z = zr self.p = pl - self.iir_plot_all(self.z,self.p,self.k) + self.iir_plot_all(self.z, self.p, self.k) self.gui.mpzPlot.insertZeros(zr) self.gui.mpzPlot.insertPoles(pl) self.update_fcoeff() @@ -1860,10 +1953,10 @@ def set_curvetaps(self, zeros_poles): retobj.update_all("iir", self.params, (self.b, self.a), 1) self.callback(retobj) else: - hz = poly1d(zr,r=1) + hz = poly1d(zr, r=1) # print hz.c. - self.taps = hz.c*self.taps[0] - self.draw_plots(self.taps,self.params) + self.taps = hz.c * self.taps[0] + self.draw_plots(self.taps, self.params) self.update_fcoeff() # update the pzplot in other view. zeros = self.get_zeros() @@ -1881,7 +1974,7 @@ def set_mcurvetaps(self, zeros_poles): if self.iir: self.z = zr self.p = pl - self.iir_plot_all(self.z,self.p,self.k) + self.iir_plot_all(self.z, self.p, self.k) self.gui.pzPlot.insertZeros(zr) self.gui.pzPlot.insertPoles(pl) self.update_fcoeff() @@ -1890,15 +1983,15 @@ def set_mcurvetaps(self, zeros_poles): retobj.update_all("iir", self.params, (self.b, self.a), 1) self.callback(retobj) else: - hz = poly1d(zr,r=1) + hz = poly1d(zr, r=1) # print hz.c. - self.taps = hz.c*self.taps[0] + self.taps = hz.c * self.taps[0] if self.gridview: self.update_fft(self.taps, self.params) self.set_mfmagresponse() self.set_mttaps() else: - self.draw_plots(self.taps,self.params) + self.draw_plots(self.taps, self.params) self.update_fcoeff() # update the pzplot in other view. zeros = self.get_zeros() @@ -1916,22 +2009,23 @@ def set_statusbar(self, point): if x == None: self.gui.pzstatusBar.showMessage("") else: - self.gui.pzstatusBar.showMessage("X: "+str(x)+" Y: "+str(y)) + self.gui.pzstatusBar.showMessage("X: " + str(x) + " Y: " + str(y)) def set_mstatusbar(self, point): x, y = point if x == None: self.gui.mpzstatusBar.showMessage("") else: - self.gui.mpzstatusBar.showMessage("X: "+str(x)+" Y: "+str(y)) + self.gui.mpzstatusBar.showMessage( + "X: " + str(x) + " Y: " + str(y)) def get_zeros(self): - hz = poly1d(self.taps,r=0) + hz = poly1d(self.taps, r=0) return hz.r def get_poles(self): if len(self.taps): - hp = zeros(len(self.taps)-1,complex) + hp = zeros(len(self.taps) - 1, complex) return hp else: return [] @@ -1958,40 +2052,44 @@ def step_response(self, b, a=1): return step def update_fcoeff(self): - fcoeff="" + fcoeff = "" if self.iir: - fcoeff="b = " + ','.join(str(e) for e in self.b) +"\na = " + ','.join(str(e) for e in self.a) + fcoeff = "b = " + \ + ','.join(str(e) for e in self.b) + "\na = " + \ + ','.join(str(e) for e in self.a) else: - fcoeff="taps = " + ','.join(str(e) for e in self.taps) + fcoeff = "taps = " + ','.join(str(e) for e in self.taps) self.gui.filterCoeff.setText(fcoeff) self.gui.mfilterCoeff.setText(fcoeff) def action_save_dialog(self): - file_dialog_output = QtGui.QFileDialog.getSaveFileName(self, "Save CSV Filter File", ".", "") + file_dialog_output = QtGui.QFileDialog.getSaveFileName( + self, "Save CSV Filter File", ".", "") filename = file_dialog_output[0] try: handle = open(filename, "w") except IOError: reply = QtGui.QMessageBox.information(self, 'File Name', - ("Could not save to file: %s" % filename), + ("Could not save to file: %s" % + filename), QtGui.QMessageBox.Ok) return csvhandle = csv.writer(handle, delimiter=",") # Indicate FIR/IIR for easy reading. if self.iir: - csvhandle.writerow(["restype","iir"]) + csvhandle.writerow(["restype", "iir"]) else: - csvhandle.writerow(["restype","fir"]) + csvhandle.writerow(["restype", "fir"]) for k in list(self.params.keys()): csvhandle.writerow([k, self.params[k]]) if self.iir: - csvhandle.writerow(["b",] + list(self.b)) - csvhandle.writerow(["a",] + list(self.a)) + csvhandle.writerow(["b", ] + list(self.b)) + csvhandle.writerow(["a", ] + list(self.a)) else: - csvhandle.writerow(["taps",] + list(self.taps)) + csvhandle.writerow(["taps", ] + list(self.taps)) handle.close() self.gui.action_save.setEnabled(False) # Iterate through all plots and delete the curves @@ -2005,7 +2103,8 @@ def action_save_dialog(self): self.replot_all() def action_open_dialog(self): - file_dialog_output = QtGui.QFileDialog.getOpenFileName(self, "Open CSV Filter File", ".", "") + file_dialog_output = QtGui.QFileDialog.getOpenFileName( + self, "Open CSV Filter File", ".", "") if(len(file_dialog_output) == 0): return # file_dialog_output returns tuple of (filename, file filter) @@ -2014,12 +2113,13 @@ def action_open_dialog(self): handle = open(filename, "r") except IOError: reply = QtGui.QMessageBox.information(self, 'File Name', - ("Could not open file: %s" % filename), + ("Could not open file: %s" % + filename), QtGui.QMessageBox.Ok) return csvhandle = csv.reader(handle, delimiter=",") - b_a={} + b_a = {} taps = [] params = {} for row in csvhandle: @@ -2027,22 +2127,22 @@ def action_open_dialog(self): restype = row[1] elif(row[0] == "taps"): testcpx = re.findall(r"[+-]?\d+\.*\d*[Ee]?[-+]?\d+j", row[1]) - if(len(testcpx) > 0): # it's a complex + if(len(testcpx) > 0): # it's a complex taps = [complex(r) for r in row[1:]] else: taps = [float(r) for r in row[1:]] elif(row[0] == "b" or row[0] == "a"): testcpx = re.findall(r"[+-]?\d+\.*\d*[Ee]?[-+]?\d+j", row[1]) - if(len(testcpx) > 0): # it's a complex + if(len(testcpx) > 0): # it's a complex b_a[row[0]] = [complex(r) for r in row[1:]] else: - b_a[row[0]]= [float(r) for r in row[1:]] + b_a[row[0]] = [float(r) for r in row[1:]] else: testcpx = re.findall(r"[+-]?\d+\.*\d*[Ee]?[-+]?\d+j", row[1]) - if(len(testcpx) > 0): # it's a complex + if(len(testcpx) > 0): # it's a complex params[row[0]] = complex(row[1]) - else: # assume it's a float. - try: # if it's not a float, its a string. + else: # assume it's a float. + try: # if it's not a float, its a string. params[row[0]] = float(row[1]) except ValueError: params[row[0]] = row[1] @@ -2066,133 +2166,152 @@ def action_open_dialog(self): # Set up GUI parameters for each filter type. if(params["filttype"] == "lpf"): self.gui.filterTypeComboBox.setCurrentIndex(0) - self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) + self.gui.filterDesignTypeComboBox.setCurrentIndex( + int(params["wintype"])) self.gui.endofLpfPassBandEdit.setText(str(params["pbend"])) self.gui.startofLpfStopBandEdit.setText(str(params["sbstart"])) self.gui.lpfStopBandAttenEdit.setText(str(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): - self.gui.lpfPassBandRippleEdit.setText(str(params["ripple"])) + self.gui.lpfPassBandRippleEdit.setText( + str(params["ripple"])) elif(params["filttype"] == "bpf"): self.gui.filterTypeComboBox.setCurrentIndex(1) - self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) + self.gui.filterDesignTypeComboBox.setCurrentIndex( + int(params["wintype"])) self.gui.startofBpfPassBandEdit.setText(str(params["pbstart"])) self.gui.endofBpfPassBandEdit.setText(str(params["pbend"])) self.gui.bpfTransitionEdit.setText(str(params["tb"])) self.gui.bpfStopBandAttenEdit.setText(str(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): - self.gui.bpfPassBandRippleEdit.setText(str(params["ripple"])) + self.gui.bpfPassBandRippleEdit.setText( + str(params["ripple"])) elif(params["filttype"] == "cbpf"): self.gui.filterTypeComboBox.setCurrentIndex(2) - self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) + self.gui.filterDesignTypeComboBox.setCurrentIndex( + int(params["wintype"])) self.gui.startofBpfPassBandEdit.setText(str(params["pbstart"])) self.gui.endofBpfPassBandEdit.setText(str(params["pbend"])) self.gui.bpfTransitionEdit.setText(str(params["tb"])) self.gui.bpfStopBandAttenEdit.setText(str(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): - self.gui.bpfPassBandRippleEdit.setText(str(params["ripple"])) + self.gui.bpfPassBandRippleEdit.setText( + str(params["ripple"])) elif(params["filttype"] == "bnf"): self.gui.filterTypeComboBox.setCurrentIndex(3) - self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) + self.gui.filterDesignTypeComboBox.setCurrentIndex( + int(params["wintype"])) self.gui.startofBnfStopBandEdit.setText(str(params["sbstart"])) self.gui.endofBnfStopBandEdit.setText(str(params["sbend"])) self.gui.bnfTransitionEdit.setText(str(params["tb"])) self.gui.bnfStopBandAttenEdit.setText(str(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): - self.gui.bnfPassBandRippleEdit.setText(str(params["ripple"])) + self.gui.bnfPassBandRippleEdit.setText( + str(params["ripple"])) elif(params["filttype"] == "hpf"): self.gui.filterTypeComboBox.setCurrentIndex(4) - self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) + self.gui.filterDesignTypeComboBox.setCurrentIndex( + int(params["wintype"])) self.gui.endofHpfStopBandEdit.setText(str(params["sbend"])) self.gui.startofHpfPassBandEdit.setText(str(params["pbstart"])) self.gui.hpfStopBandAttenEdit.setText(str(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): - self.gui.hpfPassBandRippleEdit.setText(str(params["ripple"])) + self.gui.hpfPassBandRippleEdit.setText( + str(params["ripple"])) elif(params["filttype"] == "rrc"): self.gui.filterTypeComboBox.setCurrentIndex(5) - self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) + self.gui.filterDesignTypeComboBox.setCurrentIndex( + int(params["wintype"])) self.gui.rrcSymbolRateEdit.setText(str(params["srate"])) self.gui.rrcAlphaEdit.setText(str(params["alpha"])) self.gui.rrcNumTapsEdit.setText(str(params["ntaps"])) elif(params["filttype"] == "gaus"): self.gui.filterTypeComboBox.setCurrentIndex(6) - self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) + self.gui.filterDesignTypeComboBox.setCurrentIndex( + int(params["wintype"])) self.gui.gausSymbolRateEdit.setText(str(params["srate"])) self.gui.gausBTEdit.setText(str(params["bt"])) self.gui.gausNumTapsEdit.setText(str(params["ntaps"])) else: self.iir = True - self.b, self.a = b_a["b"],b_a["a"] - (self.z,self.p,self.k) = signal.tf2zpk(self.b, self.a) + self.b, self.a = b_a["b"], b_a["a"] + (self.z, self.p, self.k) = signal.tf2zpk(self.b, self.a) self.gui.pzPlot.insertZeros(self.z) self.gui.pzPlot.insertPoles(self.p) self.gui.mpzPlot.insertZeros(self.z) self.gui.mpzPlot.insertPoles(self.p) - self.iir_plot_all(self.z,self.p,self.k) + self.iir_plot_all(self.z, self.p, self.k) self.update_fcoeff() self.gui.nTapsEdit.setText("-") self.params = params # Set GUI for IIR type. - iirft = { "ellip" : 0, - "butter" : 1, - "cheby1" : 2, - "cheby2" : 3, - "bessel" : 4 } - - paramtype = { "analog" : 1, - "digital" : 0 } + iirft = {"ellip": 0, + "butter": 1, + "cheby1": 2, + "cheby2": 3, + "bessel": 4} + + paramtype = {"analog": 1, + "digital": 0} bandpos = { - "lpf" : 0, - "bpf" : 1, - "bnf" : 2, - "hpf" : 3} - - iirboxes = {"lpf" : [self.gui.iirendofLpfPassBandEdit, - self.gui.iirstartofLpfStopBandEdit, - self.gui.iirLpfPassBandAttenEdit, - self.gui.iirLpfStopBandRippleEdit], - - "hpf" : [self.gui.iirstartofHpfPassBandEdit, - self.gui.iirendofHpfStopBandEdit, - self.gui.iirHpfPassBandAttenEdit, - self.gui.iirHpfStopBandRippleEdit], - - "bpf" : [self.gui.iirstartofBpfPassBandEdit, - self.gui.iirendofBpfPassBandEdit, - self.gui.iirendofBpfStopBandEdit1, - self.gui.iirstartofBpfStopBandEdit2, - self.gui.iirBpfPassBandAttenEdit, - self.gui.iirBpfStopBandRippleEdit], - - "bnf" : [self.gui.iirendofBsfPassBandEdit1, - self.gui.iirstartofBsfPassBandEdit2, - self.gui.iirstartofBsfStopBandEdit, - self.gui.iirendofBsfStopBandEdit, - self.gui.iirBsfPassBandAttenEdit, - self.gui.iirBsfStopBandRippleEdit] } + "lpf": 0, + "bpf": 1, + "bnf": 2, + "hpf": 3} + + iirboxes = {"lpf": [self.gui.iirendofLpfPassBandEdit, + self.gui.iirstartofLpfStopBandEdit, + self.gui.iirLpfPassBandAttenEdit, + self.gui.iirLpfStopBandRippleEdit], + + "hpf": [self.gui.iirstartofHpfPassBandEdit, + self.gui.iirendofHpfStopBandEdit, + self.gui.iirHpfPassBandAttenEdit, + self.gui.iirHpfStopBandRippleEdit], + + "bpf": [self.gui.iirstartofBpfPassBandEdit, + self.gui.iirendofBpfPassBandEdit, + self.gui.iirendofBpfStopBandEdit1, + self.gui.iirstartofBpfStopBandEdit2, + self.gui.iirBpfPassBandAttenEdit, + self.gui.iirBpfStopBandRippleEdit], + + "bnf": [self.gui.iirendofBsfPassBandEdit1, + self.gui.iirstartofBsfPassBandEdit2, + self.gui.iirstartofBsfStopBandEdit, + self.gui.iirendofBsfStopBandEdit, + self.gui.iirBsfPassBandAttenEdit, + self.gui.iirBsfStopBandRippleEdit]} self.gui.fselectComboBox.setCurrentIndex(1) - self.gui.iirfilterTypeComboBox.setCurrentIndex(iirft[params["filttype"]]) - self.gui.iirfilterBandComboBox.setCurrentIndex(bandpos[params["bandtype"]]) + self.gui.iirfilterTypeComboBox.setCurrentIndex( + iirft[params["filttype"]]) + self.gui.iirfilterBandComboBox.setCurrentIndex( + bandpos[params["bandtype"]]) if params["filttype"] == "bessel": - critfreq = [float(x) for x in params["critfreq"][1:-1].split(',')] + critfreq = [float(x) + for x in params["critfreq"][1:-1].split(',')] self.gui.besselordEdit.setText(str(params["filtord"])) self.gui.iirbesselcritEdit1.setText(str(critfreq[0])) self.gui.iirbesselcritEdit2.setText(str(critfreq[1])) else: - self.gui.adComboBox.setCurrentIndex(paramtype[params["paramtype"]]) + self.gui.adComboBox.setCurrentIndex( + paramtype[params["paramtype"]]) if len(iirboxes[params["bandtype"]]) == 4: - sdata = [params["pbedge"], params["sbedge"], params["gpass"], params["gstop"]] + sdata = [params["pbedge"], params["sbedge"], + params["gpass"], params["gstop"]] else: - pbedge = list(map(float, params["pbedge"][1:-1].split(','))) - sbedge = list(map(float, params["sbedge"][1:-1].split(','))) + pbedge = list( + map(float, params["pbedge"][1:-1].split(','))) + sbedge = list( + map(float, params["sbedge"][1:-1].split(','))) sdata = [pbedge[0], pbedge[1], sbedge[0], sbedge[1], params["gpass"], params["gstop"]] @@ -2234,16 +2353,17 @@ def mouseDragEvent(self, ev): def setup_options(): - usage="%prog: [options] (input_filename)" + usage = "%prog: [options] (input_filename)" description = "" parser = OptionParser(conflict_handler="resolve", usage=usage, description=description) return parser + def launch(args, callback=None, restype=""): parser = setup_options() - (options, args) = parser.parse_args () + (options, args) = parser.parse_args() if callback is None: app = Qt.QApplication(args) @@ -2261,9 +2381,10 @@ def launch(args, callback=None, restype=""): gplt = gr_plot_filter(options, callback, restype) return gplt + def main(args): parser = setup_options() - (options, args) = parser.parse_args () + (options, args) = parser.parse_args() app = Qt.QApplication(args) gplt = gr_plot_filter(options) @@ -2271,5 +2392,6 @@ def main(args): app.deleteLater() sys.exit() + if __name__ == '__main__': main(sys.argv) diff --git a/gr-filter/python/filter/design/fir_design.py b/gr-filter/python/filter/design/fir_design.py index 64236e5a31b..11beb9cdbf2 100644 --- a/gr-filter/python/filter/design/fir_design.py +++ b/gr-filter/python/filter/design/fir_design.py @@ -27,7 +27,7 @@ def design_win_lpf(fs, gain, wintype, mainwin): try: taps = filter.firdes.low_pass_2(gain, fs, pb, tb, atten, wintype) - except (RuntimeError, IndexError) as e: + except (RuntimeError, IndexError) as e: reply = QtGui.QMessageBox.information(mainwin, "Runtime Error", e.args[0], QtGui.QMessageBox.Ok) return ([], [], ret) @@ -169,7 +169,8 @@ def design_win_hb(fs, gain, wintype, mainwin): return ([], [], False) if(ret): - taps = scipy.signal.firwin(int(filtord)+1, 0.5, window=filtwin[wintype]) + taps = scipy.signal.firwin( + int(filtord) + 1, 0.5, window=filtwin[wintype]) taps[abs(taps) <= 1e-6] = 0. params = {"fs": fs, "gain": gain, "wintype": wintype, "filttype": "hb", "ntaps": len(taps)} @@ -371,8 +372,8 @@ def design_opt_hb(fs, gain, mainwin): if(ret): try: - bands = [0, .25 - (trwidth/fs), .25 + (trwidth/fs), 0.5] - taps = scipy.signal.remez(int(filtord)+1, bands, [1, 0], [1, 1]) + bands = [0, .25 - (trwidth / fs), .25 + (trwidth / fs), 0.5] + taps = scipy.signal.remez(int(filtord) + 1, bands, [1, 0], [1, 1]) taps[abs(taps) <= 1e-6] = 0. except RuntimeError as e: reply = QtGui.QMessageBox.information(mainwin, "Filter Design Error", diff --git a/gr-filter/python/filter/file_taps_loader.py b/gr-filter/python/filter/file_taps_loader.py index 8bdff1efd41..87e4e1ab548 100644 --- a/gr-filter/python/filter/file_taps_loader.py +++ b/gr-filter/python/filter/file_taps_loader.py @@ -16,10 +16,12 @@ import numpy as np from gnuradio import gr + class file_taps_loader(gr.basic_block): """ Block to make filter taps created by the filter design tool available in grc. """ + def __init__(self, fpath, verbose): gr.basic_block.__init__( self, @@ -38,35 +40,40 @@ def taps_from_design_tool(self, fpath): Load a file that was generated with the filter design tool """ if not os.path.isfile(self.fpath): - raise RuntimeError(self.name() + ": Can not open " + "\"" + fpath + "\"" + ".") + raise RuntimeError( + self.name() + ": Can not open " + "\"" + fpath + "\"" + ".") with open(fpath) as csvfile: readcsv = csv.reader(csvfile, delimiter=',') for row in readcsv: if row[0] == "taps": regex = re.findall(r"[+-]?\d+\.*\d*[Ee]?[-+]?\d+j", row[1]) - if regex: # it's a complex + if regex: # it's a complex # string to complex so numpy eats the taps cpx_row = [complex(x) for x in row[1:]] self.taps = tuple(np.array(cpx_row, dtype=complex)) - self.print_if(self.name() + ": Found complex taps in the file provided.\n") + self.print_if( + self.name() + ": Found complex taps in the file provided.\n") else: self.taps = tuple(np.array(row[1:], dtype=float)) - self.print_if(self.name() + ": Found real taps in the file provided.\n") + self.print_if( + self.name() + ": Found real taps in the file provided.\n") else: regex = re.findall(r"[+-]?\d+\.*\d*[Ee]?[-+]?\d+j", row[0]) - if regex: # it's a complex + if regex: # it's a complex # string to complex so numpy eats the taps cpx_row = [complex(x) for x in row[0:]] self.taps = tuple(np.array(cpx_row, dtype=complex)) - self.print_if(self.name() + ": Found complex taps in the file provided.\n") + self.print_if( + self.name() + ": Found complex taps in the file provided.\n") else: try: self.taps = tuple(np.array(row[0:], dtype=float)) - self.print_if(self.name() + ": Found real taps in the file provided.\n") + self.print_if( + self.name() + ": Found real taps in the file provided.\n") except ValueError: self.params.append(row) self.print_if( - self.name() + \ + self.name() + ": Loaded a filter with the following parameters (gr_filter_design format): \n") for param in self.params: self.print_if(param[0], ' ', param[1], '\n') diff --git a/gr-filter/python/filter/filterbank.py b/gr-filter/python/filter/filterbank.py index 39e39e5d24d..afce5cb67fd 100644 --- a/gr-filter/python/filter/filterbank.py +++ b/gr-filter/python/filter/filterbank.py @@ -13,6 +13,7 @@ from gnuradio import blocks from .filter_python import fft_filter_ccc + def _generate_synthesis_taps(mpoints): return [] # FIXME @@ -31,6 +32,7 @@ class synthesis_filterbank(gr.hier_block2): See http://cnx.org/content/m10424/latest """ + def __init__(self, mpoints, taps=None): """ Takes M complex streams in, produces single complex stream out @@ -75,10 +77,10 @@ def __init__(self, mpoints, taps=None): """ item_size = gr.sizeof_gr_complex gr.hier_block2.__init__(self, "synthesis_filterbank", - gr.io_signature(mpoints, mpoints, item_size), # Input signature + # Input signature + gr.io_signature(mpoints, mpoints, item_size), gr.io_signature(1, 1, item_size)) # Output signature - if taps is None: taps = _generate_synthesis_taps(mpoints) @@ -109,12 +111,14 @@ def __init__(self, mpoints, taps=None): self.connect(self.ss2s, self) + class analysis_filterbank(gr.hier_block2): """ Uniformly modulated polyphase DFT filter bank: analysis See http://cnx.org/content/m10424/latest """ + def __init__(self, mpoints, taps=None): """ Takes 1 complex stream in, produces M complex streams out @@ -128,8 +132,9 @@ def __init__(self, mpoints, taps=None): """ item_size = gr.sizeof_gr_complex gr.hier_block2.__init__(self, "analysis_filterbank", - gr.io_signature(1, 1, item_size), # Input signature - gr.io_signature(mpoints, mpoints, item_size)) # Output signature + # Input signature + gr.io_signature(1, 1, item_size), + gr.io_signature(mpoints, mpoints, item_size)) # Output signature if taps is None: taps = _generate_synthesis_taps(mpoints) @@ -154,7 +159,7 @@ def __init__(self, mpoints, taps=None): # build mpoints fir filters... for i in range(mpoints): - f = fft_filter_ccc(1, sub_taps[mpoints-i-1]) + f = fft_filter_ccc(1, sub_taps[mpoints - i - 1]) self.connect((self.s2ss, i), f) self.connect(f, (self.ss2v, i)) self.connect((self.v2ss, i), (self, i)) diff --git a/gr-filter/python/filter/freq_xlating_fft_filter.py b/gr-filter/python/filter/freq_xlating_fft_filter.py index af5541f2a78..55c0d1797a5 100644 --- a/gr-filter/python/filter/freq_xlating_fft_filter.py +++ b/gr-filter/python/filter/freq_xlating_fft_filter.py @@ -15,7 +15,7 @@ from .filter_python import fft_filter_ccc -__all__ = [ 'freq_xlating_fft_filter_ccc' ] +__all__ = ['freq_xlating_fft_filter_ccc'] class freq_xlating_fft_filter_ccc(gr.hier_block2): @@ -29,10 +29,10 @@ def __init__(self, decim, taps, center_freq, samp_rate): ) # Save args - self.decim = decim - self.taps = taps + self.decim = decim + self.taps = taps self.center_freq = center_freq - self.samp_rate = samp_rate + self.samp_rate = samp_rate # Sub blocks self._filter = fft_filter_ccc(decim, taps) @@ -44,7 +44,7 @@ def __init__(self, decim, taps, center_freq, samp_rate): self._refresh() def _rotate_taps(self, taps, phase_inc): - return [ x * cmath.exp(i * phase_inc * 1j) for i,x in enumerate(taps) ] + return [x * cmath.exp(i * phase_inc * 1j) for i, x in enumerate(taps)] def _refresh(self): phase_inc = (2.0 * math.pi * self.center_freq) / self.samp_rate diff --git a/gr-filter/python/filter/gui/CustomViewBox.py b/gr-filter/python/filter/gui/CustomViewBox.py index 40e3b2f9377..4920f723827 100644 --- a/gr-filter/python/filter/gui/CustomViewBox.py +++ b/gr-filter/python/filter/gui/CustomViewBox.py @@ -1,6 +1,7 @@ import pyqtgraph as pg from PyQt5 import QtCore + class CustomViewBox(pg.ViewBox): def __init__(self, *args, **kwds): pg.ViewBox.__init__(self, *args, **kwds) diff --git a/gr-filter/python/filter/gui/GrFilterPlotWidget.py b/gr-filter/python/filter/gui/GrFilterPlotWidget.py index 93793c3562f..48db5ae76bb 100644 --- a/gr-filter/python/filter/gui/GrFilterPlotWidget.py +++ b/gr-filter/python/filter/gui/GrFilterPlotWidget.py @@ -3,10 +3,11 @@ class GrFilterPlotWidget(PlotWidget): - def __init__(self,parent=None, background='default', **kargs): - PlotWidget.__init__(self,parent,background,enableMenu=False,viewBox=CustomViewBox()) + def __init__(self, parent=None, background='default', **kargs): + PlotWidget.__init__(self, parent, background, + enableMenu=False, viewBox=CustomViewBox()) def drop_plotdata(self): for plitem in self.items(): - if isinstance(plitem, (graphicsItems.PlotCurveItem.PlotCurveItem, graphicsItems.ScatterPlotItem.ScatterPlotItem,graphicsItems.PlotDataItem.PlotDataItem)): + if isinstance(plitem, (graphicsItems.PlotCurveItem.PlotCurveItem, graphicsItems.ScatterPlotItem.ScatterPlotItem, graphicsItems.PlotDataItem.PlotDataItem)): plitem.clear() diff --git a/gr-filter/python/filter/gui/bandgraphicsview.py b/gr-filter/python/filter/gui/bandgraphicsview.py index 8c8f523116f..ccc78dce45b 100644 --- a/gr-filter/python/filter/gui/bandgraphicsview.py +++ b/gr-filter/python/filter/gui/bandgraphicsview.py @@ -8,9 +8,11 @@ from PyQt5 import QtWidgets, QtCore, Qt + class BandGraphicsView(QtWidgets.QGraphicsView): def resizeEvent(self, event): self.setAlignment(Qt.Qt.AlignCenter) - self.fitInView(self.scene().itemsBoundingRect(), QtCore.Qt.KeepAspectRatio) - self.scale(1.3,1.3) - self.setViewportMargins(10,10,10,10) + self.fitInView(self.scene().itemsBoundingRect(), + QtCore.Qt.KeepAspectRatio) + self.scale(1.3, 1.3) + self.setViewportMargins(10, 10, 10, 10) diff --git a/gr-filter/python/filter/gui/banditems.py b/gr-filter/python/filter/gui/banditems.py index 4fc0071a775..15303300de1 100644 --- a/gr-filter/python/filter/gui/banditems.py +++ b/gr-filter/python/filter/gui/banditems.py @@ -10,7 +10,8 @@ try: from PyQt5 import Qt, QtCore, QtGui except ImportError: - raise SystemExit('Please install PyQt5 to run this script (http://www.riverbankcomputing.co.uk/software/pyqt/download)') + raise SystemExit( + 'Please install PyQt5 to run this script (http://www.riverbankcomputing.co.uk/software/pyqt/download)') # Movable solid line for filter ideal-band diagram. @@ -31,12 +32,12 @@ def __init__(self, x1, y1, x2, y2, lower, upper, split=False, sx1=0, sy1=0, sx2= def paint(self, painter, option, widget): painter.setPen(QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)) painter.drawLine(self.x1, self.y1, self.x2, self.y2) - painter.drawLine(self.x1, self.y1, self.x1, self.y1-5) - painter.drawLine(self.x2, self.y2, self.x2, self.y2-5) + painter.drawLine(self.x1, self.y1, self.x1, self.y1 - 5) + painter.drawLine(self.x2, self.y2, self.x2, self.y2 - 5) if self.split: painter.drawLine(self.sx1, self.sy1, self.sx2, self.sy2) - painter.drawLine(self.sx1, self.sy1, self.sx1, self.sy1-5) - painter.drawLine(self.sx2, self.sy2, self.sx2, self.sy2-5) + painter.drawLine(self.sx1, self.sy1, self.sx1, self.sy1 - 5) + painter.drawLine(self.sx2, self.sy2, self.sx2, self.sy2 - 5) def boundingRect(self): return QtCore.QRectF(0, 0, 400, 400) @@ -189,7 +190,8 @@ def boundingRect(self): hpfItems.append(hpfsLines()) # bpfitems list. -bpfItems.append(filtermovlineItem(6, 175, 110, 175, 0, -60, True, 300, 175, 400, 175)) +bpfItems.append(filtermovlineItem(6, 175, 110, 175, + 0, -60, True, 300, 175, 400, 175)) bpfItems[0].setFlags(QtGui.QGraphicsItem.ItemIsSelectable | QtGui.QGraphicsItem.ItemIsMovable | QtGui.QGraphicsItem.ItemSendsGeometryChanges) bpfItems.append(bpfsLines()) diff --git a/gr-filter/python/filter/gui/icons_rc.py b/gr-filter/python/filter/gui/icons_rc.py index eaa388ebe3f..272aed1b630 100644 --- a/gr-filter/python/filter/gui/icons_rc.py +++ b/gr-filter/python/filter/gui/icons_rc.py @@ -2412,10 +2412,15 @@ rcc_version = 2 qt_resource_struct = qt_resource_struct_v2 + def qInitResources(): - QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + QtCore.qRegisterResourceData( + rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + def qCleanupResources(): - QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + QtCore.qUnregisterResourceData( + rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + qInitResources() diff --git a/gr-filter/python/filter/gui/idealbanditems.py b/gr-filter/python/filter/gui/idealbanditems.py index 65a4d100446..ac0af5d3013 100644 --- a/gr-filter/python/filter/gui/idealbanditems.py +++ b/gr-filter/python/filter/gui/idealbanditems.py @@ -15,9 +15,12 @@ class IdealBandItems(object): def __init__(self): # Set Global pyqtgraph options - pg.setConfigOption('foreground', 'k') # Default foreground color for text, lines, axes, etc. - pg.setConfigOption('background', None) # Default background for GraphicsView. - pg.setConfigOptions(antialias=True) # Draw lines with smooth edges at the cost of reduced performance. + # Default foreground color for text, lines, axes, etc. + pg.setConfigOption('foreground', 'k') + # Default background for GraphicsView. + pg.setConfigOption('background', None) + # Draw lines with smooth edges at the cost of reduced performance. + pg.setConfigOptions(antialias=True) self.win = pg.GraphicsWindow() self.plot = self.win.addPlot() @@ -36,139 +39,142 @@ def plotIdealCurves(self, ftype, params, plot): try: if (ftype == "Low Pass"): self.detach_unwantedcurves(plot) - x=[0, self.params["pbend"]] - y=[20.0*numpy.log10(self.params["gain"])]*2 + x = [0, self.params["pbend"]] + y = [20.0 * numpy.log10(self.params["gain"])] * 2 self.idealbandhcurves[0].setData(x, y) - x=[self.params["pbend"]]*2 - y=[20.0*numpy.log10(self.params["gain"]), - plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] + x = [self.params["pbend"]] * 2 + y = [20.0 * numpy.log10(self.params["gain"]), + plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) - x = [self.params["sbstart"], self.params["fs"]/2.0] - y = [-self.params["atten"]]*2 + x = [self.params["sbstart"], self.params["fs"] / 2.0] + y = [-self.params["atten"]] * 2 self.idealbandhcurves[1].setData(x, y) - x = [self.params["sbstart"]]*2 + x = [self.params["sbstart"]] * 2 y = [-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) elif ftype == "High Pass": self.detach_unwantedcurves(plot) - x=[self.params["pbstart"],self.params["fs"] / 2.0] - y=[20.0*numpy.log10(self.params["gain"])]*2 + x = [self.params["pbstart"], self.params["fs"] / 2.0] + y = [20.0 * numpy.log10(self.params["gain"])] * 2 self.idealbandhcurves[0].setData(x, y) - x=[self.params["pbstart"]]*2 - y=[20.0*numpy.log10(self.params["gain"]), - plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] + x = [self.params["pbstart"]] * 2 + y = [20.0 * numpy.log10(self.params["gain"]), + plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) x = [0, self.params["sbend"]] - y = [-self.params["atten"]]*2 + y = [-self.params["atten"]] * 2 self.idealbandhcurves[1].setData(x, y) - x = [self.params["sbend"]]*2 + x = [self.params["sbend"]] * 2 y = [-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) elif ftype == "Band Notch": x = [self.params["sbstart"], self.params["sbend"]] - y = [-self.params["atten"]]*2 + y = [-self.params["atten"]] * 2 self.idealbandhcurves[0].setData(x, y) - x = [self.params["sbstart"]]*2 + x = [self.params["sbstart"]] * 2 y = [-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) - x = [self.params["sbend"]]*2 + x = [self.params["sbend"]] * 2 y = [-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) - x=[0,self.params["sbstart"]-self.params["tb"]] - y=[20.0*numpy.log10(self.params["gain"])]*2 + x = [0, self.params["sbstart"] - self.params["tb"]] + y = [20.0 * numpy.log10(self.params["gain"])] * 2 self.idealbandhcurves[1].setData(x, y) - x=[self.params["sbstart"]-self.params["tb"]]*2 - y=[20.0*numpy.log10(self.params["gain"]), - plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] + x = [self.params["sbstart"] - self.params["tb"]] * 2 + y = [20.0 * numpy.log10(self.params["gain"]), + plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[2].setData(x, y) - x=[self.params["sbend"]+self.params["tb"],self.params["fs"] / 2.0] - y=[20.0*numpy.log10(self.params["gain"])]*2 + x = [self.params["sbend"] + self.params["tb"], + self.params["fs"] / 2.0] + y = [20.0 * numpy.log10(self.params["gain"])] * 2 self.idealbandhcurves[2].setData(x, y) - x=[self.params["sbend"]+self.params["tb"]]*2 - y=[20.0*numpy.log10(self.params["gain"]), - plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] + x = [self.params["sbend"] + self.params["tb"]] * 2 + y = [20.0 * numpy.log10(self.params["gain"]), + plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[3].setData(x, y) elif ftype == "Band Pass": - x=[self.params["pbstart"],self.params["pbend"]] - y=[20.0*numpy.log10(self.params["gain"])]*2 + x = [self.params["pbstart"], self.params["pbend"]] + y = [20.0 * numpy.log10(self.params["gain"])] * 2 self.idealbandhcurves[0].setData(x, y) - x=[self.params["pbstart"]]*2 - y=[20.0*numpy.log10(self.params["gain"]), - plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] + x = [self.params["pbstart"]] * 2 + y = [20.0 * numpy.log10(self.params["gain"]), + plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) - x=[self.params["pbend"]]*2 - y=[20.0*numpy.log10(self.params["gain"]), - plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] + x = [self.params["pbend"]] * 2 + y = [20.0 * numpy.log10(self.params["gain"]), + plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) - x = [0, self.params["pbstart"]-self.params["tb"]] - y = [-self.params["atten"]]*2 + x = [0, self.params["pbstart"] - self.params["tb"]] + y = [-self.params["atten"]] * 2 self.idealbandhcurves[1].setData(x, y) - x = [self.params["pbstart"]-self.params["tb"]]*2 + x = [self.params["pbstart"] - self.params["tb"]] * 2 y = [-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[2].setData(x, y) - x = [self.params["pbend"]+self.params["tb"], self.params["fs"]/2.0] - y = [-self.params["atten"]]*2 + x = [self.params["pbend"] + self.params["tb"], + self.params["fs"] / 2.0] + y = [-self.params["atten"]] * 2 self.idealbandhcurves[2].setData(x, y) - x = [self.params["pbend"]+self.params["tb"]]*2 + x = [self.params["pbend"] + self.params["tb"]] * 2 y = [-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[3].setData(x, y) elif ftype == "Complex Band Pass": - x=[self.params["pbstart"],self.params["pbend"]] - y=[20.0*numpy.log10(self.params["gain"])]*2 + x = [self.params["pbstart"], self.params["pbend"]] + y = [20.0 * numpy.log10(self.params["gain"])] * 2 self.idealbandhcurves[0].setData(x, y) - x=[self.params["pbstart"]]*2 - y=[20.0*numpy.log10(self.params["gain"]), - plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] + x = [self.params["pbstart"]] * 2 + y = [20.0 * numpy.log10(self.params["gain"]), + plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) - x=[self.params["pbend"]]*2 - y=[20.0*numpy.log10(self.params["gain"]), - plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] + x = [self.params["pbend"]] * 2 + y = [20.0 * numpy.log10(self.params["gain"]), + plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) - x = [0, self.params["pbstart"]-self.params["tb"]] - y = [-self.params["atten"]]*2 + x = [0, self.params["pbstart"] - self.params["tb"]] + y = [-self.params["atten"]] * 2 self.idealbandhcurves[1].setData(x, y) - x = [self.params["pbstart"]-self.params["tb"]]*2 + x = [self.params["pbstart"] - self.params["tb"]] * 2 y = [-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[2].setData(x, y) - x = [self.params["pbend"]+self.params["tb"], self.params["fs"]/2.0] - y = [-self.params["atten"]]*2 + x = [self.params["pbend"] + self.params["tb"], + self.params["fs"] / 2.0] + y = [-self.params["atten"]] * 2 self.idealbandhcurves[2].setData(x, y) - x = [self.params["pbend"]+self.params["tb"]]*2 + x = [self.params["pbend"] + self.params["tb"]] * 2 y = [-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[3].setData(x, y) diff --git a/gr-filter/python/filter/gui/polezero_plot.py b/gr-filter/python/filter/gui/polezero_plot.py index 3b3b99b6060..859cd5c2d63 100644 --- a/gr-filter/python/filter/gui/polezero_plot.py +++ b/gr-filter/python/filter/gui/polezero_plot.py @@ -22,9 +22,12 @@ def __init__(self, *args): pg.PlotWidget.__init__(self, *args) # Set Global pyqtgraph options - pg.setConfigOption('foreground', 'k') # Default foreground color for text, lines, axes, etc. - pg.setConfigOption('background', None) # Default background for GraphicsView. - pg.setConfigOptions(antialias=True) # Draw lines with smooth edges at the cost of reduced performance. + # Default foreground color for text, lines, axes, etc. + pg.setConfigOption('foreground', 'k') + # Default background for GraphicsView. + pg.setConfigOption('background', None) + # Draw lines with smooth edges at the cost of reduced performance. + pg.setConfigOptions(antialias=True) self.ymax = 0 self.xmax = 0 @@ -76,44 +79,45 @@ def insertZeros(self, roots): if self.ymin >= -1: self.ymin = -1.5 - self.setRange(xRange=[self.xmin, self.xmax], yRange=[self.ymin, self.ymax]) + self.setRange(xRange=[self.xmin, self.xmax], + yRange=[self.ymin, self.ymax]) def insertPoles(self, roots): - if len(roots): - self.__insertPole(Qt.Qt.black, roots.real, roots.imag) - ymax = max(roots.imag) - ymax = max(ymax, self.ymax) - ymin = min(roots.imag) - ymin = min(ymin, self.ymin) - xmax = max(roots.real) - xmax = max(xmax, self.xmax) - xmin = min(roots.real) - xmin = min(xmin, self.xmin) - - # To make the plot look good. - if xmax <= 1.3: - xmax = 2 - else: - xmax = 1.2 * xmax + if len(roots): + self.__insertPole(Qt.Qt.black, roots.real, roots.imag) + ymax = max(roots.imag) + ymax = max(ymax, self.ymax) + ymin = min(roots.imag) + ymin = min(ymin, self.ymin) + xmax = max(roots.real) + xmax = max(xmax, self.xmax) + xmin = min(roots.real) + xmin = min(xmin, self.xmin) - if xmin >= -1.3: - xmin = -2 - else: - xmin = 1.2 * xmin + # To make the plot look good. + if xmax <= 1.3: + xmax = 2 + else: + xmax = 1.2 * xmax - if ymax <= 1: - ymax = 1.5 - else: - ymax = 1.2 * ymax + if xmin >= -1.3: + xmin = -2 + else: + xmin = 1.2 * xmin - if ymin >= -1: - ymin = -1.5 - else: - ymin = 1.2 * ymin + if ymax <= 1: + ymax = 1.5 + else: + ymax = 1.2 * ymax + + if ymin >= -1: + ymin = -1.5 + else: + ymin = 1.2 * ymin - self.setRange(xRange=[xmin, xmax], yRange=[ymin, ymax]) - self.drawUnitcircle() - self.replot() + self.setRange(xRange=[xmin, xmax], yRange=[ymin, ymax]) + self.drawUnitcircle() + self.replot() def __insertZero(self, color, px, py): curve = self.plot(name="Zero") @@ -135,8 +139,8 @@ def __insertPole(self, color, px, py): def removeallCurves(self): # TODO for curve in self.itemList(): - # if isinstance(curve, Qwt.QwtPlotCurve): - # curve.detach() + # if isinstance(curve, Qwt.QwtPlotCurve): + # curve.detach() self.replot() @@ -319,8 +323,8 @@ def __deleteZero(self): yData = delete(yData, self.__selectedPoint) # One less to accommodate previous delete. if(self.__selectedcPoint != -1): - xData = delete(xData, self.__selectedcPoint-1) - yData = delete(yData, self.__selectedcPoint-1) + xData = delete(xData, self.__selectedcPoint - 1) + yData = delete(yData, self.__selectedcPoint - 1) curve.setData(xData, yData) self.__plot.replot() @@ -330,7 +334,8 @@ def __deleteZero(self): if isinstance(c, Qwt.QwtPlotCurve): px.append([c.x(i) for i in range(c.dataSize())]) py.append([c.y(i) for i in range(c.dataSize())]) - tp = (vectorize(complex)(px[0], py[0]), vectorize(complex)(px[1], py[1])) + tp = (vectorize(complex)(px[0], py[0]), + vectorize(complex)(px[1], py[1])) self.curveChanged.emit(tp) def __moveBy(self, dx, dy): @@ -379,7 +384,8 @@ def __move(self, pos): if isinstance(c, Qwt.QwtPlotCurve): px.append([c.x(i) for i in range(c.dataSize())]) py.append([c.y(i) for i in range(c.dataSize())]) - tp = (vectorize(complex)(px[0], py[0]), vectorize(complex)(px[1], py[1])) + tp = (vectorize(complex)(px[0], py[0]), + vectorize(complex)(px[1], py[1])) self.curveChanged.emit(tp) self.__showCursor(True) @@ -409,23 +415,23 @@ def __drawAddedzero_pole(self, showIt, pos): else: extrapoints = 1 - xData = zeros(editcurve.dataSize()+extrapoints, Float) - yData = zeros(editcurve.dataSize()+extrapoints, Float) + xData = zeros(editcurve.dataSize() + extrapoints, Float) + yData = zeros(editcurve.dataSize() + extrapoints, Float) for i in range(editcurve.dataSize()): xData[i] = editcurve.x(i) yData[i] = editcurve.y(i) - xData[i+1] = self.__plot.invTransform(editcurve.xAxis(), pos.x()) - yData[i+1] = self.__plot.invTransform(editcurve.yAxis(), pos.y()) + xData[i + 1] = self.__plot.invTransform(editcurve.xAxis(), pos.x()) + yData[i + 1] = self.__plot.invTransform(editcurve.yAxis(), pos.y()) if self.changeConjugate: - xData[i+2] = xData[i+1] - yData[i+2] = -yData[i+1] - self.__addedcZero = i+2 + xData[i + 2] = xData[i + 1] + yData[i + 2] = -yData[i + 1] + self.__addedcZero = i + 2 editcurve.setData(xData, yData) - self.__addedZero = i+1 + self.__addedZero = i + 1 symbol = Qwt.QwtSymbol(editcurve.symbol()) newSymbol = Qwt.QwtSymbol(symbol) newSymbol.setPen(Qt.QPen(Qt.Qt.red)) @@ -446,7 +452,8 @@ def __drawAddedzero_pole(self, showIt, pos): if isinstance(c, Qwt.QwtPlotCurve): px.append([c.x(i) for i in range(c.dataSize())]) py.append([c.y(i) for i in range(c.dataSize())]) - tp = (vectorize(complex)(px[0], py[0]), vectorize(complex)(px[1], py[1])) + tp = (vectorize(complex)(px[0], py[0]), + vectorize(complex)(px[1], py[1])) self.curveChanged.emit(tp) self.__showCursor(True) diff --git a/gr-filter/python/filter/gui/pyqt_filter_stacked.py b/gr-filter/python/filter/gui/pyqt_filter_stacked.py index 9bd2ab8148e..48095ee36d1 100644 --- a/gr-filter/python/filter/gui/pyqt_filter_stacked.py +++ b/gr-filter/python/filter/gui/pyqt_filter_stacked.py @@ -6,8 +6,13 @@ # # WARNING! All changes made in this file will be lost! +from .GrFilterPlotWidget import GrFilterPlotWidget +from . import icons_rc +from .polezero_plot import PzPlot +from .bandgraphicsview import BandGraphicsView from PyQt5 import QtCore, QtGui, QtWidgets + class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") @@ -17,36 +22,44 @@ def setupUi(self, MainWindow): self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.stackedWindows = QtWidgets.QStackedWidget(self.centralwidget) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.stackedWindows.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.stackedWindows.sizePolicy().hasHeightForWidth()) self.stackedWindows.setSizePolicy(sizePolicy) self.stackedWindows.setObjectName("stackedWindows") self.classic = QtWidgets.QWidget() - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.classic.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.classic.sizePolicy().hasHeightForWidth()) self.classic.setSizePolicy(sizePolicy) self.classic.setObjectName("classic") self.horizontalLayout = QtWidgets.QHBoxLayout(self.classic) self.horizontalLayout.setObjectName("horizontalLayout") self.splitter = QtWidgets.QSplitter(self.classic) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) - sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.splitter.sizePolicy().hasHeightForWidth()) self.splitter.setSizePolicy(sizePolicy) self.splitter.setMinimumSize(QtCore.QSize(600, 0)) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName("splitter") self.tabGroup = QtWidgets.QTabWidget(self.splitter) self.tabGroup.setEnabled(True) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) - sizePolicy.setHeightForWidth(self.tabGroup.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.tabGroup.sizePolicy().hasHeightForWidth()) self.tabGroup.setSizePolicy(sizePolicy) self.tabGroup.setTabsClosable(False) self.tabGroup.setMovable(False) @@ -116,10 +129,12 @@ def setupUi(self, MainWindow): self.horizontalLayout_17.addWidget(self.pdelayPlot) self.tabGroup.addTab(self.pdelayTab, "") self.filterspecView = QtWidgets.QTabWidget(self.splitter) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.filterspecView.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.filterspecView.sizePolicy().hasHeightForWidth()) self.filterspecView.setSizePolicy(sizePolicy) self.filterspecView.setMinimumSize(QtCore.QSize(613, 250)) self.filterspecView.setBaseSize(QtCore.QSize(0, 100)) @@ -127,19 +142,23 @@ def setupUi(self, MainWindow): self.filterspecView.setTabsClosable(False) self.filterspecView.setObjectName("filterspecView") self.bandDiagram = QtWidgets.QWidget() - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.bandDiagram.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.bandDiagram.sizePolicy().hasHeightForWidth()) self.bandDiagram.setSizePolicy(sizePolicy) self.bandDiagram.setObjectName("bandDiagram") self.horizontalLayout_13 = QtWidgets.QHBoxLayout(self.bandDiagram) self.horizontalLayout_13.setObjectName("horizontalLayout_13") self.bandView = BandGraphicsView(self.bandDiagram) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) - sizePolicy.setHeightForWidth(self.bandView.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.bandView.sizePolicy().hasHeightForWidth()) self.bandView.setSizePolicy(sizePolicy) self.bandView.setMinimumSize(QtCore.QSize(525, 249)) self.bandView.setObjectName("bandView") @@ -163,7 +182,8 @@ def setupUi(self, MainWindow): self.verticalLayout_3.setObjectName("verticalLayout_3") self.addzeroPush = QtWidgets.QToolButton(self.pzgroupBox) icon = QtGui.QIcon() - icon.addPixmap(QtGui.QPixmap(":/icons/add_zero.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon.addPixmap(QtGui.QPixmap(":/icons/add_zero.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.addzeroPush.setIcon(icon) self.addzeroPush.setIconSize(QtCore.QSize(16, 16)) self.addzeroPush.setCheckable(True) @@ -171,21 +191,24 @@ def setupUi(self, MainWindow): self.verticalLayout_3.addWidget(self.addzeroPush) self.addpolePush = QtWidgets.QToolButton(self.pzgroupBox) icon1 = QtGui.QIcon() - icon1.addPixmap(QtGui.QPixmap(":/icons/add_pole.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon1.addPixmap(QtGui.QPixmap(":/icons/add_pole.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.addpolePush.setIcon(icon1) self.addpolePush.setCheckable(True) self.addpolePush.setObjectName("addpolePush") self.verticalLayout_3.addWidget(self.addpolePush) self.delPush = QtWidgets.QToolButton(self.pzgroupBox) icon2 = QtGui.QIcon() - icon2.addPixmap(QtGui.QPixmap(":/icons/remove_red.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon2.addPixmap(QtGui.QPixmap(":/icons/remove_red.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.delPush.setIcon(icon2) self.delPush.setCheckable(True) self.delPush.setObjectName("delPush") self.verticalLayout_3.addWidget(self.delPush) self.conjPush = QtWidgets.QToolButton(self.pzgroupBox) icon3 = QtGui.QIcon() - icon3.addPixmap(QtGui.QPixmap(":/icons/conjugate.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon3.addPixmap(QtGui.QPixmap(":/icons/conjugate.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.conjPush.setIcon(icon3) self.conjPush.setIconSize(QtCore.QSize(16, 16)) self.conjPush.setCheckable(True) @@ -193,10 +216,12 @@ def setupUi(self, MainWindow): self.verticalLayout_3.addWidget(self.conjPush) self.gridLayout_2.addWidget(self.pzgroupBox, 0, 2, 1, 1) self.pzPlot = PzPlot(self.poleZero) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.pzPlot.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.pzPlot.sizePolicy().hasHeightForWidth()) self.pzPlot.setSizePolicy(sizePolicy) self.pzPlot.setFrameShape(QtWidgets.QFrame.StyledPanel) self.pzPlot.setFrameShadow(QtWidgets.QFrame.Sunken) @@ -263,34 +288,41 @@ def setupUi(self, MainWindow): self.sysParamsBox.setGeometry(QtCore.QRect(10, 390, 161, 91)) self.sysParamsBox.setObjectName("sysParamsBox") self.formLayout_4 = QtWidgets.QFormLayout(self.sysParamsBox) - self.formLayout_4.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_4.setFieldGrowthPolicy( + QtWidgets.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_4.setObjectName("formLayout_4") self.nfftLabel = QtWidgets.QLabel(self.sysParamsBox) self.nfftLabel.setMinimumSize(QtCore.QSize(150, 0)) self.nfftLabel.setObjectName("nfftLabel") - self.formLayout_4.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.nfftLabel) + self.formLayout_4.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.nfftLabel) self.nfftEdit = QtWidgets.QLineEdit(self.sysParamsBox) self.nfftEdit.setObjectName("nfftEdit") - self.formLayout_4.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.nfftEdit) + self.formLayout_4.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.nfftEdit) self.groupSpecs.raise_() self.responseBox.raise_() self.sysParamsBox.raise_() self.horizontalLayout.addWidget(self.quickFrame) self.stackedWindows.addWidget(self.classic) self.modern = QtWidgets.QWidget() - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.modern.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.modern.sizePolicy().hasHeightForWidth()) self.modern.setSizePolicy(sizePolicy) self.modern.setObjectName("modern") self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.modern) self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.splitter_3 = QtWidgets.QSplitter(self.modern) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.splitter_3.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.splitter_3.sizePolicy().hasHeightForWidth()) self.splitter_3.setSizePolicy(sizePolicy) self.splitter_3.setOrientation(QtCore.Qt.Vertical) self.splitter_3.setObjectName("splitter_3") @@ -301,10 +333,12 @@ def setupUi(self, MainWindow): self.mfreqTabgroup.setTabsClosable(False) self.mfreqTabgroup.setObjectName("mfreqTabgroup") self.mfreqTab = QtWidgets.QWidget() - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.mfreqTab.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.mfreqTab.sizePolicy().hasHeightForWidth()) self.mfreqTab.setSizePolicy(sizePolicy) self.mfreqTab.setObjectName("mfreqTab") self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.mfreqTab) @@ -322,7 +356,8 @@ def setupUi(self, MainWindow): self.verticalLayout_2.setObjectName("verticalLayout_2") self.mfmagPush = QtWidgets.QToolButton(self.mfgroupBox) icon4 = QtGui.QIcon() - icon4.addPixmap(QtGui.QPixmap(":/icons/mag_response.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon4.addPixmap(QtGui.QPixmap(":/icons/mag_response.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfmagPush.setIcon(icon4) self.mfmagPush.setIconSize(QtCore.QSize(16, 16)) self.mfmagPush.setCheckable(False) @@ -330,7 +365,8 @@ def setupUi(self, MainWindow): self.verticalLayout_2.addWidget(self.mfmagPush) self.mfphasePush = QtWidgets.QToolButton(self.mfgroupBox) icon5 = QtGui.QIcon() - icon5.addPixmap(QtGui.QPixmap(":/icons/phase_response.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon5.addPixmap(QtGui.QPixmap(":/icons/phase_response.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfphasePush.setIcon(icon5) self.mfphasePush.setIconSize(QtCore.QSize(16, 16)) self.mfphasePush.setCheckable(False) @@ -338,7 +374,8 @@ def setupUi(self, MainWindow): self.verticalLayout_2.addWidget(self.mfphasePush) self.mfgpdlyPush = QtWidgets.QToolButton(self.mfgroupBox) icon6 = QtGui.QIcon() - icon6.addPixmap(QtGui.QPixmap(":/icons/group_delay.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon6.addPixmap(QtGui.QPixmap(":/icons/group_delay.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfgpdlyPush.setIcon(icon6) self.mfgpdlyPush.setIconSize(QtCore.QSize(16, 16)) self.mfgpdlyPush.setCheckable(False) @@ -346,7 +383,8 @@ def setupUi(self, MainWindow): self.verticalLayout_2.addWidget(self.mfgpdlyPush) self.mfphdlyPush = QtWidgets.QToolButton(self.mfgroupBox) icon7 = QtGui.QIcon() - icon7.addPixmap(QtGui.QPixmap(":/icons/phase_delay.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon7.addPixmap(QtGui.QPixmap(":/icons/phase_delay.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfphdlyPush.setIcon(icon7) self.mfphdlyPush.setIconSize(QtCore.QSize(16, 16)) self.mfphdlyPush.setCheckable(False) @@ -354,7 +392,8 @@ def setupUi(self, MainWindow): self.verticalLayout_2.addWidget(self.mfphdlyPush) self.mfoverlayPush = QtWidgets.QToolButton(self.mfgroupBox) icon8 = QtGui.QIcon() - icon8.addPixmap(QtGui.QPixmap(":/icons/overlay.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon8.addPixmap(QtGui.QPixmap(":/icons/overlay.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfoverlayPush.setIcon(icon8) self.mfoverlayPush.setIconSize(QtCore.QSize(16, 16)) self.mfoverlayPush.setCheckable(True) @@ -365,10 +404,12 @@ def setupUi(self, MainWindow): self.mtimeTabgroup = QtWidgets.QTabWidget(self.splitter_2) self.mtimeTabgroup.setObjectName("mtimeTabgroup") self.mtimeTab = QtWidgets.QWidget() - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.mtimeTab.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.mtimeTab.sizePolicy().hasHeightForWidth()) self.mtimeTab.setSizePolicy(sizePolicy) self.mtimeTab.setObjectName("mtimeTab") self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.mtimeTab) @@ -386,7 +427,8 @@ def setupUi(self, MainWindow): self.verticalLayout_5.setObjectName("verticalLayout_5") self.mttapsPush = QtWidgets.QToolButton(self.mtgroupBox) icon9 = QtGui.QIcon() - icon9.addPixmap(QtGui.QPixmap(":/icons/filtr_taps.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon9.addPixmap(QtGui.QPixmap(":/icons/filtr_taps.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mttapsPush.setIcon(icon9) self.mttapsPush.setIconSize(QtCore.QSize(16, 16)) self.mttapsPush.setCheckable(False) @@ -394,7 +436,8 @@ def setupUi(self, MainWindow): self.verticalLayout_5.addWidget(self.mttapsPush) self.mtstepPush = QtWidgets.QToolButton(self.mtgroupBox) icon10 = QtGui.QIcon() - icon10.addPixmap(QtGui.QPixmap(":/icons/step_response.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon10.addPixmap(QtGui.QPixmap(":/icons/step_response.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mtstepPush.setIcon(icon10) self.mtstepPush.setIconSize(QtCore.QSize(16, 16)) self.mtstepPush.setCheckable(False) @@ -402,7 +445,8 @@ def setupUi(self, MainWindow): self.verticalLayout_5.addWidget(self.mtstepPush) self.mtimpPush = QtWidgets.QToolButton(self.mtgroupBox) icon11 = QtGui.QIcon() - icon11.addPixmap(QtGui.QPixmap(":/icons/impulse.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon11.addPixmap(QtGui.QPixmap(":/icons/impulse.svg"), + QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mtimpPush.setIcon(icon11) self.mtimpPush.setIconSize(QtCore.QSize(16, 16)) self.mtimpPush.setCheckable(False) @@ -411,10 +455,12 @@ def setupUi(self, MainWindow): self.horizontalLayout_3.addWidget(self.mtgroupBox) self.mtimeTabgroup.addTab(self.mtimeTab, "") self.mfilterspecView = QtWidgets.QTabWidget(self.splitter_3) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.mfilterspecView.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.mfilterspecView.sizePolicy().hasHeightForWidth()) self.mfilterspecView.setSizePolicy(sizePolicy) self.mfilterspecView.setMinimumSize(QtCore.QSize(0, 100)) self.mfilterspecView.setBaseSize(QtCore.QSize(0, 100)) @@ -422,19 +468,23 @@ def setupUi(self, MainWindow): self.mfilterspecView.setTabsClosable(False) self.mfilterspecView.setObjectName("mfilterspecView") self.mbandDiagram = QtWidgets.QWidget() - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.mbandDiagram.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.mbandDiagram.sizePolicy().hasHeightForWidth()) self.mbandDiagram.setSizePolicy(sizePolicy) self.mbandDiagram.setObjectName("mbandDiagram") self.horizontalLayout_15 = QtWidgets.QHBoxLayout(self.mbandDiagram) self.horizontalLayout_15.setObjectName("horizontalLayout_15") self.mbandView = BandGraphicsView(self.mbandDiagram) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) - sizePolicy.setHeightForWidth(self.mbandView.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.mbandView.sizePolicy().hasHeightForWidth()) self.mbandView.setSizePolicy(sizePolicy) self.mbandView.setMinimumSize(QtCore.QSize(525, 249)) self.mbandView.setObjectName("mbandView") @@ -479,10 +529,12 @@ def setupUi(self, MainWindow): self.mpzstatusBar.setObjectName("mpzstatusBar") self.gridLayout_3.addWidget(self.mpzstatusBar, 1, 0, 1, 3) self.mpzPlot = PzPlot(self.mpoleZero) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) + sizePolicy = QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.mpzPlot.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.mpzPlot.sizePolicy().hasHeightForWidth()) self.mpzPlot.setSizePolicy(sizePolicy) self.mpzPlot.setFrameShape(QtWidgets.QFrame.StyledPanel) self.mpzPlot.setFrameShadow(QtWidgets.QFrame.Sunken) @@ -561,54 +613,68 @@ def setupUi(self, MainWindow): self.globalParamsBox.setTitle("") self.globalParamsBox.setObjectName("globalParamsBox") self.formLayout_12 = QtWidgets.QFormLayout(self.globalParamsBox) - self.formLayout_12.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_12.setFieldGrowthPolicy( + QtWidgets.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_12.setObjectName("formLayout_12") self.sampleRateLabel = QtWidgets.QLabel(self.globalParamsBox) self.sampleRateLabel.setMaximumSize(QtCore.QSize(16777215, 30)) self.sampleRateLabel.setObjectName("sampleRateLabel") - self.formLayout_12.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.sampleRateLabel) + self.formLayout_12.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.sampleRateLabel) self.sampleRateEdit = QtWidgets.QLineEdit(self.globalParamsBox) self.sampleRateEdit.setMaximumSize(QtCore.QSize(16777215, 30)) self.sampleRateEdit.setObjectName("sampleRateEdit") - self.formLayout_12.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.sampleRateEdit) + self.formLayout_12.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.sampleRateEdit) self.filterGainLabel = QtWidgets.QLabel(self.globalParamsBox) self.filterGainLabel.setObjectName("filterGainLabel") - self.formLayout_12.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.filterGainLabel) + self.formLayout_12.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.filterGainLabel) self.filterGainEdit = QtWidgets.QLineEdit(self.globalParamsBox) self.filterGainEdit.setObjectName("filterGainEdit") - self.formLayout_12.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.filterGainEdit) + self.formLayout_12.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.filterGainEdit) self.verticalLayout.addWidget(self.globalParamsBox) self.filterTypeWidget = QtWidgets.QStackedWidget(self.filterFrame) self.filterTypeWidget.setObjectName("filterTypeWidget") self.firlpfPage = QtWidgets.QWidget() self.firlpfPage.setObjectName("firlpfPage") self.formLayout = QtWidgets.QFormLayout(self.firlpfPage) - self.formLayout.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout.setFieldGrowthPolicy( + QtWidgets.QFormLayout.AllNonFixedFieldsGrow) self.formLayout.setObjectName("formLayout") self.endofLpfPassBandLabel = QtWidgets.QLabel(self.firlpfPage) self.endofLpfPassBandLabel.setObjectName("endofLpfPassBandLabel") - self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.endofLpfPassBandLabel) + self.formLayout.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.endofLpfPassBandLabel) self.endofLpfPassBandEdit = QtWidgets.QLineEdit(self.firlpfPage) self.endofLpfPassBandEdit.setObjectName("endofLpfPassBandEdit") - self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.endofLpfPassBandEdit) + self.formLayout.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.endofLpfPassBandEdit) self.startofLpfStopBandLabel = QtWidgets.QLabel(self.firlpfPage) self.startofLpfStopBandLabel.setObjectName("startofLpfStopBandLabel") - self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.startofLpfStopBandLabel) + self.formLayout.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.startofLpfStopBandLabel) self.startofLpfStopBandEdit = QtWidgets.QLineEdit(self.firlpfPage) self.startofLpfStopBandEdit.setObjectName("startofLpfStopBandEdit") - self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.startofLpfStopBandEdit) + self.formLayout.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.startofLpfStopBandEdit) self.lpfStopBandAttenLabel = QtWidgets.QLabel(self.firlpfPage) self.lpfStopBandAttenLabel.setObjectName("lpfStopBandAttenLabel") - self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.lpfStopBandAttenLabel) + self.formLayout.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.lpfStopBandAttenLabel) self.lpfStopBandAttenEdit = QtWidgets.QLineEdit(self.firlpfPage) self.lpfStopBandAttenEdit.setObjectName("lpfStopBandAttenEdit") - self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.lpfStopBandAttenEdit) + self.formLayout.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.lpfStopBandAttenEdit) self.lpfPassBandRippleLabel = QtWidgets.QLabel(self.firlpfPage) self.lpfPassBandRippleLabel.setObjectName("lpfPassBandRippleLabel") - self.formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.lpfPassBandRippleLabel) + self.formLayout.setWidget( + 3, QtWidgets.QFormLayout.LabelRole, self.lpfPassBandRippleLabel) self.lpfPassBandRippleEdit = QtWidgets.QLineEdit(self.firlpfPage) self.lpfPassBandRippleEdit.setObjectName("lpfPassBandRippleEdit") - self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.lpfPassBandRippleEdit) + self.formLayout.setWidget( + 3, QtWidgets.QFormLayout.FieldRole, self.lpfPassBandRippleEdit) self.filterTypeWidget.addWidget(self.firlpfPage) self.firbpfPage = QtWidgets.QWidget() self.firbpfPage.setObjectName("firbpfPage") @@ -616,100 +682,130 @@ def setupUi(self, MainWindow): self.formLayout_2.setObjectName("formLayout_2") self.startofBpfPassBandLabel = QtWidgets.QLabel(self.firbpfPage) self.startofBpfPassBandLabel.setObjectName("startofBpfPassBandLabel") - self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.startofBpfPassBandLabel) + self.formLayout_2.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.startofBpfPassBandLabel) self.startofBpfPassBandEdit = QtWidgets.QLineEdit(self.firbpfPage) self.startofBpfPassBandEdit.setObjectName("startofBpfPassBandEdit") - self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.startofBpfPassBandEdit) + self.formLayout_2.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.startofBpfPassBandEdit) self.endofBpfPassBandLabel = QtWidgets.QLabel(self.firbpfPage) self.endofBpfPassBandLabel.setObjectName("endofBpfPassBandLabel") - self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.endofBpfPassBandLabel) + self.formLayout_2.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.endofBpfPassBandLabel) self.endofBpfPassBandEdit = QtWidgets.QLineEdit(self.firbpfPage) self.endofBpfPassBandEdit.setObjectName("endofBpfPassBandEdit") - self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.endofBpfPassBandEdit) + self.formLayout_2.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.endofBpfPassBandEdit) self.bpfStopBandAttenEdit = QtWidgets.QLineEdit(self.firbpfPage) self.bpfStopBandAttenEdit.setObjectName("bpfStopBandAttenEdit") - self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.bpfStopBandAttenEdit) + self.formLayout_2.setWidget( + 3, QtWidgets.QFormLayout.FieldRole, self.bpfStopBandAttenEdit) self.bpfStopBandAttenLabel = QtWidgets.QLabel(self.firbpfPage) self.bpfStopBandAttenLabel.setObjectName("bpfStopBandAttenLabel") - self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.bpfStopBandAttenLabel) + self.formLayout_2.setWidget( + 3, QtWidgets.QFormLayout.LabelRole, self.bpfStopBandAttenLabel) self.bpfTransitionLabel = QtWidgets.QLabel(self.firbpfPage) self.bpfTransitionLabel.setObjectName("bpfTransitionLabel") - self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.bpfTransitionLabel) + self.formLayout_2.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.bpfTransitionLabel) self.bpfTransitionEdit = QtWidgets.QLineEdit(self.firbpfPage) self.bpfTransitionEdit.setObjectName("bpfTransitionEdit") - self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.bpfTransitionEdit) + self.formLayout_2.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.bpfTransitionEdit) self.bpfPassBandRippleEdit = QtWidgets.QLineEdit(self.firbpfPage) self.bpfPassBandRippleEdit.setObjectName("bpfPassBandRippleEdit") - self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.bpfPassBandRippleEdit) + self.formLayout_2.setWidget( + 4, QtWidgets.QFormLayout.FieldRole, self.bpfPassBandRippleEdit) self.bpfPassBandRippleLabel = QtWidgets.QLabel(self.firbpfPage) self.bpfPassBandRippleLabel.setObjectName("bpfPassBandRippleLabel") - self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.bpfPassBandRippleLabel) + self.formLayout_2.setWidget( + 4, QtWidgets.QFormLayout.LabelRole, self.bpfPassBandRippleLabel) self.filterTypeWidget.addWidget(self.firbpfPage) self.firbnfPage = QtWidgets.QWidget() self.firbnfPage.setObjectName("firbnfPage") self.formLayout_5 = QtWidgets.QFormLayout(self.firbnfPage) - self.formLayout_5.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_5.setFieldGrowthPolicy( + QtWidgets.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_5.setObjectName("formLayout_5") self.startofBnfStopBandLabel = QtWidgets.QLabel(self.firbnfPage) self.startofBnfStopBandLabel.setObjectName("startofBnfStopBandLabel") - self.formLayout_5.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.startofBnfStopBandLabel) + self.formLayout_5.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.startofBnfStopBandLabel) self.startofBnfStopBandEdit = QtWidgets.QLineEdit(self.firbnfPage) self.startofBnfStopBandEdit.setObjectName("startofBnfStopBandEdit") - self.formLayout_5.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.startofBnfStopBandEdit) + self.formLayout_5.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.startofBnfStopBandEdit) self.endofBnfStopBandLabel = QtWidgets.QLabel(self.firbnfPage) self.endofBnfStopBandLabel.setObjectName("endofBnfStopBandLabel") - self.formLayout_5.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.endofBnfStopBandLabel) + self.formLayout_5.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.endofBnfStopBandLabel) self.endofBnfStopBandEdit = QtWidgets.QLineEdit(self.firbnfPage) self.endofBnfStopBandEdit.setObjectName("endofBnfStopBandEdit") - self.formLayout_5.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.endofBnfStopBandEdit) + self.formLayout_5.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.endofBnfStopBandEdit) self.bnfTransitionLabel = QtWidgets.QLabel(self.firbnfPage) self.bnfTransitionLabel.setObjectName("bnfTransitionLabel") - self.formLayout_5.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.bnfTransitionLabel) + self.formLayout_5.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.bnfTransitionLabel) self.bnfTransitionEdit = QtWidgets.QLineEdit(self.firbnfPage) self.bnfTransitionEdit.setObjectName("bnfTransitionEdit") - self.formLayout_5.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.bnfTransitionEdit) + self.formLayout_5.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.bnfTransitionEdit) self.bnfStopBandAttenLabel = QtWidgets.QLabel(self.firbnfPage) self.bnfStopBandAttenLabel.setObjectName("bnfStopBandAttenLabel") - self.formLayout_5.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.bnfStopBandAttenLabel) + self.formLayout_5.setWidget( + 3, QtWidgets.QFormLayout.LabelRole, self.bnfStopBandAttenLabel) self.bnfStopBandAttenEdit = QtWidgets.QLineEdit(self.firbnfPage) self.bnfStopBandAttenEdit.setObjectName("bnfStopBandAttenEdit") - self.formLayout_5.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.bnfStopBandAttenEdit) + self.formLayout_5.setWidget( + 3, QtWidgets.QFormLayout.FieldRole, self.bnfStopBandAttenEdit) self.bnfPassBandRippleLabel = QtWidgets.QLabel(self.firbnfPage) self.bnfPassBandRippleLabel.setObjectName("bnfPassBandRippleLabel") - self.formLayout_5.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.bnfPassBandRippleLabel) + self.formLayout_5.setWidget( + 4, QtWidgets.QFormLayout.LabelRole, self.bnfPassBandRippleLabel) self.bnfPassBandRippleEdit = QtWidgets.QLineEdit(self.firbnfPage) self.bnfPassBandRippleEdit.setObjectName("bnfPassBandRippleEdit") - self.formLayout_5.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.bnfPassBandRippleEdit) + self.formLayout_5.setWidget( + 4, QtWidgets.QFormLayout.FieldRole, self.bnfPassBandRippleEdit) self.filterTypeWidget.addWidget(self.firbnfPage) self.firhpfPage = QtWidgets.QWidget() self.firhpfPage.setObjectName("firhpfPage") self.formLayout_3 = QtWidgets.QFormLayout(self.firhpfPage) - self.formLayout_3.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_3.setFieldGrowthPolicy( + QtWidgets.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_3.setObjectName("formLayout_3") self.endofHpfStopBandLabel = QtWidgets.QLabel(self.firhpfPage) self.endofHpfStopBandLabel.setObjectName("endofHpfStopBandLabel") - self.formLayout_3.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.endofHpfStopBandLabel) + self.formLayout_3.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.endofHpfStopBandLabel) self.endofHpfStopBandEdit = QtWidgets.QLineEdit(self.firhpfPage) self.endofHpfStopBandEdit.setObjectName("endofHpfStopBandEdit") - self.formLayout_3.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.endofHpfStopBandEdit) + self.formLayout_3.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.endofHpfStopBandEdit) self.startofHpfPassBandLabel = QtWidgets.QLabel(self.firhpfPage) self.startofHpfPassBandLabel.setObjectName("startofHpfPassBandLabel") - self.formLayout_3.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.startofHpfPassBandLabel) + self.formLayout_3.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.startofHpfPassBandLabel) self.startofHpfPassBandEdit = QtWidgets.QLineEdit(self.firhpfPage) self.startofHpfPassBandEdit.setObjectName("startofHpfPassBandEdit") - self.formLayout_3.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.startofHpfPassBandEdit) + self.formLayout_3.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.startofHpfPassBandEdit) self.hpfStopBandAttenLabel = QtWidgets.QLabel(self.firhpfPage) self.hpfStopBandAttenLabel.setObjectName("hpfStopBandAttenLabel") - self.formLayout_3.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.hpfStopBandAttenLabel) + self.formLayout_3.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.hpfStopBandAttenLabel) self.hpfStopBandAttenEdit = QtWidgets.QLineEdit(self.firhpfPage) self.hpfStopBandAttenEdit.setObjectName("hpfStopBandAttenEdit") - self.formLayout_3.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.hpfStopBandAttenEdit) + self.formLayout_3.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.hpfStopBandAttenEdit) self.hpfPassBandRippleLabel = QtWidgets.QLabel(self.firhpfPage) self.hpfPassBandRippleLabel.setObjectName("hpfPassBandRippleLabel") - self.formLayout_3.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.hpfPassBandRippleLabel) + self.formLayout_3.setWidget( + 3, QtWidgets.QFormLayout.LabelRole, self.hpfPassBandRippleLabel) self.hpfPassBandRippleEdit = QtWidgets.QLineEdit(self.firhpfPage) self.hpfPassBandRippleEdit.setObjectName("hpfPassBandRippleEdit") - self.formLayout_3.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.hpfPassBandRippleEdit) + self.formLayout_3.setWidget( + 3, QtWidgets.QFormLayout.FieldRole, self.hpfPassBandRippleEdit) self.filterTypeWidget.addWidget(self.firhpfPage) self.rrcPage = QtWidgets.QWidget() self.rrcPage.setObjectName("rrcPage") @@ -717,22 +813,28 @@ def setupUi(self, MainWindow): self.formLayout_6.setObjectName("formLayout_6") self.rrcSymbolRateLabel = QtWidgets.QLabel(self.rrcPage) self.rrcSymbolRateLabel.setObjectName("rrcSymbolRateLabel") - self.formLayout_6.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.rrcSymbolRateLabel) + self.formLayout_6.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.rrcSymbolRateLabel) self.rrcAlphaLabel = QtWidgets.QLabel(self.rrcPage) self.rrcAlphaLabel.setObjectName("rrcAlphaLabel") - self.formLayout_6.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.rrcAlphaLabel) + self.formLayout_6.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.rrcAlphaLabel) self.rrcNumTapsLabel = QtWidgets.QLabel(self.rrcPage) self.rrcNumTapsLabel.setObjectName("rrcNumTapsLabel") - self.formLayout_6.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.rrcNumTapsLabel) + self.formLayout_6.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.rrcNumTapsLabel) self.rrcSymbolRateEdit = QtWidgets.QLineEdit(self.rrcPage) self.rrcSymbolRateEdit.setObjectName("rrcSymbolRateEdit") - self.formLayout_6.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.rrcSymbolRateEdit) + self.formLayout_6.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.rrcSymbolRateEdit) self.rrcAlphaEdit = QtWidgets.QLineEdit(self.rrcPage) self.rrcAlphaEdit.setObjectName("rrcAlphaEdit") - self.formLayout_6.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.rrcAlphaEdit) + self.formLayout_6.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.rrcAlphaEdit) self.rrcNumTapsEdit = QtWidgets.QLineEdit(self.rrcPage) self.rrcNumTapsEdit.setObjectName("rrcNumTapsEdit") - self.formLayout_6.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.rrcNumTapsEdit) + self.formLayout_6.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.rrcNumTapsEdit) self.filterTypeWidget.addWidget(self.rrcPage) self.gausPage = QtWidgets.QWidget() self.gausPage.setObjectName("gausPage") @@ -740,22 +842,28 @@ def setupUi(self, MainWindow): self.formLayout_7.setObjectName("formLayout_7") self.gausSymbolRateLabel = QtWidgets.QLabel(self.gausPage) self.gausSymbolRateLabel.setObjectName("gausSymbolRateLabel") - self.formLayout_7.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.gausSymbolRateLabel) + self.formLayout_7.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.gausSymbolRateLabel) self.gausSymbolRateEdit = QtWidgets.QLineEdit(self.gausPage) self.gausSymbolRateEdit.setObjectName("gausSymbolRateEdit") - self.formLayout_7.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.gausSymbolRateEdit) + self.formLayout_7.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.gausSymbolRateEdit) self.gausBTLabel = QtWidgets.QLabel(self.gausPage) self.gausBTLabel.setObjectName("gausBTLabel") - self.formLayout_7.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.gausBTLabel) + self.formLayout_7.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.gausBTLabel) self.gausBTEdit = QtWidgets.QLineEdit(self.gausPage) self.gausBTEdit.setObjectName("gausBTEdit") - self.formLayout_7.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.gausBTEdit) + self.formLayout_7.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.gausBTEdit) self.gausNumTapsLabel = QtWidgets.QLabel(self.gausPage) self.gausNumTapsLabel.setObjectName("gausNumTapsLabel") - self.formLayout_7.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.gausNumTapsLabel) + self.formLayout_7.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.gausNumTapsLabel) self.gausNumTapsEdit = QtWidgets.QLineEdit(self.gausPage) self.gausNumTapsEdit.setObjectName("gausNumTapsEdit") - self.formLayout_7.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.gausNumTapsEdit) + self.formLayout_7.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.gausNumTapsEdit) self.filterTypeWidget.addWidget(self.gausPage) self.iirlpfPage = QtWidgets.QWidget() self.iirlpfPage.setObjectName("iirlpfPage") @@ -763,28 +871,39 @@ def setupUi(self, MainWindow): self.formLayout_15.setObjectName("formLayout_15") self.iirendofLpfPassBandLabel = QtWidgets.QLabel(self.iirlpfPage) self.iirendofLpfPassBandLabel.setObjectName("iirendofLpfPassBandLabel") - self.formLayout_15.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.iirendofLpfPassBandLabel) + self.formLayout_15.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.iirendofLpfPassBandLabel) self.iirendofLpfPassBandEdit = QtWidgets.QLineEdit(self.iirlpfPage) self.iirendofLpfPassBandEdit.setObjectName("iirendofLpfPassBandEdit") - self.formLayout_15.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.iirendofLpfPassBandEdit) + self.formLayout_15.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.iirendofLpfPassBandEdit) self.iirstartofLpfStopBandLabel = QtWidgets.QLabel(self.iirlpfPage) - self.iirstartofLpfStopBandLabel.setObjectName("iirstartofLpfStopBandLabel") - self.formLayout_15.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.iirstartofLpfStopBandLabel) + self.iirstartofLpfStopBandLabel.setObjectName( + "iirstartofLpfStopBandLabel") + self.formLayout_15.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.iirstartofLpfStopBandLabel) self.iirstartofLpfStopBandEdit = QtWidgets.QLineEdit(self.iirlpfPage) - self.iirstartofLpfStopBandEdit.setObjectName("iirstartofLpfStopBandEdit") - self.formLayout_15.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.iirstartofLpfStopBandEdit) + self.iirstartofLpfStopBandEdit.setObjectName( + "iirstartofLpfStopBandEdit") + self.formLayout_15.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.iirstartofLpfStopBandEdit) self.iirLpfPassBandAttenLabel = QtWidgets.QLabel(self.iirlpfPage) self.iirLpfPassBandAttenLabel.setObjectName("iirLpfPassBandAttenLabel") - self.formLayout_15.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.iirLpfPassBandAttenLabel) + self.formLayout_15.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.iirLpfPassBandAttenLabel) self.iirLpfPassBandAttenEdit = QtWidgets.QLineEdit(self.iirlpfPage) self.iirLpfPassBandAttenEdit.setObjectName("iirLpfPassBandAttenEdit") - self.formLayout_15.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.iirLpfPassBandAttenEdit) + self.formLayout_15.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.iirLpfPassBandAttenEdit) self.iirLpfStopBandRippleLabel = QtWidgets.QLabel(self.iirlpfPage) - self.iirLpfStopBandRippleLabel.setObjectName("iirLpfStopBandRippleLabel") - self.formLayout_15.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.iirLpfStopBandRippleLabel) + self.iirLpfStopBandRippleLabel.setObjectName( + "iirLpfStopBandRippleLabel") + self.formLayout_15.setWidget( + 3, QtWidgets.QFormLayout.LabelRole, self.iirLpfStopBandRippleLabel) self.iirLpfStopBandRippleEdit = QtWidgets.QLineEdit(self.iirlpfPage) self.iirLpfStopBandRippleEdit.setObjectName("iirLpfStopBandRippleEdit") - self.formLayout_15.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.iirLpfStopBandRippleEdit) + self.formLayout_15.setWidget( + 3, QtWidgets.QFormLayout.FieldRole, self.iirLpfStopBandRippleEdit) self.filterTypeWidget.addWidget(self.iirlpfPage) self.iirhpfPage = QtWidgets.QWidget() self.iirhpfPage.setObjectName("iirhpfPage") @@ -792,170 +911,232 @@ def setupUi(self, MainWindow): self.formLayout_9.setObjectName("formLayout_9") self.iirendofHpfStopBandLabel = QtWidgets.QLabel(self.iirhpfPage) self.iirendofHpfStopBandLabel.setObjectName("iirendofHpfStopBandLabel") - self.formLayout_9.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.iirendofHpfStopBandLabel) + self.formLayout_9.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.iirendofHpfStopBandLabel) self.iirendofHpfStopBandEdit = QtWidgets.QLineEdit(self.iirhpfPage) self.iirendofHpfStopBandEdit.setObjectName("iirendofHpfStopBandEdit") - self.formLayout_9.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.iirendofHpfStopBandEdit) + self.formLayout_9.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.iirendofHpfStopBandEdit) self.iirstartofHpfPassBandLabel = QtWidgets.QLabel(self.iirhpfPage) - self.iirstartofHpfPassBandLabel.setObjectName("iirstartofHpfPassBandLabel") - self.formLayout_9.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.iirstartofHpfPassBandLabel) + self.iirstartofHpfPassBandLabel.setObjectName( + "iirstartofHpfPassBandLabel") + self.formLayout_9.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.iirstartofHpfPassBandLabel) self.iirstartofHpfPassBandEdit = QtWidgets.QLineEdit(self.iirhpfPage) - self.iirstartofHpfPassBandEdit.setObjectName("iirstartofHpfPassBandEdit") - self.formLayout_9.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.iirstartofHpfPassBandEdit) + self.iirstartofHpfPassBandEdit.setObjectName( + "iirstartofHpfPassBandEdit") + self.formLayout_9.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.iirstartofHpfPassBandEdit) self.iirHpfPassBandAttenLabel = QtWidgets.QLabel(self.iirhpfPage) self.iirHpfPassBandAttenLabel.setObjectName("iirHpfPassBandAttenLabel") - self.formLayout_9.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.iirHpfPassBandAttenLabel) + self.formLayout_9.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.iirHpfPassBandAttenLabel) self.iirHpfPassBandAttenEdit = QtWidgets.QLineEdit(self.iirhpfPage) self.iirHpfPassBandAttenEdit.setObjectName("iirHpfPassBandAttenEdit") - self.formLayout_9.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.iirHpfPassBandAttenEdit) + self.formLayout_9.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.iirHpfPassBandAttenEdit) self.iirHpfStopBandRippleLabel = QtWidgets.QLabel(self.iirhpfPage) - self.iirHpfStopBandRippleLabel.setObjectName("iirHpfStopBandRippleLabel") - self.formLayout_9.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.iirHpfStopBandRippleLabel) + self.iirHpfStopBandRippleLabel.setObjectName( + "iirHpfStopBandRippleLabel") + self.formLayout_9.setWidget( + 3, QtWidgets.QFormLayout.LabelRole, self.iirHpfStopBandRippleLabel) self.iirHpfStopBandRippleEdit = QtWidgets.QLineEdit(self.iirhpfPage) self.iirHpfStopBandRippleEdit.setObjectName("iirHpfStopBandRippleEdit") - self.formLayout_9.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.iirHpfStopBandRippleEdit) + self.formLayout_9.setWidget( + 3, QtWidgets.QFormLayout.FieldRole, self.iirHpfStopBandRippleEdit) self.filterTypeWidget.addWidget(self.iirhpfPage) self.iirbpfPage = QtWidgets.QWidget() self.iirbpfPage.setObjectName("iirbpfPage") self.formLayout_10 = QtWidgets.QFormLayout(self.iirbpfPage) self.formLayout_10.setObjectName("formLayout_10") self.iirendofBpfStopBandLabel1 = QtWidgets.QLabel(self.iirbpfPage) - self.iirendofBpfStopBandLabel1.setObjectName("iirendofBpfStopBandLabel1") - self.formLayout_10.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.iirendofBpfStopBandLabel1) + self.iirendofBpfStopBandLabel1.setObjectName( + "iirendofBpfStopBandLabel1") + self.formLayout_10.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.iirendofBpfStopBandLabel1) self.iirendofBpfStopBandEdit1 = QtWidgets.QLineEdit(self.iirbpfPage) self.iirendofBpfStopBandEdit1.setObjectName("iirendofBpfStopBandEdit1") - self.formLayout_10.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.iirendofBpfStopBandEdit1) + self.formLayout_10.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.iirendofBpfStopBandEdit1) self.iirstartofBpfPassBandLabel = QtWidgets.QLabel(self.iirbpfPage) - self.iirstartofBpfPassBandLabel.setObjectName("iirstartofBpfPassBandLabel") - self.formLayout_10.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.iirstartofBpfPassBandLabel) + self.iirstartofBpfPassBandLabel.setObjectName( + "iirstartofBpfPassBandLabel") + self.formLayout_10.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.iirstartofBpfPassBandLabel) self.iirstartofBpfPassBandEdit = QtWidgets.QLineEdit(self.iirbpfPage) - self.iirstartofBpfPassBandEdit.setObjectName("iirstartofBpfPassBandEdit") - self.formLayout_10.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.iirstartofBpfPassBandEdit) + self.iirstartofBpfPassBandEdit.setObjectName( + "iirstartofBpfPassBandEdit") + self.formLayout_10.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.iirstartofBpfPassBandEdit) self.iirendofBpfPassBandLabel = QtWidgets.QLabel(self.iirbpfPage) self.iirendofBpfPassBandLabel.setObjectName("iirendofBpfPassBandLabel") - self.formLayout_10.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.iirendofBpfPassBandLabel) + self.formLayout_10.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.iirendofBpfPassBandLabel) self.iirendofBpfPassBandEdit = QtWidgets.QLineEdit(self.iirbpfPage) self.iirendofBpfPassBandEdit.setObjectName("iirendofBpfPassBandEdit") - self.formLayout_10.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.iirendofBpfPassBandEdit) + self.formLayout_10.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.iirendofBpfPassBandEdit) self.iirstartofBpfStopBandLabel2 = QtWidgets.QLabel(self.iirbpfPage) - self.iirstartofBpfStopBandLabel2.setObjectName("iirstartofBpfStopBandLabel2") - self.formLayout_10.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.iirstartofBpfStopBandLabel2) + self.iirstartofBpfStopBandLabel2.setObjectName( + "iirstartofBpfStopBandLabel2") + self.formLayout_10.setWidget( + 3, QtWidgets.QFormLayout.LabelRole, self.iirstartofBpfStopBandLabel2) self.iirstartofBpfStopBandEdit2 = QtWidgets.QLineEdit(self.iirbpfPage) - self.iirstartofBpfStopBandEdit2.setObjectName("iirstartofBpfStopBandEdit2") - self.formLayout_10.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.iirstartofBpfStopBandEdit2) + self.iirstartofBpfStopBandEdit2.setObjectName( + "iirstartofBpfStopBandEdit2") + self.formLayout_10.setWidget( + 3, QtWidgets.QFormLayout.FieldRole, self.iirstartofBpfStopBandEdit2) self.iirBpfPassBandAttenLabel = QtWidgets.QLabel(self.iirbpfPage) self.iirBpfPassBandAttenLabel.setObjectName("iirBpfPassBandAttenLabel") - self.formLayout_10.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.iirBpfPassBandAttenLabel) + self.formLayout_10.setWidget( + 4, QtWidgets.QFormLayout.LabelRole, self.iirBpfPassBandAttenLabel) self.iirBpfPassBandAttenEdit = QtWidgets.QLineEdit(self.iirbpfPage) self.iirBpfPassBandAttenEdit.setObjectName("iirBpfPassBandAttenEdit") - self.formLayout_10.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.iirBpfPassBandAttenEdit) + self.formLayout_10.setWidget( + 4, QtWidgets.QFormLayout.FieldRole, self.iirBpfPassBandAttenEdit) self.iirBpfStopBandRippleLabel = QtWidgets.QLabel(self.iirbpfPage) - self.iirBpfStopBandRippleLabel.setObjectName("iirBpfStopBandRippleLabel") - self.formLayout_10.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.iirBpfStopBandRippleLabel) + self.iirBpfStopBandRippleLabel.setObjectName( + "iirBpfStopBandRippleLabel") + self.formLayout_10.setWidget( + 5, QtWidgets.QFormLayout.LabelRole, self.iirBpfStopBandRippleLabel) self.iirBpfStopBandRippleEdit = QtWidgets.QLineEdit(self.iirbpfPage) self.iirBpfStopBandRippleEdit.setObjectName("iirBpfStopBandRippleEdit") - self.formLayout_10.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.iirBpfStopBandRippleEdit) + self.formLayout_10.setWidget( + 5, QtWidgets.QFormLayout.FieldRole, self.iirBpfStopBandRippleEdit) self.filterTypeWidget.addWidget(self.iirbpfPage) self.iirbsfPage = QtWidgets.QWidget() self.iirbsfPage.setObjectName("iirbsfPage") self.formLayout_11 = QtWidgets.QFormLayout(self.iirbsfPage) self.formLayout_11.setObjectName("formLayout_11") self.iirendofBsfPassBandLabel1 = QtWidgets.QLabel(self.iirbsfPage) - self.iirendofBsfPassBandLabel1.setObjectName("iirendofBsfPassBandLabel1") - self.formLayout_11.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.iirendofBsfPassBandLabel1) + self.iirendofBsfPassBandLabel1.setObjectName( + "iirendofBsfPassBandLabel1") + self.formLayout_11.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.iirendofBsfPassBandLabel1) self.iirendofBsfPassBandEdit1 = QtWidgets.QLineEdit(self.iirbsfPage) self.iirendofBsfPassBandEdit1.setObjectName("iirendofBsfPassBandEdit1") - self.formLayout_11.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.iirendofBsfPassBandEdit1) + self.formLayout_11.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.iirendofBsfPassBandEdit1) self.iirstartofBsfStopBandLabel = QtWidgets.QLabel(self.iirbsfPage) - self.iirstartofBsfStopBandLabel.setObjectName("iirstartofBsfStopBandLabel") - self.formLayout_11.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.iirstartofBsfStopBandLabel) + self.iirstartofBsfStopBandLabel.setObjectName( + "iirstartofBsfStopBandLabel") + self.formLayout_11.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.iirstartofBsfStopBandLabel) self.iirstartofBsfStopBandEdit = QtWidgets.QLineEdit(self.iirbsfPage) - self.iirstartofBsfStopBandEdit.setObjectName("iirstartofBsfStopBandEdit") - self.formLayout_11.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.iirstartofBsfStopBandEdit) + self.iirstartofBsfStopBandEdit.setObjectName( + "iirstartofBsfStopBandEdit") + self.formLayout_11.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.iirstartofBsfStopBandEdit) self.iirendofBsfStopBandLabel = QtWidgets.QLabel(self.iirbsfPage) self.iirendofBsfStopBandLabel.setObjectName("iirendofBsfStopBandLabel") - self.formLayout_11.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.iirendofBsfStopBandLabel) + self.formLayout_11.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.iirendofBsfStopBandLabel) self.iirendofBsfStopBandEdit = QtWidgets.QLineEdit(self.iirbsfPage) self.iirendofBsfStopBandEdit.setObjectName("iirendofBsfStopBandEdit") - self.formLayout_11.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.iirendofBsfStopBandEdit) + self.formLayout_11.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.iirendofBsfStopBandEdit) self.iirstartofBsfPassBandLabel2 = QtWidgets.QLabel(self.iirbsfPage) - self.iirstartofBsfPassBandLabel2.setObjectName("iirstartofBsfPassBandLabel2") - self.formLayout_11.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.iirstartofBsfPassBandLabel2) + self.iirstartofBsfPassBandLabel2.setObjectName( + "iirstartofBsfPassBandLabel2") + self.formLayout_11.setWidget( + 3, QtWidgets.QFormLayout.LabelRole, self.iirstartofBsfPassBandLabel2) self.iirstartofBsfPassBandEdit2 = QtWidgets.QLineEdit(self.iirbsfPage) - self.iirstartofBsfPassBandEdit2.setObjectName("iirstartofBsfPassBandEdit2") - self.formLayout_11.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.iirstartofBsfPassBandEdit2) + self.iirstartofBsfPassBandEdit2.setObjectName( + "iirstartofBsfPassBandEdit2") + self.formLayout_11.setWidget( + 3, QtWidgets.QFormLayout.FieldRole, self.iirstartofBsfPassBandEdit2) self.iirBsfPassBandAttenLabel = QtWidgets.QLabel(self.iirbsfPage) self.iirBsfPassBandAttenLabel.setObjectName("iirBsfPassBandAttenLabel") - self.formLayout_11.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.iirBsfPassBandAttenLabel) + self.formLayout_11.setWidget( + 4, QtWidgets.QFormLayout.LabelRole, self.iirBsfPassBandAttenLabel) self.iirBsfPassBandAttenEdit = QtWidgets.QLineEdit(self.iirbsfPage) self.iirBsfPassBandAttenEdit.setObjectName("iirBsfPassBandAttenEdit") - self.formLayout_11.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.iirBsfPassBandAttenEdit) + self.formLayout_11.setWidget( + 4, QtWidgets.QFormLayout.FieldRole, self.iirBsfPassBandAttenEdit) self.iirBsfStopBandRippleLabel = QtWidgets.QLabel(self.iirbsfPage) - self.iirBsfStopBandRippleLabel.setObjectName("iirBsfStopBandRippleLabel") - self.formLayout_11.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.iirBsfStopBandRippleLabel) + self.iirBsfStopBandRippleLabel.setObjectName( + "iirBsfStopBandRippleLabel") + self.formLayout_11.setWidget( + 5, QtWidgets.QFormLayout.LabelRole, self.iirBsfStopBandRippleLabel) self.iirBsfStopBandRippleEdit = QtWidgets.QLineEdit(self.iirbsfPage) self.iirBsfStopBandRippleEdit.setObjectName("iirBsfStopBandRippleEdit") - self.formLayout_11.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.iirBsfStopBandRippleEdit) + self.formLayout_11.setWidget( + 5, QtWidgets.QFormLayout.FieldRole, self.iirBsfStopBandRippleEdit) self.filterTypeWidget.addWidget(self.iirbsfPage) self.iirbesselPage = QtWidgets.QWidget() self.iirbesselPage.setObjectName("iirbesselPage") self.formLayout_13 = QtWidgets.QFormLayout(self.iirbesselPage) - self.formLayout_13.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_13.setFieldGrowthPolicy( + QtWidgets.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_13.setObjectName("formLayout_13") self.besselordLabel = QtWidgets.QLabel(self.iirbesselPage) self.besselordLabel.setObjectName("besselordLabel") - self.formLayout_13.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.besselordLabel) + self.formLayout_13.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.besselordLabel) self.besselordEdit = QtWidgets.QLineEdit(self.iirbesselPage) self.besselordEdit.setObjectName("besselordEdit") - self.formLayout_13.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.besselordEdit) + self.formLayout_13.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.besselordEdit) self.iirbesselcritLabel1 = QtWidgets.QLabel(self.iirbesselPage) self.iirbesselcritLabel1.setObjectName("iirbesselcritLabel1") - self.formLayout_13.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.iirbesselcritLabel1) + self.formLayout_13.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.iirbesselcritLabel1) self.iirbesselcritEdit1 = QtWidgets.QLineEdit(self.iirbesselPage) self.iirbesselcritEdit1.setObjectName("iirbesselcritEdit1") - self.formLayout_13.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.iirbesselcritEdit1) + self.formLayout_13.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.iirbesselcritEdit1) self.iirbesselcritEdit2 = QtWidgets.QLineEdit(self.iirbesselPage) self.iirbesselcritEdit2.setObjectName("iirbesselcritEdit2") - self.formLayout_13.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.iirbesselcritEdit2) + self.formLayout_13.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.iirbesselcritEdit2) self.iirbesselcritLabel2 = QtWidgets.QLabel(self.iirbesselPage) self.iirbesselcritLabel2.setObjectName("iirbesselcritLabel2") - self.formLayout_13.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.iirbesselcritLabel2) + self.formLayout_13.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.iirbesselcritLabel2) self.filterTypeWidget.addWidget(self.iirbesselPage) self.firhbPage = QtWidgets.QWidget() self.firhbPage.setObjectName("firhbPage") self.formLayout_14 = QtWidgets.QFormLayout(self.firhbPage) - self.formLayout_14.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_14.setFieldGrowthPolicy( + QtWidgets.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_14.setObjectName("formLayout_14") self.firhbordLabel = QtWidgets.QLabel(self.firhbPage) self.firhbordLabel.setObjectName("firhbordLabel") - self.formLayout_14.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.firhbordLabel) + self.formLayout_14.setWidget( + 0, QtWidgets.QFormLayout.LabelRole, self.firhbordLabel) self.firhbordEdit = QtWidgets.QLineEdit(self.firhbPage) self.firhbordEdit.setObjectName("firhbordEdit") - self.formLayout_14.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.firhbordEdit) + self.formLayout_14.setWidget( + 0, QtWidgets.QFormLayout.FieldRole, self.firhbordEdit) self.firhbtrEditLabel2 = QtWidgets.QLabel(self.firhbPage) self.firhbtrEditLabel2.setObjectName("firhbtrEditLabel2") - self.formLayout_14.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.firhbtrEditLabel2) + self.formLayout_14.setWidget( + 2, QtWidgets.QFormLayout.LabelRole, self.firhbtrEditLabel2) self.firhbtrEdit = QtWidgets.QLineEdit(self.firhbPage) self.firhbtrEdit.setObjectName("firhbtrEdit") - self.formLayout_14.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.firhbtrEdit) + self.formLayout_14.setWidget( + 2, QtWidgets.QFormLayout.FieldRole, self.firhbtrEdit) self.filterTypeWidget.addWidget(self.firhbPage) self.verticalLayout.addWidget(self.filterTypeWidget) self.filterPropsBox = QtWidgets.QGroupBox(self.filterFrame) self.filterPropsBox.setObjectName("filterPropsBox") self.formLayout_8 = QtWidgets.QFormLayout(self.filterPropsBox) - self.formLayout_8.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_8.setFieldGrowthPolicy( + QtWidgets.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_8.setObjectName("formLayout_8") self.nTapsLabel = QtWidgets.QLabel(self.filterPropsBox) self.nTapsLabel.setMinimumSize(QtCore.QSize(150, 0)) self.nTapsLabel.setObjectName("nTapsLabel") - self.formLayout_8.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.nTapsLabel) + self.formLayout_8.setWidget( + 1, QtWidgets.QFormLayout.LabelRole, self.nTapsLabel) self.nTapsEdit = QtWidgets.QLabel(self.filterPropsBox) self.nTapsEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.nTapsEdit.setFrameShape(QtWidgets.QFrame.Box) self.nTapsEdit.setFrameShadow(QtWidgets.QFrame.Raised) self.nTapsEdit.setText("") self.nTapsEdit.setObjectName("nTapsEdit") - self.formLayout_8.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.nTapsEdit) + self.formLayout_8.setWidget( + 1, QtWidgets.QFormLayout.FieldRole, self.nTapsEdit) self.verticalLayout.addWidget(self.filterPropsBox) self.designButton = QtWidgets.QPushButton(self.filterFrame) self.designButton.setMinimumSize(QtCore.QSize(0, 0)) @@ -1049,7 +1230,8 @@ def setupUi(self, MainWindow): self.actionFilter_Coefficients = QtWidgets.QAction(MainWindow) self.actionFilter_Coefficients.setCheckable(True) self.actionFilter_Coefficients.setChecked(True) - self.actionFilter_Coefficients.setObjectName("actionFilter_Coefficients") + self.actionFilter_Coefficients.setObjectName( + "actionFilter_Coefficients") self.actionDesign_widget = QtWidgets.QAction(MainWindow) self.actionDesign_widget.setCheckable(True) self.actionDesign_widget.setChecked(True) @@ -1136,26 +1318,46 @@ def setupUi(self, MainWindow): self.filterTypeWidget.setCurrentIndex(11) self.action_exit.triggered.connect(MainWindow.close) QtCore.QMetaObject.connectSlotsByName(MainWindow) - MainWindow.setTabOrder(self.filterTypeComboBox, self.filterDesignTypeComboBox) - MainWindow.setTabOrder(self.filterDesignTypeComboBox, self.endofLpfPassBandEdit) - MainWindow.setTabOrder(self.endofLpfPassBandEdit, self.startofLpfStopBandEdit) - MainWindow.setTabOrder(self.startofLpfStopBandEdit, self.lpfStopBandAttenEdit) - MainWindow.setTabOrder(self.lpfStopBandAttenEdit, self.lpfPassBandRippleEdit) - MainWindow.setTabOrder(self.lpfPassBandRippleEdit, self.startofBpfPassBandEdit) - MainWindow.setTabOrder(self.startofBpfPassBandEdit, self.endofBpfPassBandEdit) - MainWindow.setTabOrder(self.endofBpfPassBandEdit, self.bpfTransitionEdit) - MainWindow.setTabOrder(self.bpfTransitionEdit, self.bpfStopBandAttenEdit) - MainWindow.setTabOrder(self.bpfStopBandAttenEdit, self.bpfPassBandRippleEdit) - MainWindow.setTabOrder(self.bpfPassBandRippleEdit, self.startofBnfStopBandEdit) - MainWindow.setTabOrder(self.startofBnfStopBandEdit, self.endofBnfStopBandEdit) - MainWindow.setTabOrder(self.endofBnfStopBandEdit, self.bnfTransitionEdit) - MainWindow.setTabOrder(self.bnfTransitionEdit, self.bnfStopBandAttenEdit) - MainWindow.setTabOrder(self.bnfStopBandAttenEdit, self.bnfPassBandRippleEdit) - MainWindow.setTabOrder(self.bnfPassBandRippleEdit, self.endofHpfStopBandEdit) - MainWindow.setTabOrder(self.endofHpfStopBandEdit, self.startofHpfPassBandEdit) - MainWindow.setTabOrder(self.startofHpfPassBandEdit, self.hpfStopBandAttenEdit) - MainWindow.setTabOrder(self.hpfStopBandAttenEdit, self.hpfPassBandRippleEdit) - MainWindow.setTabOrder(self.hpfPassBandRippleEdit, self.rrcSymbolRateEdit) + MainWindow.setTabOrder(self.filterTypeComboBox, + self.filterDesignTypeComboBox) + MainWindow.setTabOrder( + self.filterDesignTypeComboBox, self.endofLpfPassBandEdit) + MainWindow.setTabOrder(self.endofLpfPassBandEdit, + self.startofLpfStopBandEdit) + MainWindow.setTabOrder(self.startofLpfStopBandEdit, + self.lpfStopBandAttenEdit) + MainWindow.setTabOrder(self.lpfStopBandAttenEdit, + self.lpfPassBandRippleEdit) + MainWindow.setTabOrder(self.lpfPassBandRippleEdit, + self.startofBpfPassBandEdit) + MainWindow.setTabOrder(self.startofBpfPassBandEdit, + self.endofBpfPassBandEdit) + MainWindow.setTabOrder(self.endofBpfPassBandEdit, + self.bpfTransitionEdit) + MainWindow.setTabOrder(self.bpfTransitionEdit, + self.bpfStopBandAttenEdit) + MainWindow.setTabOrder(self.bpfStopBandAttenEdit, + self.bpfPassBandRippleEdit) + MainWindow.setTabOrder(self.bpfPassBandRippleEdit, + self.startofBnfStopBandEdit) + MainWindow.setTabOrder(self.startofBnfStopBandEdit, + self.endofBnfStopBandEdit) + MainWindow.setTabOrder(self.endofBnfStopBandEdit, + self.bnfTransitionEdit) + MainWindow.setTabOrder(self.bnfTransitionEdit, + self.bnfStopBandAttenEdit) + MainWindow.setTabOrder(self.bnfStopBandAttenEdit, + self.bnfPassBandRippleEdit) + MainWindow.setTabOrder(self.bnfPassBandRippleEdit, + self.endofHpfStopBandEdit) + MainWindow.setTabOrder(self.endofHpfStopBandEdit, + self.startofHpfPassBandEdit) + MainWindow.setTabOrder(self.startofHpfPassBandEdit, + self.hpfStopBandAttenEdit) + MainWindow.setTabOrder(self.hpfStopBandAttenEdit, + self.hpfPassBandRippleEdit) + MainWindow.setTabOrder( + self.hpfPassBandRippleEdit, self.rrcSymbolRateEdit) MainWindow.setTabOrder(self.rrcSymbolRateEdit, self.rrcAlphaEdit) MainWindow.setTabOrder(self.rrcAlphaEdit, self.rrcNumTapsEdit) MainWindow.setTabOrder(self.rrcNumTapsEdit, self.gausSymbolRateEdit) @@ -1165,16 +1367,26 @@ def setupUi(self, MainWindow): def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate - MainWindow.setWindowTitle(_translate("MainWindow", "GNU Radio Filter Design Tool")) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.freqTab), _translate("MainWindow", "Magnitude Response")) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.timeTab), _translate("MainWindow", "Filter Taps")) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.phaseTab), _translate("MainWindow", "Phase Response")) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.groupTab), _translate("MainWindow", "Group Delay")) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.fcTab), _translate("MainWindow", "Filter Coefficients")) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.impresTab), _translate("MainWindow", "Impulse Response")) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.stepresTab), _translate("MainWindow", "Step Response")) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.pdelayTab), _translate("MainWindow", "Phase Delay")) - self.filterspecView.setTabText(self.filterspecView.indexOf(self.bandDiagram), _translate("MainWindow", "Band Diagram")) + MainWindow.setWindowTitle(_translate( + "MainWindow", "GNU Radio Filter Design Tool")) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.freqTab), _translate("MainWindow", "Magnitude Response")) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.timeTab), _translate("MainWindow", "Filter Taps")) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.phaseTab), _translate("MainWindow", "Phase Response")) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.groupTab), _translate("MainWindow", "Group Delay")) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.fcTab), _translate("MainWindow", "Filter Coefficients")) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.impresTab), _translate("MainWindow", "Impulse Response")) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.stepresTab), _translate("MainWindow", "Step Response")) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.pdelayTab), _translate("MainWindow", "Phase Delay")) + self.filterspecView.setTabText(self.filterspecView.indexOf( + self.bandDiagram), _translate("MainWindow", "Band Diagram")) self.addzeroPush.setToolTip(_translate("MainWindow", "Add zero")) self.addzeroPush.setText(_translate("MainWindow", "...")) self.addpolePush.setToolTip(_translate("MainWindow", "Add pole")) @@ -1183,23 +1395,28 @@ def retranslateUi(self, MainWindow): self.delPush.setText(_translate("MainWindow", "...")) self.conjPush.setToolTip(_translate("MainWindow", "Conjugate")) self.conjPush.setText(_translate("MainWindow", "...")) - self.filterspecView.setTabText(self.filterspecView.indexOf(self.poleZero), _translate("MainWindow", "Pole-Zero Plot")) + self.filterspecView.setTabText(self.filterspecView.indexOf( + self.poleZero), _translate("MainWindow", "Pole-Zero Plot")) self.responseBox.setTitle(_translate("MainWindow", "Filter Responses")) - self.checkMagres.setText(_translate("MainWindow", "Magnitude Response")) + self.checkMagres.setText(_translate( + "MainWindow", "Magnitude Response")) self.checkPhase.setText(_translate("MainWindow", "Phase Response")) self.checkGdelay.setText(_translate("MainWindow", "Group Delay")) self.checkPdelay.setText(_translate("MainWindow", "Phase Delay")) self.checkImpulse.setText(_translate("MainWindow", "Impulse Response")) self.checkStep.setText(_translate("MainWindow", "Step Response")) self.checkGrid.setText(_translate("MainWindow", "Grid")) - self.checkFcoeff.setText(_translate("MainWindow", "Filter Coefficients")) - self.checkKeepcur.setText(_translate("MainWindow", "Buffer current plots")) + self.checkFcoeff.setText(_translate( + "MainWindow", "Filter Coefficients")) + self.checkKeepcur.setText(_translate( + "MainWindow", "Buffer current plots")) self.groupSpecs.setTitle(_translate("MainWindow", "Filter Specs")) self.checkBand.setText(_translate("MainWindow", "Band Diagram")) self.checkPzplot.setText(_translate("MainWindow", "Pole-Zero Plot")) self.sysParamsBox.setTitle(_translate("MainWindow", "Plot Parameter")) self.nfftLabel.setText(_translate("MainWindow", "Num FFT points")) - self.mfmagPush.setToolTip(_translate("MainWindow", "Magnitude Response")) + self.mfmagPush.setToolTip(_translate( + "MainWindow", "Magnitude Response")) self.mfmagPush.setText(_translate("MainWindow", "...")) self.mfphasePush.setToolTip(_translate("MainWindow", "Phase Response")) self.mfphasePush.setText(_translate("MainWindow", "...")) @@ -1209,15 +1426,18 @@ def retranslateUi(self, MainWindow): self.mfphdlyPush.setText(_translate("MainWindow", "...")) self.mfoverlayPush.setToolTip(_translate("MainWindow", "Overlay")) self.mfoverlayPush.setText(_translate("MainWindow", "...")) - self.mfreqTabgroup.setTabText(self.mfreqTabgroup.indexOf(self.mfreqTab), _translate("MainWindow", "Frequency Response")) + self.mfreqTabgroup.setTabText(self.mfreqTabgroup.indexOf( + self.mfreqTab), _translate("MainWindow", "Frequency Response")) self.mttapsPush.setToolTip(_translate("MainWindow", "Filter Taps")) self.mttapsPush.setText(_translate("MainWindow", "...")) self.mtstepPush.setToolTip(_translate("MainWindow", "Step Response")) self.mtstepPush.setText(_translate("MainWindow", "...")) self.mtimpPush.setToolTip(_translate("MainWindow", "Impulse Response")) self.mtimpPush.setText(_translate("MainWindow", "...")) - self.mtimeTabgroup.setTabText(self.mtimeTabgroup.indexOf(self.mtimeTab), _translate("MainWindow", "Time responses")) - self.mfilterspecView.setTabText(self.mfilterspecView.indexOf(self.mbandDiagram), _translate("MainWindow", "Ideal Band")) + self.mtimeTabgroup.setTabText(self.mtimeTabgroup.indexOf( + self.mtimeTab), _translate("MainWindow", "Time responses")) + self.mfilterspecView.setTabText(self.mfilterspecView.indexOf( + self.mbandDiagram), _translate("MainWindow", "Ideal Band")) self.maddzeroPush.setToolTip(_translate("MainWindow", "Add zero")) self.maddzeroPush.setText(_translate("MainWindow", "...")) self.maddpolePush.setToolTip(_translate("MainWindow", "Add pole")) @@ -1226,140 +1446,216 @@ def retranslateUi(self, MainWindow): self.mdelPush.setText(_translate("MainWindow", "...")) self.mconjPush.setToolTip(_translate("MainWindow", "Conjugate")) self.mconjPush.setText(_translate("MainWindow", "...")) - self.mfilterspecView.setTabText(self.mfilterspecView.indexOf(self.mpoleZero), _translate("MainWindow", "Pole-Zero Plot")) - self.mfilterspecView.setTabText(self.mfilterspecView.indexOf(self.mfcTab), _translate("MainWindow", "Filter Coefficients")) + self.mfilterspecView.setTabText(self.mfilterspecView.indexOf( + self.mpoleZero), _translate("MainWindow", "Pole-Zero Plot")) + self.mfilterspecView.setTabText(self.mfilterspecView.indexOf( + self.mfcTab), _translate("MainWindow", "Filter Coefficients")) self.fselectComboBox.setItemText(0, _translate("MainWindow", "FIR")) self.fselectComboBox.setItemText(1, _translate("MainWindow", "IIR")) - self.filterTypeComboBox.setItemText(0, _translate("MainWindow", "Low Pass")) - self.filterTypeComboBox.setItemText(1, _translate("MainWindow", "High Pass")) - self.filterTypeComboBox.setItemText(2, _translate("MainWindow", "Band Pass")) - self.filterTypeComboBox.setItemText(3, _translate("MainWindow", "Complex Band Pass")) - self.filterTypeComboBox.setItemText(4, _translate("MainWindow", "Band Notch")) - self.filterTypeComboBox.setItemText(5, _translate("MainWindow", "Root Raised Cosine")) - self.filterTypeComboBox.setItemText(6, _translate("MainWindow", "Gaussian")) - self.filterTypeComboBox.setItemText(7, _translate("MainWindow", "Half Band")) - self.iirfilterBandComboBox.setItemText(0, _translate("MainWindow", "Low Pass")) - self.iirfilterBandComboBox.setItemText(1, _translate("MainWindow", "Band Pass")) - self.iirfilterBandComboBox.setItemText(2, _translate("MainWindow", "Band Stop")) - self.iirfilterBandComboBox.setItemText(3, _translate("MainWindow", "High Pass")) - self.adComboBox.setItemText(0, _translate("MainWindow", "Digital (normalized 0-1)")) - self.adComboBox.setItemText(1, _translate("MainWindow", "Analog (rad/second)")) - self.filterDesignTypeComboBox.setItemText(0, _translate("MainWindow", "Hamming Window")) - self.filterDesignTypeComboBox.setItemText(1, _translate("MainWindow", "Hann Window")) - self.filterDesignTypeComboBox.setItemText(2, _translate("MainWindow", "Blackman Window")) - self.filterDesignTypeComboBox.setItemText(3, _translate("MainWindow", "Rectangular Window")) - self.filterDesignTypeComboBox.setItemText(4, _translate("MainWindow", "Kaiser Window")) - self.filterDesignTypeComboBox.setItemText(5, _translate("MainWindow", "Blackman-harris Window")) - self.filterDesignTypeComboBox.setItemText(6, _translate("MainWindow", "Equiripple")) - self.iirfilterTypeComboBox.setItemText(0, _translate("MainWindow", "Elliptic")) - self.iirfilterTypeComboBox.setItemText(1, _translate("MainWindow", "Butterworth")) - self.iirfilterTypeComboBox.setItemText(2, _translate("MainWindow", "Chebyshev-1")) - self.iirfilterTypeComboBox.setItemText(3, _translate("MainWindow", "Chebyshev-2")) - self.iirfilterTypeComboBox.setItemText(4, _translate("MainWindow", "Bessel")) - self.sampleRateLabel.setText(_translate("MainWindow", "Sample Rate (sps)")) + self.filterTypeComboBox.setItemText( + 0, _translate("MainWindow", "Low Pass")) + self.filterTypeComboBox.setItemText( + 1, _translate("MainWindow", "High Pass")) + self.filterTypeComboBox.setItemText( + 2, _translate("MainWindow", "Band Pass")) + self.filterTypeComboBox.setItemText( + 3, _translate("MainWindow", "Complex Band Pass")) + self.filterTypeComboBox.setItemText( + 4, _translate("MainWindow", "Band Notch")) + self.filterTypeComboBox.setItemText( + 5, _translate("MainWindow", "Root Raised Cosine")) + self.filterTypeComboBox.setItemText( + 6, _translate("MainWindow", "Gaussian")) + self.filterTypeComboBox.setItemText( + 7, _translate("MainWindow", "Half Band")) + self.iirfilterBandComboBox.setItemText( + 0, _translate("MainWindow", "Low Pass")) + self.iirfilterBandComboBox.setItemText( + 1, _translate("MainWindow", "Band Pass")) + self.iirfilterBandComboBox.setItemText( + 2, _translate("MainWindow", "Band Stop")) + self.iirfilterBandComboBox.setItemText( + 3, _translate("MainWindow", "High Pass")) + self.adComboBox.setItemText(0, _translate( + "MainWindow", "Digital (normalized 0-1)")) + self.adComboBox.setItemText(1, _translate( + "MainWindow", "Analog (rad/second)")) + self.filterDesignTypeComboBox.setItemText( + 0, _translate("MainWindow", "Hamming Window")) + self.filterDesignTypeComboBox.setItemText( + 1, _translate("MainWindow", "Hann Window")) + self.filterDesignTypeComboBox.setItemText( + 2, _translate("MainWindow", "Blackman Window")) + self.filterDesignTypeComboBox.setItemText( + 3, _translate("MainWindow", "Rectangular Window")) + self.filterDesignTypeComboBox.setItemText( + 4, _translate("MainWindow", "Kaiser Window")) + self.filterDesignTypeComboBox.setItemText( + 5, _translate("MainWindow", "Blackman-harris Window")) + self.filterDesignTypeComboBox.setItemText( + 6, _translate("MainWindow", "Equiripple")) + self.iirfilterTypeComboBox.setItemText( + 0, _translate("MainWindow", "Elliptic")) + self.iirfilterTypeComboBox.setItemText( + 1, _translate("MainWindow", "Butterworth")) + self.iirfilterTypeComboBox.setItemText( + 2, _translate("MainWindow", "Chebyshev-1")) + self.iirfilterTypeComboBox.setItemText( + 3, _translate("MainWindow", "Chebyshev-2")) + self.iirfilterTypeComboBox.setItemText( + 4, _translate("MainWindow", "Bessel")) + self.sampleRateLabel.setText( + _translate("MainWindow", "Sample Rate (sps)")) self.sampleRateEdit.setText(_translate("MainWindow", "320000")) self.filterGainLabel.setText(_translate("MainWindow", "Filter Gain")) self.filterGainEdit.setText(_translate("MainWindow", "2")) - self.endofLpfPassBandLabel.setText(_translate("MainWindow", "End of Pass Band (Hz)")) + self.endofLpfPassBandLabel.setText( + _translate("MainWindow", "End of Pass Band (Hz)")) self.endofLpfPassBandEdit.setText(_translate("MainWindow", "50000")) - self.startofLpfStopBandLabel.setText(_translate("MainWindow", "Start of Stop Band (Hz)")) + self.startofLpfStopBandLabel.setText( + _translate("MainWindow", "Start of Stop Band (Hz)")) self.startofLpfStopBandEdit.setText(_translate("MainWindow", "60000")) - self.lpfStopBandAttenLabel.setText(_translate("MainWindow", "Stop Band Attenuation (dB)")) + self.lpfStopBandAttenLabel.setText(_translate( + "MainWindow", "Stop Band Attenuation (dB)")) self.lpfStopBandAttenEdit.setText(_translate("MainWindow", "40")) - self.lpfPassBandRippleLabel.setText(_translate("MainWindow", "Pass Band Ripple (dB)")) + self.lpfPassBandRippleLabel.setText( + _translate("MainWindow", "Pass Band Ripple (dB)")) self.lpfPassBandRippleEdit.setText(_translate("MainWindow", "1")) - self.startofBpfPassBandLabel.setText(_translate("MainWindow", "Start of Pass Band (Hz)")) + self.startofBpfPassBandLabel.setText( + _translate("MainWindow", "Start of Pass Band (Hz)")) self.startofBpfPassBandEdit.setText(_translate("MainWindow", "50000")) - self.endofBpfPassBandLabel.setText(_translate("MainWindow", "End of Pass Band (Hz)")) + self.endofBpfPassBandLabel.setText( + _translate("MainWindow", "End of Pass Band (Hz)")) self.endofBpfPassBandEdit.setText(_translate("MainWindow", "80000")) self.bpfStopBandAttenEdit.setText(_translate("MainWindow", "40")) - self.bpfStopBandAttenLabel.setText(_translate("MainWindow", "Stop Band Attenuation (dB)")) - self.bpfTransitionLabel.setText(_translate("MainWindow", "Transition Width (Hz)")) + self.bpfStopBandAttenLabel.setText(_translate( + "MainWindow", "Stop Band Attenuation (dB)")) + self.bpfTransitionLabel.setText(_translate( + "MainWindow", "Transition Width (Hz)")) self.bpfTransitionEdit.setText(_translate("MainWindow", "10000")) self.bpfPassBandRippleEdit.setText(_translate("MainWindow", "1")) - self.bpfPassBandRippleLabel.setText(_translate("MainWindow", "Pass Band Ripple (dB)")) - self.startofBnfStopBandLabel.setText(_translate("MainWindow", "Start of Stop Band (Hz)")) + self.bpfPassBandRippleLabel.setText( + _translate("MainWindow", "Pass Band Ripple (dB)")) + self.startofBnfStopBandLabel.setText( + _translate("MainWindow", "Start of Stop Band (Hz)")) self.startofBnfStopBandEdit.setText(_translate("MainWindow", "50000")) - self.endofBnfStopBandLabel.setText(_translate("MainWindow", "End of Stop Band (Hz)")) + self.endofBnfStopBandLabel.setText( + _translate("MainWindow", "End of Stop Band (Hz)")) self.endofBnfStopBandEdit.setText(_translate("MainWindow", "80000")) - self.bnfTransitionLabel.setText(_translate("MainWindow", "Transition Width (Hz)")) + self.bnfTransitionLabel.setText(_translate( + "MainWindow", "Transition Width (Hz)")) self.bnfTransitionEdit.setText(_translate("MainWindow", "10000")) - self.bnfStopBandAttenLabel.setText(_translate("MainWindow", "Stop Band Attenuation (dB)")) + self.bnfStopBandAttenLabel.setText(_translate( + "MainWindow", "Stop Band Attenuation (dB)")) self.bnfStopBandAttenEdit.setText(_translate("MainWindow", "48")) - self.bnfPassBandRippleLabel.setText(_translate("MainWindow", "Pass Band Ripple (dB)")) + self.bnfPassBandRippleLabel.setText( + _translate("MainWindow", "Pass Band Ripple (dB)")) self.bnfPassBandRippleEdit.setText(_translate("MainWindow", "1")) - self.endofHpfStopBandLabel.setText(_translate("MainWindow", "End of Stop Band (Hz)")) + self.endofHpfStopBandLabel.setText( + _translate("MainWindow", "End of Stop Band (Hz)")) self.endofHpfStopBandEdit.setText(_translate("MainWindow", "50000")) - self.startofHpfPassBandLabel.setText(_translate("MainWindow", "Start of Pass Band (Hz)")) + self.startofHpfPassBandLabel.setText( + _translate("MainWindow", "Start of Pass Band (Hz)")) self.startofHpfPassBandEdit.setText(_translate("MainWindow", "55000")) - self.hpfStopBandAttenLabel.setText(_translate("MainWindow", "Stop Band Attenuation (dB)")) + self.hpfStopBandAttenLabel.setText(_translate( + "MainWindow", "Stop Band Attenuation (dB)")) self.hpfStopBandAttenEdit.setText(_translate("MainWindow", "48")) - self.hpfPassBandRippleLabel.setText(_translate("MainWindow", "Pass Band Ripple (dB)")) + self.hpfPassBandRippleLabel.setText( + _translate("MainWindow", "Pass Band Ripple (dB)")) self.hpfPassBandRippleEdit.setText(_translate("MainWindow", "1")) - self.rrcSymbolRateLabel.setText(_translate("MainWindow", "Symbol Rate (sps)")) + self.rrcSymbolRateLabel.setText( + _translate("MainWindow", "Symbol Rate (sps)")) self.rrcAlphaLabel.setText(_translate("MainWindow", "Roll-off Factor")) - self.rrcNumTapsLabel.setText(_translate("MainWindow", "Number of Taps")) + self.rrcNumTapsLabel.setText( + _translate("MainWindow", "Number of Taps")) self.rrcSymbolRateEdit.setText(_translate("MainWindow", "3200")) self.rrcAlphaEdit.setText(_translate("MainWindow", "15")) self.rrcNumTapsEdit.setText(_translate("MainWindow", "50")) - self.gausSymbolRateLabel.setText(_translate("MainWindow", "Symbol Rate (sps)")) + self.gausSymbolRateLabel.setText( + _translate("MainWindow", "Symbol Rate (sps)")) self.gausSymbolRateEdit.setText(_translate("MainWindow", "5000")) self.gausBTLabel.setText(_translate("MainWindow", "Roll-off Factor")) self.gausBTEdit.setText(_translate("MainWindow", "0.5")) - self.gausNumTapsLabel.setText(_translate("MainWindow", "Number of Taps")) + self.gausNumTapsLabel.setText( + _translate("MainWindow", "Number of Taps")) self.gausNumTapsEdit.setText(_translate("MainWindow", "30")) - self.iirendofLpfPassBandLabel.setText(_translate("MainWindow", "End of Pass Band")) + self.iirendofLpfPassBandLabel.setText( + _translate("MainWindow", "End of Pass Band")) self.iirendofLpfPassBandEdit.setText(_translate("MainWindow", "0.3")) - self.iirstartofLpfStopBandLabel.setText(_translate("MainWindow", "Start of Stop Band ")) + self.iirstartofLpfStopBandLabel.setText( + _translate("MainWindow", "Start of Stop Band ")) self.iirstartofLpfStopBandEdit.setText(_translate("MainWindow", "0.5")) - self.iirLpfPassBandAttenLabel.setText(_translate("MainWindow", "Max loss in Pass Band (dB)")) + self.iirLpfPassBandAttenLabel.setText( + _translate("MainWindow", "Max loss in Pass Band (dB)")) self.iirLpfPassBandAttenEdit.setText(_translate("MainWindow", "1")) - self.iirLpfStopBandRippleLabel.setText(_translate("MainWindow", "Min atten in Stop Band (dB)")) + self.iirLpfStopBandRippleLabel.setText( + _translate("MainWindow", "Min atten in Stop Band (dB)")) self.iirLpfStopBandRippleEdit.setText(_translate("MainWindow", "60")) - self.iirendofHpfStopBandLabel.setText(_translate("MainWindow", "End of Stop Band")) + self.iirendofHpfStopBandLabel.setText( + _translate("MainWindow", "End of Stop Band")) self.iirendofHpfStopBandEdit.setText(_translate("MainWindow", "0.3")) - self.iirstartofHpfPassBandLabel.setText(_translate("MainWindow", "Start of Pass Band ")) + self.iirstartofHpfPassBandLabel.setText( + _translate("MainWindow", "Start of Pass Band ")) self.iirstartofHpfPassBandEdit.setText(_translate("MainWindow", "0.5")) - self.iirHpfPassBandAttenLabel.setText(_translate("MainWindow", "Max loss in Pass Band (dB)")) + self.iirHpfPassBandAttenLabel.setText( + _translate("MainWindow", "Max loss in Pass Band (dB)")) self.iirHpfPassBandAttenEdit.setText(_translate("MainWindow", "1")) - self.iirHpfStopBandRippleLabel.setText(_translate("MainWindow", "Min atten in Stop Band (dB)")) + self.iirHpfStopBandRippleLabel.setText( + _translate("MainWindow", "Min atten in Stop Band (dB)")) self.iirHpfStopBandRippleEdit.setText(_translate("MainWindow", "60")) - self.iirendofBpfStopBandLabel1.setText(_translate("MainWindow", "End of Stop Band-1")) + self.iirendofBpfStopBandLabel1.setText( + _translate("MainWindow", "End of Stop Band-1")) self.iirendofBpfStopBandEdit1.setText(_translate("MainWindow", "0.2")) - self.iirstartofBpfPassBandLabel.setText(_translate("MainWindow", "Start of Pass Band ")) + self.iirstartofBpfPassBandLabel.setText( + _translate("MainWindow", "Start of Pass Band ")) self.iirstartofBpfPassBandEdit.setText(_translate("MainWindow", "0.3")) - self.iirendofBpfPassBandLabel.setText(_translate("MainWindow", "End of Pass Band ")) + self.iirendofBpfPassBandLabel.setText( + _translate("MainWindow", "End of Pass Band ")) self.iirendofBpfPassBandEdit.setText(_translate("MainWindow", "0.5")) - self.iirstartofBpfStopBandLabel2.setText(_translate("MainWindow", "Start of Stop Band-2")) - self.iirstartofBpfStopBandEdit2.setText(_translate("MainWindow", "0.6")) - self.iirBpfPassBandAttenLabel.setText(_translate("MainWindow", "Max loss in Pass Band (dB)")) + self.iirstartofBpfStopBandLabel2.setText( + _translate("MainWindow", "Start of Stop Band-2")) + self.iirstartofBpfStopBandEdit2.setText( + _translate("MainWindow", "0.6")) + self.iirBpfPassBandAttenLabel.setText( + _translate("MainWindow", "Max loss in Pass Band (dB)")) self.iirBpfPassBandAttenEdit.setText(_translate("MainWindow", "1")) - self.iirBpfStopBandRippleLabel.setText(_translate("MainWindow", "Min atten in Stop Band (dB)")) + self.iirBpfStopBandRippleLabel.setText( + _translate("MainWindow", "Min atten in Stop Band (dB)")) self.iirBpfStopBandRippleEdit.setText(_translate("MainWindow", "60")) - self.iirendofBsfPassBandLabel1.setText(_translate("MainWindow", "End of Pass Band-1")) + self.iirendofBsfPassBandLabel1.setText( + _translate("MainWindow", "End of Pass Band-1")) self.iirendofBsfPassBandEdit1.setText(_translate("MainWindow", "0.2")) - self.iirstartofBsfStopBandLabel.setText(_translate("MainWindow", "Start of Stop Band ")) + self.iirstartofBsfStopBandLabel.setText( + _translate("MainWindow", "Start of Stop Band ")) self.iirstartofBsfStopBandEdit.setText(_translate("MainWindow", "0.3")) - self.iirendofBsfStopBandLabel.setText(_translate("MainWindow", "End of Stop Band ")) + self.iirendofBsfStopBandLabel.setText( + _translate("MainWindow", "End of Stop Band ")) self.iirendofBsfStopBandEdit.setText(_translate("MainWindow", "0.6")) - self.iirstartofBsfPassBandLabel2.setText(_translate("MainWindow", "Start of Pass Band-2")) - self.iirstartofBsfPassBandEdit2.setText(_translate("MainWindow", "0.7")) - self.iirBsfPassBandAttenLabel.setText(_translate("MainWindow", "Max loss in Pass Band (dB)")) + self.iirstartofBsfPassBandLabel2.setText( + _translate("MainWindow", "Start of Pass Band-2")) + self.iirstartofBsfPassBandEdit2.setText( + _translate("MainWindow", "0.7")) + self.iirBsfPassBandAttenLabel.setText( + _translate("MainWindow", "Max loss in Pass Band (dB)")) self.iirBsfPassBandAttenEdit.setText(_translate("MainWindow", "1")) - self.iirBsfStopBandRippleLabel.setText(_translate("MainWindow", "Min atten in Stop Band (dB)")) + self.iirBsfStopBandRippleLabel.setText( + _translate("MainWindow", "Min atten in Stop Band (dB)")) self.iirBsfStopBandRippleEdit.setText(_translate("MainWindow", "60")) self.besselordLabel.setText(_translate("MainWindow", "Filter Order")) self.besselordEdit.setText(_translate("MainWindow", "10")) - self.iirbesselcritLabel1.setText(_translate("MainWindow", "Critical point-1")) + self.iirbesselcritLabel1.setText( + _translate("MainWindow", "Critical point-1")) self.iirbesselcritEdit1.setText(_translate("MainWindow", "0.2")) self.iirbesselcritEdit2.setText(_translate("MainWindow", "0.5")) - self.iirbesselcritLabel2.setText(_translate("MainWindow", "Critical point-2")) + self.iirbesselcritLabel2.setText( + _translate("MainWindow", "Critical point-2")) self.firhbordLabel.setText(_translate("MainWindow", "Filter Order")) self.firhbordEdit.setText(_translate("MainWindow", "34")) self.firhbtrEditLabel2.setText(_translate("MainWindow", "Transition width\n" -" (from fs/4)")) + " (from fs/4)")) self.firhbtrEdit.setText(_translate("MainWindow", "10000")) - self.filterPropsBox.setTitle(_translate("MainWindow", "Filter Properties")) + self.filterPropsBox.setTitle( + _translate("MainWindow", "Filter Properties")) self.nTapsLabel.setText(_translate("MainWindow", "Number of Taps:")) self.designButton.setText(_translate("MainWindow", "Design")) self.menu_File.setTitle(_translate("MainWindow", "&File")) @@ -1370,42 +1666,60 @@ def retranslateUi(self, MainWindow): self.action_save.setShortcut(_translate("MainWindow", "Ctrl+S")) self.action_open.setText(_translate("MainWindow", "&Open")) self.action_open.setShortcut(_translate("MainWindow", "Ctrl+O")) - self.actionMagnitude_Response.setText(_translate("MainWindow", "&Magnitude Response")) - self.actionPhase_Respone.setText(_translate("MainWindow", "&Phase Respone")) - self.actionGroup_Delay.setText(_translate("MainWindow", "&Group Delay")) - self.actionPhase_Delay.setText(_translate("MainWindow", "P&hase Delay")) - self.actionImpulse_Response.setText(_translate("MainWindow", "&Impulse Response")) - self.actionStep_Response.setText(_translate("MainWindow", "&Step Response")) - self.actionPole_Zero_Plot.setText(_translate("MainWindow", "Pole-Zero Plot")) + self.actionMagnitude_Response.setText( + _translate("MainWindow", "&Magnitude Response")) + self.actionPhase_Respone.setText( + _translate("MainWindow", "&Phase Respone")) + self.actionGroup_Delay.setText( + _translate("MainWindow", "&Group Delay")) + self.actionPhase_Delay.setText( + _translate("MainWindow", "P&hase Delay")) + self.actionImpulse_Response.setText( + _translate("MainWindow", "&Impulse Response")) + self.actionStep_Response.setText( + _translate("MainWindow", "&Step Response")) + self.actionPole_Zero_Plot.setText( + _translate("MainWindow", "Pole-Zero Plot")) self.actionGrid.setText(_translate("MainWindow", "Grid")) - self.actionPole_Zero_Plot_2.setText(_translate("MainWindow", "Pole &Zero Plot")) + self.actionPole_Zero_Plot_2.setText( + _translate("MainWindow", "Pole &Zero Plot")) self.actionIdeal_Band.setText(_translate("MainWindow", "Id&eal Band")) self.actionGrid_2.setText(_translate("MainWindow", "Grid")) self.actionGrid_3.setText(_translate("MainWindow", "Grid")) self.actionTabbed.setText(_translate("MainWindow", "Tabbed")) self.actionOverlay.setText(_translate("MainWindow", "Overlay")) - self.actionResponse_widget.setText(_translate("MainWindow", "Response widget")) + self.actionResponse_widget.setText( + _translate("MainWindow", "Response widget")) self.actionSpec_widget.setText(_translate("MainWindow", "Spec widget")) - self.actionQuick_access.setText(_translate("MainWindow", "Quick access")) - self.actionFilter_Coefficients.setText(_translate("MainWindow", "&Filter Coefficients")) - self.actionDesign_widget.setText(_translate("MainWindow", "Design widget")) + self.actionQuick_access.setText( + _translate("MainWindow", "Quick access")) + self.actionFilter_Coefficients.setText( + _translate("MainWindow", "&Filter Coefficients")) + self.actionDesign_widget.setText( + _translate("MainWindow", "Design widget")) self.actionOverlay_2.setText(_translate("MainWindow", "Overlay")) self.actionGridview.setText(_translate("MainWindow", "&Gridview")) - self.actionDesign_widget_2.setText(_translate("MainWindow", "Design widget")) - self.actionQuick_access_2.setText(_translate("MainWindow", "Quick access")) - self.actionSpec_widget_2.setText(_translate("MainWindow", "Spec widget")) - self.actionResponse_widget_2.setText(_translate("MainWindow", "Response widget")) - self.actionDesign_Widget.setText(_translate("MainWindow", "&Design Widget")) - self.actionQuick_Access.setText(_translate("MainWindow", "&Quick Access")) - self.actionSpec_Widget.setText(_translate("MainWindow", "Spec &Widget")) - self.actionResponse_Widget.setText(_translate("MainWindow", "&Response Widget")) + self.actionDesign_widget_2.setText( + _translate("MainWindow", "Design widget")) + self.actionQuick_access_2.setText( + _translate("MainWindow", "Quick access")) + self.actionSpec_widget_2.setText( + _translate("MainWindow", "Spec widget")) + self.actionResponse_widget_2.setText( + _translate("MainWindow", "Response widget")) + self.actionDesign_Widget.setText( + _translate("MainWindow", "&Design Widget")) + self.actionQuick_Access.setText( + _translate("MainWindow", "&Quick Access")) + self.actionSpec_Widget.setText( + _translate("MainWindow", "Spec &Widget")) + self.actionResponse_Widget.setText( + _translate("MainWindow", "&Response Widget")) self.actionTabview_2.setText(_translate("MainWindow", "Tabview")) - self.actionPlot_select.setText(_translate("MainWindow", "&Plot select")) - self.actionBand_Diagram.setText(_translate("MainWindow", "&Band Diagram")) + self.actionPlot_select.setText( + _translate("MainWindow", "&Plot select")) + self.actionBand_Diagram.setText( + _translate("MainWindow", "&Band Diagram")) self.actionCheck.setText(_translate("MainWindow", "check")) - self.actionPlot_FFT_points.setText(_translate("MainWindow", "Plot FFT points")) - -from .GrFilterPlotWidget import GrFilterPlotWidget -from .bandgraphicsview import BandGraphicsView -from .polezero_plot import PzPlot -from . import icons_rc + self.actionPlot_FFT_points.setText( + _translate("MainWindow", "Plot FFT points")) diff --git a/gr-filter/python/filter/optfir.py b/gr-filter/python/filter/optfir.py index 1e6ac5b5442..21fa53bc483 100644 --- a/gr-filter/python/filter/optfir.py +++ b/gr-filter/python/filter/optfir.py @@ -16,14 +16,15 @@ ''' - -import math, cmath +import math +import cmath from . import filter_python as filter # ---------------------------------------------------------------- -def low_pass (gain, Fs, freq1, freq2, passband_ripple_db, stopband_atten_db, - nextra_taps=2): + +def low_pass(gain, Fs, freq1, freq2, passband_ripple_db, stopband_atten_db, + nextra_taps=2): """ Builds a low pass filter. @@ -36,18 +37,19 @@ def low_pass (gain, Fs, freq1, freq2, passband_ripple_db, stopband_atten_db, stopband_atten_db: Stop band attenuation in dB (should be large, >= 60) nextra_taps: Extra taps to use in the filter (default=2) """ - passband_dev = passband_ripple_to_dev (passband_ripple_db) - stopband_dev = stopband_atten_to_dev (stopband_atten_db) + passband_dev = passband_ripple_to_dev(passband_ripple_db) + stopband_dev = stopband_atten_to_dev(stopband_atten_db) desired_ampls = (gain, 0) - (n, fo, ao, w) = remezord ([freq1, freq2], desired_ampls, - [passband_dev, stopband_dev], Fs) + (n, fo, ao, w) = remezord([freq1, freq2], desired_ampls, + [passband_dev, stopband_dev], Fs) # The remezord typically under-estimates the filter order, so add 2 taps by default - taps = filter.pm_remez (n + nextra_taps, fo, ao, w, "bandpass") + taps = filter.pm_remez(n + nextra_taps, fo, ao, w, "bandpass") return taps -def band_pass (gain, Fs, freq_sb1, freq_pb1, freq_pb2, freq_sb2, - passband_ripple_db, stopband_atten_db, - nextra_taps=2): + +def band_pass(gain, Fs, freq_sb1, freq_pb1, freq_pb2, freq_sb2, + passband_ripple_db, stopband_atten_db, + nextra_taps=2): """ Builds a band pass filter. @@ -62,20 +64,21 @@ def band_pass (gain, Fs, freq_sb1, freq_pb1, freq_pb2, freq_sb2, stopband_atten_db: Stop band attenuation in dB (should be large, >= 60) nextra_taps: Extra taps to use in the filter (default=2) """ - passband_dev = passband_ripple_to_dev (passband_ripple_db) - stopband_dev = stopband_atten_to_dev (stopband_atten_db) + passband_dev = passband_ripple_to_dev(passband_ripple_db) + stopband_dev = stopband_atten_to_dev(stopband_atten_db) desired_ampls = (0, gain, 0) desired_freqs = [freq_sb1, freq_pb1, freq_pb2, freq_sb2] desired_ripple = [stopband_dev, passband_dev, stopband_dev] - (n, fo, ao, w) = remezord (desired_freqs, desired_ampls, - desired_ripple, Fs) + (n, fo, ao, w) = remezord(desired_freqs, desired_ampls, + desired_ripple, Fs) # The remezord typically under-estimates the filter order, so add 2 taps by default - taps = filter.pm_remez (n + nextra_taps, fo, ao, w, "bandpass") + taps = filter.pm_remez(n + nextra_taps, fo, ao, w, "bandpass") return taps -def complex_band_pass (gain, Fs, freq_sb1, freq_pb1, freq_pb2, freq_sb2, - passband_ripple_db, stopband_atten_db, - nextra_taps=2): + +def complex_band_pass(gain, Fs, freq_sb1, freq_pb1, freq_pb2, freq_sb2, + passband_ripple_db, stopband_atten_db, + nextra_taps=2): """ Builds a band pass filter with complex taps by making an LPF and spinning it up to the right center frequency @@ -96,13 +99,15 @@ def complex_band_pass (gain, Fs, freq_sb1, freq_pb1, freq_pb2, freq_sb2, lp_sb = freq_sb2 - center_freq lptaps = low_pass(gain, Fs, lp_pb, lp_sb, passband_ripple_db, stopband_atten_db, nextra_taps) - spinner = [cmath.exp(2j*cmath.pi*center_freq/Fs*i) for i in range(len(lptaps))] - taps = [s*t for s,t in zip(spinner, lptaps)] + spinner = [cmath.exp(2j * cmath.pi * center_freq / Fs * i) + for i in range(len(lptaps))] + taps = [s * t for s, t in zip(spinner, lptaps)] return taps -def complex_band_reject (gain, Fs, freq_pb1, freq_sb1, freq_sb2, freq_pb2, - passband_ripple_db, stopband_atten_db, - nextra_taps=2): + +def complex_band_reject(gain, Fs, freq_pb1, freq_sb1, freq_sb2, freq_pb2, + passband_ripple_db, stopband_atten_db, + nextra_taps=2): """ Builds a band reject filter with complex taps by making an HPF and spinning it up to the right center frequency @@ -122,14 +127,16 @@ def complex_band_reject (gain, Fs, freq_pb1, freq_sb1, freq_sb2, freq_pb2, hp_pb = (freq_pb2 - center_freq) / 1.0 hp_sb = freq_sb2 - center_freq hptaps = high_pass(gain, Fs, hp_sb, hp_pb, passband_ripple_db, - stopband_atten_db, nextra_taps) - spinner = [cmath.exp(2j*cmath.pi*center_freq/Fs*i) for i in range(len(hptaps))] - taps = [s*t for s,t in zip(spinner, hptaps)] + stopband_atten_db, nextra_taps) + spinner = [cmath.exp(2j * cmath.pi * center_freq / Fs * i) + for i in range(len(hptaps))] + taps = [s * t for s, t in zip(spinner, hptaps)] return taps -def band_reject (gain, Fs, freq_pb1, freq_sb1, freq_sb2, freq_pb2, - passband_ripple_db, stopband_atten_db, - nextra_taps=2): + +def band_reject(gain, Fs, freq_pb1, freq_sb1, freq_sb2, freq_pb2, + passband_ripple_db, stopband_atten_db, + nextra_taps=2): """ Builds a band reject filter spinning it up to the right center frequency @@ -145,23 +152,23 @@ def band_reject (gain, Fs, freq_pb1, freq_sb1, freq_sb2, freq_pb2, stopband_atten_db: Stop band attenuation in dB (should be large, >= 60) nextra_taps: Extra taps to use in the filter (default=2) """ - passband_dev = passband_ripple_to_dev (passband_ripple_db) - stopband_dev = stopband_atten_to_dev (stopband_atten_db) + passband_dev = passband_ripple_to_dev(passband_ripple_db) + stopband_dev = stopband_atten_to_dev(stopband_atten_db) desired_ampls = (gain, 0, gain) desired_freqs = [freq_pb1, freq_sb1, freq_sb2, freq_pb2] desired_ripple = [passband_dev, stopband_dev, passband_dev] - (n, fo, ao, w) = remezord (desired_freqs, desired_ampls, - desired_ripple, Fs) + (n, fo, ao, w) = remezord(desired_freqs, desired_ampls, + desired_ripple, Fs) # Make sure we use an odd number of taps - if((n+nextra_taps)%2 == 1): + if((n + nextra_taps) % 2 == 1): n += 1 # The remezord typically under-estimates the filter order, so add 2 taps by default - taps = filter.pm_remez (n + nextra_taps, fo, ao, w, "bandpass") + taps = filter.pm_remez(n + nextra_taps, fo, ao, w, "bandpass") return taps -def high_pass (gain, Fs, freq1, freq2, passband_ripple_db, stopband_atten_db, - nextra_taps=2): +def high_pass(gain, Fs, freq1, freq2, passband_ripple_db, stopband_atten_db, + nextra_taps=2): """ Builds a high pass filter. @@ -174,33 +181,36 @@ def high_pass (gain, Fs, freq1, freq2, passband_ripple_db, stopband_atten_db, stopband_atten_db: Stop band attenuation in dB (should be large, >= 60) nextra_taps: Extra taps to use in the filter (default=2) """ - passband_dev = passband_ripple_to_dev (passband_ripple_db) - stopband_dev = stopband_atten_to_dev (stopband_atten_db) + passband_dev = passband_ripple_to_dev(passband_ripple_db) + stopband_dev = stopband_atten_to_dev(stopband_atten_db) desired_ampls = (0, 1) - (n, fo, ao, w) = remezord ([freq1, freq2], desired_ampls, - [stopband_dev, passband_dev], Fs) + (n, fo, ao, w) = remezord([freq1, freq2], desired_ampls, + [stopband_dev, passband_dev], Fs) # For a HPF, we need to use an odd number of taps # In filter.remez, ntaps = n+1, so n must be even - if((n+nextra_taps)%2 == 1): + if((n + nextra_taps) % 2 == 1): n += 1 # The remezord typically under-estimates the filter order, so add 2 taps by default - taps = filter.pm_remez (n + nextra_taps, fo, ao, w, "bandpass") + taps = filter.pm_remez(n + nextra_taps, fo, ao, w, "bandpass") return taps # ---------------------------------------------------------------- -def stopband_atten_to_dev (atten_db): + +def stopband_atten_to_dev(atten_db): """Convert a stopband attenuation in dB to an absolute value""" return 10**(-atten_db / 20) -def passband_ripple_to_dev (ripple_db): + +def passband_ripple_to_dev(ripple_db): """Convert passband ripple spec expressed in dB to an absolute value""" - return (10**(ripple_db / 20)-1)/(10**(ripple_db / 20)+1) + return (10**(ripple_db / 20) - 1) / (10**(ripple_db / 20) + 1) # ---------------------------------------------------------------- -def remezord (fcuts, mags, devs, fsamp = 2): + +def remezord(fcuts, mags, devs, fsamp=2): ''' FIR order estimator (lowpass, highpass, bandpass, mulitiband). @@ -244,12 +254,12 @@ def remezord (fcuts, mags, devs, fsamp = 2): mags = mags[:] devs = devs[:] - for i in range (len (fcuts)): - fcuts[i] = float (fcuts[i]) / fsamp + for i in range(len(fcuts)): + fcuts[i] = float(fcuts[i]) / fsamp - nf = len (fcuts) - nm = len (mags) - nd = len (devs) + nf = len(fcuts) + nm = len(mags) + nd = len(devs) nbands = nm if nm != nd: @@ -258,7 +268,7 @@ def remezord (fcuts, mags, devs, fsamp = 2): if nf != 2 * (nbands - 1): raise ValueError("Length of f must be 2 * len (mags) - 2") - for i in range (len (mags)): + for i in range(len(mags)): if mags[i] != 0: # if not stopband, get relative deviation devs[i] = devs[i] / mags[i] @@ -268,45 +278,46 @@ def remezord (fcuts, mags, devs, fsamp = 2): n = 0 min_delta = 2 - for i in range (len (f1)): + for i in range(len(f1)): if f2[i] - f1[i] < min_delta: n = i min_delta = f2[i] - f1[i] if nbands == 2: # lowpass or highpass case (use formula) - l = lporder (f1[n], f2[n], devs[0], devs[1]) + l = lporder(f1[n], f2[n], devs[0], devs[1]) else: # bandpass or multipass case # try different lowpasses and take the worst one that # goes through the BP specs l = 0 - for i in range (1, nbands-1): - l1 = lporder (f1[i-1], f2[i-1], devs[i], devs[i-1]) - l2 = lporder (f1[i], f2[i], devs[i], devs[i+1]) - l = max (l, l1, l2) + for i in range(1, nbands - 1): + l1 = lporder(f1[i - 1], f2[i - 1], devs[i], devs[i - 1]) + l2 = lporder(f1[i], f2[i], devs[i], devs[i + 1]) + l = max(l, l1, l2) - n = int (math.ceil (l)) - 1 # need order, not length for remez + n = int(math.ceil(l)) - 1 # need order, not length for remez # cook up remez compatible result ff = [0] + fcuts + [1] - for i in range (1, len (ff) - 1): + for i in range(1, len(ff) - 1): ff[i] *= 2 aa = [] for a in mags: aa = aa + [a, a] - max_dev = max (devs) + max_dev = max(devs) wts = [1] * len(devs) - for i in range (len (wts)): + for i in range(len(wts)): wts[i] = max_dev / devs[i] return (n, ff, aa, wts) # ---------------------------------------------------------------- -def lporder (freq1, freq2, delta_p, delta_s): + +def lporder(freq1, freq2, delta_p, delta_s): ''' FIR lowpass filter length estimator. freq1 and freq2 are normalized to the sampling frequency. delta_p is the passband @@ -318,9 +329,9 @@ def lporder (freq1, freq2, delta_p, delta_s): From Herrmann et al (1973), Practical design rules for optimum finite impulse response filters. Bell System Technical J., 52, 769-99 ''' - df = abs (freq2 - freq1) - ddp = math.log10 (delta_p) - dds = math.log10 (delta_s) + df = abs(freq2 - freq1) + ddp = math.log10(delta_p) + dds = math.log10(delta_s) a1 = 5.309e-3 a2 = 7.114e-2 @@ -337,13 +348,13 @@ def lporder (freq1, freq2, delta_p, delta_s): t3 = a4 * ddp * ddp t4 = a5 * ddp - dinf=((t1 + t2 + a3) * dds) + (t3 + t4 + a6) + dinf = ((t1 + t2 + a3) * dds) + (t3 + t4 + a6) ff = b1 + b2 * (ddp - dds) n = dinf / df - ff * df + 1 return n -def bporder (freq1, freq2, delta_p, delta_s): +def bporder(freq1, freq2, delta_p, delta_s): ''' FIR bandpass filter length estimator. freq1 and freq2 are normalized to the sampling frequency. delta_p is the passband @@ -351,9 +362,9 @@ def bporder (freq1, freq2, delta_p, delta_s): From Mintzer and Liu (1979) ''' - df = abs (freq2 - freq1) - ddp = math.log10 (delta_p) - dds = math.log10 (delta_s) + df = abs(freq2 - freq1) + ddp = math.log10(delta_p) + dds = math.log10(delta_s) a1 = 0.01201 a2 = 0.09664 @@ -368,6 +379,6 @@ def bporder (freq1, freq2, delta_p, delta_s): t4 = a5 * ddp cinf = dds * (t1 + t2 + a3) + t3 + t4 + a6 - ginf = -14.6 * math.log10 (delta_p / delta_s) - 16.9 + ginf = -14.6 * math.log10(delta_p / delta_s) - 16.9 n = cinf / df + ginf * df + 1 return n diff --git a/gr-filter/python/filter/pfb.py b/gr-filter/python/filter/pfb.py index ce8c3afae08..838883e0162 100644 --- a/gr-filter/python/filter/pfb.py +++ b/gr-filter/python/filter/pfb.py @@ -24,6 +24,7 @@ class channelizer_ccf(gr.hier_block2): This simplifies the interface by allowing a single input stream to connect to this block. It will then output a stream for each channel. ''' + def __init__(self, numchans, taps=None, oversample_rate=1, atten=100): gr.hier_block2.__init__(self, "pfb_channelizer_ccf", gr.io_signature(1, 1, gr.sizeof_gr_complex), @@ -37,14 +38,15 @@ def __init__(self, numchans, taps=None, oversample_rate=1, atten=100): else: self._taps = self.create_taps(self._nchans, atten) - self.s2ss = blocks.stream_to_streams(gr.sizeof_gr_complex, self._nchans) + self.s2ss = blocks.stream_to_streams( + gr.sizeof_gr_complex, self._nchans) self.pfb = filter.pfb_channelizer_ccf(self._nchans, self._taps, self._oversample_rate) self.connect(self, self.s2ss) for i in range(self._nchans): - self.connect((self.s2ss,i), (self.pfb,i)) - self.connect((self.pfb,i), (self,i)) + self.connect((self.s2ss, i), (self.pfb, i)) + self.connect((self.pfb, i), (self, i)) def set_channel_map(self, newmap): self.pfb.set_channel_map(newmap) @@ -57,7 +59,7 @@ def taps(self): def declare_sample_delay(self, delay): self.pfb.declare_sample_delay(delay) - + @staticmethod def create_taps(numchans, atten=100): # Create a filter that covers the full bandwidth of the input signal @@ -66,7 +68,7 @@ def create_taps(numchans, atten=100): ripple = 0.1 while True: try: - taps = optfir.low_pass(1, numchans, bw, bw+tb, ripple, atten) + taps = optfir.low_pass(1, numchans, bw, bw + tb, ripple, atten) return taps except RuntimeError: ripple += 0.01 @@ -74,7 +76,8 @@ def create_taps(numchans, atten=100): # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): - raise RuntimeError("optfir could not generate an appropriate filter.") + raise RuntimeError( + "optfir could not generate an appropriate filter.") class interpolator_ccf(gr.hier_block2): @@ -86,6 +89,7 @@ class interpolator_ccf(gr.hier_block2): streams. This block is provided to be consistent with the interface to the other PFB block. ''' + def __init__(self, interp, taps=None, atten=100): gr.hier_block2.__init__(self, "pfb_interpolator_ccf", gr.io_signature(1, 1, gr.sizeof_gr_complex), @@ -118,7 +122,8 @@ def create_taps(interp, atten): ripple = 0.99 while True: try: - taps = optfir.low_pass(interp, interp, bw, bw+tb, ripple, atten) + taps = optfir.low_pass( + interp, interp, bw, bw + tb, ripple, atten) return taps except RuntimeError: ripple += 0.01 @@ -126,8 +131,8 @@ def create_taps(interp, atten): # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): - raise RuntimeError("optfir could not generate an appropriate filter.") - + raise RuntimeError( + "optfir could not generate an appropriate filter.") class decimator_ccf(gr.hier_block2): @@ -137,6 +142,7 @@ class decimator_ccf(gr.hier_block2): This simplifies the interface by allowing a single input stream to connect to this block. It will then output a stream that is the decimated output stream. ''' + def __init__(self, decim, taps=None, channel=0, atten=100, use_fft_rotators=True, use_fft_filters=True): gr.hier_block2.__init__(self, "pfb_decimator_ccf", @@ -158,7 +164,7 @@ def __init__(self, decim, taps=None, channel=0, atten=100, self.connect(self, self.s2ss) for i in range(self._decim): - self.connect((self.s2ss,i), (self.pfb,i)) + self.connect((self.s2ss, i), (self.pfb, i)) self.connect(self.pfb, self) @@ -170,7 +176,7 @@ def set_channel(self, chan): def declare_sample_delay(self, delay): self.pfb.declare_sample_delay(delay) - + @staticmethod def create_taps(decim, atten=100): # Create a filter that covers the full bandwidth of the input signal @@ -179,7 +185,7 @@ def create_taps(decim, atten=100): ripple = 0.1 while True: try: - taps = optfir.low_pass(1, decim, bw, bw+tb, ripple, atten) + taps = optfir.low_pass(1, decim, bw, bw + tb, ripple, atten) return taps except RuntimeError: ripple += 0.01 @@ -187,7 +193,8 @@ def create_taps(decim, atten=100): # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): - raise RuntimeError("optfir could not generate an appropriate filter.") + raise RuntimeError( + "optfir could not generate an appropriate filter.") class arb_resampler_ccf(gr.hier_block2): @@ -199,10 +206,12 @@ class arb_resampler_ccf(gr.hier_block2): streams. This block is provided to be consistent with the interface to the other PFB block. ''' + def __init__(self, rate, taps=None, flt_size=32, atten=100): gr.hier_block2.__init__(self, "pfb_arb_resampler_ccf", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._rate = rate self._size = flt_size @@ -210,9 +219,10 @@ def __init__(self, rate, taps=None, flt_size=32, atten=100): if (taps is not None) and (len(taps) > 0): self._taps = taps else: - self._taps = self.create_taps(self._rate, self._size, atten); + self._taps = self.create_taps(self._rate, self._size, atten) - self.pfb = filter.pfb_arb_resampler_ccf(self._rate, self._taps, self._size) + self.pfb = filter.pfb_arb_resampler_ccf( + self._rate, self._taps, self._size) #print("PFB has %d taps\n" % (len(self._taps),)) self.connect(self, self.pfb) @@ -239,34 +249,37 @@ def create_taps(rate, flt_size=32, atten=100): # the half-band here is 0.5*rate. percent = 0.80 if(rate < 1): - halfband = 0.5*rate - bw = percent*halfband - tb = (percent / 2.0)*halfband + halfband = 0.5 * rate + bw = percent * halfband + tb = (percent / 2.0) * halfband ripple = 0.1 # As we drop the bw factor, the optfir filter has a harder time converging; # using the firdes method here for better results. return filter.firdes.low_pass_2(flt_size, flt_size, bw, tb, atten, - fft.window.WIN_BLACKMAN_HARRIS) + fft.window.WIN_BLACKMAN_HARRIS) else: halfband = 0.5 - bw = percent*halfband - tb = (percent / 2.0)*halfband + bw = percent * halfband + tb = (percent / 2.0) * halfband ripple = 0.1 taps = None while True: try: - taps = optfir.low_pass(flt_size, flt_size, bw, bw+tb, ripple, atten) + taps = optfir.low_pass( + flt_size, flt_size, bw, bw + tb, ripple, atten) return taps except RuntimeError: ripple += 0.01 - print("Warning: set ripple to %.4f dB. If this is a problem, adjust the attenuation or create your own filter taps." % (ripple)) + print( + "Warning: set ripple to %.4f dB. If this is a problem, adjust the attenuation or create your own filter taps." % (ripple)) # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): - raise RuntimeError("optfir could not generate an appropriate filter.") - + raise RuntimeError( + "optfir could not generate an appropriate filter.") + class arb_resampler_fff(gr.hier_block2): ''' @@ -277,10 +290,12 @@ class arb_resampler_fff(gr.hier_block2): streams. This block is provided to be consistent with the interface to the other PFB block. ''' + def __init__(self, rate, taps=None, flt_size=32, atten=100): gr.hier_block2.__init__(self, "pfb_arb_resampler_fff", - gr.io_signature(1, 1, gr.sizeof_float), # Input signature - gr.io_signature(1, 1, gr.sizeof_float)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_float), + gr.io_signature(1, 1, gr.sizeof_float)) # Output signature self._rate = rate self._size = flt_size @@ -290,8 +305,9 @@ def __init__(self, rate, taps=None, flt_size=32, atten=100): else: self._taps = self.create_taps(self._rate, self._size, atten) - self.pfb = filter.pfb_arb_resampler_fff(self._rate, self._taps, self._size) - #print "PFB has %d taps\n" % (len(self._taps),) + self.pfb = filter.pfb_arb_resampler_fff( + self._rate, self._taps, self._size) + # print "PFB has %d taps\n" % (len(self._taps),) self.connect(self, self.pfb) self.connect(self.pfb, self) @@ -317,32 +333,36 @@ def create_taps(rate, flt_size=32, atten=100): # the half-band here is 0.5*rate. percent = 0.80 if(rate < 1): - halfband = 0.5*rate - bw = percent*halfband - tb = (percent / 2.0)*halfband + halfband = 0.5 * rate + bw = percent * halfband + tb = (percent / 2.0) * halfband ripple = 0.1 # As we drop the bw factor, the optfir filter has a harder time converging; # using the firdes method here for better results. return filter.firdes.low_pass_2(flt_size, flt_size, bw, tb, atten, - fft.window.WIN_BLACKMAN_HARRIS) + fft.window.WIN_BLACKMAN_HARRIS) else: halfband = 0.5 - bw = percent*halfband - tb = (percent / 2.0)*halfband + bw = percent * halfband + tb = (percent / 2.0) * halfband ripple = 0.1 while True: try: - taps = optfir.low_pass(flt_size, flt_size, bw, bw+tb, ripple, atten) + taps = optfir.low_pass( + flt_size, flt_size, bw, bw + tb, ripple, atten) return taps except RuntimeError: ripple += 0.01 - print("Warning: set ripple to %.4f dB. If this is a problem, adjust the attenuation or create your own filter taps." % (ripple)) + print( + "Warning: set ripple to %.4f dB. If this is a problem, adjust the attenuation or create your own filter taps." % (ripple)) # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): - raise RuntimeError("optfir could not generate an appropriate filter.") + raise RuntimeError( + "optfir could not generate an appropriate filter.") + class arb_resampler_ccc(gr.hier_block2): ''' @@ -353,10 +373,12 @@ class arb_resampler_ccc(gr.hier_block2): streams. This block is provided to be consistent with the interface to the other PFB block. ''' + def __init__(self, rate, taps=None, flt_size=32, atten=100): gr.hier_block2.__init__(self, "pfb_arb_resampler_ccc", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._rate = rate self._size = flt_size @@ -366,8 +388,9 @@ def __init__(self, rate, taps=None, flt_size=32, atten=100): else: self._taps = self.create_taps(self._rate, self._size, atten) - self.pfb = filter.pfb_arb_resampler_ccc(self._rate, self._taps, self._size) - #print "PFB has %d taps\n" % (len(self._taps),) + self.pfb = filter.pfb_arb_resampler_ccc( + self._rate, self._taps, self._size) + # print "PFB has %d taps\n" % (len(self._taps),) self.connect(self, self.pfb) self.connect(self.pfb, self) @@ -390,7 +413,8 @@ def create_taps(rate, flt_size=32, atten=100): ripple = 0.1 while True: try: - taps = optfir.low_pass(flt_size, flt_size, bw, bw+tb, ripple, atten) + taps = optfir.low_pass( + flt_size, flt_size, bw, bw + tb, ripple, atten) return taps except RuntimeError: ripple += 0.01 @@ -398,7 +422,9 @@ def create_taps(rate, flt_size=32, atten=100): # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): - raise RuntimeError("optfir could not generate an appropriate filter.") + raise RuntimeError( + "optfir could not generate an appropriate filter.") + class channelizer_hier_ccf(gr.hier_block2): """ @@ -426,29 +452,34 @@ def __init__(self, n_chans, n_filterbanks=1, taps=None, outchans=None, gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(len(outchans), len(outchans), gr.sizeof_gr_complex)) if taps is None: - taps = self.create_taps(n_chans, atten=100, bw=1.0, tb=0.2, ripple=0.1) + taps = self.create_taps( + n_chans, atten=100, bw=1.0, tb=0.2, ripple=0.1) taps = list(taps) - extra_taps = int(math.ceil(1.0*len(taps)/n_chans)*n_chans - len(taps)) + extra_taps = int(math.ceil(1.0 * len(taps) / n_chans) * + n_chans - len(taps)) taps = taps + [0] * extra_taps # Make taps for each channel - chantaps = [list(reversed(taps[i: len(taps): n_chans])) for i in range(0, n_chans)] + chantaps = [list(reversed(taps[i: len(taps): n_chans])) + for i in range(0, n_chans)] # Convert the input stream into a stream of vectors. self.s2v = blocks.stream_to_vector(gr.sizeof_gr_complex, n_chans) # Create a mapping to separate out each filterbank (a group of channels to be processed together) # And a list of sets of taps for each filterbank. low_cpp = int(n_chans / n_filterbanks) - extra = n_chans - low_cpp*n_filterbanks - cpps = [low_cpp+1]*extra + [low_cpp]*(n_filterbanks-extra) + extra = n_chans - low_cpp * n_filterbanks + cpps = [low_cpp + 1] * extra + [low_cpp] * (n_filterbanks - extra) splitter_mapping = [] filterbanktaps = [] total = 0 for cpp in cpps: - splitter_mapping.append([(0, i) for i in range(total, total+cpp)]) - filterbanktaps.append(chantaps[total: total+cpp]) + splitter_mapping.append([(0, i) + for i in range(total, total + cpp)]) + filterbanktaps.append(chantaps[total: total + cpp]) total += cpp assert(total == n_chans) # Split the stream of vectors in n_filterbanks streams of vectors. - self.splitter = blocks.vector_map(gr.sizeof_gr_complex, [n_chans], splitter_mapping) + self.splitter = blocks.vector_map( + gr.sizeof_gr_complex, [n_chans], splitter_mapping) # Create the filterbanks self.fbs = [filter.filterbank_vcvcf(taps) for taps in filterbanktaps] # Combine the streams of vectors back into a single stream of vectors. @@ -456,15 +487,18 @@ def __init__(self, n_chans, n_filterbanks=1, taps=None, outchans=None, for i, cpp in enumerate(cpps): for j in range(cpp): combiner_mapping[0].append((i, j)) - self.combiner = blocks.vector_map(gr.sizeof_gr_complex, cpps, combiner_mapping) + self.combiner = blocks.vector_map( + gr.sizeof_gr_complex, cpps, combiner_mapping) # Add the final FFT to the channelizer. - self.fft = fft.fft_vcc(n_chans, forward=True, window=[1.0]*n_chans) + self.fft = fft.fft_vcc(n_chans, forward=True, window=[1.0] * n_chans) # Select the desired channels if outchans != list(range(n_chans)): selector_mapping = [[(0, i) for i in outchans]] - self.selector = blocks.vector_map(gr.sizeof_gr_complex, [n_chans], selector_mapping) + self.selector = blocks.vector_map( + gr.sizeof_gr_complex, [n_chans], selector_mapping) # Convert stream of vectors to a normal stream. - self.v2ss = blocks.vector_to_streams(gr.sizeof_gr_complex, len(outchans)) + self.v2ss = blocks.vector_to_streams( + gr.sizeof_gr_complex, len(outchans)) self.connect(self, self.s2v, self.splitter) for i in range(0, n_filterbanks): self.connect((self.splitter, i), self.fbs[i], (self.combiner, i)) @@ -478,5 +512,4 @@ def __init__(self, n_chans, n_filterbanks=1, taps=None, outchans=None, @staticmethod def create_taps(n_chans, atten=100, bw=1.0, tb=0.2, ripple=0.1): - return optfir.low_pass(1, n_chans, bw, bw+tb, ripple, atten) - + return optfir.low_pass(1, n_chans, bw, bw + tb, ripple, atten) diff --git a/gr-filter/python/filter/qa_freq_xlating_fir_filter.py b/gr-filter/python/filter/qa_freq_xlating_fir_filter.py index 0ca435795c4..615e5e60a11 100644 --- a/gr-filter/python/filter/qa_freq_xlating_fir_filter.py +++ b/gr-filter/python/filter/qa_freq_xlating_fir_filter.py @@ -115,7 +115,7 @@ def test_fir_filter_ccf_001(self): decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) - phase = -cmath.pi * self.fc / self.fs * (len(self.taps)-1) + phase = -cmath.pi * self.fc / self.fs * (len(self.taps) - 1) despun = mix(lo, self.src_data, phase=phase) expected_data = fir_filter(despun, self.taps, decim) @@ -134,7 +134,7 @@ def test_fir_filter_ccf_002(self): decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) - phase = -cmath.pi * self.fc / self.fs * (len(self.taps)-1) + phase = -cmath.pi * self.fc / self.fs * (len(self.taps) - 1) despun = mix(lo, self.src_data, phase=phase) expected_data = fir_filter(despun, self.taps, decim) @@ -152,7 +152,7 @@ def test_fir_filter_ccc_001(self): decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) - phase = -cmath.pi * self.fc / self.fs * (len(self.taps)-1) + phase = -cmath.pi * self.fc / self.fs * (len(self.taps) - 1) despun = mix(lo, self.src_data, phase=phase) expected_data = fir_filter(despun, self.taps, decim) @@ -170,7 +170,7 @@ def test_fir_filter_ccc_002(self): decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) - phase = -cmath.pi * self.fc / self.fs * (len(self.taps)-1) + phase = -cmath.pi * self.fc / self.fs * (len(self.taps) - 1) despun = mix(lo, self.src_data, phase=phase) expected_data = fir_filter(despun, self.taps, decim) @@ -188,7 +188,7 @@ def test_fir_filter_fcf_001(self): decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) - phase = -cmath.pi * self.fc / self.fs * (len(self.taps)-1) + phase = -cmath.pi * self.fc / self.fs * (len(self.taps) - 1) despun = mix(lo, self.src_data, phase=phase) expected_data = fir_filter(despun, self.taps, decim) @@ -206,7 +206,7 @@ def test_fir_filter_fcf_002(self): decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) - phase = -cmath.pi * self.fc / self.fs * (len(self.taps)-1) + phase = -cmath.pi * self.fc / self.fs * (len(self.taps) - 1) despun = mix(lo, self.src_data, phase=phase) expected_data = fir_filter(despun, self.taps, decim) @@ -224,7 +224,7 @@ def test_fir_filter_fcc_001(self): decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) - phase = -cmath.pi * self.fc / self.fs * (len(self.taps)-1) + phase = -cmath.pi * self.fc / self.fs * (len(self.taps) - 1) despun = mix(lo, self.src_data, phase=phase) expected_data = fir_filter(despun, self.taps, decim) @@ -242,7 +242,7 @@ def test_fir_filter_fcc_002(self): decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) - phase = -cmath.pi * self.fc / self.fs * (len(self.taps)-1) + phase = -cmath.pi * self.fc / self.fs * (len(self.taps) - 1) despun = mix(lo, self.src_data, phase=phase) expected_data = fir_filter(despun, self.taps, decim) diff --git a/gr-filter/python/filter/qa_rational_resampler.py b/gr-filter/python/filter/qa_rational_resampler.py index 4c67dc793bb..55ed431709b 100644 --- a/gr-filter/python/filter/qa_rational_resampler.py +++ b/gr-filter/python/filter/qa_rational_resampler.py @@ -18,7 +18,7 @@ def random_floats(n): r = [] for x in range(n): - # r.append(float(random.randint(-32768, 32768))) + # r.append(float(random.randint(-32768, 32768))) r.append(float(random.random())) return tuple(r) diff --git a/gr-iio/lib/device_source_impl.cc b/gr-iio/lib/device_source_impl.cc index a2d137d1cdf..00089115963 100644 --- a/gr-iio/lib/device_source_impl.cc +++ b/gr-iio/lib/device_source_impl.cc @@ -15,8 +15,6 @@ #include #include -#include - #include #include #include @@ -58,7 +56,7 @@ device_source::sptr device_source::make_from(iio_context* ctx, void device_source_impl::set_params(iio_device* phy, const iio_param_vec_t& params) { - static GR_LOG_GET_CONFIGURED_LOGGER(logger, "iio::device::set_params"); + static gr::logger logger("device_source_impl::set_params"); for (auto& param : params) { iio_channel* chn = NULL; @@ -70,7 +68,7 @@ void device_source_impl::set_params(iio_device* phy, const iio_param_vec_t& para ret = iio_device_identify_filename(phy, key.c_str(), &chn, &attr); if (ret) { - GR_LOG_WARN(logger, boost::format("Parameter not recognized: %s") % key); + logger.warn("set_params: Parameter not recognized: {}", key); continue; } @@ -81,9 +79,8 @@ void device_source_impl::set_params(iio_device* phy, const iio_param_vec_t& para else ret = iio_device_debug_attr_write(phy, attr, val.c_str()); if (ret < 0) { - GR_LOG_WARN(logger, - boost::format("Unable to write attribute %s: %d %s") % key % ret % - val); + logger.warn( + "set_params: Unable to write attribute {:s}: {:d} {:s}", key, ret, val); } } } @@ -281,8 +278,7 @@ int device_source_impl::work(int noutput_items, char buf[256]; iio_strerror(-ret, buf, sizeof(buf)); - - GR_LOG_WARN(d_logger, boost::format("Unable to refill buffer: %s") % buf); + d_logger->warn("Unable to refill buffer: {:s}", buf); } return -1; } @@ -389,13 +385,12 @@ int device_source_impl::handle_decimation_interpolation(unsigned long samplerate bool disable_dec, bool output_chan) { + static gr::logger log("device_source_impl::handle_decimation_interpolation"); int ret; iio_channel* chan; char buff[128]; unsigned long long min, max; - static GR_LOG_GET_CONFIGURED_LOGGER(logger, "iio::device::handle_decint"); - std::string an(attr_name); an.append("_available"); @@ -415,8 +410,9 @@ int device_source_impl::handle_decimation_interpolation(unsigned long samplerate min = max; ret = iio_channel_attr_write_longlong(chan, "sampling_frequency", min); - if (ret < 0) - GR_LOG_WARN(logger, "Unable to write attribute sampling_frequency!"); + if (ret < 0) { + log.warn("Unable to write attribute sampling_frequency!"); + } return ret; } diff --git a/gr-iio/lib/pluto_utils.cc b/gr-iio/lib/pluto_utils.cc index 37f78f67553..cb51000f362 100644 --- a/gr-iio/lib/pluto_utils.cc +++ b/gr-iio/lib/pluto_utils.cc @@ -19,7 +19,7 @@ namespace iio { std::string get_pluto_uri() { - GR_LOG_GET_CONFIGURED_LOGGER(d_logger, "pluto_utils::get_pluto_uri"); + auto logger = gr::logger("pluto_utils::get_pluto_uri"); iio_scan_context* ctx = iio_create_scan_context("usb", 0); if (!ctx) throw std::runtime_error("Unable to create scan context"); @@ -38,16 +38,16 @@ std::string get_pluto_uri() } if (ret > 1) { - GR_LOG_INFO(d_logger, "More than one Pluto found:"); + logger.info("More than one Pluto found:"); for (unsigned int i = 0; i < (size_t)ret; i++) { - GR_LOG_INFO(d_logger, - boost::format("\t%d: %s [%s]") % i % - iio_context_info_get_description(info[i]) % - iio_context_info_get_uri(info[i])); + logger.info((boost::format("\t%d: %s [%s]") % i % + iio_context_info_get_description(info[i]) % + iio_context_info_get_uri(info[i])) + .str()); } - GR_LOG_INFO(d_logger, "We will use the first one."); + logger.info("We will use the first one."); } std::string uri(iio_context_info_get_uri(info[0])); diff --git a/gr-iio/python/iio/qa_iio.py b/gr-iio/python/iio/qa_iio.py index f28ec76e7f9..7866f04c88a 100644 --- a/gr-iio/python/iio/qa_iio.py +++ b/gr-iio/python/iio/qa_iio.py @@ -13,6 +13,7 @@ import pmt + class test_iio(gr_unittest.TestCase): def test_import(self): @@ -28,7 +29,7 @@ def test_attribute_updater(self): msg_dic = pmt.make_dict() msg_dic = pmt.dict_add(msg_dic, key0, val0) - src = iio.attr_updater(attr,val,500) + src = iio.attr_updater(attr, val, 500) snk = blocks.message_debug() tb = gr.top_block() @@ -41,5 +42,6 @@ def test_attribute_updater(self): rec_msg = snk.get_message(0) self.assertTrue(pmt.equal(rec_msg, msg_dic)) + if __name__ == '__main__': gr_unittest.run(test_iio, "test_iio.xml") diff --git a/gr-network/lib/socket_pdu_impl.cc b/gr-network/lib/socket_pdu_impl.cc index 679ce734c93..c81b13059c8 100644 --- a/gr-network/lib/socket_pdu_impl.cc +++ b/gr-network/lib/socket_pdu_impl.cc @@ -8,6 +8,7 @@ * */ +#include #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -213,7 +214,12 @@ void socket_pdu_impl::handle_tcp_accept(tcp_connection::sptr new_connection, d_tcp_connections.push_back(new_connection); start_tcp_accept(); } else { - GR_LOG_ERROR(d_logger, error); + // need to convert error to printable string; + // can't do (std::stringstream() << error).str() since + // under some compilers, << yields an ostream and that has no .str() + std::stringstream ss; + ss << error; + GR_LOG_ERROR(d_logger, ss.str()); } } diff --git a/gr-network/python/network/qa_socket_pdu.py b/gr-network/python/network/qa_socket_pdu.py index 136f7e4cc61..075f7aaba12 100644 --- a/gr-network/python/network/qa_socket_pdu.py +++ b/gr-network/python/network/qa_socket_pdu.py @@ -117,8 +117,10 @@ def test_004(self): pdu_msg = pmt.cons(pmt.PMT_NIL, data) self.pdu_source = blocks.message_strobe(pdu_msg, 500) - self.pdu_send = network.socket_pdu("TCP_SERVER", "localhost", port, mtu) - self.pdu_recv = network.socket_pdu("TCP_CLIENT", "localhost", port, mtu) + self.pdu_send = network.socket_pdu( + "TCP_SERVER", "localhost", port, mtu) + self.pdu_recv = network.socket_pdu( + "TCP_CLIENT", "localhost", port, mtu) self.pdu_sink = blocks.message_debug() self.tb.msg_connect(self.pdu_source, "strobe", self.pdu_send, "pdus") diff --git a/gr-network/python/network/tcp_source.py b/gr-network/python/network/tcp_source.py index 4e07a684977..89efa74ce2e 100644 --- a/gr-network/python/network/tcp_source.py +++ b/gr-network/python/network/tcp_source.py @@ -23,6 +23,7 @@ import os from gnuradio import gr, blocks + def _get_sock_fd(addr, port, server): """ Get the file descriptor for the socket. @@ -74,9 +75,10 @@ def _get_sock_fd(addr, port, server): sock.connect((addr, port)) return os.dup(sock.fileno()) + class tcp_source(gr.hier_block2): def __init__(self, itemsize, addr, port, server=True): - #init hier block + # init hier block gr.hier_block2.__init__( self, 'tcp_source', gr.io_signature(0, 0, 0), diff --git a/gr-pdu/python/pdu/pdu_lambda.py b/gr-pdu/python/pdu/pdu_lambda.py index e6a286ed2a6..d80e679562a 100644 --- a/gr-pdu/python/pdu/pdu_lambda.py +++ b/gr-pdu/python/pdu/pdu_lambda.py @@ -10,7 +10,9 @@ from gnuradio import gr import numpy as np -import math, pmt, time +import math +import pmt +import time class pdu_lambda(gr.basic_block): @@ -40,8 +42,8 @@ class pdu_lambda(gr.basic_block): def __init__(self, fn, metadict, key=pmt.PMT_NIL): gr.basic_block.__init__(self, - name="pdu_lambda", - in_sig=[],out_sig=[]) + name="pdu_lambda", + in_sig=[], out_sig=[]) self.set_fn(fn) self.set_key(key) self.metadict_mode = metadict @@ -61,7 +63,7 @@ def handle_msg(self, pdu): print(e) pass self.message_port_pub(pmt.intern("pdu"), - pmt.cons(meta, pmt.cdr(pdu))); + pmt.cons(meta, pmt.cdr(pdu))) elif self.metadict_mode == "UVEC": vec = pmt.cdr(pdu) @@ -72,8 +74,8 @@ def handle_msg(self, pdu): pass self.message_port_pub(pmt.intern("pdu"), - pmt.cons(pmt.car(pdu), vec)); - + pmt.cons(pmt.car(pdu), vec)) + elif self.metadict_mode == "RAW": # TODO: This is more of a "message lambda" block, in the future it should be # a separate block outside the PDU namespace @@ -83,14 +85,14 @@ def handle_msg(self, pdu): print(e) pass self.message_port_pub(pmt.intern("pdu"), pdu) - + else: - raise ValueError("pdu_lambda block instantiated in unknown mode " + repr(self.metadict_mode)) + raise ValueError( + "pdu_lambda block instantiated in unknown mode " + repr(self.metadict_mode)) pass - - def set_fn(self,fn): + def set_fn(self, fn): self.fn = fn - def set_key(self,key): + def set_key(self, key): self.key = key diff --git a/gr-pdu/python/pdu/qa_add_system_time.py b/gr-pdu/python/pdu/qa_add_system_time.py index 44d0ad4bef3..0688122a6b6 100755 --- a/gr-pdu/python/pdu/qa_add_system_time.py +++ b/gr-pdu/python/pdu/qa_add_system_time.py @@ -32,29 +32,35 @@ def tearDown(self): def test_001_basic_io(self): self.tb.start() # provide two non PDU inputs and one PDU input - self.add_sys_time.to_basic_block()._post(pmt.intern("pdu"), pmt.intern("BAD PDU")) + self.add_sys_time.to_basic_block()._post( + pmt.intern("pdu"), pmt.intern("BAD PDU")) self.add_sys_time.to_basic_block()._post(pmt.intern("pdu"), pmt.cons(pmt.from_long(4), pmt.PMT_NIL)) self.add_sys_time.to_basic_block()._post(pmt.intern("pdu"), pmt.cons(pmt.make_dict(), pmt.init_f32vector(1, [0.0]))) - self.waitFor(lambda: self.debug.num_messages() >= 1, timeout=1.0, poll_interval=0.01) + self.waitFor(lambda: self.debug.num_messages() >= + 1, timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() # make sure we got one message and it has a systime key self.assertEqual(1, self.debug.num_messages()) - self.assertTrue(pmt.dict_has_key(pmt.car(self.debug.get_message(0)), pmt.intern('systime'))) + self.assertTrue(pmt.dict_has_key( + pmt.car(self.debug.get_message(0)), pmt.intern('systime'))) def test_002_timing(self): self.tb.start() - self.add_sys_time.to_basic_block()._post(pmt.intern("pdu"), pmt.intern("BAD PDU")) + self.add_sys_time.to_basic_block()._post( + pmt.intern("pdu"), pmt.intern("BAD PDU")) self.add_sys_time.to_basic_block()._post(pmt.intern("pdu"), pmt.cons(pmt.make_dict(), pmt.init_u8vector(1, [0]))) - time.sleep(1.0) # wait for one second to provide a time difference between messages + # wait for one second to provide a time difference between messages + time.sleep(1.0) self.add_sys_time.to_basic_block()._post(pmt.intern("pdu"), pmt.cons(pmt.make_dict(), pmt.init_u8vector(1, [0]))) - self.waitFor(lambda: self.debug.num_messages() == 2, timeout=1.0, poll_interval=0.01) + self.waitFor(lambda: self.debug.num_messages() == + 2, timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() @@ -64,7 +70,8 @@ def test_002_timing(self): t1 = pmt.to_double(pmt.dict_ref(pmt.car(self.debug.get_message(1)), pmt.intern("systime"), pmt.from_double(0.0))) - self.assertTrue(((t1 - t0) - 1) < 0.05) # should be sufficient tolerance + # should be sufficient tolerance + self.assertTrue(((t1 - t0) - 1) < 0.05) if __name__ == '__main__': diff --git a/gr-pdu/python/pdu/qa_pdu.py b/gr-pdu/python/pdu/qa_pdu.py index 388a93b9311..e194b5061a2 100644 --- a/gr-pdu/python/pdu/qa_pdu.py +++ b/gr-pdu/python/pdu/qa_pdu.py @@ -144,5 +144,6 @@ def test_004_legacy_pdu_handling(self): data = pmt.u8vector_elements(pmt.cdr(dbg.get_message(0))) self.assertEqual([1, 2, 3], data) + if __name__ == '__main__': gr_unittest.run(test_pdu) diff --git a/gr-pdu/python/pdu/qa_pdu_lambda.py b/gr-pdu/python/pdu/qa_pdu_lambda.py index f93475b8d9b..6f32695d8a2 100755 --- a/gr-pdu/python/pdu/qa_pdu_lambda.py +++ b/gr-pdu/python/pdu/qa_pdu_lambda.py @@ -11,6 +11,7 @@ from gnuradio import gr, gr_unittest from gnuradio import pdu + class qa_pdu_lambda(gr_unittest.TestCase): def setUp(self): @@ -21,7 +22,7 @@ def tearDown(self): def test_smoketest(self): # FIXME: Test will fail until you pass sensible arguments to the constructor - instance = pdu.pdu_lambda(lambda uvec: uvec*10, False) + instance = pdu.pdu_lambda(lambda uvec: uvec * 10, False) def test_001_descriptive_test_name(self): # set up fg diff --git a/gr-pdu/python/pdu/qa_pdu_split.py b/gr-pdu/python/pdu/qa_pdu_split.py index 988fb6b164a..a957c4d97df 100644 --- a/gr-pdu/python/pdu/qa_pdu_split.py +++ b/gr-pdu/python/pdu/qa_pdu_split.py @@ -16,13 +16,13 @@ class qa_pdu_split (gr_unittest.TestCase): - def setUp (self): - self.tb = gr.top_block () + def setUp(self): + self.tb = gr.top_block() - def tearDown (self): + def tearDown(self): self.tb = None - def test_001_split (self): + def test_001_split(self): split = pdu.pdu_split() d1 = blocks.message_debug() d2 = blocks.message_debug() @@ -30,28 +30,36 @@ def test_001_split (self): self.tb.msg_connect((split, 'dict'), (d1, 'store')) self.tb.msg_connect((split, 'vec'), (d2, 'store')) - in_meta1 = pmt.dict_add(pmt.make_dict(), pmt.intern('num'), pmt.from_long(4)) - in_meta2 = pmt.dict_add(pmt.make_dict(), pmt.intern('n'), pmt.from_long(99)) + in_meta1 = pmt.dict_add( + pmt.make_dict(), pmt.intern('num'), pmt.from_long(4)) + in_meta2 = pmt.dict_add( + pmt.make_dict(), pmt.intern('n'), pmt.from_long(99)) in_pdu = pmt.cons(in_meta1, pmt.init_u8vector(6, range(6))) self.tb.start() split.to_basic_block()._post(pmt.intern("pdu"), pmt.intern("MALFORMED PDU")) - split.to_basic_block()._post(pmt.intern("pdu"), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(2, range(2)))) - split.to_basic_block()._post(pmt.intern("pdu"), pmt.cons(in_meta2, pmt.init_u8vector(0, []))) + split.to_basic_block()._post(pmt.intern("pdu"), pmt.cons( + pmt.PMT_NIL, pmt.init_u8vector(2, range(2)))) + split.to_basic_block()._post(pmt.intern( + "pdu"), pmt.cons(in_meta2, pmt.init_u8vector(0, []))) split.to_basic_block()._post(pmt.intern("pdu"), in_pdu) - split.to_basic_block()._post(pmt.intern("system"), pmt.cons(pmt.intern("done"), pmt.from_long(1))) - self.waitFor(lambda: d1.num_messages() == 2, timeout=1.0, poll_interval=0.01) - self.waitFor(lambda: d2.num_messages() == 2, timeout=1.0, poll_interval=0.01) + split.to_basic_block()._post(pmt.intern("system"), + pmt.cons(pmt.intern("done"), pmt.from_long(1))) + self.waitFor(lambda: d1.num_messages() == 2, + timeout=1.0, poll_interval=0.01) + self.waitFor(lambda: d2.num_messages() == 2, + timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() self.assertTrue(pmt.equal(d1.get_message(0), in_meta2)) self.assertTrue(pmt.equal(d1.get_message(1), in_meta1)) - self.assertTrue(pmt.equal(d2.get_message(0), pmt.init_u8vector(2, range(2)))) - self.assertTrue(pmt.equal(d2.get_message(1), pmt.init_u8vector(6, range(6)))) + self.assertTrue(pmt.equal(d2.get_message( + 0), pmt.init_u8vector(2, range(2)))) + self.assertTrue(pmt.equal(d2.get_message( + 1), pmt.init_u8vector(6, range(6)))) - - def test_002_pass_empty (self): + def test_002_pass_empty(self): split = pdu.pdu_split(True) d1 = blocks.message_debug() d2 = blocks.message_debug() @@ -59,26 +67,35 @@ def test_002_pass_empty (self): self.tb.msg_connect((split, 'dict'), (d1, 'store')) self.tb.msg_connect((split, 'vec'), (d2, 'store')) - in_meta1 = pmt.dict_add(pmt.make_dict(), pmt.intern('num'), pmt.from_long(4)) - in_meta2 = pmt.dict_add(pmt.make_dict(), pmt.intern('n'), pmt.from_long(99)) + in_meta1 = pmt.dict_add( + pmt.make_dict(), pmt.intern('num'), pmt.from_long(4)) + in_meta2 = pmt.dict_add( + pmt.make_dict(), pmt.intern('n'), pmt.from_long(99)) in_pdu = pmt.cons(in_meta1, pmt.init_u8vector(6, range(6))) self.tb.start() split.to_basic_block()._post(pmt.intern("pdu"), pmt.intern("MALFORMED PDU")) - split.to_basic_block()._post(pmt.intern("pdu"), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(2, range(2)))) - split.to_basic_block()._post(pmt.intern("pdu"), pmt.cons(in_meta2, pmt.init_u8vector(0, []))) + split.to_basic_block()._post(pmt.intern("pdu"), pmt.cons( + pmt.PMT_NIL, pmt.init_u8vector(2, range(2)))) + split.to_basic_block()._post(pmt.intern( + "pdu"), pmt.cons(in_meta2, pmt.init_u8vector(0, []))) split.to_basic_block()._post(pmt.intern("pdu"), in_pdu) - split.to_basic_block()._post(pmt.intern("system"), pmt.cons(pmt.intern("done"), pmt.from_long(1))) - self.waitFor(lambda: d1.num_messages() == 3, timeout=1.0, poll_interval=0.01) - self.waitFor(lambda: d2.num_messages() == 3, timeout=1.0, poll_interval=0.01) + split.to_basic_block()._post(pmt.intern("system"), + pmt.cons(pmt.intern("done"), pmt.from_long(1))) + self.waitFor(lambda: d1.num_messages() == 3, + timeout=1.0, poll_interval=0.01) + self.waitFor(lambda: d2.num_messages() == 3, + timeout=1.0, poll_interval=0.01) self.tb.wait() self.assertTrue(pmt.equal(d1.get_message(0), pmt.PMT_NIL)) self.assertTrue(pmt.equal(d1.get_message(1), in_meta2)) self.assertTrue(pmt.equal(d1.get_message(2), in_meta1)) - self.assertTrue(pmt.equal(d2.get_message(0), pmt.init_u8vector(2, range(2)))) + self.assertTrue(pmt.equal(d2.get_message( + 0), pmt.init_u8vector(2, range(2)))) self.assertTrue(pmt.equal(d2.get_message(1), pmt.init_u8vector(0, []))) - self.assertTrue(pmt.equal(d2.get_message(2), pmt.init_u8vector(6, range(6)))) + self.assertTrue(pmt.equal(d2.get_message( + 2), pmt.init_u8vector(6, range(6)))) if __name__ == '__main__': diff --git a/gr-pdu/python/pdu/qa_pdu_to_stream.py b/gr-pdu/python/pdu/qa_pdu_to_stream.py index c2f69c21865..9890c1021be 100755 --- a/gr-pdu/python/pdu/qa_pdu_to_stream.py +++ b/gr-pdu/python/pdu/qa_pdu_to_stream.py @@ -13,31 +13,37 @@ import pmt import time + class qa_pdu_to_bursts (gr_unittest.TestCase): - def setUp (self): + def setUp(self): self.tb = gr.top_block() self.p2s = pdu.pdu_to_stream_c(pdu.EARLY_BURST_APPEND, 64) self.vs = blocks.vector_sink_c(1) - self.tag_debug = blocks.tag_debug(gr.sizeof_gr_complex*1, '', "") + self.tag_debug = blocks.tag_debug(gr.sizeof_gr_complex * 1, '', "") self.tag_debug.set_display(True) self.tb.connect((self.p2s, 0), (self.vs, 0)) self.tb.connect((self.p2s, 0), (self.tag_debug, 0)) - def tearDown (self): + def tearDown(self): self.tb = None - def test_001_basic (self): - in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] - in_pdu = pmt.cons(pmt.make_dict(), pmt.init_c32vector(len(in_data), in_data)) - e_tag_0 = gr.tag_utils.python_to_tag((0, pmt.intern("tx_sob"), pmt.PMT_T, pmt.PMT_NIL)) - e_tag_1 = gr.tag_utils.python_to_tag((len(in_data)-1, pmt.intern("tx_eob"), pmt.PMT_T, pmt.PMT_NIL)) + def test_001_basic(self): + in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] + in_pdu = pmt.cons( + pmt.make_dict(), pmt.init_c32vector(len(in_data), in_data)) + e_tag_0 = gr.tag_utils.python_to_tag( + (0, pmt.intern("tx_sob"), pmt.PMT_T, pmt.PMT_NIL)) + e_tag_1 = gr.tag_utils.python_to_tag( + (len(in_data) - 1, pmt.intern("tx_eob"), pmt.PMT_T, pmt.PMT_NIL)) self.tb.start() self.p2s.to_basic_block()._post(pmt.intern("pdus"), pmt.intern("MALFORMED PDU")) self.p2s.to_basic_block()._post(pmt.intern("pdus"), in_pdu) - self.waitFor(lambda: len(self.vs.tags()) == 2, timeout=1.0, poll_interval=0.01) + self.waitFor(lambda: len(self.vs.tags()) == 2, + timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() @@ -51,19 +57,26 @@ def test_001_basic (self): self.assertTrue(pmt.equal(tags[1].value, e_tag_1.value)) self.assertTrue((in_data == np.real(self.vs.data())).all()) - def test_002_timed (self): - in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] - tag_time = pmt.make_tuple(pmt.from_uint64(11), pmt.from_double(0.123456)) - in_dict = pmt.dict_add(pmt.make_dict(), pmt.intern("tx_time"), tag_time) + def test_002_timed(self): + in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] + tag_time = pmt.make_tuple( + pmt.from_uint64(11), pmt.from_double(0.123456)) + in_dict = pmt.dict_add( + pmt.make_dict(), pmt.intern("tx_time"), tag_time) in_pdu = pmt.cons(in_dict, pmt.init_c32vector(len(in_data), in_data)) - e_tag_0 = gr.tag_utils.python_to_tag((0, pmt.intern("tx_sob"), pmt.PMT_T, pmt.PMT_NIL)) - e_tag_1 = gr.tag_utils.python_to_tag((0, pmt.intern("tx_time"), tag_time, pmt.PMT_NIL)) - e_tag_2 = gr.tag_utils.python_to_tag((len(in_data)-1, pmt.intern("tx_eob"), pmt.PMT_T, pmt.PMT_NIL)) + e_tag_0 = gr.tag_utils.python_to_tag( + (0, pmt.intern("tx_sob"), pmt.PMT_T, pmt.PMT_NIL)) + e_tag_1 = gr.tag_utils.python_to_tag( + (0, pmt.intern("tx_time"), tag_time, pmt.PMT_NIL)) + e_tag_2 = gr.tag_utils.python_to_tag( + (len(in_data) - 1, pmt.intern("tx_eob"), pmt.PMT_T, pmt.PMT_NIL)) self.tb.start() self.p2s.to_basic_block()._post(pmt.intern("pdus"), pmt.intern("MALFORMED PDU")) self.p2s.to_basic_block()._post(pmt.intern("pdus"), in_pdu) - self.waitFor(lambda: len(self.vs.tags()) == 3, timeout=1.0, poll_interval=0.01) + self.waitFor(lambda: len(self.vs.tags()) == 3, + timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() @@ -80,19 +93,25 @@ def test_002_timed (self): self.assertTrue(pmt.equal(tags[2].value, e_tag_2.value)) self.assertTrue((in_data == np.real(self.vs.data())).all()) - def test_003_timed_long (self): + def test_003_timed_long(self): in_data = np.arange(25000).tolist() - tag_time = pmt.make_tuple(pmt.from_uint64(11), pmt.from_double(0.123456)) - in_dict = pmt.dict_add(pmt.make_dict(), pmt.intern("tx_time"), tag_time) + tag_time = pmt.make_tuple( + pmt.from_uint64(11), pmt.from_double(0.123456)) + in_dict = pmt.dict_add( + pmt.make_dict(), pmt.intern("tx_time"), tag_time) in_pdu = pmt.cons(in_dict, pmt.init_c32vector(len(in_data), in_data)) - e_tag_0 = gr.tag_utils.python_to_tag((0, pmt.intern("tx_sob"), pmt.PMT_T, pmt.PMT_NIL)) - e_tag_1 = gr.tag_utils.python_to_tag((0, pmt.intern("tx_time"), tag_time, pmt.PMT_NIL)) - e_tag_2 = gr.tag_utils.python_to_tag((len(in_data)-1, pmt.intern("tx_eob"), pmt.PMT_T, pmt.PMT_NIL)) + e_tag_0 = gr.tag_utils.python_to_tag( + (0, pmt.intern("tx_sob"), pmt.PMT_T, pmt.PMT_NIL)) + e_tag_1 = gr.tag_utils.python_to_tag( + (0, pmt.intern("tx_time"), tag_time, pmt.PMT_NIL)) + e_tag_2 = gr.tag_utils.python_to_tag( + (len(in_data) - 1, pmt.intern("tx_eob"), pmt.PMT_T, pmt.PMT_NIL)) self.tb.start() self.p2s.to_basic_block()._post(pmt.intern("pdus"), pmt.intern("MALFORMED PDU")) self.p2s.to_basic_block()._post(pmt.intern("pdus"), in_pdu) - self.waitFor(lambda: len(self.vs.tags()) == 3, timeout=1.0, poll_interval=0.01) + self.waitFor(lambda: len(self.vs.tags()) == 3, + timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() diff --git a/gr-pdu/python/pdu/qa_tags_to_pdu.py b/gr-pdu/python/pdu/qa_tags_to_pdu.py index de12af4f205..9e3be511996 100755 --- a/gr-pdu/python/pdu/qa_tags_to_pdu.py +++ b/gr-pdu/python/pdu/qa_tags_to_pdu.py @@ -13,211 +13,261 @@ import pmt import time + class qa_tags_to_pdu (gr_unittest.TestCase): - def setUp (self): + def setUp(self): pass - def tearDown (self): + def tearDown(self): pass - def test_001_simple (self): - self.tb = gr.top_block () + def test_001_simple(self): + self.tb = gr.top_block() start_time = 0.1 - sob_tag = gr.tag_utils.python_to_tag((34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - eob_tag = gr.tag_utils.python_to_tag((34+(8*31), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) + sob_tag = gr.tag_utils.python_to_tag( + (34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + eob_tag = gr.tag_utils.python_to_tag( + (34 + (8 * 31), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(350), False, 1, [sob_tag, eob_tag]) - t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 512000, ([]), False, 0, start_time) + t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern( + 'EOB'), 1024, 512000, ([]), False, 0, start_time) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdus'), (dbg, 'store')) - expected_vec = pmt.init_s16vector((8*31), range(34,34+(8*31))) + expected_vec = pmt.init_s16vector((8 * 31), range(34, 34 + (8 * 31))) expected_time = start_time + (34 / 512000.0) - self.tb.run () + self.tb.run() self.assertEqual(dbg.num_messages(), 1) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) - time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) - self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time) + time_tuple1 = pmt.dict_ref( + pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) + self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref( + time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time) self.tb = None - - def test_002_secondSOB (self): - self.tb = gr.top_block () + def test_002_secondSOB(self): + self.tb = gr.top_block() start_time = 4.999999999 - sob_tag = gr.tag_utils.python_to_tag((34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - sob_tag2 = gr.tag_utils.python_to_tag((51, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - eob_tag = gr.tag_utils.python_to_tag((51+(8*26), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) - vs = blocks.vector_source_s(range(350), False, 1, [sob_tag, sob_tag2, eob_tag]) - t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 460800, ([]), False, 0, start_time) + sob_tag = gr.tag_utils.python_to_tag( + (34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + sob_tag2 = gr.tag_utils.python_to_tag( + (51, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + eob_tag = gr.tag_utils.python_to_tag( + (51 + (8 * 26), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) + vs = blocks.vector_source_s(range(350), False, 1, [ + sob_tag, sob_tag2, eob_tag]) + t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern( + 'EOB'), 1024, 460800, ([]), False, 0, start_time) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdus'), (dbg, 'store')) - expected_vec = pmt.init_s16vector((8*26), range(51,51+(8*26))) + expected_vec = pmt.init_s16vector((8 * 26), range(51, 51 + (8 * 26))) expected_time = start_time + (51 / 460800.0) - self.tb.run () + self.tb.run() self.assertEqual(dbg.num_messages(), 1) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) - time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) - self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time) + time_tuple1 = pmt.dict_ref( + pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) + self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref( + time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time) self.tb = None - - def test_003_double_eob_rej_tt_update (self): - self.tb = gr.top_block () + def test_003_double_eob_rej_tt_update(self): + self.tb = gr.top_block() start_time = 0.0 - sob_tag = gr.tag_utils.python_to_tag((51, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - eob_tag = gr.tag_utils.python_to_tag((51+(8*11), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) - time_tuple = pmt.make_tuple(pmt.from_uint64(4), pmt.from_double(0.125), pmt.from_uint64(10000000), pmt.from_double(4000000.0)) - time_tag = gr.tag_utils.python_to_tag((360, pmt.intern("rx_time"), time_tuple, pmt.intern("src"))) - sob_tag2 = gr.tag_utils.python_to_tag((400, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - eob_tag2e = gr.tag_utils.python_to_tag((409, pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) - eob_tag2 = gr.tag_utils.python_to_tag((416, pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) - vs = blocks.vector_source_s(range(500), False, 1, [sob_tag, eob_tag, time_tag, sob_tag2, eob_tag2e, eob_tag2]) - t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 1000000, ([]), False, 0, start_time) + sob_tag = gr.tag_utils.python_to_tag( + (51, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + eob_tag = gr.tag_utils.python_to_tag( + (51 + (8 * 11), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) + time_tuple = pmt.make_tuple(pmt.from_uint64(4), pmt.from_double( + 0.125), pmt.from_uint64(10000000), pmt.from_double(4000000.0)) + time_tag = gr.tag_utils.python_to_tag( + (360, pmt.intern("rx_time"), time_tuple, pmt.intern("src"))) + sob_tag2 = gr.tag_utils.python_to_tag( + (400, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + eob_tag2e = gr.tag_utils.python_to_tag( + (409, pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) + eob_tag2 = gr.tag_utils.python_to_tag( + (416, pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) + vs = blocks.vector_source_s(range(500), False, 1, [ + sob_tag, eob_tag, time_tag, sob_tag2, eob_tag2e, eob_tag2]) + t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern( + 'EOB'), 1024, 1000000, ([]), False, 0, start_time) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdus'), (dbg, 'store')) - expected_vec1 = pmt.init_s16vector((8*11), range(51,51+(8*11))) - expected_vec2 = pmt.init_s16vector(16, list(range(400,409)) + [0]*7) + expected_vec1 = pmt.init_s16vector((8 * 11), range(51, 51 + (8 * 11))) + expected_vec2 = pmt.init_s16vector(16, list(range(400, 409)) + [0] * 7) expected_time1 = start_time + (51 / 1000000.0) - expected_time2 = 4.125 + ((400-360) / 1000000.0) + expected_time2 = 4.125 + ((400 - 360) / 1000000.0) - self.tb.run () + self.tb.run() self.assertEqual(dbg.num_messages(), 2) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec1)) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(1)), expected_vec2)) - time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) - time_tuple2 = pmt.dict_ref(pmt.car(dbg.get_message(1)), pmt.intern("rx_time"), pmt.PMT_NIL) - self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time1) - self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple2,0)) + pmt.to_double(pmt.tuple_ref(time_tuple2,1)), expected_time2) + time_tuple1 = pmt.dict_ref( + pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) + time_tuple2 = pmt.dict_ref( + pmt.car(dbg.get_message(1)), pmt.intern("rx_time"), pmt.PMT_NIL) + self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref( + time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time1) + self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref( + time_tuple2, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple2, 1)), expected_time2) self.tb = None - def test_004_boost_time (self): - self.tb = gr.top_block () + def test_004_boost_time(self): + self.tb = gr.top_block() start_time = 0.1 - sob_tag = gr.tag_utils.python_to_tag((34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - eob_tag = gr.tag_utils.python_to_tag((34+(8*31), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) + sob_tag = gr.tag_utils.python_to_tag( + (34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + eob_tag = gr.tag_utils.python_to_tag( + (34 + (8 * 31), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(350), False, 1, [sob_tag, eob_tag]) - t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 512000, ([]), False, 0, start_time) + t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern( + 'EOB'), 1024, 512000, ([]), False, 0, start_time) t2p.enable_time_debug(True) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdus'), (dbg, 'store')) - expected_vec = pmt.init_s16vector((8*31), range(34,34+(8*31))) + expected_vec = pmt.init_s16vector((8 * 31), range(34, 34 + (8 * 31))) expected_time = start_time + (34 / 512000.0) ts = time.time() - self.tb.run () + self.tb.run() self.assertEqual(dbg.num_messages(), 1) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) - time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) - self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time) + time_tuple1 = pmt.dict_ref( + pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) + self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref( + time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time) #wct = pmt.to_double(pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("wall_clock_time"), pmt.PMT_NIL)) #self.assertTrue((wct - ts) < 1.0) self.tb = None - def test_005_two_sobs_misaligned (self): + def test_005_two_sobs_misaligned(self): # Two SOB tags and the SOB-to-EOB length is not aligned - self.tb = gr.top_block () + self.tb = gr.top_block() start_time = 0.1 - sob_tag = gr.tag_utils.python_to_tag((34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - sob_tag2 = gr.tag_utils.python_to_tag((35, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - eob_tag = gr.tag_utils.python_to_tag((34+(8*31), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) - vs = blocks.vector_source_s(range(1350), False, 1, [sob_tag, sob_tag2, eob_tag]) - t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 512000, ([]), False, 0, start_time) + sob_tag = gr.tag_utils.python_to_tag( + (34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + sob_tag2 = gr.tag_utils.python_to_tag( + (35, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + eob_tag = gr.tag_utils.python_to_tag( + (34 + (8 * 31), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) + vs = blocks.vector_source_s(range(1350), False, 1, [ + sob_tag, sob_tag2, eob_tag]) + t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern( + 'EOB'), 1024, 512000, ([]), False, 0, start_time) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdus'), (dbg, 'store')) - expected_vec = pmt.init_s16vector((8*31), list(range(35,34+(8*31))) + [0]) + expected_vec = pmt.init_s16vector( + (8 * 31), list(range(35, 34 + (8 * 31))) + [0]) expected_time = start_time + (35 / 512000.0) - self.tb.run () + self.tb.run() self.assertEqual(dbg.num_messages(), 1) - #print "got ", dbg.get_message(0) - #print "expected", expected_vec - #print "len is {}".format(len(pmt.to_python(pmt.cdr(dbg.get_message(0))))) + # print "got ", dbg.get_message(0) + # print "expected", expected_vec + # print "len is {}".format(len(pmt.to_python(pmt.cdr(dbg.get_message(0))))) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) - time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) - self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time) + time_tuple1 = pmt.dict_ref( + pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) + self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref( + time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time) self.tb = None - def test_006_max_pdu_size (self): + def test_006_max_pdu_size(self): # two SOB tags exactly max_pdu_size samples apart, with an SOB-to-EOB length that is not divisible by the alignment size - self.tb = gr.top_block () + self.tb = gr.top_block() start_time = 0.1 max_size = 100 - sob_tag = gr.tag_utils.python_to_tag((10, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - eob_tag = gr.tag_utils.python_to_tag((91, pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) - sob_tag3 = gr.tag_utils.python_to_tag((11+max_size, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - vs = blocks.vector_source_s(range(1350), False, 1, [sob_tag, eob_tag, sob_tag3]) - t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 512000, ([]), False, 0, start_time) + sob_tag = gr.tag_utils.python_to_tag( + (10, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + eob_tag = gr.tag_utils.python_to_tag( + (91, pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) + sob_tag3 = gr.tag_utils.python_to_tag( + (11 + max_size, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + vs = blocks.vector_source_s(range(1350), False, 1, [ + sob_tag, eob_tag, sob_tag3]) + t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern( + 'EOB'), 1024, 512000, ([]), False, 0, start_time) t2p.set_eob_parameters(10, 0) t2p.set_max_pdu_size(max_size) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdus'), (dbg, 'store')) - expected_vec = pmt.init_s16vector((9*10), list(range(10,91)) + [0]*9) + expected_vec = pmt.init_s16vector( + (9 * 10), list(range(10, 91)) + [0] * 9) expected_time = start_time + (10 / 512000.0) - self.tb.run () + self.tb.run() # assertions for the first PDU only, second PDU will exist self.assertEqual(dbg.num_messages(), 2) - #print "got ", dbg.get_message(0) - #print "expected", expected_vec - #print "len is {}".format(len(pmt.to_python(pmt.cdr(dbg.get_message(0))))) + # print "got ", dbg.get_message(0) + # print "expected", expected_vec + # print "len is {}".format(len(pmt.to_python(pmt.cdr(dbg.get_message(0))))) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) - time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) - self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time) + time_tuple1 = pmt.dict_ref( + pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) + self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref( + time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time) self.tb = None - def test_007_max_pdu_size_SOBs (self): + def test_007_max_pdu_size_SOBs(self): # two SOB tags exactly max_pdu_size samples apart - self.tb = gr.top_block () + self.tb = gr.top_block() start_time = 0.1 max_size = 100 - sob_tag = gr.tag_utils.python_to_tag((10, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) - sob_tag3 = gr.tag_utils.python_to_tag((10+max_size, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + sob_tag = gr.tag_utils.python_to_tag( + (10, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) + sob_tag3 = gr.tag_utils.python_to_tag( + (10 + max_size, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(1350), False, 1, [sob_tag, sob_tag3]) - t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 512000, ([]), False, 0, start_time) + t2p = pdu.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern( + 'EOB'), 1024, 512000, ([]), False, 0, start_time) t2p.set_eob_parameters(10, 0) t2p.set_max_pdu_size(max_size) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdus'), (dbg, 'store')) - expected_vec = pmt.init_s16vector((max_size), range(10,10+max_size)) + expected_vec = pmt.init_s16vector((max_size), range(10, 10 + max_size)) expected_time = start_time + (10 / 512000.0) - self.tb.run () + self.tb.run() # assertions for the first PDU only, second PDU will exist self.assertEqual(dbg.num_messages(), 2) - #print "got ", dbg.get_message(0) - #print "expected", expected_vec + # print "got ", dbg.get_message(0) + # print "expected", expected_vec self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) - time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) - self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time) + time_tuple1 = pmt.dict_ref( + pmt.car(dbg.get_message(0)), pmt.intern("rx_time"), pmt.PMT_NIL) + self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref( + time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time) self.tb = None diff --git a/gr-pdu/python/pdu/qa_take_skip_to_pdu.py b/gr-pdu/python/pdu/qa_take_skip_to_pdu.py index 76414c857ab..bcc33e6f4f7 100755 --- a/gr-pdu/python/pdu/qa_take_skip_to_pdu.py +++ b/gr-pdu/python/pdu/qa_take_skip_to_pdu.py @@ -14,6 +14,7 @@ import time import numpy + class qa_take_skip_to_pdu_X (gr_unittest.TestCase): # this method is necessary because by default pmt.equal does not evaluate @@ -34,67 +35,70 @@ def assertEqualPDU(self, pdu1, pdu2): print("vectors not equal? " + repr(vec1) + repr(vec2)) self.assertTrue(False) - def setUp (self): - self.tb = gr.top_block () + def setUp(self): + self.tb = gr.top_block() - def tearDown (self): + def tearDown(self): self.tb = None - def test_001_f_32 (self): - self.source = blocks.vector_source_f(range(0,32*3), False, 1, []) + def test_001_f_32(self): + self.source = blocks.vector_source_f(range(0, 32 * 3), False, 1, []) self.ts_pdu = pdu.take_skip_to_pdu_f(32, 32) self.debug = blocks.message_debug() self.tb.connect((self.source, 0), (self.ts_pdu, 0)) self.tb.msg_connect((self.ts_pdu, 'pdus'), (self.debug, 'store')) - dic = pmt.dict_add(pmt.make_dict(), pmt.intern("pdu_num"), pmt.from_uint64(0)) - vec = pmt.init_f32vector(32, range(0,32)) - expected = pmt.cons(dic,vec) - self.tb.run () + dic = pmt.dict_add(pmt.make_dict(), pmt.intern( + "pdu_num"), pmt.from_uint64(0)) + vec = pmt.init_f32vector(32, range(0, 32)) + expected = pmt.cons(dic, vec) + self.tb.run() actual = self.debug.get_message(0) self.assertEqualPDU(actual, expected) - def test_002_c_80 (self): - self.source = blocks.vector_source_c(range(0,32*3), False, 1, []) + def test_002_c_80(self): + self.source = blocks.vector_source_c(range(0, 32 * 3), False, 1, []) self.ts_pdu = pdu.take_skip_to_pdu_c(80, 32) self.debug = blocks.message_debug() self.tb.connect((self.source, 0), (self.ts_pdu, 0)) self.tb.msg_connect((self.ts_pdu, 'pdus'), (self.debug, 'store')) - dic = pmt.dict_add(pmt.make_dict(), pmt.intern("pdu_num"), pmt.from_uint64(0)) - vec = pmt.init_c32vector(80, range(0,80)) - expected = pmt.cons(dic,vec) - self.tb.run () + dic = pmt.dict_add(pmt.make_dict(), pmt.intern( + "pdu_num"), pmt.from_uint64(0)) + vec = pmt.init_c32vector(80, range(0, 80)) + expected = pmt.cons(dic, vec) + self.tb.run() actual = self.debug.get_message(0) self.assertEqualPDU(actual, expected) - - def test_003_s_2_11_7 (self): - self.source = blocks.vector_source_s(range(0,32*3), False, 1, []) + def test_003_s_2_11_7(self): + self.source = blocks.vector_source_s(range(0, 32 * 3), False, 1, []) self.ts_pdu = pdu.take_skip_to_pdu_s(2, 11) self.debug = blocks.message_debug() self.tb.connect((self.source, 0), (self.ts_pdu, 0)) self.tb.msg_connect((self.ts_pdu, 'pdus'), (self.debug, 'store')) - dic = pmt.dict_add(pmt.make_dict(), pmt.intern("pdu_num"), pmt.from_uint64(7)) - vec = pmt.init_s16vector(2, list(range(91,93))) - expected = pmt.cons(dic,vec) - self.tb.run () + dic = pmt.dict_add(pmt.make_dict(), pmt.intern( + "pdu_num"), pmt.from_uint64(7)) + vec = pmt.init_s16vector(2, list(range(91, 93))) + expected = pmt.cons(dic, vec) + self.tb.run() actual = self.debug.get_message(7) self.assertEqualPDU(actual, expected) - - def test_004_b_512 (self): - self.source = blocks.vector_source_b(list(range(0,256))*4, False, 1, []) - self.ts_pdu = pdu.take_skip_to_pdu_b(512,1) + def test_004_b_512(self): + self.source = blocks.vector_source_b( + list(range(0, 256)) * 4, False, 1, []) + self.ts_pdu = pdu.take_skip_to_pdu_b(512, 1) self.debug = blocks.message_debug() self.tb.connect((self.source, 0), (self.ts_pdu, 0)) self.tb.msg_connect((self.ts_pdu, 'pdus'), (self.debug, 'store')) - dic = pmt.dict_add(pmt.make_dict(), pmt.intern("pdu_num"), pmt.from_uint64(0)) - vec = pmt.init_u8vector(512, list(range(0,256))*2) - expected = pmt.cons(dic,vec) - self.tb.run () + dic = pmt.dict_add(pmt.make_dict(), pmt.intern( + "pdu_num"), pmt.from_uint64(0)) + vec = pmt.init_u8vector(512, list(range(0, 256)) * 2) + expected = pmt.cons(dic, vec) + self.tb.run() actual = self.debug.get_message(0) self.assertEqualPDU(actual, expected) diff --git a/gr-pdu/python/pdu/qa_time_delta.py b/gr-pdu/python/pdu/qa_time_delta.py index 0cb0f990201..2003419ba79 100755 --- a/gr-pdu/python/pdu/qa_time_delta.py +++ b/gr-pdu/python/pdu/qa_time_delta.py @@ -20,7 +20,8 @@ class qa_time_delta(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() - self.time_delta = pdu.time_delta(pmt.intern("sys time delta (ms)"), pmt.intern("system_time")) + self.time_delta = pdu.time_delta(pmt.intern( + "sys time delta (ms)"), pmt.intern("system_time")) self.debug = blocks.message_debug() self.tb.msg_connect((self.time_delta, 'pdu'), (self.debug, 'store')) @@ -30,8 +31,9 @@ def tearDown(self): def test_001_invalid_a(self): self.tb.start() - self.time_delta.to_basic_block()._post(pmt.intern("pdu"), pmt.intern("NOT A PDU")) - time.sleep(0.01) # short delay to ensure the message is processed + self.time_delta.to_basic_block()._post( + pmt.intern("pdu"), pmt.intern("NOT A PDU")) + time.sleep(0.01) # short delay to ensure the message is processed self.tb.stop() self.tb.wait() @@ -39,14 +41,16 @@ def test_001_invalid_a(self): self.assertEqual(0, self.debug.num_messages()) def test_001_invalid_b(self): - in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] - meta = pmt.dict_add(pmt.make_dict(), pmt.intern('sam'), pmt.from_double(25.1)) + in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] + meta = pmt.dict_add(pmt.make_dict(), pmt.intern( + 'sam'), pmt.from_double(25.1)) in_pdu = pmt.cons(meta, pmt.init_c32vector(len(in_data), in_data)) # set up fg self.tb.start() self.time_delta.to_basic_block()._post(pmt.intern("pdu"), in_pdu) - time.sleep(0.01) # short delay to ensure the message is processed + time.sleep(0.01) # short delay to ensure the message is processed self.tb.stop() self.tb.wait() @@ -56,19 +60,25 @@ def test_001_invalid_b(self): def test_002_normal(self): tnow = time.time() - in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] - meta = pmt.dict_add(pmt.make_dict(), pmt.intern('system_time'), pmt.from_double(tnow - 10.0)) + in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] + meta = pmt.dict_add(pmt.make_dict(), pmt.intern( + 'system_time'), pmt.from_double(tnow - 10.0)) in_pdu = pmt.cons(meta, pmt.init_c32vector(len(in_data), in_data)) - e_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] - e_meta = pmt.dict_add(pmt.make_dict(), pmt.intern('system_time'), pmt.from_double(tnow)) - e_meta = pmt.dict_add(e_meta, pmt.intern('sys time delta (ms)'), pmt.from_double(10000.0)) + e_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] + e_meta = pmt.dict_add(pmt.make_dict(), pmt.intern( + 'system_time'), pmt.from_double(tnow)) + e_meta = pmt.dict_add(e_meta, pmt.intern( + 'sys time delta (ms)'), pmt.from_double(10000.0)) e_pdu = pmt.cons(e_meta, pmt.init_c32vector(len(e_data), e_data)) # set up fg self.tb.start() self.time_delta.to_basic_block()._post(pmt.intern("pdu"), in_pdu) - self.waitFor(lambda: self.debug.num_messages() == 1, timeout=1.0, poll_interval=0.01) + self.waitFor(lambda: self.debug.num_messages() == + 1, timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() @@ -76,7 +86,8 @@ def test_002_normal(self): self.assertEqual(1, self.debug.num_messages()) a_meta = pmt.car(self.debug.get_message(0)) time_tag = pmt.dict_ref(a_meta, pmt.intern("system_time"), pmt.PMT_NIL) - delta_tag = pmt.dict_ref(a_meta, pmt.intern("sys time delta (ms)"), pmt.PMT_NIL) + delta_tag = pmt.dict_ref(a_meta, pmt.intern( + "sys time delta (ms)"), pmt.PMT_NIL) self.assertAlmostEqual(tnow, pmt.to_double(time_tag), delta=60) self.assertAlmostEqual(10000, pmt.to_double(delta_tag), delta=10) diff --git a/gr-qtgui/apps/uhd_display.py b/gr-qtgui/apps/uhd_display.py index 39e5cfbfc74..be501a01821 100644 --- a/gr-qtgui/apps/uhd_display.py +++ b/gr-qtgui/apps/uhd_display.py @@ -82,8 +82,8 @@ def pauseFg(self): self.fg.start() self.gui.pauseButton.setText("Pause") - # Functions to set the values in the GUI + def set_frequency(self, freq): self.freq = freq sfreq = eng_notation.num_to_str(self.freq) @@ -102,11 +102,12 @@ def set_amplifier(self, amp): self.amp = amp self.gui.amplifierEdit.setText(QtCore.QString("%1").arg(self.amp)) - # Functions called when signals are triggered in the GUI + def frequencyEditText(self): try: - freq = eng_notation.str_to_num(self.gui.frequencyEdit.text().toAscii()) + freq = eng_notation.str_to_num( + self.gui.frequencyEdit.text().toAscii()) self.fg.set_frequency(freq) self.freq = freq except RuntimeError: @@ -122,7 +123,8 @@ def gainEditText(self): def bandwidthEditText(self): try: - bw = eng_notation.str_to_num(self.gui.bandwidthEdit.text().toAscii()) + bw = eng_notation.str_to_num( + self.gui.bandwidthEdit.text().toAscii()) self.fg.set_bandwidth(bw) self.bw = bw except ValueError: @@ -137,7 +139,8 @@ def amplifierEditText(self): pass def saveData(self): - fileName = QtGui.QFileDialog.getSaveFileName(self, "Save data to file", "."); + fileName = QtGui.QFileDialog.getSaveFileName( + self, "Save data to file", ".") if(len(fileName)): self.fg.save_to_file(str(fileName)) @@ -150,7 +153,6 @@ def dcCancelClicked(self, state): self.fg.cancel_dc(state) - class my_top_block(gr.top_block): def __init__(self, options): gr.top_block.__init__(self) @@ -160,7 +162,8 @@ def __init__(self, options): self.qapp = QtGui.QApplication(sys.argv) - self.u = uhd.usrp_source(device_addr=options.address, stream_args=uhd.stream_args('fc32')) + self.u = uhd.usrp_source( + device_addr=options.address, stream_args=uhd.stream_args('fc32')) if(options.antenna): self.u.set_antenna(options.antenna, 0) @@ -170,13 +173,13 @@ def __init__(self, options): if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() - options.gain = float(g.start()+g.stop()) / 2 + options.gain = float(g.start() + g.stop()) / 2 self.set_gain(options.gain) if options.freq is None: # if no freq was specified, use the mid-point r = self.u.get_freq_range() - options.freq = float(r.start()+r.stop()) / 2 + options.freq = float(r.start() + r.stop()) / 2 self.set_frequency(options.freq) self._fftsize = options.fft_size @@ -218,7 +221,6 @@ def __init__(self, options): self.main_win.show() - def save_to_file(self, name): self.lock() @@ -262,19 +264,20 @@ def cancel_dc(self, state): if(state): self.disconnect(self.u, self.amp) - self.connect(self.u, (self.dc_sub,0)) - self.connect(self.u, self.dc, (self.dc_sub,1)) + self.connect(self.u, (self.dc_sub, 0)) + self.connect(self.u, self.dc, (self.dc_sub, 1)) self.connect(self.dc_sub, self.amp) else: self.disconnect(self.dc_sub, self.amp) - self.disconnect(self.dc, (self.dc_sub,1)) + self.disconnect(self.dc, (self.dc_sub, 1)) self.disconnect(self.u, self.dc) - self.disconnect(self.u, (self.dc_sub,0)) + self.disconnect(self.u, (self.dc_sub, 0)) self.connect(self.u, self.amp) self.unlock() -def main (): + +def main(): parser = OptionParser(option_class=eng_option) parser.add_option("-a", "--address", type="string", default="addr=192.168.10.2", help="Address of UHD device, [default=%default]") @@ -296,11 +299,11 @@ def main (): tb = my_top_block(options) tb.start() - tb.snk.exec_(); + tb.snk.exec_() + if __name__ == '__main__': try: - main () + main() except KeyboardInterrupt: pass - diff --git a/gr-qtgui/apps/usrp_display_qtgui.py b/gr-qtgui/apps/usrp_display_qtgui.py index d14c7535c87..1a1522cf6fb 100644 --- a/gr-qtgui/apps/usrp_display_qtgui.py +++ b/gr-qtgui/apps/usrp_display_qtgui.py @@ -9,6 +9,7 @@ from PyQt5 import QtCore, QtGui + class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") @@ -20,10 +21,12 @@ def setupUi(self, MainWindow): self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.groupBox = QtGui.QGroupBox(self.centralwidget) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) + sizePolicy = QtGui.QSizePolicy( + QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.groupBox.sizePolicy().hasHeightForWidth()) self.groupBox.setSizePolicy(sizePolicy) self.groupBox.setMinimumSize(QtCore.QSize(240, 150)) self.groupBox.setMaximumSize(QtCore.QSize(240, 16777215)) @@ -35,52 +38,68 @@ def setupUi(self, MainWindow): self.formLayout.setObjectName("formLayout") self.frequencyLabel = QtGui.QLabel(self.formLayoutWidget) self.frequencyLabel.setObjectName("frequencyLabel") - self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.frequencyLabel) + self.formLayout.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.frequencyLabel) self.gainLabel = QtGui.QLabel(self.formLayoutWidget) self.gainLabel.setObjectName("gainLabel") - self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.gainLabel) + self.formLayout.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.gainLabel) self.bandwidthLabel = QtGui.QLabel(self.formLayoutWidget) self.bandwidthLabel.setObjectName("bandwidthLabel") - self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.bandwidthLabel) + self.formLayout.setWidget( + 2, QtGui.QFormLayout.LabelRole, self.bandwidthLabel) self.frequencyEdit = QtGui.QLineEdit(self.formLayoutWidget) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) + sizePolicy = QtGui.QSizePolicy( + QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.frequencyEdit.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.frequencyEdit.sizePolicy().hasHeightForWidth()) self.frequencyEdit.setSizePolicy(sizePolicy) self.frequencyEdit.setMinimumSize(QtCore.QSize(120, 26)) self.frequencyEdit.setObjectName("frequencyEdit") - self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.frequencyEdit) + self.formLayout.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.frequencyEdit) self.gainEdit = QtGui.QLineEdit(self.formLayoutWidget) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) + sizePolicy = QtGui.QSizePolicy( + QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.gainEdit.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.gainEdit.sizePolicy().hasHeightForWidth()) self.gainEdit.setSizePolicy(sizePolicy) self.gainEdit.setMinimumSize(QtCore.QSize(120, 26)) self.gainEdit.setObjectName("gainEdit") - self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.gainEdit) + self.formLayout.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.gainEdit) self.bandwidthEdit = QtGui.QLineEdit(self.formLayoutWidget) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) + sizePolicy = QtGui.QSizePolicy( + QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.bandwidthEdit.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.bandwidthEdit.sizePolicy().hasHeightForWidth()) self.bandwidthEdit.setSizePolicy(sizePolicy) self.bandwidthEdit.setMinimumSize(QtCore.QSize(120, 26)) self.bandwidthEdit.setObjectName("bandwidthEdit") - self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.bandwidthEdit) + self.formLayout.setWidget( + 2, QtGui.QFormLayout.FieldRole, self.bandwidthEdit) self.amplifierLabel = QtGui.QLabel(self.formLayoutWidget) self.amplifierLabel.setObjectName("amplifierLabel") - self.formLayout.setWidget(3, QtGui.QFormLayout.LabelRole, self.amplifierLabel) + self.formLayout.setWidget( + 3, QtGui.QFormLayout.LabelRole, self.amplifierLabel) self.amplifierEdit = QtGui.QLineEdit(self.formLayoutWidget) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) + sizePolicy = QtGui.QSizePolicy( + QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.amplifierEdit.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.amplifierEdit.sizePolicy().hasHeightForWidth()) self.amplifierEdit.setSizePolicy(sizePolicy) self.amplifierEdit.setMinimumSize(QtCore.QSize(120, 26)) self.amplifierEdit.setObjectName("amplifierEdit") - self.formLayout.setWidget(3, QtGui.QFormLayout.FieldRole, self.amplifierEdit) + self.formLayout.setWidget( + 3, QtGui.QFormLayout.FieldRole, self.amplifierEdit) self.horizontalLayout_2.addWidget(self.groupBox) self.frame_2 = QtGui.QFrame(self.centralwidget) self.frame_2.setMinimumSize(QtCore.QSize(200, 0)) @@ -104,28 +123,35 @@ def setupUi(self, MainWindow): self.dcGainEdit.setObjectName("dcGainEdit") self.horizontalLayout.addWidget(self.dcGainEdit) self.verticalLayout_3.addLayout(self.horizontalLayout) - spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) + spacerItem = QtGui.QSpacerItem( + 20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_3.addItem(spacerItem) self.horizontalLayout_2.addWidget(self.frame_2) - spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) + spacerItem1 = QtGui.QSpacerItem( + 40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem1) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") - spacerItem2 = QtGui.QSpacerItem(20, 80, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) + spacerItem2 = QtGui.QSpacerItem( + 20, 80, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) self.verticalLayout.addItem(spacerItem2) self.pauseButton = QtGui.QPushButton(self.centralwidget) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) + sizePolicy = QtGui.QSizePolicy( + QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.pauseButton.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.pauseButton.sizePolicy().hasHeightForWidth()) self.pauseButton.setSizePolicy(sizePolicy) self.pauseButton.setObjectName("pauseButton") self.verticalLayout.addWidget(self.pauseButton) self.closeButton = QtGui.QPushButton(self.centralwidget) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) + sizePolicy = QtGui.QSizePolicy( + QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.closeButton.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.closeButton.sizePolicy().hasHeightForWidth()) self.closeButton.setSizePolicy(sizePolicy) self.closeButton.setMinimumSize(QtCore.QSize(75, 0)) self.closeButton.setObjectName("closeButton") @@ -135,10 +161,12 @@ def setupUi(self, MainWindow): self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.frame = QtGui.QFrame(self.centralwidget) - sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + sizePolicy = QtGui.QSizePolicy( + QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) - sizePolicy.setHeightForWidth(self.frame.sizePolicy().hasHeightForWidth()) + sizePolicy.setHeightForWidth( + self.frame.sizePolicy().hasHeightForWidth()) self.frame.setSizePolicy(sizePolicy) self.frame.setMinimumSize(QtCore.QSize(800, 550)) self.frame.setFrameShape(QtGui.QFrame.StyledPanel) @@ -170,22 +198,36 @@ def setupUi(self, MainWindow): self.menubar.addAction(self.menuFile.menuAction()) self.retranslateUi(MainWindow) - QtCore.QObject.connect(self.closeButton, QtCore.SIGNAL("clicked()"), MainWindow.close) - QtCore.QObject.connect(self.actionExit, QtCore.SIGNAL("triggered()"), MainWindow.close) + QtCore.QObject.connect(self.closeButton, QtCore.SIGNAL( + "clicked()"), MainWindow.close) + QtCore.QObject.connect(self.actionExit, QtCore.SIGNAL( + "triggered()"), MainWindow.close) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): - MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "USRP Display", None, QtGui.QApplication.UnicodeUTF8)) - self.groupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Receiver Parameters", None, QtGui.QApplication.UnicodeUTF8)) - self.frequencyLabel.setText(QtGui.QApplication.translate("MainWindow", "Frequency (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.gainLabel.setText(QtGui.QApplication.translate("MainWindow", "RF Gain", None, QtGui.QApplication.UnicodeUTF8)) - self.bandwidthLabel.setText(QtGui.QApplication.translate("MainWindow", "Bandwidth", None, QtGui.QApplication.UnicodeUTF8)) - self.amplifierLabel.setText(QtGui.QApplication.translate("MainWindow", "Amplifier", None, QtGui.QApplication.UnicodeUTF8)) - self.dcCancelCheckBox.setText(QtGui.QApplication.translate("MainWindow", "Cancel DC", None, QtGui.QApplication.UnicodeUTF8)) - self.dcGainLabel.setText(QtGui.QApplication.translate("MainWindow", "DC Canceller Gain", None, QtGui.QApplication.UnicodeUTF8)) - self.pauseButton.setText(QtGui.QApplication.translate("MainWindow", "Pause", None, QtGui.QApplication.UnicodeUTF8)) - self.closeButton.setText(QtGui.QApplication.translate("MainWindow", "Close", None, QtGui.QApplication.UnicodeUTF8)) - self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "&File", None, QtGui.QApplication.UnicodeUTF8)) - self.actionExit.setText(QtGui.QApplication.translate("MainWindow", "E&xit", None, QtGui.QApplication.UnicodeUTF8)) - self.actionSaveData.setText(QtGui.QApplication.translate("MainWindow", "&Save Data", None, QtGui.QApplication.UnicodeUTF8)) - + MainWindow.setWindowTitle(QtGui.QApplication.translate( + "MainWindow", "USRP Display", None, QtGui.QApplication.UnicodeUTF8)) + self.groupBox.setTitle(QtGui.QApplication.translate( + "MainWindow", "Receiver Parameters", None, QtGui.QApplication.UnicodeUTF8)) + self.frequencyLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Frequency (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.gainLabel.setText(QtGui.QApplication.translate( + "MainWindow", "RF Gain", None, QtGui.QApplication.UnicodeUTF8)) + self.bandwidthLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Bandwidth", None, QtGui.QApplication.UnicodeUTF8)) + self.amplifierLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Amplifier", None, QtGui.QApplication.UnicodeUTF8)) + self.dcCancelCheckBox.setText(QtGui.QApplication.translate( + "MainWindow", "Cancel DC", None, QtGui.QApplication.UnicodeUTF8)) + self.dcGainLabel.setText(QtGui.QApplication.translate( + "MainWindow", "DC Canceller Gain", None, QtGui.QApplication.UnicodeUTF8)) + self.pauseButton.setText(QtGui.QApplication.translate( + "MainWindow", "Pause", None, QtGui.QApplication.UnicodeUTF8)) + self.closeButton.setText(QtGui.QApplication.translate( + "MainWindow", "Close", None, QtGui.QApplication.UnicodeUTF8)) + self.menuFile.setTitle(QtGui.QApplication.translate( + "MainWindow", "&File", None, QtGui.QApplication.UnicodeUTF8)) + self.actionExit.setText(QtGui.QApplication.translate( + "MainWindow", "E&xit", None, QtGui.QApplication.UnicodeUTF8)) + self.actionSaveData.setText(QtGui.QApplication.translate( + "MainWindow", "&Save Data", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/gr-qtgui/examples/pyqt_const_c.py b/gr-qtgui/examples/pyqt_const_c.py index 0f3cf60606e..9442feb5485 100644 --- a/gr-qtgui/examples/pyqt_const_c.py +++ b/gr-qtgui/examples/pyqt_const_c.py @@ -32,17 +32,20 @@ sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -64,14 +67,12 @@ def __init__(self, parent=None): self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) - self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) @@ -106,7 +107,6 @@ def amp1EditText(self): except ValueError: print("Bad amplitude value entered") - def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) @@ -136,22 +136,22 @@ def __init__(self): src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.5, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.5, 0) - src = blocks.add_cc() + src = blocks.add_cc() channel = channels.channel_model(0.001) - thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) + thr = blocks.throttle(gr.sizeof_gr_complex, 100 * npts) self.snk1 = qtgui.const_sink_c(npts, "Constellation Example", 1, None) self.snk1.disable_legend() - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, channel, thr, (self.snk1, 0)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, channel, thr, (self.snk1, 0)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget @@ -160,8 +160,9 @@ def __init__(self): self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_example_c.py b/gr-qtgui/examples/pyqt_example_c.py index 9485c050a8d..7ccd42f7724 100644 --- a/gr-qtgui/examples/pyqt_example_c.py +++ b/gr-qtgui/examples/pyqt_example_c.py @@ -33,17 +33,20 @@ sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -65,14 +68,12 @@ def __init__(self, parent=None): self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) - self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) @@ -108,7 +109,6 @@ def amp1EditText(self): except ValueError: print("Bad amplitude value entered") - def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) @@ -142,24 +142,24 @@ def __init__(self): src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) - src = blocks.add_cc() + src = blocks.add_cc() channel = channels.channel_model(0.001) - thr = blocks.throttle(gr.sizeof_gr_complex, 100*fftsize) + thr = blocks.throttle(gr.sizeof_gr_complex, 100 * fftsize) self.snk1 = qtgui.sink_c(fftsize, window.WIN_BLACKMAN_hARRIS, 0, Rs, "Complex Signal Example", True, True, True, False, None) - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, channel, thr, self.snk1) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, channel, thr, self.snk1) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget @@ -169,8 +169,9 @@ def __init__(self): self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_example_f.py b/gr-qtgui/examples/pyqt_example_f.py index c8e06b87203..172e51c2808 100644 --- a/gr-qtgui/examples/pyqt_example_f.py +++ b/gr-qtgui/examples/pyqt_example_f.py @@ -27,17 +27,20 @@ sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -59,14 +62,12 @@ def __init__(self, parent=None): self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) - self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) @@ -102,7 +103,6 @@ def amp1EditText(self): except ValueError: print("Bad amplitude value entered") - def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) @@ -132,8 +132,8 @@ def __init__(self): src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) - src = blocks.add_ff() - thr = blocks.throttle(gr.sizeof_float, 100*fftsize) + src = blocks.add_ff() + thr = blocks.throttle(gr.sizeof_float, 100 * fftsize) noise = analog.noise_source_f(analog.GR_GAUSSIAN, 0.001) add = blocks.add_ff() self.snk1 = qtgui.sink_f(fftsize, window.WIN_BLACKMAN_hARRIS, @@ -141,10 +141,10 @@ def __init__(self): "Float Signal Example", True, True, True, False, None) - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, thr, (add,0)) - self.connect(noise, (add,1)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, thr, (add, 0)) + self.connect(noise, (add, 1)) self.connect(add, self.snk1) self.ctrl_win = control_box() @@ -152,7 +152,7 @@ def __init__(self): self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget @@ -162,8 +162,9 @@ def __init__(self): self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_freq_c.py b/gr-qtgui/examples/pyqt_freq_c.py index 8f3387befb2..5ba641c86f8 100644 --- a/gr-qtgui/examples/pyqt_freq_c.py +++ b/gr-qtgui/examples/pyqt_freq_c.py @@ -33,17 +33,20 @@ sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -65,14 +68,12 @@ def __init__(self, parent=None): self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) - self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) @@ -108,7 +109,6 @@ def amp1EditText(self): except ValueError: print("Bad amplitude value entered") - def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) @@ -142,36 +142,37 @@ def __init__(self): src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) - src = blocks.add_cc() + src = blocks.add_cc() channel = channels.channel_model(0.01) - thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) + thr = blocks.throttle(gr.sizeof_gr_complex, 100 * npts) self.snk1 = qtgui.freq_sink_c(npts, window.WIN_BLACKMAN_hARRIS, 0, Rs, "Complex Freq Example", 3, None) - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, channel, thr, (self.snk1, 0)) - self.connect(src1, (self.snk1, 1)) - self.connect(src2, (self.snk1, 2)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, channel, thr, (self.snk1, 0)) + self.connect(src1, (self.snk1, 1)) + self.connect(src2, (self.snk1, 2)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget pyWin = sip.wrapinstance(pyQt, QtWidgets.QWidget) - #pyWin.show() + # pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_freq_f.py b/gr-qtgui/examples/pyqt_freq_f.py index 15949495cc6..274e45de7a2 100644 --- a/gr-qtgui/examples/pyqt_freq_f.py +++ b/gr-qtgui/examples/pyqt_freq_f.py @@ -33,12 +33,14 @@ def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -60,14 +62,12 @@ def __init__(self, parent=None): self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) - self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) @@ -103,7 +103,6 @@ def amp1EditText(self): except ValueError: print("Bad amplitude value entered") - def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) @@ -133,35 +132,36 @@ def __init__(self): src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) - src = blocks.add_ff() - thr = blocks.throttle(gr.sizeof_float, 100*npts) + src = blocks.add_ff() + thr = blocks.throttle(gr.sizeof_float, 100 * npts) self.snk1 = qtgui.freq_sink_f(npts, window.WIN_BLACKMAN_hARRIS, 0, Rs, "Real freq Example", 3, None) - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, thr, (self.snk1, 0)) - self.connect(src1, (self.snk1, 1)) - self.connect(src2, (self.snk1, 2)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, thr, (self.snk1, 0)) + self.connect(src1, (self.snk1, 1)) + self.connect(src2, (self.snk1, 2)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget pyWin = sip.wrapinstance(pyQt, QtWidgets.QWidget) - #pyWin.show() + # pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_histogram_f.py b/gr-qtgui/examples/pyqt_histogram_f.py index d35cc90cc9b..8360e5aec0a 100644 --- a/gr-qtgui/examples/pyqt_histogram_f.py +++ b/gr-qtgui/examples/pyqt_histogram_f.py @@ -26,17 +26,20 @@ sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, snk, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -59,7 +62,6 @@ def __init__(self, snk, parent=None): self.layout.addRow("Sine Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) @@ -91,7 +93,6 @@ def __init__(self, snk, parent=None): self.quit.clicked.connect(QtWidgets.qApp.quit) - def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(("{0}").format(self.signal1.frequency())) @@ -149,14 +150,14 @@ def __init__(self): src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0, 0) src2 = analog.noise_source_f(analog.GR_GAUSSIAN, 1) - src = blocks.add_ff() - thr = blocks.throttle(gr.sizeof_float, 100*npts) + src = blocks.add_ff() + thr = blocks.throttle(gr.sizeof_float, 100 * npts) self.snk1 = qtgui.histogram_sink_f(npts, 200, -5, 5, "Histogram", 1, None) self.snk1.disable_legend() - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) self.connect(src, thr, self.snk1) self.ctrl_win = control_box(self.snk1) @@ -164,18 +165,19 @@ def __init__(self): self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget pyWin = sip.wrapinstance(pyQt, QtWidgets.QWidget) - #pyWin.show() + # pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_time_c.py b/gr-qtgui/examples/pyqt_time_c.py index 3a47a6d5761..e784b7e4d41 100644 --- a/gr-qtgui/examples/pyqt_time_c.py +++ b/gr-qtgui/examples/pyqt_time_c.py @@ -32,17 +32,20 @@ sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -64,14 +67,12 @@ def __init__(self, parent=None): self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) - self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) @@ -107,7 +108,6 @@ def amp1EditText(self): except ValueError: print("Bad amplitude value entered") - def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) @@ -141,15 +141,15 @@ def __init__(self): src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) - src = blocks.add_cc() + src = blocks.add_cc() channel = channels.channel_model(0.01) - thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) + thr = blocks.throttle(gr.sizeof_gr_complex, 100 * npts) self.snk1 = qtgui.time_sink_c(npts, Rs, "Complex Time Example", 1, None) - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, channel, thr, (self.snk1, 0)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, channel, thr, (self.snk1, 0)) #self.connect(src1, (self.snk1, 1)) #self.connect(src2, (self.snk1, 2)) @@ -158,7 +158,7 @@ def __init__(self): self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget @@ -166,7 +166,7 @@ def __init__(self): # Example of using signal/slot to set the title of a curve # FIXME: update for Qt5 - #pyWin.setLineLabel.connect(pyWin.setLineLabel) + # pyWin.setLineLabel.connect(pyWin.setLineLabel) #pyWin.emit(QtCore.SIGNAL("setLineLabel(int, QString)"), 0, "Re{sum}") self.snk1.set_line_label(0, "Re{Sum}") self.snk1.set_line_label(1, "Im{Sum}") @@ -180,12 +180,13 @@ def __init__(self): self.snk1.set_update_time(0.5) - #pyWin.show() + # pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_time_f.py b/gr-qtgui/examples/pyqt_time_f.py index 0bbbfa57d4f..2ec181fb566 100644 --- a/gr-qtgui/examples/pyqt_time_f.py +++ b/gr-qtgui/examples/pyqt_time_f.py @@ -26,17 +26,20 @@ sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -58,14 +61,12 @@ def __init__(self, parent=None): self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) - self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) @@ -101,7 +102,6 @@ def amp1EditText(self): except ValueError: print("Bad amplitude value entered") - def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) @@ -131,17 +131,17 @@ def __init__(self): src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) - src = blocks.add_ff() - thr = blocks.throttle(gr.sizeof_float, 100*npts) + src = blocks.add_ff() + thr = blocks.throttle(gr.sizeof_float, 100 * npts) noise = analog.noise_source_f(analog.GR_GAUSSIAN, 0.001) add = blocks.add_ff() self.snk1 = qtgui.time_sink_f(npts, Rs, "Complex Time Example", 3, None) - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, thr, (add,0)) - self.connect(noise, (add,1)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, thr, (add, 0)) + self.connect(noise, (add, 1)) self.connect(add, self.snk1) self.connect(src1, (self.snk1, 1)) self.connect(src2, (self.snk1, 2)) @@ -151,7 +151,7 @@ def __init__(self): self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget @@ -159,7 +159,7 @@ def __init__(self): # Example of using signal/slot to set the title of a curve # FIXME: update for Qt5 - #pyWin.setLineLabel.connect(pyWin.setLineLabel) + # pyWin.setLineLabel.connect(pyWin.setLineLabel) #pyWin.emit(QtCore.SIGNAL("setLineLabel(int, QString)"), 0, "Re{sum}") self.snk1.set_line_label(0, "Re{sum}") self.snk1.set_line_label(1, "src1") @@ -168,12 +168,13 @@ def __init__(self): # Can also set the color of a curve #self.snk1.set_color(5, "blue") - #pyWin.show() + # pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_time_raster_b.py b/gr-qtgui/examples/pyqt_time_raster_b.py index 712fe395678..25c283385bd 100644 --- a/gr-qtgui/examples/pyqt_time_raster_b.py +++ b/gr-qtgui/examples/pyqt_time_raster_b.py @@ -21,25 +21,28 @@ print("Error: Program requires PyQt5 and gr-qtgui.") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.resize(800, 500) + class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self.qapp = QtWidgets.QApplication(sys.argv) - data0 = 10*[0,] + 40*[1,0] + 10*[0,] - data0 += 10*[0,] + 40*[0,1] + 10*[0,] - data1 = 20*[0,] + [0,0,0,1,1,1,0,0,0,0] + 70*[0,] + data0 = 10 * [0, ] + 40 * [1, 0] + 10 * [0, ] + data0 += 10 * [0, ] + 40 * [0, 1] + 10 * [0, ] + data1 = 20 * [0, ] + [0, 0, 0, 1, 1, 1, 0, 0, 0, 0] + 70 * [0, ] # Adjust these to change the layout of the plot. # Can be set to fractions. @@ -49,7 +52,7 @@ def __init__(self): fs = 200 src0 = blocks.vector_source_b(data0, True) src1 = blocks.vector_source_b(data1, True) - thr = blocks.throttle(gr.sizeof_char, 50000) + thr = blocks.throttle(gr.sizeof_char, 50000) head = blocks.head(gr.sizeof_char, 10000000) self.snk1 = qtgui.time_raster_sink_b(fs, nrows, ncols, [], [], "Time Raster Example", 2, None) @@ -67,8 +70,9 @@ def __init__(self): self.main_box = dialog_box(pyWin) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_time_raster_f.py b/gr-qtgui/examples/pyqt_time_raster_f.py index aa4e4a80005..a86b7c910ea 100644 --- a/gr-qtgui/examples/pyqt_time_raster_f.py +++ b/gr-qtgui/examples/pyqt_time_raster_f.py @@ -20,25 +20,28 @@ print("Error: Program requires PyQt5 and gr-qtgui.") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.resize(800, 500) + class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self.qapp = QtWidgets.QApplication(sys.argv) - data0 = 10*[0,] + 40*[1,0] + 10*[0,] - data0 += 10*[0,] + 40*[0,1] + 10*[0,] - data1 = 20*[0,] + [0,0,0,1,1,1,0,0,0,0] + 70*[0,] + data0 = 10 * [0, ] + 40 * [1, 0] + 10 * [0, ] + data0 += 10 * [0, ] + 40 * [0, 1] + 10 * [0, ] + data1 = 20 * [0, ] + [0, 0, 0, 1, 1, 1, 0, 0, 0, 0] + 70 * [0, ] # Adjust these to change the layout of the plot. # Can be set to fractions. @@ -66,8 +69,9 @@ def __init__(self): self.main_box = dialog_box(pyWin) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_waterfall_c.py b/gr-qtgui/examples/pyqt_waterfall_c.py index a3bf5282cbe..778a91ead93 100644 --- a/gr-qtgui/examples/pyqt_waterfall_c.py +++ b/gr-qtgui/examples/pyqt_waterfall_c.py @@ -33,17 +33,20 @@ sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -65,14 +68,12 @@ def __init__(self, parent=None): self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) - self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) @@ -108,7 +109,6 @@ def amp1EditText(self): except ValueError: print("Bad amplitude value entered") - def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) @@ -144,9 +144,9 @@ def __init__(self): src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) - src = blocks.add_cc() + src = blocks.add_cc() channel = channels.channel_model(0.01) - thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) + thr = blocks.throttle(gr.sizeof_gr_complex, 100 * npts) filt = filter.fft_filter_ccc(1, taps) self.snk1 = qtgui.waterfall_sink_c(npts, window.WIN_BLACKMAN_hARRIS, 0, Rs, @@ -154,9 +154,9 @@ def __init__(self): self.snk1.set_color_map(0, qtgui.INTENSITY_COLOR_MAP_TYPE_COOL) self.snk1.set_color_map(1, qtgui.INTENSITY_COLOR_MAP_TYPE_COOL) - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, channel, thr, (self.snk1, 0)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, channel, thr, (self.snk1, 0)) self.connect(thr, filt, (self.snk1, 1)) self.ctrl_win = control_box() @@ -164,18 +164,19 @@ def __init__(self): self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget pyWin = sip.wrapinstance(pyQt, QtWidgets.QWidget) - #pyWin.show() + # pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/examples/pyqt_waterfall_f.py b/gr-qtgui/examples/pyqt_waterfall_f.py index 15e0512df41..ecbe84dee5c 100644 --- a/gr-qtgui/examples/pyqt_waterfall_f.py +++ b/gr-qtgui/examples/pyqt_waterfall_f.py @@ -27,17 +27,20 @@ sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) + class dialog_box(QtWidgets.QWidget): def __init__(self, display, control): QtWidgets.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') - self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self) + self.boxlayout = QtWidgets.QBoxLayout( + QtWidgets.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) + class control_box(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) @@ -59,14 +62,12 @@ def __init__(self, parent=None): self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.amp1Edit.editingFinished.connect(self.amp1EditText) - # Control the second signal self.freq2Edit = QtWidgets.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.freq2Edit.editingFinished.connect(self.freq2EditText) - self.amp2Edit = QtWidgets.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) @@ -102,7 +103,6 @@ def amp1EditText(self): except ValueError: print("Bad amplitude value entered") - def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) @@ -132,17 +132,17 @@ def __init__(self): src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) - src = blocks.add_ff() - thr = blocks.throttle(gr.sizeof_float, 100*npts) + src = blocks.add_ff() + thr = blocks.throttle(gr.sizeof_float, 100 * npts) self.snk1 = qtgui.waterfall_sink_f(npts, window.WIN_BLACKMAN_hARRIS, 0, Rs, "Real Waterfall Example", 2, None) self.snk1.set_color_map(0, qtgui.INTENSITY_COLOR_MAP_TYPE_COOL) self.snk1.set_color_map(1, qtgui.INTENSITY_COLOR_MAP_TYPE_COOL) - self.connect(src1, (src,0)) - self.connect(src2, (src,1)) - self.connect(src, thr, (self.snk1, 0)) + self.connect(src1, (src, 0)) + self.connect(src2, (src, 1)) + self.connect(src, thr, (self.snk1, 0)) self.connect(src1, (self.snk1, 1)) self.ctrl_win = control_box() @@ -150,18 +150,19 @@ def __init__(self): self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget - pyQt = self.snk1.qwidget() + pyQt = self.snk1.qwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt5.QtWidgets.QWidget pyWin = sip.wrapinstance(pyQt, QtWidgets.QWidget) - #pyWin.show() + # pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() + if __name__ == "__main__": - tb = my_top_block(); + tb = my_top_block() tb.start() tb.qapp.exec_() tb.stop() diff --git a/gr-qtgui/grc/qtgui_time_sink_x.block.yml.py b/gr-qtgui/grc/qtgui_time_sink_x.block.yml.py index ca3178e86b5..d40b0b82585 100644 --- a/gr-qtgui/grc/qtgui_time_sink_x.block.yml.py +++ b/gr-qtgui/grc/qtgui_time_sink_x.block.yml.py @@ -167,7 +167,7 @@ hide: ${{ ('part' if ( int(nconnections) >= {i} or (type == "complex" and int(nconnections) >= {i_cplx}) - or (type == "msg_complex" and {i_cplx} <= 1) + or (type == "msg_complex" and {i_cplx} <= 1) or (type == "msg_float" and {i} <= 1)) else 'all') }} @@ -179,7 +179,7 @@ hide: ${{ ('part' if ( int(nconnections) >= {i} or (type == "complex" and int(nconnections) >= {i_cplx}) - or (type == "msg_complex" and {i_cplx} <= 1) + or (type == "msg_complex" and {i_cplx} <= 1) or (type == "msg_float" and {i} <= 1)) else 'all') }} @@ -194,7 +194,7 @@ hide: ${{ ('part' if ( int(nconnections) >= {i} or (type == "complex" and int(nconnections) >= {i_cplx}) - or (type == "msg_complex" and {i_cplx} <= 1) + or (type == "msg_complex" and {i_cplx} <= 1) or (type == "msg_float" and {i} <= 1)) else 'all') }} @@ -209,7 +209,7 @@ hide: ${{ ('part' if ( int(nconnections) >= {i} or (type == "complex" and int(nconnections) >= {i_cplx}) - or (type == "msg_complex" and {i_cplx} <= 1) + or (type == "msg_complex" and {i_cplx} <= 1) or (type == "msg_float" and {i} <= 1)) else 'all') }} @@ -224,7 +224,7 @@ hide: ${{ ('part' if ( int(nconnections) >= {i} or (type == "complex" and int(nconnections) >= {i_cplx}) - or (type == "msg_complex" and {i_cplx} <= 1) + or (type == "msg_complex" and {i_cplx} <= 1) or (type == "msg_float" and {i} <= 1)) else 'all') }} @@ -237,7 +237,7 @@ hide: ${{ ('part' if ( int(nconnections) >= {i} or (type == "complex" and int(nconnections) >= {i_cplx}) - or (type == "msg_complex" and {i_cplx} <= 1) + or (type == "msg_complex" and {i_cplx} <= 1) or (type == "msg_float" and {i} <= 1)) else 'all') }} @@ -345,19 +345,21 @@ file_format: 1 """ + def make_yml(): """Return the YML file as a string""" default_colors = [ 'blue', 'red', 'green', 'black', 'cyan', 'magenta', 'yellow', 'dark red', 'dark green', 'dark blue' ] - line_params_1 = LINE_PARAMS.format(i=1, i_cplx=1, i_color=default_colors[0]) + line_params_1 = LINE_PARAMS.format( + i=1, i_cplx=1, i_color=default_colors[0]) line_params_1 = re.sub(r' base_key:.*\n', '', line_params_1) line_params_n = ''.join([ LINE_PARAMS.format( i=i, - i_cplx=int(math.ceil(float(i)/2)), - i_color=default_colors[(i-1) % len(default_colors)], + i_cplx=int(math.ceil(float(i) / 2)), + i_color=default_colors[(i - 1) % len(default_colors)], ) for i in range(2, 11) ]) @@ -378,4 +380,3 @@ def make_yml(): data = make_yml() with open(filename, 'wb') as fp: fp.write(data.encode()) - diff --git a/gr-qtgui/include/gnuradio/qtgui/DisplayPlot.h b/gr-qtgui/include/gnuradio/qtgui/DisplayPlot.h index 04de962fa3d..4e8afa26794 100644 --- a/gr-qtgui/include/gnuradio/qtgui/DisplayPlot.h +++ b/gr-qtgui/include/gnuradio/qtgui/DisplayPlot.h @@ -29,7 +29,10 @@ #include #if QWT_VERSION >= 0x060000 -#include +typedef QPointF QwtDoublePoint; +typedef QRectF QwtDoubleRect; + +typedef QwtInterval QwtDoubleInterval; #endif typedef QList QColorList; diff --git a/gr-qtgui/include/gnuradio/qtgui/TimeRasterDisplayPlot.h b/gr-qtgui/include/gnuradio/qtgui/TimeRasterDisplayPlot.h index 170b62cafbf..09bad218bee 100644 --- a/gr-qtgui/include/gnuradio/qtgui/TimeRasterDisplayPlot.h +++ b/gr-qtgui/include/gnuradio/qtgui/TimeRasterDisplayPlot.h @@ -23,7 +23,9 @@ #if QWT_VERSION < 0x060000 #include #else -#include +#include + +typedef QwtInterval QwtDoubleInterval; #endif /*! diff --git a/gr-qtgui/include/gnuradio/qtgui/WaterfallDisplayPlot.h b/gr-qtgui/include/gnuradio/qtgui/WaterfallDisplayPlot.h index ed2196b63ef..afe7a6a6774 100644 --- a/gr-qtgui/include/gnuradio/qtgui/WaterfallDisplayPlot.h +++ b/gr-qtgui/include/gnuradio/qtgui/WaterfallDisplayPlot.h @@ -22,7 +22,9 @@ #if QWT_VERSION < 0x060000 #include #else -#include +#include + +typedef QwtInterval QwtDoubleInterval; #endif /*! diff --git a/gr-qtgui/include/gnuradio/qtgui/plot_raster.h b/gr-qtgui/include/gnuradio/qtgui/plot_raster.h index dc7ee543872..4b4c4f2afb2 100644 --- a/gr-qtgui/include/gnuradio/qtgui/plot_raster.h +++ b/gr-qtgui/include/gnuradio/qtgui/plot_raster.h @@ -16,8 +16,10 @@ #include #if QWT_VERSION >= 0x060000 -#include -#include // doesn't seem necessary, but is... +#include +#include + +typedef QwtInterval QwtDoubleInterval; #endif class QwtColorMap; diff --git a/gr-qtgui/include/gnuradio/qtgui/plot_waterfall.h b/gr-qtgui/include/gnuradio/qtgui/plot_waterfall.h index c3dba76bb95..f40446e25ca 100644 --- a/gr-qtgui/include/gnuradio/qtgui/plot_waterfall.h +++ b/gr-qtgui/include/gnuradio/qtgui/plot_waterfall.h @@ -16,8 +16,10 @@ #include #if QWT_VERSION >= 0x060000 -#include -#include // doesn't seem necessary, but is... +#include +#include + +typedef QwtInterval QwtDoubleInterval; #endif class QwtColorMap; diff --git a/gr-qtgui/include/gnuradio/qtgui/qtgui_types.h b/gr-qtgui/include/gnuradio/qtgui/qtgui_types.h index e2735cf945d..670876afc7c 100644 --- a/gr-qtgui/include/gnuradio/qtgui/qtgui_types.h +++ b/gr-qtgui/include/gnuradio/qtgui/qtgui_types.h @@ -14,6 +14,7 @@ #include #include #include +#include namespace gr { namespace qtgui { diff --git a/gr-qtgui/include/gnuradio/qtgui/timeRasterGlobalData.h b/gr-qtgui/include/gnuradio/qtgui/timeRasterGlobalData.h index 09cd42883cd..4dfc5578448 100644 --- a/gr-qtgui/include/gnuradio/qtgui/timeRasterGlobalData.h +++ b/gr-qtgui/include/gnuradio/qtgui/timeRasterGlobalData.h @@ -15,8 +15,9 @@ #include #if QWT_VERSION >= 0x060000 -#include -#include // doesn't seem necessary, but is... +#include + +typedef QwtInterval QwtDoubleInterval; #endif class TimeRasterData : public QwtRasterData @@ -35,6 +36,9 @@ class TimeRasterData : public QwtRasterData #if QWT_VERSION < 0x060000 virtual QwtDoubleInterval range() const; virtual void setRange(const QwtDoubleInterval&); +#elif QWT_VERSION >= 0x060200 + virtual QwtInterval interval(Qt::Axis) const; + void setInterval(Qt::Axis, const QwtInterval&); #endif double value(double x, double y) const override; @@ -58,6 +62,10 @@ class TimeRasterData : public QwtRasterData QwtInterval d_intensityRange; #endif +#if QWT_VERSION >= 0x060200 + QwtInterval d_intervals[3]; +#endif + private: }; diff --git a/gr-qtgui/include/gnuradio/qtgui/waterfallGlobalData.h b/gr-qtgui/include/gnuradio/qtgui/waterfallGlobalData.h index 03d9d13dc6a..54aa1073453 100644 --- a/gr-qtgui/include/gnuradio/qtgui/waterfallGlobalData.h +++ b/gr-qtgui/include/gnuradio/qtgui/waterfallGlobalData.h @@ -15,8 +15,9 @@ #include #if QWT_VERSION >= 0x060000 -#include -#include // doesn't seem necessary, but is... +#include + +typedef QwtInterval QwtDoubleInterval; #endif class WaterfallData : public QwtRasterData @@ -36,6 +37,9 @@ class WaterfallData : public QwtRasterData #if QWT_VERSION < 0x060000 virtual QwtDoubleInterval range() const; virtual void setRange(const QwtDoubleInterval&); +#elif QWT_VERSION >= 0x060200 + virtual QwtInterval interval(Qt::Axis) const; + void setInterval(Qt::Axis, const QwtInterval&); #endif double value(double x, double y) const override; @@ -62,6 +66,10 @@ class WaterfallData : public QwtRasterData QwtInterval _intensityRange; #endif +#if QWT_VERSION >= 0x060200 + QwtInterval d_intervals[3]; +#endif + private: }; diff --git a/gr-qtgui/lib/ConstellationDisplayPlot.cc b/gr-qtgui/lib/ConstellationDisplayPlot.cc index ffd3ecf5943..4283fad40f9 100644 --- a/gr-qtgui/lib/ConstellationDisplayPlot.cc +++ b/gr-qtgui/lib/ConstellationDisplayPlot.cc @@ -16,6 +16,7 @@ #include #include #include +#include class ConstellationDisplayZoomer : public QwtPlotZoomer { diff --git a/gr-qtgui/lib/plot_raster.cc b/gr-qtgui/lib/plot_raster.cc index 7bb439881a4..d79def0f44a 100644 --- a/gr-qtgui/lib/plot_raster.cc +++ b/gr-qtgui/lib/plot_raster.cc @@ -244,7 +244,11 @@ QImage PlotTimeRaster::renderImage(const QwtScaleMap& xMap, } d_data->data->incrementResidual(); } else if (d_data->colorMap->format() == QwtColorMap::Indexed) { +#if QWT_VERSION >= 0x060200 + image.setColorTable(d_data->colorMap->colorTable(256)); +#else image.setColorTable(d_data->colorMap->colorTable(intensityRange)); +#endif for (int y = rect.top(); y <= rect.bottom(); y++) { const double ty = yyMap.invTransform(y); @@ -253,8 +257,13 @@ QImage PlotTimeRaster::renderImage(const QwtScaleMap& xMap, for (int x = rect.left(); x <= rect.right(); x++) { const double tx = xxMap.invTransform(x); +#if QWT_VERSION >= 0x060200 + *line++ = d_data->colorMap->colorIndex( + 256, intensityRange, d_data->data->value(tx, ty)); +#else *line++ = d_data->colorMap->colorIndex(intensityRange, d_data->data->value(tx, ty)); +#endif } } } diff --git a/gr-qtgui/lib/plot_waterfall.cc b/gr-qtgui/lib/plot_waterfall.cc index ff47ea20032..94c44051d6d 100644 --- a/gr-qtgui/lib/plot_waterfall.cc +++ b/gr-qtgui/lib/plot_waterfall.cc @@ -240,7 +240,11 @@ QImage PlotWaterfall::renderImage(const QwtScaleMap& xMap, } } } else if (d_data->colorMap->format() == QwtColorMap::Indexed) { +#if QWT_VERSION >= 0x060200 + image.setColorTable(d_data->colorMap->colorTable(256)); +#else image.setColorTable(d_data->colorMap->colorTable(intensityRange)); +#endif for (int y = rect.top(); y <= rect.bottom(); y++) { const double ty = yyMap.invTransform(y); @@ -249,8 +253,13 @@ QImage PlotWaterfall::renderImage(const QwtScaleMap& xMap, for (int x = rect.left(); x <= rect.right(); x++) { const double tx = xxMap.invTransform(x); +#if QWT_VERSION >= 0x060200 + *line++ = d_data->colorMap->colorIndex( + 256, intensityRange, d_data->data->value(tx, ty)); +#else *line++ = d_data->colorMap->colorIndex(intensityRange, d_data->data->value(tx, ty)); +#endif } } } diff --git a/gr-qtgui/lib/timeRasterGlobalData.cc b/gr-qtgui/lib/timeRasterGlobalData.cc index 1b9e7a0332d..c93f2d13412 100644 --- a/gr-qtgui/lib/timeRasterGlobalData.cc +++ b/gr-qtgui/lib/timeRasterGlobalData.cc @@ -132,6 +132,13 @@ void TimeRasterData::setRange(const QwtDoubleInterval& newRange) { d_intensityRange = newRange; } +#elif QWT_VERSION >= 0x060200 +void TimeRasterData::setInterval(Qt::Axis axis, const QwtInterval& interval) +{ + d_intervals[axis] = interval; +} + +QwtInterval TimeRasterData::interval(Qt::Axis a) const { return d_intervals[a]; } #endif diff --git a/gr-qtgui/lib/waterfallGlobalData.cc b/gr-qtgui/lib/waterfallGlobalData.cc index 4c703310475..e1fc9da8556 100644 --- a/gr-qtgui/lib/waterfallGlobalData.cc +++ b/gr-qtgui/lib/waterfallGlobalData.cc @@ -139,7 +139,13 @@ void WaterfallData::setRange(const QwtDoubleInterval& newRange) { _intensityRange = newRange; } +#elif QWT_VERSION >= 0x060200 +void WaterfallData::setInterval(Qt::Axis axis, const QwtInterval& interval) +{ + d_intervals[axis] = interval; +} +QwtInterval WaterfallData::interval(Qt::Axis a) const { return d_intervals[a]; } #endif diff --git a/gr-qtgui/python/qtgui/__init__.py b/gr-qtgui/python/qtgui/__init__.py index 0522fed8276..6edb8253f0a 100644 --- a/gr-qtgui/python/qtgui/__init__.py +++ b/gr-qtgui/python/qtgui/__init__.py @@ -23,12 +23,12 @@ from .qtgui_python import * try: - import matplotlib.pyplot as plt - from .distanceradar import DistanceRadar - from .azelplot import AzElPlot + import matplotlib.pyplot as plt + from .distanceradar import DistanceRadar + from .azelplot import AzElPlot except ImportError: - from gnuradio import gr - gr.log.warn("Matplotlib is a required dependency to use DistanceRadar and AzElPlot." + from gnuradio import gr + gr.log.warn("Matplotlib is a required dependency to use DistanceRadar and AzElPlot." " Please install matplotlib to use these blocks (https://matplotlib.org/)") from .range import Range, RangeWidget @@ -49,4 +49,3 @@ from .auto_correlator_sink import AutoCorrelatorSink from .auto_correlator_sink import AutoCorrelator from .auto_correlator_sink import Normalize - diff --git a/gr-qtgui/python/qtgui/auto_correlator_sink.py b/gr-qtgui/python/qtgui/auto_correlator_sink.py index ed69395d1aa..d1aa7728add 100644 --- a/gr-qtgui/python/qtgui/auto_correlator_sink.py +++ b/gr-qtgui/python/qtgui/auto_correlator_sink.py @@ -19,12 +19,13 @@ from PyQt5 import QtGui from PyQt5.QtWidgets import QWidget + class Normalize(gr.hier_block2): def __init__(self, vecsize=1024): gr.hier_block2.__init__( self, "Normalize", - gr.io_signature(1, 1, gr.sizeof_float*vecsize), - gr.io_signature(1, 1, gr.sizeof_float*vecsize), + gr.io_signature(1, 1, gr.sizeof_float * vecsize), + gr.io_signature(1, 1, gr.sizeof_float * vecsize), ) ################################################## @@ -35,7 +36,8 @@ def __init__(self, vecsize=1024): ################################################## # Blocks ################################################## - self.blocks_stream_to_vector_0 = blocks.stream_to_vector(gr.sizeof_float, vecsize) + self.blocks_stream_to_vector_0 = blocks.stream_to_vector( + gr.sizeof_float, vecsize) self.blocks_repeat_0 = blocks.repeat(gr.sizeof_float, vecsize) self.blocks_max_xx_0 = blocks.max_ff(vecsize) self.blocks_divide_xx_0 = blocks.divide_ff(vecsize) @@ -44,19 +46,21 @@ def __init__(self, vecsize=1024): # Connections ################################################## self.connect((self.blocks_divide_xx_0, 0), (self, 0)) - self.connect((self.blocks_stream_to_vector_0, 0), (self.blocks_divide_xx_0, 1)) + self.connect((self.blocks_stream_to_vector_0, 0), + (self.blocks_divide_xx_0, 1)) self.connect((self, 0), (self.blocks_max_xx_0, 0)) - self.connect((self.blocks_repeat_0, 0), (self.blocks_stream_to_vector_0, 0)) + self.connect((self.blocks_repeat_0, 0), + (self.blocks_stream_to_vector_0, 0)) self.connect((self.blocks_max_xx_0, 0), (self.blocks_repeat_0, 0)) self.connect((self, 0), (self.blocks_divide_xx_0, 0)) - def get_vecsize(self): return self.vecsize def set_vecsize(self, vecsize): self.vecsize = vecsize + class AutoCorrelator(gr.hier_block2): """ This block uses the Wiener Khinchin theorem that the FFT of a signal's @@ -64,19 +68,24 @@ class AutoCorrelator(gr.hier_block2): FAC Size controls the FFT size and therefore the length of time (samp_rate/fac_size) the auto-correlation runs over. """ + def __init__(self, sample_rate, fac_size, fac_decimation, use_db): - gr.hier_block2.__init__(self,"AutoCorrelator", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input sig - gr.io_signature(1, 1, gr.sizeof_float*fac_size)) # Output sig + gr.hier_block2.__init__(self, "AutoCorrelator", + gr.io_signature( + 1, 1, gr.sizeof_gr_complex), # Input sig + gr.io_signature(1, 1, gr.sizeof_float * fac_size)) # Output sig self.fac_size = fac_size self.fac_decimation = fac_decimation self.sample_rate = sample_rate - streamToVec = blocks.stream_to_vector(gr.sizeof_gr_complex, self.fac_size) + streamToVec = blocks.stream_to_vector( + gr.sizeof_gr_complex, self.fac_size) # Make sure N is at least 1 - decimation = int(self.sample_rate/self.fac_size/self.fac_decimation) - self.one_in_n = blocks.keep_one_in_n(gr.sizeof_gr_complex * self.fac_size, max(1, decimation)) + decimation = int(self.sample_rate / + self.fac_size / self.fac_decimation) + self.one_in_n = blocks.keep_one_in_n( + gr.sizeof_gr_complex * self.fac_size, max(1, decimation)) # FFT Note: No windowing. fac = fft.fft_vcc(self.fac_size, True, ()) @@ -84,7 +93,7 @@ def __init__(self, sample_rate, fac_size, fac_decimation, use_db): complex2Mag = blocks.complex_to_mag(self.fac_size) self.avg = filter.single_pole_iir_filter_ff(1.0, self.fac_size) - fac_fac = fft.fft_vfc(self.fac_size, True, ()) + fac_fac = fft.fft_vfc(self.fac_size, True, ()) fac_c2mag = blocks.complex_to_mag(fac_size) # There's a note in Baz's block about needing to add 3 dB to each bin but the DC bin, however it was never implemented @@ -93,28 +102,35 @@ def __init__(self, sample_rate, fac_size, fac_decimation, use_db): log = blocks.nlog10_ff(n, self.fac_size, k) if use_db: - self.connect(self, streamToVec, self.one_in_n, fac, complex2Mag, fac_fac, fac_c2mag, self.avg, log, self) + self.connect(self, streamToVec, self.one_in_n, fac, + complex2Mag, fac_fac, fac_c2mag, self.avg, log, self) else: - self.connect(self, streamToVec, self.one_in_n, fac, complex2Mag, fac_fac, fac_c2mag, self.avg, self) + self.connect(self, streamToVec, self.one_in_n, fac, + complex2Mag, fac_fac, fac_c2mag, self.avg, self) + class AutoCorrelatorSink(gr.hier_block2): """ docstring for block AutoCorrelatorSink """ + def __init__(self, sample_rate, fac_size, fac_decimation, title, autoScale, grid, yMin, yMax, use_db): gr.hier_block2.__init__(self, - "AutoCorrelatorSink", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature - gr.io_signature(0, 0, 0)) # Output signature + "AutoCorrelatorSink", + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(0, 0, 0)) # Output signature self.fac_size = fac_size self.fac_decimation = fac_decimation self.sample_rate = sample_rate - autoCorr = AutoCorrelator(sample_rate, fac_size, fac_decimation, use_db) + autoCorr = AutoCorrelator( + sample_rate, fac_size, fac_decimation, use_db) vecToStream = blocks.vector_to_stream(gr.sizeof_float, self.fac_size) - self.timeSink = qtgui.time_sink_f(self.fac_size//2, sample_rate, title, 1, None) + self.timeSink = qtgui.time_sink_f( + self.fac_size // 2, sample_rate, title, 1, None) self.timeSink.enable_grid(grid) self.timeSink.set_y_axis(yMin, yMax) self.timeSink.enable_autoscale(autoScale) @@ -127,6 +143,5 @@ def __init__(self, sample_rate, fac_size, fac_decimation, title, autoScale, grid norm = Normalize(self.fac_size) self.connect(self, autoCorr, norm, vecToStream, self.timeSink) - def getWidget(self): return sip.wrapinstance(self.timeSink.qwidget(), QWidget) diff --git a/gr-qtgui/python/qtgui/azelplot.py b/gr-qtgui/python/qtgui/azelplot.py index d23d39234db..e091f7cc079 100644 --- a/gr-qtgui/python/qtgui/azelplot.py +++ b/gr-qtgui/python/qtgui/azelplot.py @@ -18,6 +18,7 @@ from gnuradio import gr import pmt + class AzElPlot(gr.sync_block, FigureCanvas): """ This block creates a polar plot with azimuth represented as the angle @@ -27,10 +28,11 @@ class AzElPlot(gr.sync_block, FigureCanvas): elevation < 0 is provided, the marker will turn to an open circle on the perimeter at the specified azimuth angle. """ + def __init__(self, lbl, backgroundColor, dotColor, Parent=None, width=4, height=4, dpi=90): - gr.sync_block.__init__(self, name = "MsgPushButton", in_sig = None, - out_sig = None) + gr.sync_block.__init__(self, name="MsgPushButton", in_sig=None, + out_sig=None) self.lbl = lbl @@ -46,15 +48,16 @@ def __init__(self, lbl, backgroundColor, dotColor, Parent=None, self.fig = Figure(figsize=(width, height), dpi=dpi) self.fig.patch.set_facecolor(self.backgroundColor) - self.axes = self.fig.add_subplot(111, polar=True, facecolor=self.backgroundColor) + self.axes = self.fig.add_subplot( + 111, polar=True, facecolor=self.backgroundColor) # Create an "invisible" line at 90 to set the max for the plot - self.axes.plot(np.linspace(0, 2*np.pi, 90), np.ones(90)*90, color=self.scaleColor, + self.axes.plot(np.linspace(0, 2 * np.pi, 90), np.ones(90) * 90, color=self.scaleColor, linestyle='') # Plot line: Initialize out to 90 and blank radius = 90 - self.blackline = self.axes.plot(np.linspace(0, 2*np.pi, 90), np.ones(90)*radius, + self.blackline = self.axes.plot(np.linspace(0, 2 * np.pi, 90), np.ones(90) * radius, color=self.scaleColor, linestyle='-') self.reddot = None @@ -71,7 +74,8 @@ def __init__(self, lbl, backgroundColor, dotColor, Parent=None, FigureCanvas.__init__(self, self.fig) self.setParent(Parent) - self.title = self.fig.suptitle(self.lbl, fontsize=8, fontweight='bold', color='black') + self.title = self.fig.suptitle( + self.lbl, fontsize=8, fontweight='bold', color='black') FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, @@ -88,17 +92,20 @@ def msgHandler(self, msg): if new_val is not None: if type(new_val) == dict: if 'az' in new_val and 'el' in new_val: - self.updateData(float(new_val['az']), float(new_val['el'])) + self.updateData( + float(new_val['az']), float(new_val['el'])) else: - gr.log.error("az and el keys were not found in the dictionary.") + gr.log.error( + "az and el keys were not found in the dictionary.") else: gr.log.error("Value received was not a dictionary. Expecting a dictionary " "in the car message component with az and el keys.") else: gr.log.error("The CAR section of the inbound message was None. " - "This part should contain the dictionary with 'az' and 'el' float keys.") + "This part should contain the dictionary with 'az' and 'el' float keys.") except Exception as e: - gr.log.error("[AzElPlot] Error with message conversion: %s" % str(e)) + gr.log.error( + "[AzElPlot] Error with message conversion: %s" % str(e)) if new_val is not None: gr.log.error(str(new_val)) @@ -116,13 +123,12 @@ def updateData(self, azimuth, elevation): convertedElevation = 90.0 - elevation # Note: +azimuth for the plot is measured counter-clockwise, so need to reverse it. - self.reddot = self.axes.plot(-azimuth * math.pi/180.0, convertedElevation, self.dotColor, + self.reddot = self.axes.plot(-azimuth * math.pi / 180.0, convertedElevation, self.dotColor, markersize=8) else: # It's below the horizon. Show an open circle at the perimeter elevation = 0.0 - self.reddot = self.axes.plot(-azimuth * math.pi/180.0, 89.0, self.dotColor, + self.reddot = self.axes.plot(-azimuth * math.pi / 180.0, 89.0, self.dotColor, markerfacecolor="None", markersize=16, fillstyle=None) self.draw() - diff --git a/gr-qtgui/python/qtgui/compass.py b/gr-qtgui/python/qtgui/compass.py index 2c8a766f149..f1cdabf7d90 100644 --- a/gr-qtgui/python/qtgui/compass.py +++ b/gr-qtgui/python/qtgui/compass.py @@ -27,13 +27,14 @@ NeedleIndicator = 0 NeedleMirrored = 2 + class LabeledCompass(QFrame): def __init__(self, lbl, min_size, update_time, setDebug=False, needleType=NeedleFull, position=1, backgroundColor='default'): # Positions: 1 = above, 2=below, 3=left, 4=right QFrame.__init__(self) self.numberControl = Compass(min_size, update_time, setDebug, - needleType, position, backgroundColor) + needleType, position, backgroundColor) if position < 3: layout = QVBoxLayout() @@ -62,17 +63,20 @@ def __init__(self, lbl, min_size, update_time, setDebug=False, self.setLayout(layout) if lbl: - self.setMinimumSize(min_size+30, min_size+35) + self.setMinimumSize(min_size + 30, min_size + 35) else: self.setMinimumSize(min_size, min_size) self.show() + def change_angle(self, angle): self.numberControl.change_angle(angle) def setColors(self, backgroundColor='default', needleTip='red', needleBody='black', scaleColor='black'): - self.numberControl.setColors(backgroundColor, needleTip, needleBody, scaleColor) + self.numberControl.setColors( + backgroundColor, needleTip, needleBody, scaleColor) + class Compass(QWidget): angleChanged = pyqtSignal(float) @@ -116,16 +120,18 @@ def paintEvent(self, event): painter.setRenderHint(QPainter.Antialiasing) if self.backgroundColor == 'default': - painter.fillRect(event.rect(), self.palette().brush(QPalette.Window)) + painter.fillRect( + event.rect(), self.palette().brush(QPalette.Window)) else: size = self.size() - center_x = size.width()/2 + center_x = size.width() / 2 diameter = size.height() brush = QBrush(QColor(self.backgroundColor), Qtc.SolidPattern) painter.setBrush(brush) painter.setPen(QPen(QColor(self.scaleColor), 2)) painter.setRenderHint(QPainter.Antialiasing) - painter.drawEllipse(center_x-diameter/2+1, 1, diameter-4, diameter-4) + painter.drawEllipse(center_x - diameter / 2 + 1, + 1, diameter - 4, diameter - 4) self.drawMarkings(painter) self.drawNeedle(painter) @@ -134,9 +140,9 @@ def paintEvent(self, event): def drawMarkings(self, painter): painter.save() - painter.translate(self.width()/2, self.height()/2) - scale = min((self.width() - self._margins)/120.0, - (self.height() - self._margins)/120.0) + painter.translate(self.width() / 2, self.height() / 2) + scale = min((self.width() - self._margins) / 120.0, + (self.height() - self._margins) / 120.0) painter.scale(scale, scale) font = QFont(self.font()) @@ -151,7 +157,8 @@ def drawMarkings(self, painter): if i % 45 == 0: painter.drawLine(0, -40, 0, -50) - painter.drawText(-metrics.width(self._pointText[i])/2.0, -52, self._pointText[i]) + painter.drawText(-metrics.width( + self._pointText[i]) / 2.0, -52, self._pointText[i]) else: painter.drawLine(0, -45, 0, -50) @@ -163,9 +170,9 @@ def drawMarkings(self, painter): def drawNeedle(self, painter): painter.save() # Set up painter - painter.translate(self.width()/2, self.height()/2) - scale = min((self.width() - self._margins)/120.0, - (self.height() - self._margins)/120.0) + painter.translate(self.width() / 2, self.height() / 2) + scale = min((self.width() - self._margins) / 120.0, + (self.height() - self._margins) / 120.0) painter.scale(scale, scale) painter.setPen(QPen(Qtc.NoPen)) @@ -211,7 +218,7 @@ def drawNeedle(self, painter): painter.drawPolygon( QPolygon([QPoint(-3, -25), QPoint(0, -45), QPoint(3, -25), QPoint(0, -30), QPoint(-3, -25)]) - ) + ) painter.restore() @@ -240,12 +247,15 @@ class GrCompass(gr.sync_block, LabeledCompass): and mirrored (mirrored is useful for direction-finding where an ambiguity exists in front/back detection angle). """ + def __init__(self, title, min_size, update_time, setDebug=False, needleType=NeedleFull, usemsg=False, position=1, backgroundColor='default'): if usemsg: - gr.sync_block.__init__(self, name="QTCompass", in_sig=[], out_sig=[]) + gr.sync_block.__init__( + self, name="QTCompass", in_sig=[], out_sig=[]) else: - gr.sync_block.__init__(self, name="QTCompass", in_sig=[numpy.float32], out_sig=[]) + gr.sync_block.__init__(self, name="QTCompass", in_sig=[ + numpy.float32], out_sig=[]) LabeledCompass.__init__(self, title, min_size, update_time, setDebug, needleType, position, backgroundColor) @@ -266,7 +276,8 @@ def msgHandler(self, msg): if type(new_val) == float or type(new_val) == int: super().change_angle(float(new_val)) else: - gr.log.error("Value received was not an int or a float: %s" % str(type(new_val))) + gr.log.error( + "Value received was not an int or a float: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) diff --git a/gr-qtgui/python/qtgui/dialcontrol.py b/gr-qtgui/python/qtgui/dialcontrol.py index 2e19e182192..1c7077176c3 100644 --- a/gr-qtgui/python/qtgui/dialcontrol.py +++ b/gr-qtgui/python/qtgui/dialcontrol.py @@ -16,6 +16,7 @@ from gnuradio import gr import pmt + class LabeledDialControl(QFrame): def __init__(self, lbl='', parent=None, minimum=0, maximum=100, defaultvalue=0, backgroundColor='default', changedCallback=None, @@ -36,7 +37,7 @@ def __init__(self, lbl='', parent=None, minimum=0, maximum=100, defaultvalue=0, self.lblcontrol.setAlignment(Qtc.AlignCenter) if self.showvalue: - textstr = self.buildTextStr(defaultvalue*self.scaleFactor) + textstr = self.buildTextStr(defaultvalue * self.scaleFactor) self.lblcontrol.setText(textstr) if len or self.showvalue: @@ -73,6 +74,7 @@ def valChanged(self, new_value): textstr = self.buildTextStr(new_value) self.lblcontrol.setText(textstr) + class DialControl(Qt.QDial): def __init__(self, minimum=0, maximum=100, defaultvalue=0, backgroundColor='default', lablelCallback=None, changedCallback=None, minsize=100): @@ -99,6 +101,7 @@ def sliderMoved(self): if self.lablelCallback is not None: self.lablelCallback(self.value()) + class GrDialControl(gr.sync_block, LabeledDialControl): """ This block creates a dial control. The control does control a @@ -112,10 +115,12 @@ class GrDialControl(gr.sync_block, LabeledDialControl): the desired range. Think of the min/max as the increments, and the scale factor as the adjustment to get the values you want. """ + def __init__(self, lbl, parent, minimum, maximum, defaultvalue, backgroundColor='default', varCallback=None, isFloat=False, scaleFactor=1, minsize=100, showvalue=False, outputmsgname='value'): - gr.sync_block.__init__(self, name="GrDialControl", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="GrDialControl", + in_sig=None, out_sig=None) LabeledDialControl.__init__(self, lbl, parent, minimum, maximum, defaultvalue, backgroundColor, self.valueChanged, minsize, isFloat, scaleFactor, showvalue) @@ -139,4 +144,3 @@ def valueChanged(self, new_value): else: self.message_port_pub(pmt.intern("value"), pmt.cons(pmt.intern(self.outputmsgname), pmt.from_long(new_value))) - diff --git a/gr-qtgui/python/qtgui/dialgauge.py b/gr-qtgui/python/qtgui/dialgauge.py index af96f2e096c..6dbb1bf84b9 100644 --- a/gr-qtgui/python/qtgui/dialgauge.py +++ b/gr-qtgui/python/qtgui/dialgauge.py @@ -18,6 +18,7 @@ from gnuradio import gr import pmt + class LabeledDialGauge(QFrame): # Positions: 1 = above, 2=below, 3=left, 4=right def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor='black', @@ -45,7 +46,8 @@ def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor=' self.lblcontrol.setText(lbl) if fontColor != 'default': - self.lblcontrol.setStyleSheet("QLabel { color : " + fontColor + "; }") + self.lblcontrol.setStyleSheet( + "QLabel { color : " + fontColor + "; }") # add top or left if len: @@ -69,6 +71,7 @@ def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor=' def setValue(self, new_value): self.numberControl.setValue(new_value) + class DialGauge(QFrame): def __init__(self, barColor='blue', backgroundColor='white', fontColor='black', minValue=0, maxValue=100, maxSize=80, @@ -97,7 +100,7 @@ def __init__(self, barColor='blue', backgroundColor='white', fontColor='black', self.startAngle = 0.0 self.endAngle = 360.0 - self.degScaler = 16.0 # The span angle must be specified in 1/16 of a degree units + self.degScaler = 16.0 # The span angle must be specified in 1/16 of a degree units self.penWidth = max(int(0.1 * maxSize), 6) self.halfPenWidth = int(self.penWidth / 2) @@ -122,15 +125,17 @@ def paintEvent(self, event): size = self.size() - percentRange = float(self.value - self.minValue) / float(self.maxValue - self.minValue) - endAngle = self.startAngle + round(percentRange * float(self.endAngle - self.startAngle), 0) + percentRange = float(self.value - self.minValue) / \ + float(self.maxValue - self.minValue) + endAngle = self.startAngle + \ + round(percentRange * float(self.endAngle - self.startAngle), 0) # Now convert angles to 1/16 scale startAngle = int(round(self.startAngle * self.degScaler, 0)) endAngle = int(round(endAngle * self.degScaler, 0)) - rect = QtCore.QRect(self.halfPenWidth, self.halfPenWidth, size.width()-self.penWidth, - size.height()-self.penWidth) + rect = QtCore.QRect(self.halfPenWidth, self.halfPenWidth, size.width() - self.penWidth, + size.height() - self.penWidth) # Set up the painting canvass painter = QPainter() @@ -146,7 +151,7 @@ def paintEvent(self, event): else: printText = str(int(self.value)) - painter.drawText(size.width()/2-self.metrics.width(printText)/2, size.height()/2, + painter.drawText(size.width() / 2 - self.metrics.width(printText) / 2, size.height() / 2, printText) painter.save() @@ -155,27 +160,31 @@ def paintEvent(self, event): # First draw complete circle painter.setPen(QPen(QColor(self.backgroundColor), self.penWidth)) - painter.drawArc(rect, startAngle, self.endAngle*self.degScaler) + painter.drawArc(rect, startAngle, self.endAngle * self.degScaler) # First draw complete circle painter.setPen(QPen(QColor(self.barColor), self.penWidth)) painter.drawArc(rect, startAngle, -endAngle) painter.setPen(QPen(QColor('darkgray'), 2)) - painter.drawEllipse(1, 1, rect.width()+self.penWidth-2, rect.width()+self.penWidth-2) - painter.drawEllipse(1+self.penWidth, 1+self.penWidth, rect.width()-self.penWidth-2, - rect.width()-self.penWidth-2) + painter.drawEllipse(1, 1, rect.width() + self.penWidth - + 2, rect.width() + self.penWidth - 2) + painter.drawEllipse(1 + self.penWidth, 1 + self.penWidth, rect.width() - self.penWidth - 2, + rect.width() - self.penWidth - 2) painter.restore() painter.end() + class GrDialGauge(gr.sync_block, LabeledDialGauge): """ This block creates a dial-style gauge. The value can be set either with a variable or an input message. """ + def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor='black', minValue=0, maxValue=100, maxSize=80, position=1, isFloat=False, showValue=False, fixedOrMin=True, parent=None): - gr.sync_block.__init__(self, name="DialGauge", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="DialGauge", + in_sig=None, out_sig=None) LabeledDialGauge.__init__(self, lbl, barColor, backgroundColor, fontColor, minValue, maxValue, maxSize, position, isFloat, showValue, fixedOrMin, parent) @@ -188,7 +197,6 @@ def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor=' self.message_port_register_in(pmt.intern("value")) self.set_msg_handler(pmt.intern("value"), self.msgHandler) - def msgHandler(self, msg): try: new_val = pmt.to_python(pmt.cdr(msg)) @@ -197,12 +205,10 @@ def msgHandler(self, msg): super().setValue(new_val) else: gr.log.error("Value received was not an int or a float. " - "Received %s" % str(type(new_val))) + "Received %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) - def setValue(self, new_value): super().setValue(new_value) - diff --git a/gr-qtgui/python/qtgui/digitalnumbercontrol.py b/gr-qtgui/python/qtgui/digitalnumbercontrol.py index 44ddfbd8cae..cbaf322b7de 100644 --- a/gr-qtgui/python/qtgui/digitalnumbercontrol.py +++ b/gr-qtgui/python/qtgui/digitalnumbercontrol.py @@ -23,13 +23,14 @@ # # + class LabeledDigitalNumberControl(QFrame): def __init__(self, lbl='', min_freq_hz=0, max_freq_hz=6000000000, parent=None, thousands_separator=',', background_color='black', fontColor='white', click_callback=None): QFrame.__init__(self, parent) self.numberControl = DigitalNumberControl(min_freq_hz, max_freq_hz, self, - thousands_separator, background_color, fontColor, click_callback) + thousands_separator, background_color, fontColor, click_callback) layout = QVBoxLayout() @@ -47,9 +48,9 @@ def __init__(self, lbl='', min_freq_hz=0, max_freq_hz=6000000000, parent=None, def minimumSizeHint(self): if self.hasLabel: - return QSize(self.numberControl.minimumWidth()+10, 100) + return QSize(self.numberControl.minimumWidth() + 10, 100) else: - return QSize(self.numberControl.minimumWidth()+10, 50) + return QSize(self.numberControl.minimumWidth() + 10, 50) def setReadOnly(self, b_read_only): self.numberControl.setReadOnly(b_read_only) @@ -60,6 +61,7 @@ def setFrequency(self, new_freq): def getFrequency(self): return self.numberControl.getFrequency() + class DigitalNumberControl(QFrame): # Notifies to avoid thread conflicts on paints updateInt = pyqtSignal(int) @@ -96,7 +98,7 @@ def __init__(self, min_freq_hz=0, max_freq_hz=6000000000, parent=None, thousands fm = QFontMetrics(self.numberFont) if len(self.thousands_separator) > 0: # The -1 makes sure we don't count an extra for 123,456,789. Answer should be 2 not 3. - numgroups = int(float(self.numDigitsInFreq-1) / 3.0) + numgroups = int(float(self.numDigitsInFreq - 1) / 3.0) if numgroups > 0: for i in range(0, numgroups): teststr += self.thousands_separator @@ -129,7 +131,8 @@ def mousePressEvent(self, event): if self.read_only: if self.debug_click: - gr.log.info("click received but read-only. Not changing frequency.") + gr.log.info( + "click received but read-only. Not changing frequency.") return fm = QFontMetrics(self.numberFont) @@ -154,12 +157,12 @@ def mousePressEvent(self, event): found_number = False clicked_thousands = False - for i in range(1, len(textstr)+1): + for i in range(1, len(textstr) + 1): width = fm.width(textstr[-i:]) charstr = textstr[-i:] widthchar = fm.width(charstr[0]) - if clickpos >= (width-widthchar) and clickpos <= width: - clicked_char = i-1 + if clickpos >= (width - widthchar) and clickpos <= width: + clicked_char = i - 1 clicked_num_index = clicked_char @@ -170,7 +173,8 @@ def mousePressEvent(self, event): numSeps = charstr.count(self.thousands_separator) clicked_num_index -= numSeps if self.debug_click: - gr.log.info("clicked number: " + str(clicked_num_index)) + gr.log.info("clicked number: " + + str(clicked_num_index)) else: clicked_thousands = True if self.debug_click: @@ -181,7 +185,7 @@ def mousePressEvent(self, event): # Remember y=0 is at the top so this is reversed clicked_up = False - if self.offset.y() > self.size().height()/2: + if self.offset.y() > self.size().height() / 2: if self.debug_click: gr.log.info('clicked down') else: @@ -200,7 +204,7 @@ def mousePressEvent(self, event): # Cannot call setFrequency to emit. Change must happen now for # paint event when clicked. self.setFrequencyNow(cur_freq) - + if self.click_callback is not None: self.click_callback(self.getFrequency()) break @@ -208,7 +212,7 @@ def mousePressEvent(self, event): if (not found_number) and (not clicked_thousands): # See if we clicked in the high area, if so, increment there. clicked_up = False - if self.offset.y() > self.size().height()/2: + if self.offset.y() > self.size().height() / 2: if self.debug_click: gr.log.info('clicked down in the high area') else: @@ -228,16 +232,17 @@ def mousePressEvent(self, event): # Cannot call setFrequency to emit. Change must happen now for # paint event when clicked. self.setFrequencyNow(cur_freq) - + if self.click_callback is not None: if self.debug_click: gr.log.info('Calling self.click_callback') - + self.click_callback(self.getFrequency()) else: if self.debug_click: - gr.log.info('self.click_callback is None. Not calling callback.') - + gr.log.info( + 'self.click_callback is None. Not calling callback.') + def setColors(self, background, fontColor): self.background_color = background self.fontColor = fontColor @@ -265,7 +270,7 @@ def setFrequencyNow(self, new_freq): if (new_freq >= self.min_freq) and (new_freq <= self.max_freq): self.cur_freq = int(new_freq) self.update() - + def setFrequency(self, new_freq): if type(new_freq) == int: self.updateInt.emit(new_freq) @@ -290,7 +295,7 @@ def paintEvent(self, event): brush = QBrush() brush.setColor(self.background_color) brush.setStyle(Qt.SolidPattern) - rect = QtCore.QRect(2, 2, size.width()-4, size.height()-4) + rect = QtCore.QRect(2, 2, size.width() - 4, size.height() - 4) painter.fillRect(rect, brush) self.numberFont.setPixelSize(0.9 * size.height()) @@ -307,13 +312,15 @@ def paintEvent(self, event): else: textstr = str(self.getFrequency()) - rect = QtCore.QRect(0, 0, size.width()-4, size.height()) - + rect = QtCore.QRect(0, 0, size.width() - 4, size.height()) + painter.drawText(rect, Qt.AlignRight + Qt.AlignVCenter, textstr) # ################################################################################ # GNU Radio Class + + class MsgDigitalNumberControl(gr.sync_block, LabeledDigitalNumberControl): def __init__(self, lbl='', min_freq_hz=0, max_freq_hz=6000000000, parent=None, thousands_separator=',', background_color='black', fontColor='white', @@ -321,7 +328,7 @@ def __init__(self, lbl='', min_freq_hz=0, max_freq_hz=6000000000, parent=None, gr.sync_block.__init__(self, name="MsgDigitalNumberControl", in_sig=None, out_sig=None) LabeledDigitalNumberControl.__init__(self, lbl, min_freq_hz, max_freq_hz, parent, - thousands_separator, background_color, fontColor, self.click_callback) + thousands_separator, background_color, fontColor, self.click_callback) self.var_callback = var_callback self.outputmsgname = outputmsgname @@ -339,7 +346,8 @@ def msgHandler(self, msg): self.setValue(new_val) else: - gr.log.error("Value received was not an int or a float. %s" % str(type(new_val))) + gr.log.error( + "Value received was not an int or a float. %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) @@ -354,16 +362,17 @@ def call_var_callback(self, new_value): def click_callback(self, new_value): self.call_var_callback(new_value) - self.message_port_pub(pmt.intern("valueout"), pmt.cons(pmt.intern(self.outputmsgname), pmt.from_double(float(new_value)))) + self.message_port_pub(pmt.intern("valueout"), pmt.cons( + pmt.intern(self.outputmsgname), pmt.from_double(float(new_value)))) def setValue(self, new_val): self.setFrequency(new_val) - self.message_port_pub(pmt.intern("valueout"), pmt.cons(pmt.intern(self.outputmsgname), pmt.from_double(float(self.getFrequency())))) + self.message_port_pub(pmt.intern("valueout"), pmt.cons(pmt.intern( + self.outputmsgname), pmt.from_double(float(self.getFrequency())))) def getValue(self): self.getFrequency() def setReadOnly(self, b_read_only): super().setReadOnly(b_read_only) - diff --git a/gr-qtgui/python/qtgui/distanceradar.py b/gr-qtgui/python/qtgui/distanceradar.py index 5659045c27b..6619ef2174f 100644 --- a/gr-qtgui/python/qtgui/distanceradar.py +++ b/gr-qtgui/python/qtgui/distanceradar.py @@ -15,10 +15,11 @@ import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure - + from gnuradio import gr import pmt + class DistanceRadar(gr.sync_block, FigureCanvas): """ This block creates a radar-like screen used to represent distance or size. @@ -28,9 +29,11 @@ class DistanceRadar(gr.sync_block, FigureCanvas): Note: Incoming values should range between 0 (center bullseye) and 100 (all the way out) """ + def __init__(self, lbl, ticklabels, backgroundColor, fontColor, ringColor, Parent=None, width=4, height=4, dpi=100): - gr.sync_block.__init__(self, name="distanceradar", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="distanceradar", + in_sig=None, out_sig=None) self.lbl = lbl @@ -43,15 +46,16 @@ def __init__(self, lbl, ticklabels, backgroundColor, fontColor, ringColor, Paren self.fig = Figure(figsize=(width, height), dpi=dpi) self.fig.patch.set_facecolor(self.backgroundColor) - self.axes = self.fig.add_subplot(111, polar=True, facecolor=self.backgroundColor) + self.axes = self.fig.add_subplot( + 111, polar=True, facecolor=self.backgroundColor) # Create an "invisible" line at 100 to set the max for the plot - self.axes.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*100, color=self.fontColor, + self.axes.plot(np.linspace(0, 2 * np.pi, 100), np.ones(100) * 100, color=self.fontColor, linestyle='') # Plot line: Initialize out to 100 and blank radius = 100 - self.blackline = self.axes.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*radius, + self.blackline = self.axes.plot(np.linspace(0, 2 * np.pi, 100), np.ones(100) * radius, color=self.fontColor, linestyle='-') self.redline = None @@ -70,9 +74,8 @@ def __init__(self, lbl, ticklabels, backgroundColor, fontColor, ringColor, Paren FigureCanvas.__init__(self, self.fig) self.setParent(Parent) - self.title = self.fig.suptitle(self.lbl, fontsize=8, fontweight='bold', - color=self.fontColor) + color=self.fontColor) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, @@ -87,7 +90,7 @@ def msgHandler(self, msg): self.updateData(new_val) else: gr.log.error("Value received was not an int or a " - "float: %s" % str(type(new_val))) + "float: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) @@ -95,7 +98,7 @@ def msgHandler(self, msg): def updateData(self, radius): if self.redline is not None: self.redline.pop(0).remove() - self.redline = self.axes.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*radius, + self.redline = self.axes.plot(np.linspace(0, 2 * np.pi, 100), np.ones(100) * radius, color='r', linestyle='-') if self.filledcircle: @@ -111,4 +114,3 @@ def updateData(self, radius): self.bullseye = self.axes.add_artist(circle) self.draw() - diff --git a/gr-qtgui/python/qtgui/graphicitem.py b/gr-qtgui/python/qtgui/graphicitem.py index ecc7cc20fc4..871aa094972 100644 --- a/gr-qtgui/python/qtgui/graphicitem.py +++ b/gr-qtgui/python/qtgui/graphicitem.py @@ -20,6 +20,7 @@ from gnuradio import gr import pmt + class GrGraphicItem(gr.sync_block, QLabel): """ This block displays the selected graphic item. You can pass a @@ -32,8 +33,10 @@ class GrGraphicItem(gr.sync_block, QLabel): Otherwise items are indexed by filename and can be animated throughout the background image. """ + def __init__(self, image_file, scaleImage=True, fixedSize=False, setWidth=0, setHeight=0): - gr.sync_block.__init__(self, name="GrGraphicsItem", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="GrGraphicsItem", + in_sig=None, out_sig=None) QLabel.__init__(self) if not os.path.isfile(image_file): @@ -67,9 +70,9 @@ def overlayHandler(self, msg): overlayitem = pmt.to_python(pmt.car(msg)) if overlayitem is None: gr.log.error('Overlay message contains None in the car portion ' - 'of the message. Please pass in a dictionary or list of dictionaries in this ' - 'portion of the message. Each dictionary should have the following keys: ' - 'filename,x,y. Use x=y=-1 to remove an overlay item.') + 'of the message. Please pass in a dictionary or list of dictionaries in this ' + 'portion of the message. Each dictionary should have the following keys: ' + 'filename,x,y. Use x=y=-1 to remove an overlay item.') return if type(overlayitem) is dict: @@ -79,41 +82,43 @@ def overlayHandler(self, msg): itemlist = overlayitem else: gr.log.error("Overlay message type is not correct. Please pass in " - "a dictionary or list of dictionaries in this portion of the message. Each " - "dictionary should have the following keys: filename,x,y. Use x=y=-1 to " - "remove an overlay item.") + "a dictionary or list of dictionaries in this portion of the message. Each " + "dictionary should have the following keys: filename,x,y. Use x=y=-1 to " + "remove an overlay item.") return # Check each dict item to make sure it's valid. for curitem in itemlist: if type(curitem) == dict: if 'filename' not in curitem: - gr.log.error("Dictionary item did not contain the 'filename' key.") + gr.log.error( + "Dictionary item did not contain the 'filename' key.") gr.log.error("Received " + str(curitem)) continue if 'x' not in curitem: gr.log.error("The dictionary for filename " + - curitem['filename'] + " did not contain an 'x' key.") + curitem['filename'] + " did not contain an 'x' key.") gr.log.error("Received " + str(curitem)) continue if 'y' not in curitem: gr.log.error("The dictionary for filename " + - curitem['filename'] + " did not contain an 'y' key.") + curitem['filename'] + " did not contain an 'y' key.") gr.log.error("Received " + str(curitem)) continue if not os.path.isfile(curitem['filename']): gr.log.error("Unable to find overlay file " + - curitem['filename']) + curitem['filename']) gr.log.error("Received " + str(curitem)) continue # Now either add/update our list or remove the item. if curitem['x'] == -1 and curitem['y'] == -1: try: - del self.overlays[curitem['filename']] # remove item + # remove item + del self.overlays[curitem['filename']] except: pass else: @@ -142,9 +147,10 @@ def updateGraphic(self): scale = curOverlay['scalefactor'] w = newOverlay.width() h = newOverlay.height() - newOverlay = newOverlay.scaled(int(w*scale), int(h*scale), + newOverlay = newOverlay.scaled(int(w * scale), int(h * scale), Qtc.KeepAspectRatio) - painter.drawPixmap(curOverlay['x'], curOverlay['y'], newOverlay) + painter.drawPixmap( + curOverlay['x'], curOverlay['y'], newOverlay) except Exception as e: gr.log.error("Error adding overlay: %s" % str(e)) return @@ -172,13 +178,13 @@ def msgHandler(self, msg): self.updateGraphic() else: gr.log.error("Value received was not an int or " - "a bool: %s" % str(type(new_val))) + "a bool: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) def minimumSizeHint(self): - return QSize(self.pixmap.width(),self.pixmap.height()) + return QSize(self.pixmap.width(), self.pixmap.height()) def resizeEvent(self, event): if self.scaleImage: @@ -191,4 +197,3 @@ def resizeEvent(self, event): Qtc.KeepAspectRatio) self.updateGraphic() - diff --git a/gr-qtgui/python/qtgui/graphicoverlay.py b/gr-qtgui/python/qtgui/graphicoverlay.py index defef31d174..dad40dfe13c 100644 --- a/gr-qtgui/python/qtgui/graphicoverlay.py +++ b/gr-qtgui/python/qtgui/graphicoverlay.py @@ -18,39 +18,42 @@ # This thread just gets us out of the sync_block's init function so the messaging # system and scheduler are active. + + class offloadThread(threading.Thread): - def __init__(self, callback, overlayList, listDelay, repeat): - threading.Thread.__init__(self) - self.callback = callback - self.overlayList = overlayList - self.listDelay = listDelay - self.threadRunning = False - self.stopThread = False - self.repeat = repeat + def __init__(self, callback, overlayList, listDelay, repeat): + threading.Thread.__init__(self) + self.callback = callback + self.overlayList = overlayList + self.listDelay = listDelay + self.threadRunning = False + self.stopThread = False + self.repeat = repeat - def run(self): - self.stopThread = False - self.threadRunning = True + def run(self): + self.stopThread = False + self.threadRunning = True - # Wait for main __init__ to finish - time.sleep(0.5) + # Wait for main __init__ to finish + time.sleep(0.5) - if (type(self.overlayList) == list and self.listDelay > 0.0): - while self.repeat and not self.stopThread: - for curItem in self.overlayList: - self.callback(curItem) + if (type(self.overlayList) == list and self.listDelay > 0.0): + while self.repeat and not self.stopThread: + for curItem in self.overlayList: + self.callback(curItem) - if self.stopThread: - break + if self.stopThread: + break - time.sleep(self.listDelay) + time.sleep(self.listDelay) - if self.stopThread: - break - else: - self.callback(self.overlayList) + if self.stopThread: + break + else: + self.callback(self.overlayList) + + self.threadRunning = False - self.threadRunning = False class GrGraphicOverlay(gr.sync_block): """ @@ -69,6 +72,7 @@ class GrGraphicOverlay(gr.sync_block): you can use a list with the same file but different coordinates and use the update delay > 0.0 to animate it. """ + def __init__(self, overlayList, listDelay, repeat): gr.sync_block.__init__(self, name="GrGraphicsOverlay", in_sig=None, out_sig=None) @@ -77,8 +81,8 @@ def __init__(self, overlayList, listDelay, repeat): self.listDelay = listDelay if type(self.overlayList) is not dict and type(self.overlayList) is not list: gr.log.error("The specified input is not valid. " - "Please specify either a dictionary item with the following keys: " - "'filename','x','y'[,'scalefactor'] or a list of dictionary items.") + "Please specify either a dictionary item with the following keys: " + "'filename','x','y'[,'scalefactor'] or a list of dictionary items.") sys.exit(1) self.message_port_register_out(pmt.intern("overlay")) @@ -100,4 +104,3 @@ def stop(self): time.sleep(0.1) return True - diff --git a/gr-qtgui/python/qtgui/ledindicator.py b/gr-qtgui/python/qtgui/ledindicator.py index 09b2bd8e199..094197cf201 100644 --- a/gr-qtgui/python/qtgui/ledindicator.py +++ b/gr-qtgui/python/qtgui/ledindicator.py @@ -18,12 +18,14 @@ from gnuradio import gr import pmt + class LabeledLEDIndicator(QFrame): # Positions: 1 = above, 2=below, 3=left, 4=right def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=80, position=1, alignment=1, valignment=1, parent=None): QFrame.__init__(self, parent) - self.numberControl = LEDIndicator(onColor, offColor, initialState, maxSize, parent) + self.numberControl = LEDIndicator( + onColor, offColor, initialState, maxSize, parent) if position < 3: layout = QVBoxLayout() @@ -72,17 +74,18 @@ def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, textfont = self.lblcontrol.font() metrics = QFontMetricsF(textfont) - maxWidth = max((maxSize+30), (maxSize + metrics.width(lbl)+4)) - maxHeight = max((maxSize+35), (maxSize + metrics.height()+2)) + maxWidth = max((maxSize + 30), (maxSize + metrics.width(lbl) + 4)) + maxHeight = max((maxSize + 35), (maxSize + metrics.height() + 2)) self.setMinimumSize(maxWidth, maxHeight) else: - self.setMinimumSize(maxSize+2, maxSize+2) + self.setMinimumSize(maxSize + 2, maxSize + 2) self.show() def setState(self, on_off): self.numberControl.setState(on_off) + class LEDIndicator(QFrame): def __init__(self, onColor='green', offColor='red', initialState=False, maxSize=80, parent=None): @@ -112,11 +115,11 @@ def paintEvent(self, event): if smallest_dim > size.height(): smallest_dim = size.height() - smallest_dim = smallest_dim/2 + smallest_dim = smallest_dim / 2 smallest_dim -= 2 - center_x = size.width()/2 - center_y = size.height()/2 + center_x = size.width() / 2 + center_y = size.height() / 2 centerpoint = QPoint(center_x, center_y) radius = smallest_dim @@ -124,14 +127,14 @@ def paintEvent(self, event): painter.setPen(QPen(QColor('lightgray'), 0)) brush.setStyle(Qtc.SolidPattern) - radial = QRadialGradient(center_x, center_y/2, radius) + radial = QRadialGradient(center_x, center_y / 2, radius) radial.setColorAt(0, Qtc.white) radial.setColorAt(0.8, Qtc.darkGray) painter.setBrush(QBrush(radial)) painter.drawEllipse(centerpoint, radius, radius) # Draw the colored center - radial = QRadialGradient(center_x, center_y/2, radius) + radial = QRadialGradient(center_x, center_y / 2, radius) radial.setColorAt(0, Qtc.white) if self.curState: @@ -159,13 +162,16 @@ def paintEvent(self, event): radius = radius - 9 painter.drawEllipse(centerpoint, radius, radius) + class GrLEDIndicator(gr.sync_block, LabeledLEDIndicator): """ This block makes a basic LED indicator """ + def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=80, position=1, alignment=1, valignment=1, parent=None): - gr.sync_block.__init__(self, name="LEDIndicator", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="LEDIndicator", + in_sig=None, out_sig=None) LabeledLEDIndicator.__init__(self, lbl, onColor, offColor, initialState, maxSize, position, alignment, valignment, parent) self.lbl = lbl @@ -173,7 +179,6 @@ def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, self.message_port_register_in(pmt.intern("state")) self.set_msg_handler(pmt.intern("state"), self.msgHandler) - def msgHandler(self, msg): try: new_val = pmt.to_python(pmt.cdr(msg)) @@ -187,11 +192,11 @@ def msgHandler(self, msg): else: super().setState(False) else: - gr.log.error("Value received was not an int or a bool: %s" % str(type(new_val))) + gr.log.error( + "Value received was not an int or a bool: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) def setState(self, on_off): super().setState(on_off) - diff --git a/gr-qtgui/python/qtgui/levelgauge.py b/gr-qtgui/python/qtgui/levelgauge.py index cee33eb58dc..77034000346 100644 --- a/gr-qtgui/python/qtgui/levelgauge.py +++ b/gr-qtgui/python/qtgui/levelgauge.py @@ -21,6 +21,7 @@ from gnuradio import gr import pmt + class LabeledLevelGauge(QFrame): # Positions: 1 = above, 2=below, 3=left, 4=right def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor='black', @@ -48,11 +49,12 @@ def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor=' # For whatever reason, the progressbar doesn't show the number in the bar if it's # vertical, only if it's horizontal if self.showvalue and (isFloat or self.isVertical): - textstr = self.buildTextStr(minValue/self.scaleFactor) + textstr = self.buildTextStr(minValue / self.scaleFactor) self.lblcontrol.setText(textstr) if fontColor != 'default': - self.lblcontrol.setStyleSheet("QLabel { color : " + fontColor + "; }") + self.lblcontrol.setStyleSheet( + "QLabel { color : " + fontColor + "; }") # add top or left if len: @@ -102,6 +104,7 @@ def setValue(self, new_value): self.numberControl.setValue(new_value) + class LevelGauge(QProgressBar): # Notifies to avoid thread conflicts on paints updateInt = pyqtSignal(int) @@ -170,6 +173,7 @@ def setValue(self, new_value): else: self.updateFloat.emit(new_value) + class GrLevelGauge(gr.sync_block, LabeledLevelGauge): """ This block creates a level gauge. The value can be set either @@ -182,10 +186,12 @@ class GrLevelGauge(gr.sync_block, LabeledLevelGauge): are 0-100 but your incoming values are 0.0-1.0, you will need to set a scalefactor of 100. """ + def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor='black', minValue=0, maxValue=100, maxSize=80, isVertical=True, position=1, isFloat=False, scaleFactor=1, showValue=False, parent=None): - gr.sync_block.__init__(self, name="LevelGauge", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="LevelGauge", + in_sig=None, out_sig=None) LabeledLevelGauge.__init__(self, lbl, barColor, backgroundColor, fontColor, minValue, maxValue, maxSize, position, isVertical, isFloat, scaleFactor, showValue, parent) @@ -205,7 +211,8 @@ def msgHandler(self, msg): if type(new_val) == float or type(new_val) == int: super().setValue(new_val) else: - gr.log.error("Value received was not an int or a float: %s" % str(type(new_val))) + gr.log.error( + "Value received was not an int or a float: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) diff --git a/gr-qtgui/python/qtgui/msgcheckbox.py b/gr-qtgui/python/qtgui/msgcheckbox.py index f01c78bc02c..d1fde95a578 100644 --- a/gr-qtgui/python/qtgui/msgcheckbox.py +++ b/gr-qtgui/python/qtgui/msgcheckbox.py @@ -16,6 +16,7 @@ from gnuradio import gr import pmt + class CheckBoxEx(Qt.QCheckBox): def __init__(self, lbl, callback=None): Qt.QCheckBox.__init__(self) @@ -28,6 +29,7 @@ def onToggleClicked(self): if self.callback is not None: self.callback(super().isChecked()) + class MsgCheckBox(gr.sync_block, QFrame): """ This block creates a variable checkbox. Leave the label blank to @@ -39,9 +41,11 @@ class MsgCheckBox(gr.sync_block, QFrame): This control will also produce a state message matching the set values. """ + def __init__(self, callback, lbl, pressedReleasedDict, initPressed, alignment, valignment, outputmsgname='value'): - gr.sync_block.__init__(self, name="MsgCheckBox", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="MsgCheckBox", + in_sig=None, out_sig=None) QFrame.__init__(self) self.outputmsgname = outputmsgname @@ -84,36 +88,36 @@ def onToggleClicked(self, checked): if type(self.pressReleasedDict['Pressed']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Pressed']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Pressed']))) else: self.callback(self.pressReleasedDict['Released']) if type(self.pressReleasedDict['Released']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Released']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Released']))) diff --git a/gr-qtgui/python/qtgui/msgpushbutton.py b/gr-qtgui/python/qtgui/msgpushbutton.py index a3ecaf06c5c..4865cc1eb9d 100644 --- a/gr-qtgui/python/qtgui/msgpushbutton.py +++ b/gr-qtgui/python/qtgui/msgpushbutton.py @@ -13,6 +13,7 @@ from gnuradio import gr import pmt + class MsgPushButton(gr.sync_block, Qt.QPushButton): """ This block creates a variable push button that creates a message @@ -20,8 +21,10 @@ class MsgPushButton(gr.sync_block, Qt.QPushButton): the label. You can define both the output message pmt name as well as the value and value type. """ + def __init__(self, lbl, msgName, msgValue, relBackColor, relFontColor): - gr.sync_block.__init__(self, name="MsgPushButton", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="MsgPushButton", + in_sig=None, out_sig=None) Qt.QPushButton.__init__(self, lbl) self.lbl = lbl @@ -44,13 +47,13 @@ def __init__(self, lbl, msgName, msgValue, relBackColor, relFontColor): def onBtnClicked(self, pressed): if type(self.msgValue) == int: self.message_port_pub(pmt.intern("pressed"), - pmt.cons(pmt.intern(self.msgName), pmt.from_long(self.msgValue))) + pmt.cons(pmt.intern(self.msgName), pmt.from_long(self.msgValue))) elif type(self.msgValue) == float: self.message_port_pub(pmt.intern("pressed"), - pmt.cons(pmt.intern(self.msgName), pmt.from_double(self.msgValue))) + pmt.cons(pmt.intern(self.msgName), pmt.from_double(self.msgValue))) elif type(self.msgValue) == str: self.message_port_pub(pmt.intern("pressed"), - pmt.cons(pmt.intern(self.msgName), pmt.intern(self.msgValue))) + pmt.cons(pmt.intern(self.msgName), pmt.intern(self.msgValue))) elif type(self.msgValue) == bool: self.message_port_pub(pmt.intern("pressed"), - pmt.cons(pmt.intern(self.msgName), pmt.from_bool(self.msgValue))) + pmt.cons(pmt.intern(self.msgName), pmt.from_bool(self.msgValue))) diff --git a/gr-qtgui/python/qtgui/togglebutton.py b/gr-qtgui/python/qtgui/togglebutton.py index 99358cd0e44..cfa0f91d331 100644 --- a/gr-qtgui/python/qtgui/togglebutton.py +++ b/gr-qtgui/python/qtgui/togglebutton.py @@ -14,6 +14,7 @@ from gnuradio import gr import pmt + class ToggleButton(gr.sync_block, Qt.QPushButton): """ This block creates a variable toggle button. Leave the label @@ -24,8 +25,10 @@ class ToggleButton(gr.sync_block, Qt.QPushButton): or released. This button will also produce a state message matching the set values. """ + def __init__(self, callback, lbl, pressedReleasedDict, initPressed, outputmsgname='value'): - gr.sync_block.__init__(self, name="ToggleButton", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="ToggleButton", + in_sig=None, out_sig=None) Qt.QPushButton.__init__(self, lbl) self.setCheckable(True) self.lbl = lbl @@ -89,34 +92,34 @@ def onToggleClicked(self, pressed): if pressed: if type(self.pressReleasedDict['Pressed']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Pressed']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Pressed']))) else: if type(self.pressReleasedDict['Released']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Released']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Released']))) diff --git a/gr-qtgui/python/qtgui/toggleswitch.py b/gr-qtgui/python/qtgui/toggleswitch.py index a869e574de4..ce57f907bb0 100644 --- a/gr-qtgui/python/qtgui/toggleswitch.py +++ b/gr-qtgui/python/qtgui/toggleswitch.py @@ -17,13 +17,14 @@ from PyQt5.QtCore import Qt as Qtc from PyQt5.QtCore import QRect + class LabeledToggleSwitch(QFrame): # Positions: 1 = above, 2=below, 3=left, 4=right def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=50, position=1, parent=None, callback=None, alignment=1, valignment=1): QFrame.__init__(self, parent) self.numberControl = ToggleSwitch(onColor, offColor, initialState, maxSize, - parent, callback) + parent, callback) if position < 3: layout = QVBoxLayout() @@ -33,9 +34,9 @@ def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, self.lbl = lbl self.lblcontrol = QLabel(lbl, self) - if position == 3: # left of switch + if position == 3: # left of switch self.lblcontrol.setAlignment(Qtc.AlignRight) - elif position == 4: # right of switch + elif position == 4: # right of switch self.lblcontrol.setAlignment(Qtc.AlignLeft) else: # Above or below @@ -74,8 +75,9 @@ def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, textfont = self.lblcontrol.font() metrics = QFontMetricsF(textfont) - maxWidth = max((maxSize+4), (maxSize*2 + metrics.width(lbl))) - maxHeight = max((maxSize/2+4), (maxSize/2 + metrics.height()+2)) + maxWidth = max((maxSize + 4), (maxSize * 2 + metrics.width(lbl))) + maxHeight = max((maxSize / 2 + 4), + (maxSize / 2 + metrics.height() + 2)) self.setMinimumSize(int(maxWidth), int(maxHeight)) @@ -84,6 +86,7 @@ def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, def setState(self, on_off): self.numberControl.setState(on_off) + class ToggleSwitch(QFrame): def __init__(self, onColor='green', offColor='red', initialState=False, maxSize=50, parent=None, callback=None): @@ -94,8 +97,8 @@ def __init__(self, onColor='green', offColor='red', initialState=False, maxSize= self.onColor = QColor(onColor) self.offColor = QColor(offColor) self.callback = callback - self.setMinimumSize(maxSize, maxSize/2) - self.setMaximumSize(maxSize, maxSize/2) + self.setMinimumSize(maxSize, maxSize / 2) + self.setMaximumSize(maxSize, maxSize / 2) def setState(self, on_off): self.curState = on_off @@ -113,7 +116,7 @@ def paintEvent(self, event): size = self.size() brush = QBrush() - center_x = size.width()/2 + center_x = size.width() / 2 if self.curState: brush.setColor(self.onColor) @@ -126,38 +129,43 @@ def paintEvent(self, event): painter.setBrush(brush) # Draw the switch background - centerRect = QRect(size.width()/4, 0, size.width()/2-4, size.height()) + centerRect = QRect(size.width() / 4, 0, + size.width() / 2 - 4, size.height()) painter.drawRect(centerRect) painter.drawEllipse(0, 0, size.height(), size.height()) - painter.drawEllipse(size.width()/2, 0, size.height(), size.height()) + painter.drawEllipse(size.width() / 2, 0, size.height(), size.height()) # Draw the switch itself brush.setColor(QColor('white')) painter.setBrush(brush) painter.setPen(QPen(QColor('white'), 0)) if self.curState: - painter.drawEllipse(center_x+2, 2, size.height() - 4, size.height() - 4) + painter.drawEllipse( + center_x + 2, 2, size.height() - 4, size.height() - 4) else: painter.drawEllipse(2, 2, size.height() - 4, size.height() - 4) def mousePressEvent(self, event): - if event.x() <= self.size().width()/2: + if event.x() <= self.size().width() / 2: self.setState(False) else: self.setState(True) super().update() + class GrToggleSwitch(gr.sync_block, LabeledToggleSwitch): """ This block creates a modern toggle switch. The variable will take on one value or the other as set in the dialog. This button will also produce a state message matching the set values. """ + def __init__(self, callback, lbl, pressedReleasedDict, initialState=False, onColor='green', offColor='silver', position=3, maxSize=50, alignment=1, valignment=1, parent=None, outputmsgname='value'): - gr.sync_block.__init__(self, name="ToggleSwitch", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="ToggleSwitch", + in_sig=None, out_sig=None) LabeledToggleSwitch.__init__(self, lbl, onColor, offColor, initialState, maxSize, position, parent, self.notifyUpdate, alignment, valignment) @@ -177,34 +185,34 @@ def notifyUpdate(self, new_val): if new_val: if type(self.pressReleasedDict['Pressed']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Pressed']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Pressed']))) else: if type(self.pressReleasedDict['Released']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Released']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Released']))) diff --git a/gr-soapy/python/soapy/qa_soapy_types.py b/gr-soapy/python/soapy/qa_soapy_types.py index af8ab3864a2..64cf4147bff 100644 --- a/gr-soapy/python/soapy/qa_soapy_types.py +++ b/gr-soapy/python/soapy/qa_soapy_types.py @@ -9,6 +9,7 @@ from gnuradio import gr, gr_unittest, blocks from gnuradio import soapy + class test_soapy_types(gr_unittest.TestCase): def test_range(self): @@ -46,7 +47,7 @@ def test_arginfo(self): test_arginfo.type = val self.assertEqual(test_arginfo.type, val) - test_arginfo.range = soapy.range_t(1,2,0.5) + test_arginfo.range = soapy.range_t(1, 2, 0.5) self.assertAlmostEqual(test_arginfo.range.minimum(), 1, 9) self.assertAlmostEqual(test_arginfo.range.maximum(), 2, 9) self.assertAlmostEqual(test_arginfo.range.step(), 0.5, 9) diff --git a/gr-trellis/docs/make_numbered_listing.py b/gr-trellis/docs/make_numbered_listing.py index c295dc8763a..cdef9161fbd 100644 --- a/gr-trellis/docs/make_numbered_listing.py +++ b/gr-trellis/docs/make_numbered_listing.py @@ -1,45 +1,48 @@ #!/usr/bin/env python import sys -import os, os.path +import os +import os.path from optparse import OptionParser -def quote_line (line): - line = line.replace ('&', '&') - line = line.replace ('<', '<') - line = line.replace ('>', '>') - line = line.replace ("'", ''') - line = line.replace ('"', '"') + +def quote_line(line): + line = line.replace('&', '&') + line = line.replace('<', '<') + line = line.replace('>', '>') + line = line.replace("'", ''') + line = line.replace('"', '"') return line -def generate_listing (input_filename, title=None): - inf = open (input_filename, "r") - output_filename = os.path.basename (input_filename) + '.xml' - outf = open (output_filename, "w") - outf.write ('\n') + +def generate_listing(input_filename, title=None): + inf = open(input_filename, "r") + output_filename = os.path.basename(input_filename) + '.xml' + outf = open(output_filename, "w") + outf.write('\n') # outf.write ('\n' % (input_filename,)) # if not title: # title = input_filename # outf.write ('') # outf.write (title) # outf.write ('\n') - outf.write ('\n'); + outf.write('\n') lineno = 0 for line in inf: - line = line.expandtabs (8) - line = quote_line (line) + line = line.expandtabs(8) + line = quote_line(line) lineno = lineno + 1 - outf.write ('%3d %s' % (lineno, line)) + outf.write('%3d %s' % (lineno, line)) - outf.write ('\n') + outf.write('\n') # outf.write ('\n') -def main (): +def main(): for file in sys.argv[1:]: - generate_listing (file) + generate_listing(file) -if __name__ == '__main__': - main () +if __name__ == '__main__': + main() diff --git a/gr-trellis/docs/test_tcm.py b/gr-trellis/docs/test_tcm.py index f9442dbc9fd..65df9a2dbe3 100644 --- a/gr-trellis/docs/test_tcm.py +++ b/gr-trellis/docs/test_tcm.py @@ -15,84 +15,97 @@ sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) -def run_test (f,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed): - tb = gr.top_block () + +def run_test(f, Kb, bitspersymbol, K, dimensionality, constellation, N0, seed): + tb = gr.top_block() # TX src = blocks.lfsr_32k_source_s() - src_head = blocks.head (gr.sizeof_short,Kb / 16) # packet size in shorts - s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality - enc = trellis.encoder_ss(f,0) # initial state = 0 - mod = digital.chunks_to_symbols_sf(constellation,dimensionality) + src_head = blocks.head(gr.sizeof_short, Kb / 16) # packet size in shorts + # unpack shorts to symbols compatible with the FSM input cardinality + s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol, gr.GR_MSB_FIRST) + enc = trellis.encoder_ss(f, 0) # initial state = 0 + mod = digital.chunks_to_symbols_sf(constellation, dimensionality) # CHANNEL add = blocks.add_ff() - noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0 / 2),seed) + noise = analog.noise_source_f(analog.GR_GAUSSIAN, math.sqrt(N0 / 2), seed) # RX - metrics = trellis.metrics_f(f.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi - va = trellis.viterbi_s(f,K,0,-1) # Put -1 if the Initial/Final states are not set. - fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts - dst = blocks.check_lfsr_32k_s(); - - tb.connect (src,src_head,s2fsmi,enc,mod) - tb.connect (mod,(add,0)) - tb.connect (noise,(add,1)) - tb.connect (add,metrics) - tb.connect (metrics,va,fsmi2s,dst) + # data preprocessing to generate metrics for Viterbi + metrics = trellis.metrics_f( + f.O(), dimensionality, constellation, digital.TRELLIS_EUCLIDEAN) + # Put -1 if the Initial/Final states are not set. + va = trellis.viterbi_s(f, K, 0, -1) + fsmi2s = blocks.unpacked_to_packed_ss( + bitspersymbol, gr.GR_MSB_FIRST) # pack FSM input symbols to shorts + dst = blocks.check_lfsr_32k_s() + + tb.connect(src, src_head, s2fsmi, enc, mod) + tb.connect(mod, (add, 0)) + tb.connect(noise, (add, 1)) + tb.connect(add, metrics) + tb.connect(metrics, va, fsmi2s, dst) tb.run() # A bit of cheating: run the program once and print the # final encoder state. # Then put it as the last argument in the viterbi block - #print "final state = " , enc.ST() + # print "final state = " , enc.ST() - ntotal = dst.ntotal () - nright = dst.nright () - runlength = dst.runlength () - return (ntotal,ntotal-nright) + ntotal = dst.ntotal() + nright = dst.nright() + runlength = dst.runlength() + return (ntotal, ntotal - nright) def main(args): - nargs = len (args) + nargs = len(args) if nargs == 3: - fname=args[0] - esn0_db=float(args[1]) # Es/No in dB - rep=int(args[2]) # number of times the experiment is run to collect enough errors + fname = args[0] + esn0_db = float(args[1]) # Es/No in dB + # number of times the experiment is run to collect enough errors + rep = int(args[2]) else: - sys.stderr.write ('usage: test_tcm.py fsm_fname Es/No_db repetitions\n') - sys.exit (1) + sys.stderr.write( + 'usage: test_tcm.py fsm_fname Es/No_db repetitions\n') + sys.exit(1) # system parameters - f=trellis.fsm(fname) # get the FSM specification from a file - Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) - bitspersymbol = int(round(math.log(f.I()) / math.log(2))) # bits per FSM input symbol - K=Kb / bitspersymbol # packet size in trellis steps - modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations + f = trellis.fsm(fname) # get the FSM specification from a file + # packet size in bits (make it multiple of 16 so it can be packed in a short) + Kb = 1024 * 16 + # bits per FSM input symbol + bitspersymbol = int(round(math.log(f.I()) / math.log(2))) + K = Kb / bitspersymbol # packet size in trellis steps + modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation) / dimensionality != f.O(): - sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') - sys.exit (1) + sys.stderr.write( + 'Incompatible FSM output cardinality and modulation size.\n') + sys.exit(1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 - Es = Es / (len(constellation)//dimensionality) - N0=Es / pow(10.0,esn0_db/10.0); # noise variance + Es = Es / (len(constellation) // dimensionality) + N0 = Es / pow(10.0, esn0_db / 10.0) # noise variance - tot_s=0 - terr_s=0 + tot_s = 0 + terr_s = 0 for i in range(rep): - (s,e)=run_test(f,Kb,bitspersymbol,K,dimensionality,constellation,N0,-int(666+i)) # run experiment with different seed to get different noise realizations - tot_s=tot_s+s - terr_s=terr_s+e - if (i%100==0): - print(i,s,e,tot_s,terr_s, '%e' % ((1.0*terr_s) / tot_s)) + # run experiment with different seed to get different noise realizations + (s, e) = run_test(f, Kb, bitspersymbol, K, + dimensionality, constellation, N0, -int(666 + i)) + tot_s = tot_s + s + terr_s = terr_s + e + if (i % 100 == 0): + print(i, s, e, tot_s, terr_s, '%e' % ((1.0 * terr_s) / tot_s)) # estimate of the (short) error rate - print(tot_s,terr_s, '%e' % ((1.0*terr_s) / tot_s)) + print(tot_s, terr_s, '%e' % ((1.0 * terr_s) / tot_s)) if __name__ == '__main__': - main (sys.argv[1:]) + main(sys.argv[1:]) diff --git a/gr-trellis/docs/test_viterbi_equalization1.py b/gr-trellis/docs/test_viterbi_equalization1.py index 1302712d988..88b425ac8bc 100644 --- a/gr-trellis/docs/test_viterbi_equalization1.py +++ b/gr-trellis/docs/test_viterbi_equalization1.py @@ -15,94 +15,107 @@ sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) -def run_test (f,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,N0,seed): - tb = gr.top_block () + +def run_test(f, Kb, bitspersymbol, K, channel, modulation, dimensionality, tot_constellation, N0, seed): + tb = gr.top_block() L = len(channel) # TX # this for loop is TOO slow in python!!! - packet = [0]*(K+2*L) + packet = [0] * (K + 2 * L) random.seed(seed) for i in range(len(packet)): - packet[i] = random.randint(0, 2**bitspersymbol - 1) # random symbols - for i in range(L): # first/last L symbols set to 0 + packet[i] = random.randint(0, 2**bitspersymbol - 1) # random symbols + for i in range(L): # first/last L symbols set to 0 packet[i] = 0 - packet[len(packet)-i-1] = 0 - src = blocks.vector_source_s(packet,False) - mod = digital.chunks_to_symbols_sf(modulation[1],modulation[0]) + packet[len(packet) - i - 1] = 0 + src = blocks.vector_source_s(packet, False) + mod = digital.chunks_to_symbols_sf(modulation[1], modulation[0]) # CHANNEL - isi = filter.fir_filter_fff(1,channel) + isi = filter.fir_filter_fff(1, channel) add = blocks.add_ff() - noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0 / 2),seed) + noise = analog.noise_source_f(analog.GR_GAUSSIAN, math.sqrt(N0 / 2), seed) # RX - skip = blocks.skiphead(gr.sizeof_float, L) # skip the first L samples since you know they are coming from the L zero symbols - #metrics = trellis.metrics_f(f.O(),dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi - #va = trellis.viterbi_s(f,K+L,0,0) # Put -1 if the Initial/Final states are not set. - va = trellis.viterbi_combined_s(f,K+L,0,0,dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # using viterbi_combined_s instead of metrics_f/viterbi_s allows larger packet lengths because metrics_f is complaining for not being able to allocate large buffers. This is due to the large f.O() in this application... + # skip the first L samples since you know they are coming from the L zero symbols + skip = blocks.skiphead(gr.sizeof_float, L) + # metrics = trellis.metrics_f(f.O(),dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi + # va = trellis.viterbi_s(f,K+L,0,0) # Put -1 if the Initial/Final states are not set. + # using viterbi_combined_s instead of metrics_f/viterbi_s allows larger packet lengths because metrics_f is complaining for not being able to allocate large buffers. This is due to the large f.O() in this application... + va = trellis.viterbi_combined_s( + f, K + L, 0, 0, dimensionality, tot_constellation, digital.TRELLIS_EUCLIDEAN) dst = blocks.vector_sink_s() - tb.connect (src,mod) - tb.connect (mod,isi,(add,0)) - tb.connect (noise,(add,1)) + tb.connect(src, mod) + tb.connect(mod, isi, (add, 0)) + tb.connect(noise, (add, 1)) #tb.connect (add,metrics) #tb.connect (metrics,va,dst) - tb.connect (add,skip,va,dst) + tb.connect(add, skip, va, dst) tb.run() data = dst.data() ntotal = len(data) - L - nright=0 + nright = 0 for i in range(ntotal): - if packet[i+L]==data[i]: - nright=nright+1 - #else: - #print "Error in ", i + if packet[i + L] == data[i]: + nright = nright + 1 + # else: + # print "Error in ", i - return (ntotal,ntotal-nright) + return (ntotal, ntotal - nright) def main(args): - nargs = len (args) + nargs = len(args) if nargs == 2: - esn0_db=float(args[0]) - rep=int(args[1]) + esn0_db = float(args[0]) + rep = int(args[1]) else: - sys.stderr.write ('usage: test_viterbi_equalization1.py Es/No_db repetitions\n') - sys.exit (1) + sys.stderr.write( + 'usage: test_viterbi_equalization1.py Es/No_db repetitions\n') + sys.exit(1) # system parameters - Kb=2048 # packet size in bits - modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations - channel = fsm_utils.c_channel # see fsm_utlis.py for available predefined test channels - f=trellis.fsm(len(modulation[1]),len(channel)) # generate the FSM automatically - bitspersymbol = int(round(math.log(f.I()) / math.log(2))) # bits per FSM input symbol - K=Kb / bitspersymbol # packet size in trellis steps - - tot_channel = fsm_utils.make_isi_lookup(modulation,channel,True) # generate the lookup table (normalize energy to 1) + Kb = 2048 # packet size in bits + modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations + # see fsm_utlis.py for available predefined test channels + channel = fsm_utils.c_channel + # generate the FSM automatically + f = trellis.fsm(len(modulation[1]), len(channel)) + # bits per FSM input symbol + bitspersymbol = int(round(math.log(f.I()) / math.log(2))) + K = Kb / bitspersymbol # packet size in trellis steps + + # generate the lookup table (normalize energy to 1) + tot_channel = fsm_utils.make_isi_lookup(modulation, channel, True) dimensionality = tot_channel[0] tot_constellation = tot_channel[1] - N0=pow(10.0,-esn0_db / 10.0); # noise variance + N0 = pow(10.0, -esn0_db / 10.0) # noise variance if len(tot_constellation) / dimensionality != f.O(): - sys.stderr.write ('Incompatible FSM output cardinality and lookup table size.\n') - sys.exit (1) + sys.stderr.write( + 'Incompatible FSM output cardinality and lookup table size.\n') + sys.exit(1) - tot_s=0 # total number of transmitted shorts - terr_s=0 # total number of shorts in error - terr_p=0 # total number of packets in error + tot_s = 0 # total number of transmitted shorts + terr_s = 0 # total number of shorts in error + terr_p = 0 # total number of packets in error for i in range(rep): - (s,e)=run_test(f,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,N0,-int(666+i)) # run experiment with different seed to get different data and noise realizations - tot_s=tot_s+s - terr_s=terr_s+e - terr_p=terr_p+(terr_s!=0) - if ((i+1)%100==0) : # display progress - print(i+1,terr_p, '%.2e' % ((1.0*terr_p) / (i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s) / tot_s)) + (s, e) = run_test(f, Kb, bitspersymbol, K, channel, modulation, dimensionality, tot_constellation, + N0, -int(666 + i)) # run experiment with different seed to get different data and noise realizations + tot_s = tot_s + s + terr_s = terr_s + e + terr_p = terr_p + (terr_s != 0) + if ((i + 1) % 100 == 0): # display progress + print(i + 1, terr_p, '%.2e' % ((1.0 * terr_p) / (i + 1)), + tot_s, terr_s, '%.2e' % ((1.0 * terr_s) / tot_s)) # estimate of the (short or symbol) error rate - print(rep,terr_p, '%.2e' % ((1.0*terr_p) / (i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s) / tot_s)) + print(rep, terr_p, '%.2e' % ((1.0 * terr_p) / (i + 1)), + tot_s, terr_s, '%.2e' % ((1.0 * terr_s) / tot_s)) if __name__ == '__main__': - main (sys.argv[1:]) + main(sys.argv[1:]) diff --git a/gr-trellis/examples/python/test_tcm.py b/gr-trellis/examples/python/test_tcm.py index 958a4b5c64f..c747b5b13c4 100644 --- a/gr-trellis/examples/python/test_tcm.py +++ b/gr-trellis/examples/python/test_tcm.py @@ -17,108 +17,120 @@ sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) -def run_test (f,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed): - tb = gr.top_block () + +def run_test(f, Kb, bitspersymbol, K, dimensionality, constellation, N0, seed): + tb = gr.top_block() # TX numpy.random.seed(-seed) - packet = numpy.random.randint(0,2,Kb) # create Kb random bits - packet[Kb-10:Kb]=0 - packet[0:Kb]=0 - src = blocks.vector_source_s(packet.tolist(),False) - b2s = blocks.unpacked_to_packed_ss(1,gr.GR_MSB_FIRST) # pack bits in shorts - s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality - enc = trellis.encoder_ss(f,0) # initial state = 0 - mod = digital.chunks_to_symbols_sf(constellation,dimensionality) + packet = numpy.random.randint(0, 2, Kb) # create Kb random bits + packet[Kb - 10:Kb] = 0 + packet[0:Kb] = 0 + src = blocks.vector_source_s(packet.tolist(), False) + b2s = blocks.unpacked_to_packed_ss( + 1, gr.GR_MSB_FIRST) # pack bits in shorts + # unpack shorts to symbols compatible with the FSM input cardinality + s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol, gr.GR_MSB_FIRST) + enc = trellis.encoder_ss(f, 0) # initial state = 0 + mod = digital.chunks_to_symbols_sf(constellation, dimensionality) # CHANNEL add = blocks.add_ff() - noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0 / 2),int(seed)) + noise = analog.noise_source_f( + analog.GR_GAUSSIAN, math.sqrt(N0 / 2), int(seed)) # RX - va = trellis.viterbi_combined_fs(f,K,0,0,dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # Put -1 if the Initial/Final states are not set. - fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts - s2b = blocks.packed_to_unpacked_ss(1,gr.GR_MSB_FIRST) # unpack shorts to bits - dst = blocks.vector_sink_s(); - - - tb.connect (src,b2s,s2fsmi,enc,mod) - tb.connect (mod,(add,0)) - tb.connect (noise,(add,1)) - tb.connect (add,va,fsmi2s,s2b,dst) - + # Put -1 if the Initial/Final states are not set. + va = trellis.viterbi_combined_fs( + f, K, 0, 0, dimensionality, constellation, digital.TRELLIS_EUCLIDEAN) + fsmi2s = blocks.unpacked_to_packed_ss( + bitspersymbol, gr.GR_MSB_FIRST) # pack FSM input symbols to shorts + s2b = blocks.packed_to_unpacked_ss( + 1, gr.GR_MSB_FIRST) # unpack shorts to bits + dst = blocks.vector_sink_s() + + tb.connect(src, b2s, s2fsmi, enc, mod) + tb.connect(mod, (add, 0)) + tb.connect(noise, (add, 1)) + tb.connect(add, va, fsmi2s, s2b, dst) tb.run() # A bit of cheating: run the program once and print the # final encoder state.. # Then put it as the last argument in the viterbi block - #print "final state = " , enc.ST() + # print "final state = " , enc.ST() if len(dst.data()) != len(packet): print("Error: not enough data:", len(dst.data()), len(packet)) - ntotal=len(packet) - nwrong = sum(abs(packet-numpy.array(dst.data()))); - return (ntotal,nwrong,abs(packet-numpy.array(dst.data()))) - - + ntotal = len(packet) + nwrong = sum(abs(packet - numpy.array(dst.data()))) + return (ntotal, nwrong, abs(packet - numpy.array(dst.data()))) def main(): parser = OptionParser(option_class=eng_option) - parser.add_option("-f", "--fsm_file", type="string", default="fsm_files/awgn1o2_4.fsm", help="Filename containing the fsm specification, e.g. -f fsm_files/awgn1o2_4.fsm (default=fsm_files/awgn1o2_4.fsm)") - parser.add_option("-e", "--esn0", type="eng_float", default=10.0, help="Symbol energy to noise PSD level ratio in dB, e.g., -e 10.0 (default=10.0)") - parser.add_option("-r", "--repetitions", type="int", default=100, help="Number of packets to be generated for the simulation, e.g., -r 100 (default=100)") - - (options, args) = parser.parse_args () + parser.add_option("-f", "--fsm_file", type="string", default="fsm_files/awgn1o2_4.fsm", + help="Filename containing the fsm specification, e.g. -f fsm_files/awgn1o2_4.fsm (default=fsm_files/awgn1o2_4.fsm)") + parser.add_option("-e", "--esn0", type="eng_float", default=10.0, + help="Symbol energy to noise PSD level ratio in dB, e.g., -e 10.0 (default=10.0)") + parser.add_option("-r", "--repetitions", type="int", default=100, + help="Number of packets to be generated for the simulation, e.g., -r 100 (default=100)") + + (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit(1) - fname=options.fsm_file - esn0_db=float(options.esn0) - rep=int(options.repetitions) + fname = options.fsm_file + esn0_db = float(options.esn0) + rep = int(options.repetitions) # system parameters - f=trellis.fsm(fname) # get the FSM specification from a file + f = trellis.fsm(fname) # get the FSM specification from a file # alternatively you can specify the fsm from its generator matrix - #f=trellis.fsm(1,2,[5,7]) - Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) - bitspersymbol = int(round(math.log(f.I()) / math.log(2))) # bits per FSM input symbol - K=Kb / bitspersymbol # packet size in trellis steps - modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations + # f=trellis.fsm(1,2,[5,7]) + # packet size in bits (make it multiple of 16 so it can be packed in a short) + Kb = 1024 * 16 + # bits per FSM input symbol + bitspersymbol = int(round(math.log(f.I()) / math.log(2))) + K = Kb / bitspersymbol # packet size in trellis steps + modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation) / dimensionality != f.O(): - sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') - sys.exit (1) + sys.stderr.write( + 'Incompatible FSM output cardinality and modulation size.\n') + sys.exit(1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 - Es = Es / (len(constellation)//dimensionality) - N0=Es / pow(10.0,esn0_db/10.0); # calculate noise variance + Es = Es / (len(constellation) // dimensionality) + N0 = Es / pow(10.0, esn0_db / 10.0) # calculate noise variance - tot_b=0 # total number of transmitted bits - terr_b=0 # total number of bits in error - terr_p=0 # total number of packets in error + tot_b = 0 # total number of transmitted bits + terr_b = 0 # total number of bits in error + terr_p = 0 # total number of packets in error for i in range(rep): - (b,e,pattern)=run_test(f,Kb,bitspersymbol,K,dimensionality,constellation,N0,-(666+i)) # run experiment with different seed to get different noise realizations - tot_b=tot_b+b - terr_b=terr_b+e - terr_p=terr_p+(e!=0) - if ((i+1)%100==0) : # display progress - print(i+1,terr_p, '%.2e' % ((1.0*terr_p) / (i+1)),tot_b,terr_b, '%.2e' % ((1.0*terr_b) / tot_b)) - if e!=0: - print("rep=",i, e) + # run experiment with different seed to get different noise realizations + (b, e, pattern) = run_test(f, Kb, bitspersymbol, + K, dimensionality, constellation, N0, -(666 + i)) + tot_b = tot_b + b + terr_b = terr_b + e + terr_p = terr_p + (e != 0) + if ((i + 1) % 100 == 0): # display progress + print(i + 1, terr_p, '%.2e' % ((1.0 * terr_p) / (i + 1)), + tot_b, terr_b, '%.2e' % ((1.0 * terr_b) / tot_b)) + if e != 0: + print("rep=", i, e) for k in range(Kb): - if pattern[k]!=0: + if pattern[k] != 0: print(k) # estimate of the bit error rate - print(rep,terr_p, '%.2e' % ((1.0*terr_p) / (i+1)),tot_b,terr_b, '%.2e' % ((1.0*terr_b) / tot_b)) - + print(rep, terr_p, '%.2e' % ((1.0 * terr_p) / (i + 1)), + tot_b, terr_b, '%.2e' % ((1.0 * terr_b) / tot_b)) if __name__ == '__main__': main() - diff --git a/gr-trellis/python/trellis/fsm_utils.py b/gr-trellis/python/trellis/fsm_utils.py index 0cbd6b6750c..7e78b19fa0c 100644 --- a/gr-trellis/python/trellis/fsm_utils.py +++ b/gr-trellis/python/trellis/fsm_utils.py @@ -30,9 +30,9 @@ def dec2base(num, base, l): s = list(range(l)) n = num for i in range(l): - s[l-i-1]=n%base - n=int(n / base) - if n!=0: + s[l - i - 1] = n % base + n = int(n / base) + if n != 0: print('Number ', num, ' requires more than ', l, 'digits.') return s @@ -68,14 +68,14 @@ def make_isi_lookup(mod, channel, normalize): for i in range(len(channel)): channel[i] = channel[i] / math.sqrt(p) - lookup=list(range(len(constellation)**len(channel))) + lookup = list(range(len(constellation)**len(channel))) for o in range(len(constellation)**len(channel)): ss = dec2base(o, len(constellation), len(channel)) ll = 0 for i in range(len(channel)): - ll=ll+constellation[ss[i]]*channel[i] - lookup[o]=ll - return (1,lookup) + ll = ll + constellation[ss[i]] * channel[i] + lookup[o] = ll + return (1, lookup) def make_cpm_signals(K, P, M, L, q, frac): @@ -101,51 +101,50 @@ def make_cpm_signals(K, P, M, L, q, frac): X = (M**L) * P PSI = numpy.empty((X, Q)) for x in range(X): - xv=dec2base(x / P,M,L) - xv=numpy.append(xv, x%P) - qq1=numpy.zeros(Q) - for m in range(L): - qq1=qq1+xv[m]*q[m*Q:m*Q+Q] - psi=2*math.pi*h*xv[-1]+4*math.pi*h*qq1+w - #print(psi) - PSI[x]=psi + xv = dec2base(x / P, M, L) + xv = numpy.append(xv, x % P) + qq1 = numpy.zeros(Q) + for m in range(L): + qq1 = qq1 + xv[m] * q[m * Q:m * Q + Q] + psi = 2 * math.pi * h * xv[-1] + 4 * math.pi * h * qq1 + w + # print(psi) + PSI[x] = psi PSI = numpy.transpose(PSI) - SS=numpy.exp(1j*PSI) # contains all signals as columns - #print(SS) - + SS = numpy.exp(1j * PSI) # contains all signals as columns + # print(SS) # Now we need to orthogonalize the signals - F = scipy.linalg.orth(SS) # find an orthonormal basis for SS - #print(numpy.dot(numpy.transpose(F.conjugate()),F) # check for orthonormality) - S = numpy.dot(numpy.transpose(F.conjugate()),SS) - #print(F) - #print(S) + F = scipy.linalg.orth(SS) # find an orthonormal basis for SS + # print(numpy.dot(numpy.transpose(F.conjugate()),F) # check for orthonormality) + S = numpy.dot(numpy.transpose(F.conjugate()), SS) + # print(F) + # print(S) # We only want to keep those dimensions that contain most # of the energy of the overall constellation (eg, frac=0.9 ==> 90%) # evaluate mean energy in each dimension - E=numpy.sum(numpy.absolute(S)**2, axis=1) / Q - E=E / numpy.sum(E) - #print(E) + E = numpy.sum(numpy.absolute(S)**2, axis=1) / Q + E = E / numpy.sum(E) + # print(E) Es = -numpy.sort(-E) Esi = numpy.argsort(-E) - #print(Es) - #print(Esi) - Ecum=numpy.cumsum(Es) - #print(Ecum) - v0=numpy.searchsorted(Ecum,frac) - N = v0+1 - #print(v0) - #print(Esi[0:v0+1]) - Ff=numpy.transpose(numpy.transpose(F)[Esi[0:v0+1]]) - #print(Ff) - Sf = S[Esi[0:v0+1]] - #print(Sf) + # print(Es) + # print(Esi) + Ecum = numpy.cumsum(Es) + # print(Ecum) + v0 = numpy.searchsorted(Ecum, frac) + N = v0 + 1 + # print(v0) + # print(Esi[0:v0+1]) + Ff = numpy.transpose(numpy.transpose(F)[Esi[0:v0 + 1]]) + # print(Ff) + Sf = S[Esi[0:v0 + 1]] + # print(Sf) return (f0, SS, S, F, Sf, Ff, N) -#return f0 +# return f0 ###################################################################### # A list of common modulations. @@ -155,52 +154,52 @@ def make_cpm_signals(K, P, M, L, q, frac): pam4 = (1, [-3, -1, 3, 1]) # includes Gray mapping pam8 = (1, [-7, -5, -3, -1, 1, 3, 5, 7]) -psk4=(2,[1, 0, \ - 0, 1, \ - 0, -1,\ - -1, 0]) # includes Gray mapping - -psk8=(2,[math.cos(2*math.pi*0/8), math.sin(2*math.pi*0/8), \ - math.cos(2*math.pi*1/8), math.sin(2*math.pi*1/8), \ - math.cos(2*math.pi*2/8), math.sin(2*math.pi*2/8), \ - math.cos(2*math.pi*3/8), math.sin(2*math.pi*3/8), \ - math.cos(2*math.pi*4/8), math.sin(2*math.pi*4/8), \ - math.cos(2*math.pi*5/8), math.sin(2*math.pi*5/8), \ - math.cos(2*math.pi*6/8), math.sin(2*math.pi*6/8), \ - math.cos(2*math.pi*7/8), math.sin(2*math.pi*7/8)]) - -psk2x3 = (3,[-1,-1,-1, \ - -1,-1,1, \ - -1,1,-1, \ - -1,1,1, \ - 1,-1,-1, \ - 1,-1,1, \ - 1,1,-1, \ - 1,1,1]) - -psk2x4 = (4,[-1,-1,-1,-1, \ - -1,-1,-1,1, \ - -1,-1,1,-1, \ - -1,-1,1,1, \ - -1,1,-1,-1, \ - -1,1,-1,1, \ - -1,1,1,-1, \ - -1,1,1,1, \ - 1,-1,-1,-1, \ - 1,-1,-1,1, \ - 1,-1,1,-1, \ - 1,-1,1,1, \ - 1,1,-1,-1, \ - 1,1,-1,1, \ - 1,1,1,-1, \ - 1,1,1,1]) - -orth2 = (2,[1, 0, \ - 0, 1]) -orth4=(4,[1, 0, 0, 0, \ - 0, 1, 0, 0, \ - 0, 0, 1, 0, \ - 0, 0, 0, 1]) +psk4 = (2, [1, 0, + 0, 1, + 0, -1, + -1, 0]) # includes Gray mapping + +psk8 = (2, [math.cos(2 * math.pi * 0 / 8), math.sin(2 * math.pi * 0 / 8), + math.cos(2 * math.pi * 1 / 8), math.sin(2 * math.pi * 1 / 8), + math.cos(2 * math.pi * 2 / 8), math.sin(2 * math.pi * 2 / 8), + math.cos(2 * math.pi * 3 / 8), math.sin(2 * math.pi * 3 / 8), + math.cos(2 * math.pi * 4 / 8), math.sin(2 * math.pi * 4 / 8), + math.cos(2 * math.pi * 5 / 8), math.sin(2 * math.pi * 5 / 8), + math.cos(2 * math.pi * 6 / 8), math.sin(2 * math.pi * 6 / 8), + math.cos(2 * math.pi * 7 / 8), math.sin(2 * math.pi * 7 / 8)]) + +psk2x3 = (3, [-1, -1, -1, + -1, -1, 1, + -1, 1, -1, + -1, 1, 1, + 1, -1, -1, + 1, -1, 1, + 1, 1, -1, + 1, 1, 1]) + +psk2x4 = (4, [-1, -1, -1, -1, + -1, -1, -1, 1, + -1, -1, 1, -1, + -1, -1, 1, 1, + -1, 1, -1, -1, + -1, 1, -1, 1, + -1, 1, 1, -1, + -1, 1, 1, 1, + 1, -1, -1, -1, + 1, -1, -1, 1, + 1, -1, 1, -1, + 1, -1, 1, 1, + 1, 1, -1, -1, + 1, 1, -1, 1, + 1, 1, 1, -1, + 1, 1, 1, 1]) + +orth2 = (2, [1, 0, + 0, 1]) +orth4 = (4, [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]) ###################################################################### # A list of channels to be tested diff --git a/gr-uhd/apps/msgq_runner.py b/gr-uhd/apps/msgq_runner.py index 31bebcf0dfb..1fe86f1ad15 100644 --- a/gr-uhd/apps/msgq_runner.py +++ b/gr-uhd/apps/msgq_runner.py @@ -32,6 +32,7 @@ from gnuradio import gr import threading + class msgq_runner(threading.Thread): def __init__(self, msgq, callback, exit_on_error=False): diff --git a/gr-uhd/apps/uhd_app.py b/gr-uhd/apps/uhd_app.py index 65b35ac7361..55c2a71d2f3 100644 --- a/gr-uhd/apps/uhd_app.py +++ b/gr-uhd/apps/uhd_app.py @@ -18,7 +18,7 @@ from gnuradio import uhd from gnuradio import gr -COMMAND_DELAY = .2 # Seconds +COMMAND_DELAY = .2 # Seconds COMPACT_TPL = "{mb_id} ({mb_serial}), {db_subdev} ({subdev}, {ant}{db_serial})" LONG_TPL = """{prefix} Motherboard: {mb_id} ({mb_serial}) @@ -30,11 +30,13 @@ # PyLint can't reliably detect C++ exports in modules, so let's disable that # pylint: disable=no-member + class UHDApp: GAIN_TYPE_GAIN = 'dB' GAIN_TYPE_POWER = 'power_dbm' " Base class for simple UHD-based applications " + def __init__(self, prefix=None, args=None): self.prefix = prefix self.args = args @@ -42,7 +44,7 @@ def __init__(self, prefix=None, args=None): if self.args.sync == 'auto' and len(self.args.channels) > 1: self.args.sync = 'pps' self.antenna = None - self.gain_range = None # Can also be power range + self.gain_range = None # Can also be power range self.samp_rate = None self.has_lo_sensor = None self.async_msgq = None @@ -87,8 +89,10 @@ def get_usrp_info_string(self, compact=False, tx_or_rx='rx', chan=0, mboard=0): info_pp['mb_serial'] = usrp_info['mboard_serial'] if info_pp['mb_serial'] == "": info_pp['mb_serial'] = "no serial" - info_pp['db_subdev'] = usrp_info["{xx}_subdev_name".format(xx=tx_or_rx)] - info_pp['db_serial'] = ", " + usrp_info["{xx}_serial".format(xx=tx_or_rx)] + info_pp['db_subdev'] = usrp_info["{xx}_subdev_name".format( + xx=tx_or_rx)] + info_pp['db_serial'] = ", " + \ + usrp_info["{xx}_serial".format(xx=tx_or_rx)] if info_pp['db_serial'] == "": info_pp['db_serial'] = "no serial" info_pp['subdev'] = self.usrp.get_subdev_spec(mboard) @@ -173,11 +177,13 @@ def setup_usrp(self, ctor, args, cpu_format='fc32'): self.samp_rate = self.usrp.get_samp_rate() self.vprint("Using sampling rate: {rate}".format(rate=self.samp_rate)) # Set the antenna: - self.antenna = self.normalize_sel("channels", "antenna", len(args.channels), args.antenna) + self.antenna = self.normalize_sel( + "channels", "antenna", len(args.channels), args.antenna) if self.antenna is not None: for i, chan in enumerate(self.channels): if not self.antenna[i] in self.usrp.get_antennas(i): - print("[ERROR] {} is not a valid antenna name for this USRP device!".format(self.antenna[i])) + print("[ERROR] {} is not a valid antenna name for this USRP device!".format( + self.antenna[i])) sys.exit(1) self.usrp.set_antenna(self.antenna[i], i) self.vprint("[{prefix}] Channel {chan}: Using antenna {ant}.".format( @@ -207,14 +213,16 @@ def setup_usrp(self, ctor, args, cpu_format='fc32'): self.has_lo_sensor = 'lo_locked' in self.usrp.get_sensor_names() # Set LO export and LO source operation if (args.lo_export is not None) and (args.lo_source is not None): - self.lo_source = self.normalize_sel("channels", "lo-source", len(self.channels), args.lo_source) - self.lo_export = self.normalize_sel("channels", "lo-export", len(self.channels), args.lo_export) + self.lo_source = self.normalize_sel( + "channels", "lo-source", len(self.channels), args.lo_source) + self.lo_export = self.normalize_sel( + "channels", "lo-export", len(self.channels), args.lo_export) self.lo_source_channel = None for chan, lo_source, lo_export in zip(self.channels, self.lo_source, self.lo_export): if (lo_source == "None") or (lo_export == "None"): continue if lo_export == "True": - #If channel is LO source set frequency and store response + # If channel is LO source set frequency and store response self.usrp.set_lo_export_enabled(True, uhd.ALL_LOS, chan) if lo_source == "internal": self.lo_source_channel = chan @@ -225,7 +233,7 @@ def setup_usrp(self, ctor, args, cpu_format='fc32'): if getattr(args, 'lo_offset', None) is not None: treq = uhd.tune_request( target_freq=args.freq, - rf_freq=args.freq+args.lo_offset, + rf_freq=args.freq + args.lo_offset, rf_freq_policy=uhd.tune_request.POLICY_MANUAL, dsp_freq=tune_resp.actual_dsp_freq, dsp_freq_policy=uhd.tune_request.POLICY_MANUAL) @@ -251,7 +259,8 @@ def setup_usrp(self, ctor, args, cpu_format='fc32'): self.usrp.set_command_time(cmd_time, mb_idx) command_time_set = True except RuntimeError: - sys.stderr.write('[{prefix}] [WARNING] Failed to set command times.\n'.format(prefix=self.prefix)) + sys.stderr.write('[{prefix}] [WARNING] Failed to set command times.\n'.format( + prefix=self.prefix)) for i, chan in enumerate(self.channels): self.tr = self.usrp.set_center_freq(treq, i) if self.tr is None: @@ -268,7 +277,8 @@ def setup_usrp(self, ctor, args, cpu_format='fc32'): if args.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) - self.async_rcv = uhd.msgq_runner(self.async_msgq, self.async_callback) + self.async_rcv = uhd.msgq_runner( + self.async_msgq, self.async_callback) def set_gain(self, gain): """ @@ -278,7 +288,8 @@ def set_gain(self, gain): """ if gain is None: if self.args.verbose: - self.vprint("Defaulting to mid-point gains:".format(prefix=self.prefix)) + self.vprint( + "Defaulting to mid-point gains:".format(prefix=self.prefix)) for i, chan in enumerate(self.channels): self.usrp.set_normalized_gain(.5, i) if self.args.verbose: @@ -304,7 +315,8 @@ def set_freq(self, freq, skip_sync=False): """ Safely tune all channels to freq. """ - self.vprint("Tuning all channels to {freq} MHz.".format(freq=freq / 1e6)) + self.vprint( + "Tuning all channels to {freq} MHz.".format(freq=freq / 1e6)) # Set frequency (tune request takes lo_offset): if hasattr(self.args, 'lo_offset') and self.args.lo_offset is not None: treq = uhd.tune_request(freq, self.args.lo_offset) @@ -316,7 +328,7 @@ def set_freq(self, freq, skip_sync=False): if getattr(self.args, 'lo_offset', None) is not None: treq = uhd.tune_request( target_freq=freq, - rf_freq=freq+self.args.lo_offset, + rf_freq=freq + self.args.lo_offset, rf_freq_policy=uhd.tune_request.POLICY_MANUAL, dsp_freq=tune_resp.actual_dsp_freq, dsp_freq_policy=uhd.tune_request.POLICY_MANUAL) @@ -340,7 +352,8 @@ def set_freq(self, freq, skip_sync=False): self.usrp.set_command_time(cmd_time, mb_idx) command_time_set = True except RuntimeError: - sys.stderr.write('[{prefix}] [WARNING] Failed to set command times.\n'.format(prefix=self.prefix)) + sys.stderr.write('[{prefix}] [WARNING] Failed to set command times.\n'.format( + prefix=self.prefix)) for i, chan in enumerate(self.channels): self.tr = self.usrp.set_center_freq(treq, i) if self.tr is None: @@ -354,16 +367,17 @@ def set_freq(self, freq, skip_sync=False): self.vprint("Syncing channels...".format(prefix=self.prefix)) time.sleep(COMMAND_DELAY) self.freq = self.usrp.get_center_freq(0) - self.vprint("First channel has freq: {freq} MHz.".format(freq=self.freq / 1e6)) + self.vprint("First channel has freq: {freq} MHz.".format( + freq=self.freq / 1e6)) @staticmethod def setup_argparser( - parser=None, - description='USRP App', - allow_mimo=True, - tx_or_rx="", - skip_freq=False, - ): + parser=None, + description='USRP App', + allow_mimo=True, + tx_or_rx="", + skip_freq=False, + ): """ Create or amend an argument parser with typical USRP options. """ @@ -374,19 +388,22 @@ def cslist(string): try: return [int(x.strip()) for x in string.split(",")] except ValueError: - raise argparse.ArgumentTypeError("Not a comma-separated list: {string}".format(string=string)) + raise argparse.ArgumentTypeError( + "Not a comma-separated list: {string}".format(string=string)) if parser is None: parser = argparse.ArgumentParser( description=description, ) tx_or_rx = tx_or_rx.strip() + " " group = parser.add_argument_group('USRP Arguments') - group.add_argument("-a", "--args", default="", help="UHD device address args") + group.add_argument("-a", "--args", default="", + help="UHD device address args") group.add_argument( "--spec", help="Subdevice(s) of UHD device where appropriate. " "Use a comma-separated list to set different boards to different specs.") - group.add_argument("-A", "--antenna", help="Select {xx}antenna(s) where appropriate".format(xx=tx_or_rx)) + group.add_argument( + "-A", "--antenna", help="Select {xx}antenna(s) where appropriate".format(xx=tx_or_rx)) group.add_argument("-s", "--samp-rate", type=eng_arg.eng_float, default=1e6, help="Sample rate") group.add_argument("-g", "--gain", type=eng_arg.eng_float, default=None, @@ -403,7 +420,7 @@ def cslist(string): group.add_argument("--lo-offset", type=eng_arg.eng_float, default=0.0, help="Set daughterboard LO offset to OFFSET [default=hw default]") if allow_mimo: - group.add_argument("-c", "--channels", default=[0,], type=cslist, + group.add_argument("-c", "--channels", default=[0, ], type=cslist, help="Select {xx} Channels".format(xx=tx_or_rx)) group.add_argument( "--lo-export", @@ -415,8 +432,10 @@ def cslist(string): "for each channel with a comma-separated list. None skips this channel.") group.add_argument("--otw-format", choices=['sc16', 'sc12', 'sc8'], default='sc16', help="Choose over-the-wire data format") - group.add_argument("--stream-args", default="", help="Set additional stream arguments") - group.add_argument("-v", "--verbose", action="count", help="Use verbose console output") + group.add_argument("--stream-args", default="", + help="Set additional stream arguments") + group.add_argument("-v", "--verbose", action="count", + help="Use verbose console output") group.add_argument("--show-async-msg", action="store_true", help="Show asynchronous message notifications from UHD") group.add_argument("--sync", choices=('default', 'pps', 'auto'), diff --git a/gr-uhd/apps/uhd_fft b/gr-uhd/apps/uhd_fft index 05f2ee30085..fc5e9276c26 100755 --- a/gr-uhd/apps/uhd_fft +++ b/gr-uhd/apps/uhd_fft @@ -42,7 +42,7 @@ import time import math import signal from PyQt5 import Qt -import sip # Needs to be imported after PyQt5, could fail otherwise +import sip # Needs to be imported after PyQt5, could fail otherwise from gnuradio import eng_notation from gnuradio import eng_arg from gnuradio import gr @@ -60,10 +60,12 @@ except ImportError: # pylint: disable=c-extension-no-member # pylint: disable=no-member + class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): """ Simple UHD Spectrum Analyzer / Scope App. """ + def __init__(self, args): UHDApp.__init__(self, args=args, prefix="UHD FFT") gr.top_block.__init__(self, "UHD FFT") @@ -137,13 +139,15 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): self._ant_options = self.usrp.get_antennas(0) for c in range(len(self.channels)): self.usrp.set_bandwidth(self.samp_rate + abs(self.lo_offset), c) - self.usrp_device_info = self.get_usrp_info_string(compact=True, tx_or_rx='rx') + self.usrp_device_info = self.get_usrp_info_string( + compact=True, tx_or_rx='rx') ### Now set up the GUI widgets: ##################################### # Sampling rate: self._samp_rate__tool_bar = Qt.QToolBar(self) self._samp_rate__tool_bar.addWidget(Qt.QLabel("Sampling Rate: ")) - self._samp_rate__line_edit = Qt.QLineEdit(eng_notation.num_to_str(self.samp_rate)) + self._samp_rate__line_edit = Qt.QLineEdit( + eng_notation.num_to_str(self.samp_rate)) self._samp_rate__tool_bar.addWidget(self._samp_rate__line_edit) self._samp_rate__line_edit.returnPressed.connect( lambda: self.set_samp_rate(eng_notation.str_to_num( @@ -190,28 +194,32 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): for label in self._ant_labels: self._ant_combo_box.addItem(label) self._ant_callback = \ - lambda i: Qt.QMetaObject.invokeMethod( - self._ant_combo_box, - "setCurrentIndex", - Qt.Q_ARG("int", self._ant_options.index(i))) + lambda i: Qt.QMetaObject.invokeMethod( + self._ant_combo_box, + "setCurrentIndex", + Qt.Q_ARG("int", self._ant_options.index(i))) self._ant_callback(self.antenna) - self._ant_combo_box.currentIndexChanged.connect(lambda i: self.set_ant(self._ant_options[i])) + self._ant_combo_box.currentIndexChanged.connect( + lambda i: self.set_ant(self._ant_options[i])) self.top_grid_layout.addWidget(self._ant_tool_bar, 4, 2, 1, 2) # Device + UHD info: self._usrp_device_info_tool_bar = Qt.QToolBar(self) self._usrp_device_info_formatter = lambda x: x - self._usrp_device_info_tool_bar.addWidget(Qt.QLabel("Device Information: ")) + self._usrp_device_info_tool_bar.addWidget( + Qt.QLabel("Device Information: ")) self._usrp_device_info_label = Qt.QLabel( str(self._usrp_device_info_formatter(self.usrp_device_info))) self._usrp_device_info_tool_bar.addWidget(self._usrp_device_info_label) - self.top_grid_layout.addWidget(self._usrp_device_info_tool_bar, 1, 2, 1, 2) + self.top_grid_layout.addWidget( + self._usrp_device_info_tool_bar, 1, 2, 1, 2) self._uhd_version_info_tool_bar = Qt.QToolBar(self) self._uhd_version_info_formatter = lambda x: x self._uhd_version_info_tool_bar.addWidget(Qt.QLabel("UHD Version: ")) self._uhd_version_info_label = Qt.QLabel( str(self._uhd_version_info_formatter(self.uhd_version_info))) self._uhd_version_info_tool_bar.addWidget(self._uhd_version_info_label) - self.top_grid_layout.addWidget(self._uhd_version_info_tool_bar, 1, 0, 1, 2) + self.top_grid_layout.addWidget( + self._uhd_version_info_tool_bar, 1, 0, 1, 2) ### Plot GUIs ####################################################### widths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] colors = ["blue", "red", "green", "cyan", "magenta", "black", "yellow", @@ -221,48 +229,53 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): alphas = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] self.display = Qt.QTabWidget() self.display_widget_0 = Qt.QWidget() - self.display_layout_0 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.display_widget_0) + self.display_layout_0 = Qt.QBoxLayout( + Qt.QBoxLayout.TopToBottom, self.display_widget_0) self.display_grid_layout_0 = Qt.QGridLayout() self.display_layout_0.addLayout(self.display_grid_layout_0) self.display.addTab(self.display_widget_0, "Spectrum") self.display_widget_1 = Qt.QWidget() - self.display_layout_1 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.display_widget_1) + self.display_layout_1 = Qt.QBoxLayout( + Qt.QBoxLayout.TopToBottom, self.display_widget_1) self.display_grid_layout_1 = Qt.QGridLayout() self.display_layout_1.addLayout(self.display_grid_layout_1) self.display.addTab(self.display_widget_1, "Waterfall") self.display_widget_2 = Qt.QWidget() - self.display_layout_2 = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.display_widget_2) + self.display_layout_2 = Qt.QBoxLayout( + Qt.QBoxLayout.TopToBottom, self.display_widget_2) self.display_grid_layout_2 = Qt.QGridLayout() self.display_layout_2.addLayout(self.display_grid_layout_2) self.display.addTab(self.display_widget_2, "Scope") self.top_grid_layout.addWidget(self.display, 0, 0, 1, 4) self.qtgui_waterfall_sink_x_0 = qtgui.waterfall_sink_c( - self.fft_size, #size - fft.window.WIN_BLACKMAN_hARRIS, #wintype - self.freq, #fc - self.samp_rate, #bw - "", #name - len(self.channels), #number of inputs - None # parent + self.fft_size, # size + fft.window.WIN_BLACKMAN_hARRIS, # wintype + self.freq, # fc + self.samp_rate, # bw + "", # name + len(self.channels), # number of inputs + None # parent ) self.qtgui_waterfall_sink_x_0.set_update_time(self.update_rate) self.qtgui_waterfall_sink_x_0.enable_grid(False) self.qtgui_waterfall_sink_x_0.disable_legend() - alpha = 10.**(len(self.channels)-1) + alpha = 10.**(len(self.channels) - 1) for i in range(len(self.channels)): - self.qtgui_waterfall_sink_x_0.set_line_label(i, "Channel {0}".format(i)) + self.qtgui_waterfall_sink_x_0.set_line_label( + i, "Channel {0}".format(i)) self.qtgui_waterfall_sink_x_0.set_color_map(i, 0) self.qtgui_waterfall_sink_x_0.set_line_alpha(i, alpha) self.qtgui_waterfall_sink_x_0.set_intensity_range(-90, 10) self._qtgui_waterfall_sink_x_0_win = sip.wrapinstance( self.qtgui_waterfall_sink_x_0.qwidget(), Qt.QWidget) - self.display_grid_layout_1.addWidget(self._qtgui_waterfall_sink_x_0_win, 0, 0, 1, 4) + self.display_grid_layout_1.addWidget( + self._qtgui_waterfall_sink_x_0_win, 0, 0, 1, 4) self.qtgui_time_sink_x_0 = qtgui.time_sink_c( - 1024, #size - self.samp_rate, #samp_rate - "", #name - len(self.channels), #number of inputs - None # parent + 1024, # size + self.samp_rate, # samp_rate + "", # name + len(self.channels), # number of inputs + None # parent ) self.qtgui_time_sink_x_0.set_update_time(self.update_rate) self.qtgui_time_sink_x_0.set_y_axis(-1, 1) @@ -274,11 +287,13 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): self.qtgui_time_sink_x_0.enable_grid(False) self.qtgui_time_sink_x_0.enable_control_panel(True) self.qtgui_time_sink_x_0.disable_legend() - for i in range(2*len(self.channels)): + for i in range(2 * len(self.channels)): if i % 2 == 0: - self.qtgui_time_sink_x_0.set_line_label(i, "Re{{Channel {0}}}".format(i//2)) + self.qtgui_time_sink_x_0.set_line_label( + i, "Re{{Channel {0}}}".format(i // 2)) else: - self.qtgui_time_sink_x_0.set_line_label(i, "Im{{Channel {0}}}".format(i//2)) + self.qtgui_time_sink_x_0.set_line_label( + i, "Im{{Channel {0}}}".format(i // 2)) self.qtgui_time_sink_x_0.set_line_width(i, widths[i]) self.qtgui_time_sink_x_0.set_line_color(i, colors[i]) self.qtgui_time_sink_x_0.set_line_style(i, styles[i]) @@ -286,15 +301,16 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): self.qtgui_time_sink_x_0.set_line_alpha(i, alphas[i]) self._qtgui_time_sink_x_0_win = sip.wrapinstance( self.qtgui_time_sink_x_0.qwidget(), Qt.QWidget) - self.display_grid_layout_2.addWidget(self._qtgui_time_sink_x_0_win, 0, 0, 1, 4) + self.display_grid_layout_2.addWidget( + self._qtgui_time_sink_x_0_win, 0, 0, 1, 4) self.qtgui_freq_sink_x_0 = qtgui.freq_sink_c( - self.fft_size, #size - fft.window.WIN_BLACKMAN_hARRIS, #wintype - self.freq, #fc - self.samp_rate, #bw - "", #name - len(self.channels), #number of inputs - None #parent + self.fft_size, # size + fft.window.WIN_BLACKMAN_hARRIS, # wintype + self.freq, # fc + self.samp_rate, # bw + "", # name + len(self.channels), # number of inputs + None # parent ) self.qtgui_freq_sink_x_0.set_update_time(self.update_rate) self.qtgui_freq_sink_x_0.set_y_axis(-100, 10) @@ -302,7 +318,8 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): self.qtgui_freq_sink_x_0.set_y_label("Relative Gain", "dB") else: self.qtgui_freq_sink_x_0.set_y_label("Received Power", "dBm") - self.qtgui_freq_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, 0.0, 0, "") + self.qtgui_freq_sink_x_0.set_trigger_mode( + qtgui.TRIG_MODE_FREE, 0.0, 0, "") self.qtgui_freq_sink_x_0.enable_autoscale(True) self.qtgui_freq_sink_x_0.enable_grid(True) self.qtgui_freq_sink_x_0.set_fft_average(self.fft_average) @@ -318,12 +335,14 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): self.qtgui_freq_sink_x_0.set_line_alpha(i, alphas[i]) self._qtgui_freq_sink_x_0_win = sip.wrapinstance( self.qtgui_freq_sink_x_0.qwidget(), Qt.QWidget) - self.display_grid_layout_0.addWidget(self._qtgui_freq_sink_x_0_win, 0, 0, 1, 4) + self.display_grid_layout_0.addWidget( + self._qtgui_freq_sink_x_0_win, 0, 0, 1, 4) + def _freeze_scaling(widget, sleep_time): time.sleep(sleep_time) widget.enable_autoscale(False) _freeze_fft_thread = threading.Thread( - target=lambda: _freeze_scaling(self.qtgui_freq_sink_x_0, .5/self.fft_average)) + target=lambda: _freeze_scaling(self.qtgui_freq_sink_x_0, .5 / self.fft_average)) _freeze_fft_thread.daemon = True _freeze_fft_thread.start() _freeze_scope_thread = threading.Thread( @@ -338,11 +357,11 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): self.display_layout_phase.addLayout(self.display_grid_layout_phase) self.display.addTab(self.display_widget_phase, "Rel. Phase") self.qtgui_phase_plot = qtgui.time_sink_f( - 1024, #size - self.samp_rate, #samp_rate - "", #name + 1024, # size + self.samp_rate, # samp_rate + "", # name len(self.channels) - 1, - None # parent + None # parent ) self.qtgui_phase_plot.set_update_time(self.update_rate) self.qtgui_phase_plot.set_y_axis(-3.5, 3.5) @@ -356,7 +375,7 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): self.qtgui_phase_plot.disable_legend() for i in range(len(self.channels) - 1): self.qtgui_phase_plot.set_line_label( - i, "Phase Delta Channels {0}/{1}".format(i, i+1)) + i, "Phase Delta Channels {0}/{1}".format(i, i + 1)) self.qtgui_phase_plot.set_line_width(i, widths[i]) self.qtgui_phase_plot.set_line_color(i, colors[i]) self.qtgui_phase_plot.set_line_style(i, styles[i]) @@ -364,14 +383,17 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): self.qtgui_phase_plot.set_line_alpha(i, alphas[i]) self._qtgui_phase_plot_win = sip.wrapinstance( self.qtgui_phase_plot.qwidget(), Qt.QWidget) - self.display_grid_layout_phase.addWidget(self._qtgui_phase_plot_win, 0, 0, 1, 4) + self.display_grid_layout_phase.addWidget( + self._qtgui_phase_plot_win, 0, 0, 1, 4) ### Other widgets ################################################### self._lo_locked_probe_tool_bar = Qt.QToolBar(self) - self._lo_locked_probe_formatter = lambda x: {True: 'Yes', False: 'No'}[x] + self._lo_locked_probe_formatter = lambda x: { + True: 'Yes', False: 'No'}[x] if self.has_lo_sensor: self._lo_locked_probe_tool_bar.addWidget(Qt.QLabel("LO locked: ")) self._lo_locked_probe_label = Qt.QLabel( str(self._lo_locked_probe_formatter(self.lo_locked_probe))) + def _chan0_lo_locked_probe(): while self.has_lo_sensor: self.chan0_lo_locked = self.usrp.get_sensor('lo_locked') @@ -382,14 +404,18 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): except AttributeError: pass time.sleep(1.0 / (10)) - _chan0_lo_locked_thread = threading.Thread(target=_chan0_lo_locked_probe) + _chan0_lo_locked_thread = threading.Thread( + target=_chan0_lo_locked_probe) _chan0_lo_locked_thread.daemon = True _chan0_lo_locked_thread.start() else: - self._lo_locked_probe_tool_bar.addWidget(Qt.QLabel("No LO lock sensor available.")) + self._lo_locked_probe_tool_bar.addWidget( + Qt.QLabel("No LO lock sensor available.")) self._lo_locked_probe_label = Qt.QLabel("") self._lo_locked_probe_tool_bar.addWidget(self._lo_locked_probe_label) - self.top_grid_layout.addWidget(self._lo_locked_probe_tool_bar, 4, 0, 1, 2) + self.top_grid_layout.addWidget( + self._lo_locked_probe_tool_bar, 4, 0, 1, 2) + def _current_freq_probe(): while True: val = self.usrp.get_center_freq(0) @@ -437,19 +463,21 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): else: self.connect((self.usrp, idx), (self.qtgui_freq_sink_x_0, idx)) self.connect((self.usrp, idx), (self.qtgui_time_sink_x_0, idx)) - self.connect((self.usrp, idx), (self.qtgui_waterfall_sink_x_0, idx)) + self.connect((self.usrp, idx), + (self.qtgui_waterfall_sink_x_0, idx)) if args.phase_relations and len(self.channels) > 1: for idx in range(len(self.channels[:-1])): self.connect_phase_plot( (self.usrp, idx), - (self.usrp, idx+1), + (self.usrp, idx + 1), (self.qtgui_phase_plot, idx) ) def connect_phase_plot(self, src_port1, src_port2, dst_port): " Calculate relative phase between two src ports and send it dst_port " multiplier = blocks.multiply_cc() - self.connect(src_port1, (multiplier, 0), blocks.complex_to_arg(), dst_port) + self.connect(src_port1, (multiplier, 0), + blocks.complex_to_arg(), dst_port) self.connect(src_port2, blocks.conjugate_cc(), (multiplier, 1)) # This is a Qt name: @@ -484,9 +512,11 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): self._freq_line_edit, "setText", Qt.Q_ARG("QString", eng_notation.num_to_str(self.freq)) ) - self.qtgui_waterfall_sink_x_0.set_frequency_range(self.freq, self.samp_rate) + self.qtgui_waterfall_sink_x_0.set_frequency_range( + self.freq, self.samp_rate) if tune_source != 'freqsink_msg': - self.qtgui_freq_sink_x_0.set_frequency_range(self.freq, self.samp_rate) + self.qtgui_freq_sink_x_0.set_frequency_range( + self.freq, self.samp_rate) if self.gain_type == self.GAIN_TYPE_POWER: self.gain = self.get_gain_or_power() self._gain__win.d_widget.setValue(self.gain) @@ -501,7 +531,8 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): ) self.qtgui_freq_sink_x_0.set_frequency_range(self.freq, self.samp_rate) self.qtgui_time_sink_x_0.set_samp_rate(self.samp_rate) - self.qtgui_waterfall_sink_x_0.set_frequency_range(self.freq, self.samp_rate) + self.qtgui_waterfall_sink_x_0.set_frequency_range( + self.freq, self.samp_rate) self.usrp.set_samp_rate(self.samp_rate) for c in range(len(self.channels)): self.usrp.set_bandwidth(self.samp_rate + abs(self.lo_offset), c) @@ -541,7 +572,7 @@ class uhd_fft(UHDApp, gr.top_block, Qt.QWidget): Return the input to the power scaler as a function of the current power reference level. """ - return 10**(self.gain/20) + return 10**(self.gain / 20) def setup_argparser(): @@ -560,7 +591,8 @@ def setup_argparser(): group.add_argument("--avg-alpha", type=float, default=None, help="Specify FFT average alpha (overrides --fft-average)") group.add_argument("--update-rate", dest="update_rate", - type=eng_arg.eng_float, default=eng_notation.num_to_str(.1), + type=eng_arg.eng_float, default=eng_notation.num_to_str( + .1), help="Set GUI widget update period in seconds") group.add_argument("--phase-relations", action="store_true", help="Plot relative phases between multiple channels") @@ -578,6 +610,7 @@ def main(): top_block.show() # Make sure SIGINT/SIGTERM handling is enabled # pylint: disable=unused-argument + def sig_handler(sig=None, frame=None): top_block.stop() top_block.wait() @@ -589,5 +622,6 @@ def main(): timer.timeout.connect(lambda: None) qapp.exec_() + if __name__ == '__main__': main() diff --git a/gr-uhd/apps/uhd_rx_cfile b/gr-uhd/apps/uhd_rx_cfile index 2ed83c47f0c..b6dbb15ccd4 100755 --- a/gr-uhd/apps/uhd_rx_cfile +++ b/gr-uhd/apps/uhd_rx_cfile @@ -27,26 +27,31 @@ from optparse import OptionParser n2s = eng_notation.num_to_str COMMAND_DELAY = .2 + class rx_cfile_block(gr.top_block): """ Simple flowgraph that streams from USRP source to file. """ + def __init__(self, options, filename): gr.top_block.__init__(self) # Dissect the channel list: try: - self.channels = [int(x.strip()) for x in options.channels.split(",")] + self.channels = [int(x.strip()) + for x in options.channels.split(",")] except ValueError: - sys.stderr.write("[UHD_RX] [ERROR] Invalid channel list: {}".format(options.channels)) + sys.stderr.write( + "[UHD_RX] [ERROR] Invalid channel list: {}".format(options.channels)) exit(1) # Create file names: if len(self.channels) == 1: - self.filenames = [filename,] + self.filenames = [filename, ] else: base, ext = os.path.splitext(filename) self.filenames = [] for i in range(len(self.channels)): - self.filenames.append("{base}.{num}{ext}".format(base=base, num=i, ext=ext)) + self.filenames.append( + "{base}.{num}{ext}".format(base=base, num=i, ext=ext)) # Check CPU format: self.cpu_format = 'fc32' self.item_size = gr.sizeof_gr_complex @@ -78,7 +83,7 @@ class rx_cfile_block(gr.top_block): )) exit(1) if len(self.antenna) == 1 and len(self.channels) > 1: - self.antenna = [self.antenna[0],] * len(self.channels) + self.antenna = [self.antenna[0], ] * len(self.channels) for i, chan in enumerate(self.channels): self._u.set_antenna(self.antenna[i], chan) if options.verbose: @@ -93,7 +98,8 @@ class rx_cfile_block(gr.top_block): print("[UHD_RX] Defaulting to mid-point gains:") for chan in self.channels: self._u.set_normalized_gain(.5, chan) - print("[UHD_RX] Channel {chan} gain: {g} dB".format(chan=chan, g=self._u.get_gain(chan))) + print("[UHD_RX] Channel {chan} gain: {g} dB".format( + chan=chan, g=self._u.get_gain(chan))) else: for chan in self.channels: if options.normalized_gain: @@ -117,11 +123,13 @@ class rx_cfile_block(gr.top_block): self._u.set_command_time(cmd_time, mb_idx) command_time_set = True except RuntimeError: - sys.stderr.write('[UHD_RX] [WARNING] Failed to set command times.\n') + sys.stderr.write( + '[UHD_RX] [WARNING] Failed to set command times.\n') for chan in self.channels: tr = self._u.set_center_freq(treq, chan) if tr == None: - sys.stderr.write('[UHD_RX] [ERROR] Failed to set center frequency on channel {chan}\n'.format(chan=chan)) + sys.stderr.write( + '[UHD_RX] [ERROR] Failed to set center frequency on channel {chan}\n'.format(chan=chan)) exit(1) if command_time_set: for mb_idx in range(self._u.get_num_mboards()): @@ -135,16 +143,18 @@ class rx_cfile_block(gr.top_block): if options.metafile: # store additional metadata extras = pmt.make_dict() - extras = pmt.dict_add(extras, pmt.intern("rx_gain"), pmt.from_double(gain)) + extras = pmt.dict_add(extras, pmt.intern( + "rx_gain"), pmt.from_double(gain)) extras_str = pmt.serialize_str(extras) self._sink.append(blocks.file_meta_sink( - self.item_size, self.filenames[i], - samp_rate, 1, - self.meta_file_type, True, - 1000000, extras_str, False + self.item_size, self.filenames[i], + samp_rate, 1, + self.meta_file_type, True, + 1000000, extras_str, False )) else: - self._sink.append(blocks.file_sink(self.item_size, self.filenames[i])) + self._sink.append(blocks.file_sink( + self.item_size, self.filenames[i])) # Create head block if needed and wire it up: if options.nsamples is None: self.connect((self._u, i), self._sink[i]) @@ -167,40 +177,51 @@ class rx_cfile_block(gr.top_block): rx_serial = info["rx_serial"] rx_antenna = info["rx_antenna"] rx_subdev_spec = info["rx_subdev_spec"] - print("[UHD_RX] Motherboard: %s (%s)" % (mboard_id, mboard_serial)) + print("[UHD_RX] Motherboard: %s (%s)" % + (mboard_id, mboard_serial)) if "B200" in mboard_id or "B210" in mboard_id or "E310" in mboard_id: - print("[UHD_RX] Daughterboard: %s (%s, %s)" % (mboard_id, rx_antenna, rx_subdev_spec)) + print("[UHD_RX] Daughterboard: %s (%s, %s)" % + (mboard_id, rx_antenna, rx_subdev_spec)) else: - print("[UHD_RX] Daughterboard: %s (%s, %s, %s)" % (rx_id, rx_serial, rx_antenna, rx_subdev_spec)) + print("[UHD_RX] Daughterboard: %s (%s, %s, %s)" % + (rx_id, rx_serial, rx_antenna, rx_subdev_spec)) except KeyError: print("[UHD_RX] Args: ", options.args) print("[UHD_RX] Receiving on {} channels.".format(len(self.channels))) print("[UHD_RX] Rx gain: {gain}".format(gain=gain)) print("[UHD_RX] Rx frequency: {freq}".format(freq=freq)) - print("[UHD_RX] Rx baseband frequency: {actual}".format(actual=n2s(tr.actual_rf_freq))) - print("[UHD_RX] Rx DDC frequency: {dsp}".format(dsp=n2s(tr.actual_dsp_freq))) - print("[UHD_RX] Rx Sample Rate: {rate}".format(rate=n2s(samp_rate))) + print("[UHD_RX] Rx baseband frequency: {actual}".format( + actual=n2s(tr.actual_rf_freq))) + print("[UHD_RX] Rx DDC frequency: {dsp}".format( + dsp=n2s(tr.actual_dsp_freq))) + print("[UHD_RX] Rx Sample Rate: {rate}".format( + rate=n2s(samp_rate))) if options.nsamples is None: print("[UHD_RX] Receiving samples until Ctrl-C") else: - print("[UHD_RX] Receiving {n} samples.".format(n=n2s(options.nsamples))) + print("[UHD_RX] Receiving {n} samples.".format( + n=n2s(options.nsamples))) if options.output_shorts: print("[UHD_RX] Writing 16-bit complex shorts") else: print("[UHD_RX] Writing 32-bit complex floats") - print("[UHD_RX] Output file(s): {files}".format(files=", ".join(self.filenames))) + print("[UHD_RX] Output file(s): {files}".format( + files=", ".join(self.filenames))) # Direct asynchronous notifications to callback function: if options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) - self.async_rcv = uhd.msgq_runner(self.async_msgq, self.async_callback) + self.async_rcv = uhd.msgq_runner( + self.async_msgq, self.async_callback) def async_callback(self, msg): md = self.async_src.msg_to_async_metadata_t(msg) - print("[UHD_RX] Channel: %i Time: %f Event: %i" % (md.channel, md.time_spec.get_real_secs(), md.event_code)) + print("[UHD_RX] Channel: %i Time: %f Event: %i" % + (md.channel, md.time_spec.get_real_secs(), md.event_code)) + def get_options(): - usage="%prog: [options] output_filename" + usage = "%prog: [options] output_filename" parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args , [default=%default]") @@ -220,9 +241,9 @@ def get_options(): help="Set gain in dB (default is midpoint)") parser.add_option("--normalized-gain", action="store_true", help="Specify gain as normalized value (in [0, 1])") - parser.add_option( "-m","--metafile", action="store_true", default=False, + parser.add_option("-m", "--metafile", action="store_true", default=False, help="output metadata to file [default=%default]") - parser.add_option( "-s","--output-shorts", action="store_true", default=False, + parser.add_option("-s", "--output-shorts", action="store_true", default=False, help="Output interleaved shorts instead of complex floats") parser.add_option("-N", "--nsamples", type="eng_float", default=None, help="Number of samples to collect [default=+inf]") @@ -246,6 +267,7 @@ def get_options(): exit(1) return (options, args[0]) + if __name__ == '__main__': (options, filename) = get_options() tb = rx_cfile_block(options, filename) diff --git a/gr-uhd/apps/uhd_rx_nogui b/gr-uhd/apps/uhd_rx_nogui index 06bce7ea7f5..e091df1327d 100755 --- a/gr-uhd/apps/uhd_rx_nogui +++ b/gr-uhd/apps/uhd_rx_nogui @@ -60,10 +60,11 @@ from gnuradio.eng_option import eng_option # (device_rate, channel_rate, audio_rate, channel_pass, channel_stop, demod) DEMOD_PARAMS = { - 'AM' : (256000, 16000, 16000, 5000, 8000, analog.demod_10k0a3e_cf), - 'FM' : (256000, 32000, 8000, 8000, 9000, analog.demod_20k0f3e_cf), - 'WFM' : (320000, 320000, 32000, 80000, 115000, analog.demod_200kf3e_cf) - } + 'AM': (256000, 16000, 16000, 5000, 8000, analog.demod_10k0a3e_cf), + 'FM': (256000, 32000, 8000, 8000, 9000, analog.demod_20k0f3e_cf), + 'WFM': (320000, 320000, 32000, 80000, 115000, analog.demod_200kf3e_cf) +} + class uhd_src(gr.hier_block2): """ @@ -74,14 +75,16 @@ class uhd_src(gr.hier_block2): Calibration value is the offset from the tuned frequency to the actual frequency. """ + def __init__(self, args, spec, antenna, samp_rate, gain=None, calibration=0.0): gr.hier_block2.__init__( self, "uhd_src", gr.io_signature(0, 0, 0), # Input signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._src = \ - uhd.usrp_source(device_addr=args, stream_args=uhd.stream_args('fc32')) + uhd.usrp_source(device_addr=args, + stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if spec: @@ -102,7 +105,7 @@ class uhd_src(gr.hier_block2): # If no gain specified, set to midrange gain_range = self._src.get_gain_range() if gain is None: - gain = (gain_range.start()+gain_range.stop())/2.0 + gain = (gain_range.start() + gain_range.stop()) / 2.0 print("Using gain: ", gain) self._src.set_gain(gain) @@ -117,6 +120,7 @@ class uhd_src(gr.hier_block2): """ Set sampling rate """ return self._samp_rate + class app_top_block(gr.top_block): def __init__(self, options): gr.top_block.__init__(self) @@ -139,24 +143,24 @@ class app_top_block(gr.top_block): chan_taps = filter.optfir.low_pass(1.0, # Filter gain if_rate, # Sample rate - channel_pass, # One sided modulation bandwidth - channel_stop, # One sided channel bandwidth + channel_pass, # One sided modulation bandwidth + channel_stop, # One sided channel bandwidth 0.1, # Passband ripple 60) # Stopband attenuation chan = filter.freq_xlating_fir_filter_ccf( - channel_decim, # Decimation rate + channel_decim, # Decimation rate chan_taps, # Filter taps 0.0, # Offset frequency if_rate) # Sample rate rfsql = analog.pwr_squelch_cc( options.rf_squelch, # Power threshold - 125.0/channel_rate, # Time constant - int(channel_rate/20), # 50ms rise/fall + 125.0 / channel_rate, # Time constant + int(channel_rate / 20), # 50ms rise/fall False) # Zero, not gate output - agc = analog.agc_cc(1.0/channel_rate, # Time constant + agc = analog.agc_cc(1.0 / channel_rate, # Time constant 1.0, # Reference power 1.0) # Gain @@ -170,7 +174,7 @@ class app_top_block(gr.top_block): tail = demod if options.ctcss != None and options.ctcss > 60.0: ctcss = analog.ctcss_squelch_ff(audio_rate, # Sample rate - options.ctcss) # Squelch tone + options.ctcss) # Squelch tone self.connect(demod, ctcss) tail = ctcss @@ -191,7 +195,8 @@ class app_top_block(gr.top_block): if self.options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) - self.async_rcv = uhd.msgq_runner(self.async_msgq, self.async_callback) + self.async_rcv = uhd.msgq_runner( + self.async_msgq, self.async_callback) def async_callback(self, msg): """ Callback for processing async messages """ @@ -252,5 +257,6 @@ def main(): except KeyboardInterrupt: pass + if __name__ == "__main__": main() diff --git a/gr-uhd/apps/uhd_siggen_base.py b/gr-uhd/apps/uhd_siggen_base.py index daf8184f564..8d1b37012c4 100644 --- a/gr-uhd/apps/uhd_siggen_base.py +++ b/gr-uhd/apps/uhd_siggen_base.py @@ -41,14 +41,15 @@ TYPE_KEY = 'type' WAVEFORMS = { - analog.GR_CONST_WAVE : "Constant", - analog.GR_SIN_WAVE : "Complex Sinusoid", - analog.GR_GAUSSIAN : "Gaussian Noise", - analog.GR_UNIFORM : "Uniform Noise", - "2tone" : "Two Tone", - "sweep" : "Sweep", + analog.GR_CONST_WAVE: "Constant", + analog.GR_SIN_WAVE: "Complex Sinusoid", + analog.GR_GAUSSIAN: "Gaussian Noise", + analog.GR_UNIFORM: "Uniform Noise", + "2tone": "Two Tone", + "sweep": "Sweep", } + class USRPSiggen(gr.top_block, pubsub, UHDApp): """ GUI-unaware GNU Radio flowgraph. This may be used either with command @@ -87,15 +88,18 @@ def __init__(self, args): args=args, ) print("[UHD-SIGGEN] UHD Signal Generator") - print("[UHD-SIGGEN] UHD Version: {ver}".format(ver=uhd.get_version_string())) + print( + "[UHD-SIGGEN] UHD Version: {ver}".format(ver=uhd.get_version_string())) print("[UHD-SIGGEN] Using USRP configuration:") print(self.get_usrp_info_string(tx_or_rx="tx")) - self.usrp_description = self.get_usrp_info_string(tx_or_rx="tx", compact=True) + self.usrp_description = self.get_usrp_info_string( + tx_or_rx="tx", compact=True) - ### Set subscribers and publishers: + # Set subscribers and publishers: self.publish(SAMP_RATE_KEY, lambda: self.usrp.get_samp_rate()) self.publish(DESC_KEY, lambda: self.usrp_description) - self.publish(FREQ_RANGE_KEY, lambda: self.usrp.get_freq_range(self.channels[0])) + self.publish(FREQ_RANGE_KEY, + lambda: self.usrp.get_freq_range(self.channels[0])) self.publish(GAIN_KEY, lambda: self.get_gain_or_power()) self[SAMP_RATE_KEY] = args.samp_rate @@ -107,7 +111,7 @@ def __init__(self, args): self[DSP_FREQ_KEY] = 0 self[RF_FREQ_KEY] = 0 - #subscribe set methods + # subscribe set methods self.subscribe(SAMP_RATE_KEY, self.set_samp_rate) self.subscribe(GAIN_KEY, self.set_gain_or_power) self.subscribe(TX_FREQ_KEY, self.set_freq) @@ -117,18 +121,19 @@ def __init__(self, args): self.subscribe(TYPE_KEY, self.set_waveform) self.subscribe(RF_FREQ_KEY, self.update_gain_range) - #force update on pubsub keys + # force update on pubsub keys for key in (SAMP_RATE_KEY, GAIN_KEY, TX_FREQ_KEY, AMPLITUDE_KEY, WAVEFORM_FREQ_KEY, WAVEFORM_OFFSET_KEY, WAVEFORM2_FREQ_KEY): self[key] = self[key] - self[TYPE_KEY] = args.type #set type last + self[TYPE_KEY] = args.type # set type last def set_samp_rate(self, samp_rate): """ When sampling rate is updated, also update the signal sources. """ - self.vprint("Setting sampling rate to: {rate} Msps".format(rate=samp_rate / 1e6)) + self.vprint("Setting sampling rate to: {rate} Msps".format( + rate=samp_rate / 1e6)) self.usrp.set_samp_rate(samp_rate) samp_rate = self.usrp.get_samp_rate() if self[TYPE_KEY] in (analog.GR_SIN_WAVE, analog.GR_CONST_WAVE): @@ -138,10 +143,12 @@ def set_samp_rate(self, samp_rate): self._src2.set_sampling_freq(self[SAMP_RATE_KEY]) elif self[TYPE_KEY] == "sweep": self._src1.set_sampling_freq(self[SAMP_RATE_KEY]) - self._src2.set_sampling_freq(self[WAVEFORM_FREQ_KEY]*2*math.pi/self[SAMP_RATE_KEY]) + self._src2.set_sampling_freq( + self[WAVEFORM_FREQ_KEY] * 2 * math.pi / self[SAMP_RATE_KEY]) else: - return True # Waveform not yet set - self.vprint("Set sample rate to: {rate} Msps".format(rate=samp_rate / 1e6)) + return True # Waveform not yet set + self.vprint("Set sample rate to: {rate} Msps".format( + rate=samp_rate / 1e6)) return True def set_waveform_freq(self, freq): @@ -151,7 +158,7 @@ def set_waveform_freq(self, freq): elif self[TYPE_KEY] == "2tone": self._src1.set_frequency(freq) elif self[TYPE_KEY] == 'sweep': - #there is no set sensitivity, redo fg + # there is no set sensitivity, redo fg self[TYPE_KEY] = self[TYPE_KEY] return True @@ -178,11 +185,14 @@ def set_waveform(self, waveform_type): if waveform_type in (analog.GR_SIN_WAVE, analog.GR_CONST_WAVE): self._src = analog.sig_source_c(self[SAMP_RATE_KEY], # Sample rate waveform_type, # Waveform waveform_type - self[WAVEFORM_FREQ_KEY], # Waveform frequency - self[AMPLITUDE_KEY], # Waveform amplitude - self[WAVEFORM_OFFSET_KEY]) # Waveform offset + # Waveform frequency + self[WAVEFORM_FREQ_KEY], + # Waveform amplitude + self[AMPLITUDE_KEY], + self[WAVEFORM_OFFSET_KEY]) # Waveform offset elif waveform_type in (analog.GR_GAUSSIAN, analog.GR_UNIFORM): - self._src = analog.noise_source_c(waveform_type, self[AMPLITUDE_KEY]) + self._src = analog.noise_source_c( + waveform_type, self[AMPLITUDE_KEY]) elif waveform_type == "2tone": self._src1 = analog.sig_source_c(self[SAMP_RATE_KEY], analog.GR_SIN_WAVE, @@ -211,7 +221,8 @@ def set_waveform(self, waveform_type): self[WAVEFORM2_FREQ_KEY], 1.0, -0.5) - self._src2 = analog.frequency_modulator_fc(self[WAVEFORM_FREQ_KEY]*2*math.pi/self[SAMP_RATE_KEY]) + self._src2 = analog.frequency_modulator_fc( + self[WAVEFORM_FREQ_KEY] * 2 * math.pi / self[SAMP_RATE_KEY]) self._src = blocks.multiply_const_cc(self[AMPLITUDE_KEY]) self.connect(self._src1, self._src2, self._src) else: @@ -224,7 +235,8 @@ def set_waveform(self, waveform_type): self.vprint("Set baseband modulation to:", WAVEFORMS[waveform_type]) n2s = eng_notation.num_to_str if waveform_type == analog.GR_SIN_WAVE: - self.vprint("Modulation frequency: %sHz" % (n2s(self[WAVEFORM_FREQ_KEY]),)) + self.vprint("Modulation frequency: %sHz" % + (n2s(self[WAVEFORM_FREQ_KEY]),)) self.vprint("Initial phase:", self[WAVEFORM_OFFSET_KEY]) elif waveform_type == "2tone": self.vprint("Tone 1: %sHz" % (n2s(self[WAVEFORM_FREQ_KEY]),)) @@ -250,7 +262,7 @@ def set_amplitude(self, amplitude): elif self[TYPE_KEY] == "sweep": self._src.set_k(amplitude) else: - return True # Waveform not yet set + return True # Waveform not yet set self.vprint("Set amplitude to:", amplitude) self.update_gain_range() return True @@ -262,7 +274,7 @@ def get_gain_or_power(self): if self.gain_type == self.GAIN_TYPE_GAIN: return self.usrp.get_gain(self.channels[0]) return self.usrp.get_power_reference(self.channels[0]) \ - + 20 * math.log10(self[AMPLITUDE_KEY]) + + 20 * math.log10(self[AMPLITUDE_KEY]) def set_gain_or_power(self, gain_or_power): """ @@ -333,6 +345,7 @@ def setup_argparser(): help="Generate a swept sine wave") return parser + def main(): " Go, go, go! " if gr.enable_realtime_scheduling() != gr.RT_OK: @@ -350,5 +363,6 @@ def main(): tb.stop() tb.wait() + if __name__ == "__main__": main() diff --git a/gr-uhd/apps/uhd_siggen_gui b/gr-uhd/apps/uhd_siggen_gui index 191837ff27a..0d9cb56c28c 100755 --- a/gr-uhd/apps/uhd_siggen_gui +++ b/gr-uhd/apps/uhd_siggen_gui @@ -39,7 +39,7 @@ import time import math from PyQt5 import Qt from PyQt5.QtCore import pyqtSlot -import sip # Needs to be imported after PyQt5, could fail otherwise +import sip # Needs to be imported after PyQt5, could fail otherwise from gnuradio import analog from gnuradio import eng_notation from gnuradio import qtgui @@ -59,6 +59,7 @@ class uhd_siggen_gui(Qt.QWidget): """ Signal Generator Flowgraph """ + def __init__(self, args): ################################################## # Set up the siggen app @@ -94,14 +95,16 @@ class uhd_siggen_gui(Qt.QWidget): ################################################## # Widgets + Controls ################################################## - ### Waveform Selector + # Waveform Selector self._waveform_options = list(uhd_siggen.WAVEFORMS.keys()) self._waveform_labels = list(uhd_siggen.WAVEFORMS.values()) self._waveform_group_box = Qt.QGroupBox("Waveform") self._waveform_box = Qt.QHBoxLayout() + class variable_chooser_button_group(Qt.QButtonGroup): def __init__(self, parent=None): Qt.QButtonGroup.__init__(self, parent) + @pyqtSlot(int) def updateButtonChecked(self, button_id): self.button(button_id).setChecked(True) @@ -121,14 +124,14 @@ class uhd_siggen_gui(Qt.QWidget): lambda i: self.set_waveform(self._waveform_options[i]) ) self.top_grid_layout.addWidget(self._waveform_group_box, 0, 0, 1, 5) - ### Center Frequency Sliders + # Center Frequency Sliders self.freq_coarse = self._sg.usrp.get_center_freq(self._sg.channels[0]) self._freq_coarse_range = Range( self.usrp.get_freq_range(self._sg.channels[0]).start(), self.usrp.get_freq_range(self._sg.channels[0]).stop(), - 1e3, # Step + 1e3, # Step self.freq_coarse, - 200, # Min Width + 200, # Min Width ) self._freq_coarse_win = RangeWidget( self._freq_coarse_range, @@ -154,8 +157,8 @@ class uhd_siggen_gui(Qt.QWidget): self.top_grid_layout.addWidget(self._freq_fine_win, 2, 0, 1, 5) self.lo_offset = self._sg.args.lo_offset self._lo_offset_range = Range( - -self._sg[uhd_siggen.SAMP_RATE_KEY]/2, - self._sg[uhd_siggen.SAMP_RATE_KEY]/2, + -self._sg[uhd_siggen.SAMP_RATE_KEY] / 2, + self._sg[uhd_siggen.SAMP_RATE_KEY] / 2, 1e3, self.lo_offset, 200 @@ -168,11 +171,11 @@ class uhd_siggen_gui(Qt.QWidget): float ) self.top_grid_layout.addWidget(self._lo_offset_win, 3, 0, 1, 5) - ### Signal frequencies + # Signal frequencies self._freq1_enable_on = (analog.GR_SIN_WAVE, "2tone", "sweep") self._freq1_offset_range = Range( - -self._sg[uhd_siggen.SAMP_RATE_KEY]/2, - self._sg[uhd_siggen.SAMP_RATE_KEY]/2, + -self._sg[uhd_siggen.SAMP_RATE_KEY] / 2, + self._sg[uhd_siggen.SAMP_RATE_KEY] / 2, 100, self._sg.args.waveform_freq, 200 @@ -184,12 +187,13 @@ class uhd_siggen_gui(Qt.QWidget): "counter_slider", float ) - self._freq1_offset_win.setEnabled(self._sg[uhd_siggen.TYPE_KEY] in self._freq1_enable_on) + self._freq1_offset_win.setEnabled( + self._sg[uhd_siggen.TYPE_KEY] in self._freq1_enable_on) self.top_grid_layout.addWidget(self._freq1_offset_win, 4, 0, 1, 3) self._freq2_enable_on = ("2tone", "sweep") self._freq2_offset_range = Range( - -self._sg[uhd_siggen.SAMP_RATE_KEY]/2, - self._sg[uhd_siggen.SAMP_RATE_KEY]/2, + -self._sg[uhd_siggen.SAMP_RATE_KEY] / 2, + self._sg[uhd_siggen.SAMP_RATE_KEY] / 2, 100, self._sg.args.waveform2_freq, 200 @@ -201,9 +205,10 @@ class uhd_siggen_gui(Qt.QWidget): "counter_slider", float ) - self._freq2_offset_win.setEnabled(self._sg[uhd_siggen.TYPE_KEY] in self._freq2_enable_on) + self._freq2_offset_win.setEnabled( + self._sg[uhd_siggen.TYPE_KEY] in self._freq2_enable_on) self.top_grid_layout.addWidget(self._freq2_offset_win, 4, 3, 1, 2) - ### Amplitude + # Amplitude min_ampl = \ self._sg.MIN_AMP_POWER_MODE \ if self._sg.gain_type == self._sg.GAIN_TYPE_POWER else 0 @@ -235,7 +240,7 @@ class uhd_siggen_gui(Qt.QWidget): float ) self.top_grid_layout.addWidget(self._gain_win, 6, 0, 1, 5) - ### Samp rate, LO sync, Antenna Select + # Samp rate, LO sync, Antenna Select self.samp_rate = self._sg[uhd_siggen.SAMP_RATE_KEY] self._samp_rate_tool_bar = Qt.QToolBar(self) self._samp_rate_tool_bar.addWidget(Qt.QLabel("Sampling Rate: ")) @@ -248,7 +253,8 @@ class uhd_siggen_gui(Qt.QWidget): ) self.top_grid_layout.addWidget(self._samp_rate_tool_bar, 7, 0, 1, 2) _sync_phases_push_button = Qt.QPushButton("Sync LOs") - _sync_phases_push_button.pressed.connect(lambda: self.set_sync_phases(True)) + _sync_phases_push_button.pressed.connect( + lambda: self.set_sync_phases(True)) _sync_phases_push_button.setEnabled(bool(len(self._sg.channels) > 1)) self.top_grid_layout.addWidget(_sync_phases_push_button, 7, 2, 1, 1) # Antenna Select @@ -272,8 +278,11 @@ class uhd_siggen_gui(Qt.QWidget): self._lo_locked_probe_0_formatter = lambda x: x self._lo_locked_probe_0_tool_bar.addWidget(Qt.QLabel("LO locked: ")) self._lo_locked_probe_0_label = Qt.QLabel(str(False)) - self._lo_locked_probe_0_tool_bar.addWidget(self._lo_locked_probe_0_label) - self.top_grid_layout.addWidget(self._lo_locked_probe_0_tool_bar, 8, 0, 1, 1) + self._lo_locked_probe_0_tool_bar.addWidget( + self._lo_locked_probe_0_label) + self.top_grid_layout.addWidget( + self._lo_locked_probe_0_tool_bar, 8, 0, 1, 1) + def _chan0_lo_locked_probe(): " Monitor lock status of LO on channel 0 " while True: @@ -285,7 +294,8 @@ class uhd_siggen_gui(Qt.QWidget): except: self.set_chan0_lo_locked("Lock Detect Failed!") time.sleep(.1) - _chan0_lo_locked_thread = threading.Thread(target=_chan0_lo_locked_probe) + _chan0_lo_locked_thread = threading.Thread( + target=_chan0_lo_locked_probe) _chan0_lo_locked_thread.daemon = True _chan0_lo_locked_thread.start() self.label_rf_freq = self._sg.tr.actual_rf_freq @@ -295,7 +305,8 @@ class uhd_siggen_gui(Qt.QWidget): self._label_rf_freq_label = \ Qt.QLabel(str(self._label_rf_freq_formatter(self.label_rf_freq))) self._label_rf_freq_tool_bar.addWidget(self._label_rf_freq_label) - self.top_grid_layout.addWidget(self._label_rf_freq_tool_bar, 8, 1, 1, 1) + self.top_grid_layout.addWidget( + self._label_rf_freq_tool_bar, 8, 1, 1, 1) self.label_dsp_freq = self._sg.tr.actual_dsp_freq self._label_dsp_freq_tool_bar = Qt.QToolBar(self) self._label_dsp_freq_formatter = lambda x: x @@ -303,22 +314,24 @@ class uhd_siggen_gui(Qt.QWidget): self._label_dsp_freq_label = \ Qt.QLabel(str(self._label_dsp_freq_formatter(self.label_dsp_freq))) self._label_dsp_freq_tool_bar.addWidget(self._label_dsp_freq_label) - self.top_grid_layout.addWidget(self._label_dsp_freq_tool_bar, 8, 2, 1, 1) + self.top_grid_layout.addWidget( + self._label_dsp_freq_tool_bar, 8, 2, 1, 1) ################################################## # Freq Sink ################################################## if self._sg.args.show_freq_sink: self.qtgui_freq_sink_x_0 = qtgui.freq_sink_c( - 1024, #size - fft.window.WIN_BLACKMAN_hARRIS, #wintype - self.freq_coarse + self.freq_fine, #fc - self.samp_rate, #bw - "", #name - 1 #number of inputs + 1024, # size + fft.window.WIN_BLACKMAN_hARRIS, # wintype + self.freq_coarse + self.freq_fine, # fc + self.samp_rate, # bw + "", # name + 1 # number of inputs ) self.qtgui_freq_sink_x_0.set_update_time(0.10) self.qtgui_freq_sink_x_0.set_y_axis(-100, 10) - self.qtgui_freq_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, 0.0, 0, "") + self.qtgui_freq_sink_x_0.set_trigger_mode( + qtgui.TRIG_MODE_FREE, 0.0, 0, "") self.qtgui_freq_sink_x_0.enable_autoscale(False) self.qtgui_freq_sink_x_0.enable_grid(False) self.qtgui_freq_sink_x_0.set_fft_average(1.0) @@ -327,8 +340,10 @@ class uhd_siggen_gui(Qt.QWidget): self.qtgui_freq_sink_x_0.set_line_width(0, 1) self.qtgui_freq_sink_x_0.set_line_color(0, "blue") self.qtgui_freq_sink_x_0.set_line_alpha(0, 1.0) - self._qtgui_freq_sink_x_0_win = sip.wrapinstance(self.qtgui_freq_sink_x_0.qwidget(), Qt.QWidget) - self.top_grid_layout.addWidget(self._qtgui_freq_sink_x_0_win, 9, 0, 2, 5) + self._qtgui_freq_sink_x_0_win = sip.wrapinstance( + self.qtgui_freq_sink_x_0.qwidget(), Qt.QWidget) + self.top_grid_layout.addWidget( + self._qtgui_freq_sink_x_0_win, 9, 0, 2, 5) # Reconnect: self._sg.extra_sink = self.qtgui_freq_sink_x_0 self._sg[uhd_siggen.TYPE_KEY] = self._sg[uhd_siggen.TYPE_KEY] @@ -435,7 +450,8 @@ class uhd_siggen_gui(Qt.QWidget): def set_sync_phases(self, sync): """ Execute when the sync-phases button is pushed """ if sync: - self._sg.vprint("Attempting to sync LO phases. This does not work with all boards.") + self._sg.vprint( + "Attempting to sync LO phases. This does not work with all boards.") self._sg.set_freq(self.freq_coarse + self.freq_fine, False) def set_ant(self, ant): @@ -484,6 +500,7 @@ class uhd_siggen_gui(Qt.QWidget): Qt.Q_ARG("QString", str(chan0_lo_locked)) ) + def setup_parser(): """ Argument parser for siggen_gui @@ -496,6 +513,7 @@ def setup_parser(): ) return parser + def main(): """ Go, go, go! """ parser = setup_parser() @@ -504,6 +522,7 @@ def main(): siggen_gui = uhd_siggen_gui(args) siggen_gui.show() # pylint: disable=unused-argument + def sig_handler(sig=None, frame=None): siggen_gui.stop() Qt.QApplication.quit() @@ -514,5 +533,6 @@ def main(): timer.timeout.connect(lambda: None) qapp.exec_() + if __name__ == '__main__': main() diff --git a/gr-uhd/examples/python/freq_hopping.py b/gr-uhd/examples/python/freq_hopping.py index 8fd65aade89..871181e045d 100755 --- a/gr-uhd/examples/python/freq_hopping.py +++ b/gr-uhd/examples/python/freq_hopping.py @@ -19,6 +19,7 @@ from gnuradio import blocks from gnuradio import uhd + def setup_parser(): """ Setup the parser for the frequency hopper. """ parser = argparse.ArgumentParser( @@ -77,31 +78,34 @@ def setup_parser(): class FrequencyHopperSrc(gr.hier_block2): """ Provides tags for frequency hopping """ + def __init__( - self, - n_bursts, n_channels, - freq_delta, base_freq, dsp_tuning, - burst_length, base_time, hop_time, - post_tuning=False, - tx_gain=0, - verbose=False - ): + self, + n_bursts, n_channels, + freq_delta, base_freq, dsp_tuning, + burst_length, base_time, hop_time, + post_tuning=False, + tx_gain=0, + verbose=False + ): gr.hier_block2.__init__( self, "FrequencyHopperSrc", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_gr_complex), ) n_samples_total = n_bursts * burst_length - lowest_frequency = base_freq - numpy.floor(n_channels/2) * freq_delta - self.hop_sequence = [lowest_frequency + n * freq_delta for n in range(n_channels)] + lowest_frequency = base_freq - numpy.floor(n_channels / 2) * freq_delta + self.hop_sequence = [lowest_frequency + n * + freq_delta for n in range(n_channels)] numpy.random.shuffle(self.hop_sequence) # Repeat that: - self.hop_sequence = [self.hop_sequence[x % n_channels] for x in range(n_bursts)] + self.hop_sequence = [self.hop_sequence[x % n_channels] + for x in range(n_bursts)] if verbose: print("Hop Frequencies | Hop Pattern") print("=================|================================") for f in self.hop_sequence: - print("{:6.3f} MHz | ".format(f/1e6), end='') + print("{:6.3f} MHz | ".format(f / 1e6), end='') if n_channels < 50: print(" " * int((f - base_freq) / freq_delta) + "#") else: @@ -113,25 +117,28 @@ def __init__( gain_tag.offset = 0 gain_tag.key = pmt.string_to_symbol('tx_command') gain_tag.value = pmt.to_pmt({'gain': tx_gain}) - tag_list = [gain_tag,] + tag_list = [gain_tag, ] for i in range(len(self.hop_sequence)): time = pmt.cons( - pmt.from_uint64(int(base_time + i * hop_time+0.01)), - pmt.from_double((base_time + i * hop_time+0.01) % 1), + pmt.from_uint64(int(base_time + i * hop_time + 0.01)), + pmt.from_double((base_time + i * hop_time + 0.01) % 1), ) tune_tag = gr.tag_t() tune_tag.offset = i * burst_length # TODO dsp_tuning should also be able to do post_tuning if i > 0 and post_tuning and not dsp_tuning: - tune_tag.offset -= 1 # Move it to last sample of previous burst + tune_tag.offset -= 1 # Move it to last sample of previous burst if dsp_tuning: tune_tag.key = pmt.string_to_symbol('tx_command') - tune_tag.value = pmt.to_pmt({'lo_freq': base_freq, 'dsp_freq': base_freq - self.hop_sequence[i]}) - tune_tag.value = pmt.dict_add(tune_tag.value, pmt.intern("time"),time) + tune_tag.value = pmt.to_pmt( + {'lo_freq': base_freq, 'dsp_freq': base_freq - self.hop_sequence[i]}) + tune_tag.value = pmt.dict_add( + tune_tag.value, pmt.intern("time"), time) else: tune_tag.key = pmt.string_to_symbol('tx_command') tune_tag.value = pmt.to_pmt({'freq': self.hop_sequence[i]}) - tune_tag.value = pmt.dict_add(tune_tag.value, pmt.intern('time'), time) + tune_tag.value = pmt.dict_add( + tune_tag.value, pmt.intern('time'), time) tag_list.append(tune_tag) length_tag = gr.tag_t() length_tag.offset = i * burst_length @@ -142,11 +149,12 @@ def __init__( time_tag.offset = i * burst_length time_tag.key = pmt.string_to_symbol('tx_time') time_tag.value = pmt.make_tuple( - pmt.car(time), - pmt.cdr(time) + pmt.car(time), + pmt.cdr(time) ) tag_list.append(time_tag) - tag_source = blocks.vector_source_c((1.0,) * n_samples_total, repeat=False, tags=tag_list) + tag_source = blocks.vector_source_c( + (1.0,) * n_samples_total, repeat=False, tags=tag_list) mult = blocks.multiply_cc() self.connect(self, mult, self) self.connect(tag_source, (mult, 1)) @@ -154,10 +162,12 @@ def __init__( class FlowGraph(gr.top_block): """ Flow graph that does the frequency hopping. """ + def __init__(self, args): gr.top_block.__init__(self) if args.input_file is not None: - src = blocks.file_source(gr.sizeof_gr_complex, args.input_file, repeat=True) + src = blocks.file_source( + gr.sizeof_gr_complex, args.input_file, repeat=True) else: src = blocks.vector_source_c((.5,) * int(1e6) * 2, repeat=True) # Setup USRP @@ -189,6 +199,7 @@ def __init__(self, args): ) self.connect(src, hopper_block, self.usrp) + def print_hopper_stats(args): """ Nothing to do with Grace Hopper """ print(""" @@ -205,14 +216,16 @@ def print_hopper_stats(args): ===================+========================= """.format( hop_time=args.hop_time, - hop_duration=1000.0/args.rate*args.samp_per_burst, + hop_duration=1000.0 / args.rate * args.samp_per_burst, gain=args.gain if args.gain else "(midpoint)", - lowest_freq=args.freq/1e6, - highest_freq=(args.freq + (args.num_channels-1) * args.freq_delta)/1e6, - freq_delta=args.freq_delta/1e6, + lowest_freq=args.freq / 1e6, + highest_freq=(args.freq + (args.num_channels - 1) * + args.freq_delta) / 1e6, + freq_delta=args.freq_delta / 1e6, num_channels=args.num_channels, - rate=args.rate/1e6, - )) + rate=args.rate / 1e6, + )) + def main(): """ Go, go, go! """ @@ -227,6 +240,7 @@ def main(): top_block.usrp.set_time_now(uhd.time_spec(0.0)) top_block.run() + if __name__ == '__main__': try: main() diff --git a/gr-uhd/grc/gen_uhd_usrp_blocks.py b/gr-uhd/grc/gen_uhd_usrp_blocks.py index 8c31038d072..371fe937ccc 100644 --- a/gr-uhd/grc/gen_uhd_usrp_blocks.py +++ b/gr-uhd/grc/gen_uhd_usrp_blocks.py @@ -594,14 +594,16 @@ ${'%'} endif """ + def parse_tmpl(_tmpl, **kwargs): """ Render _tmpl using the kwargs. """ from mako.template import Template block_template = Template(_tmpl) return str(block_template.render(**kwargs)) + MAX_NUM_MBOARDS = 8 -MAX_NUM_CHANNELS = MAX_NUM_MBOARDS*4 +MAX_NUM_CHANNELS = MAX_NUM_MBOARDS * 4 if __name__ == '__main__': for file in sys.argv[1:]: @@ -612,7 +614,7 @@ def parse_tmpl(_tmpl, **kwargs): sourk = 'sink' direction = 'in' else: - raise Exception('is % a source or sink?'%file) + raise Exception('is % a source or sink?' % file) params = ''.join([ parse_tmpl(PARAMS_TMPL, n=n, sourk=sourk) for n in range(MAX_NUM_CHANNELS) diff --git a/gr-uhd/python/uhd/__init__.py b/gr-uhd/python/uhd/__init__.py index 7c0f23dde1d..1ffa94e8212 100644 --- a/gr-uhd/python/uhd/__init__.py +++ b/gr-uhd/python/uhd/__init__.py @@ -16,6 +16,8 @@ ######################################################################## # Prepare uhd swig module to make it more pythonic ######################################################################## + + def _prepare_uhd_python(): try: from . import uhd_python @@ -25,45 +27,56 @@ def _prepare_uhd_python(): __path__.append(os.path.join(dirname, "bindings")) from . import uhd_python - #some useful typedefs for the user + # some useful typedefs for the user setattr(uhd_python, 'freq_range_t', uhd_python.meta_range_t) setattr(uhd_python, 'gain_range_t', uhd_python.meta_range_t) - #Make the python tune request object inherit from float - #so that it can be passed in GRC as a frequency parameter. - #The type checking in GRC will accept the tune request. - #Also use kwargs to construct individual struct elements. + # Make the python tune request object inherit from float + # so that it can be passed in GRC as a frequency parameter. + # The type checking in GRC will accept the tune request. + # Also use kwargs to construct individual struct elements. class tune_request_t(uhd_python.tune_request_t): # def __new__(self, *args, **kwargs): return float.__new__(self) def __float__(self): return self.target_freq + def __init__(self, *args, **kwargs): super().__init__(*args) - for key, val in list(kwargs.items()): setattr(self, key, val) + for key, val in list(kwargs.items()): + setattr(self, key, val) setattr(uhd_python, 'tune_request_t', tune_request_t) - #handle general things on all uhd_python attributes - #Install the __str__ and __repr__ handlers if applicable - #Create aliases for uhd swig attributes to avoid the "_t" + # handle general things on all uhd_python attributes + # Install the __str__ and __repr__ handlers if applicable + # Create aliases for uhd swig attributes to avoid the "_t" for attr in dir(uhd_python): myobj = getattr(uhd_python, attr) - if hasattr(myobj, 'to_string'): myobj.__repr__ = lambda o: o.to_string().strip() - if hasattr(myobj, 'to_pp_string'): myobj.__str__ = lambda o: o.to_pp_string().strip() - if hasattr(myobj, 'to_bool'): myobj.__nonzero__ = lambda o: o.to_bool() - if hasattr(myobj, 'to_int'): myobj.__int__ = lambda o: o.to_int() - if hasattr(myobj, 'to_real'): myobj.__float__ = lambda o: o.to_real() - if attr.endswith('_t'): setattr(uhd_python, attr[:-2], myobj) + if hasattr(myobj, 'to_string'): + myobj.__repr__ = lambda o: o.to_string().strip() + if hasattr(myobj, 'to_pp_string'): + myobj.__str__ = lambda o: o.to_pp_string().strip() + if hasattr(myobj, 'to_bool'): + myobj.__nonzero__ = lambda o: o.to_bool() + if hasattr(myobj, 'to_int'): + myobj.__int__ = lambda o: o.to_int() + if hasattr(myobj, 'to_real'): + myobj.__float__ = lambda o: o.to_real() + if attr.endswith('_t'): + setattr(uhd_python, attr[:-2], myobj) - #make a new find devices that casts everything with the pythonized device_addr_t which has __str__ + # make a new find devices that casts everything with the pythonized device_addr_t which has __str__ def find_devices(*args, **kwargs): def to_pythonized_dev_addr(dev_addr): new_dev_addr = uhd_python.device_addr_t() - for key in list(dev_addr.keys()): new_dev_addr[key] = dev_addr.get(key) + for key in list(dev_addr.keys()): + new_dev_addr[key] = dev_addr.get(key) return new_dev_addr return __builtins__['map'](to_pythonized_dev_addr, uhd_python.find_devices_raw(*args, **kwargs)) setattr(uhd_python, 'find_devices', find_devices) + ######################################################################## # Initialize this module with the contents of uhd pybind ######################################################################## _prepare_uhd_python() + from .uhd_python import * diff --git a/gr-uhd/python/uhd/qa_uhd.py b/gr-uhd/python/uhd/qa_uhd.py index 65b50d794b6..c8fb65c1445 100644 --- a/gr-uhd/python/uhd/qa_uhd.py +++ b/gr-uhd/python/uhd/qa_uhd.py @@ -12,6 +12,7 @@ from gnuradio import gr, gr_unittest, uhd + class test_uhd(gr_unittest.TestCase): def setUp(self): diff --git a/gr-utils/bindtool/__init__.py b/gr-utils/bindtool/__init__.py index 81eafae2e6e..8bed5d5069b 100644 --- a/gr-utils/bindtool/__init__.py +++ b/gr-utils/bindtool/__init__.py @@ -1 +1 @@ -from .core.generator import BindingGenerator \ No newline at end of file +from .core.generator import BindingGenerator diff --git a/gr-utils/bindtool/core/base.py b/gr-utils/bindtool/core/base.py index f7e713f0340..24213a25a5a 100644 --- a/gr-utils/bindtool/core/base.py +++ b/gr-utils/bindtool/core/base.py @@ -1,9 +1,8 @@ - class BindTool(object): - + target_bindings = 'pybind11' - + def __init__(self): - pass \ No newline at end of file + pass diff --git a/gr-utils/bindtool/core/generator.py b/gr-utils/bindtool/core/generator.py index feceb29705e..79c56213d4f 100644 --- a/gr-utils/bindtool/core/generator.py +++ b/gr-utils/bindtool/core/generator.py @@ -18,11 +18,12 @@ import hashlib import re + class BindingGenerator: - def __init__(self, prefix, namespace, prefix_include_root, output_dir="", define_symbols=None, addl_includes= None, - match_include_structure=False, catch_exceptions=True, write_json_output=False, status_output=None, - flag_automatic=False, flag_pygccxml=False, update_hash_only=False): + def __init__(self, prefix, namespace, prefix_include_root, output_dir="", define_symbols=None, addl_includes=None, + match_include_structure=False, catch_exceptions=True, write_json_output=False, status_output=None, + flag_automatic=False, flag_pygccxml=False, update_hash_only=False): """Initialize BindingGenerator prefix -- path to installed gnuradio prefix (use gr.prefix() if unsure) namespace -- desired namespace to parse e.g. ['gr','module_name'] @@ -33,14 +34,14 @@ def __init__(self, prefix, namespace, prefix_include_root, output_dir="", define output_dir -- path where bindings will be placed define_symbols -- comma separated tuple of defines addl_includes -- comma separated list of additional include directories (default "") - match_include_structure -- + match_include_structure -- If set to False, a bindings/ dir will be placed directly under the specified output_dir If set to True, the directory structure under include/ will be mirrored - update_hash_only -- If set to true, only update the hash in the pybind + update_hash_only -- If set to true, only update the hash in the pybind """ self.header_extensions = ['.h', '.hh', '.hpp'] - self.define_symbols=define_symbols + self.define_symbols = define_symbols self.addl_include = addl_includes self.prefix = prefix self.namespace = namespace @@ -81,7 +82,6 @@ def gen_pybind_cc(self, header_info, base_name): tpl = Template(filename=os.path.join(current_path, '..', 'templates', 'generic_python_cc.mako')) - return tpl.render( license=license, header_info=header_info, @@ -134,7 +134,7 @@ def read_json(self, pathname): header_info = json.load(fp) return header_info - def fix_file_hash(self, file_to_process): + def fix_file_hash(self, file_to_process): """Update the hash in blockname_python.cc python bindings""" output_dir = self.get_output_dir(file_to_process) @@ -151,14 +151,13 @@ def fix_file_hash(self, file_to_process): with open(binding_pathname_cc, 'r') as f: file_contents = f.read() - new_file_contents = re.sub(r'BINDTOOL_HEADER_FILE_HASH\([a-zA-Z0-9]+\)', - f"BINDTOOL_HEADER_FILE_HASH({newhash})", file_contents) + new_file_contents = re.sub(r'BINDTOOL_HEADER_FILE_HASH\([a-zA-Z0-9]+\)', + f"BINDTOOL_HEADER_FILE_HASH({newhash})", file_contents) with open(binding_pathname_cc, 'w') as updated_f: updated_f.write(new_file_contents) print(f"Update hash in {binding_pathname_cc} to {newhash}") - def gen_file_binding(self, file_to_process): """Produce the blockname_python.cc python bindings""" output_dir = self.get_output_dir(file_to_process) @@ -166,7 +165,7 @@ def gen_file_binding(self, file_to_process): base_name = os.path.splitext(os.path.basename(file_to_process))[0] module_include_path = os.path.abspath(os.path.dirname(file_to_process)) top_include_path = os.path.join( - module_include_path.split('include'+os.path.sep)[0], 'include') + module_include_path.split('include' + os.path.sep)[0], 'include') include_paths = ','.join( (module_include_path, top_include_path)) @@ -180,10 +179,10 @@ def gen_file_binding(self, file_to_process): include_paths = ','.join((include_paths, self.addl_include)) parser = GenericHeaderParser( - define_symbols = self.define_symbols, include_paths=include_paths, file_path=file_to_process) + define_symbols=self.define_symbols, include_paths=include_paths, file_path=file_to_process) try: header_info = parser.get_header_info(self.namespace) - + if self.write_json_output: self.write_json(header_info, base_name, output_dir) self.write_pybind_cc(header_info, base_name, output_dir) @@ -211,9 +210,9 @@ def get_output_dir(self, filename): output_dir = self.output_dir rel_path_after_include = "" if self.match_include_structure: - if 'include'+os.path.sep in filename: + if 'include' + os.path.sep in filename: rel_path_after_include = os.path.split( - filename.split('include'+os.path.sep)[-1])[0] + filename.split('include' + os.path.sep)[-1])[0] output_dir = os.path.join( self.output_dir, rel_path_after_include, 'bindings') @@ -301,7 +300,7 @@ def get_file_list(self, include_path): def gen_bindings(self, module_dir): """Generate bindings for an entire GR module - Produces CMakeLists.txt, python_bindings.cc, and blockname_python.cc + Produces CMakeLists.txt, python_bindings.cc, and blockname_python.cc for each block in the module module_dir -- path to the include directory where the public headers live diff --git a/gr-utils/bindtool/scripts/bind_from_json.py b/gr-utils/bindtool/scripts/bind_from_json.py index 863b40f5b48..cfaf2842df5 100644 --- a/gr-utils/bindtool/scripts/bind_from_json.py +++ b/gr-utils/bindtool/scripts/bind_from_json.py @@ -3,7 +3,8 @@ from gnuradio.bindtool import BindingGenerator import pathlib -parser = argparse.ArgumentParser(description='Bind a GR header file from the generated json') +parser = argparse.ArgumentParser( + description='Bind a GR header file from the generated json') parser.add_argument('pathnames', type=str, nargs='+', help='Json files to bind') @@ -12,4 +13,4 @@ bg = BindingGenerator() for p in args.pathnames: - bg.bind_from_json(p) \ No newline at end of file + bg.bind_from_json(p) diff --git a/gr-utils/bindtool/scripts/bind_gr_module.py b/gr-utils/bindtool/scripts/bind_gr_module.py index 297e0d920b2..577216d9a45 100644 --- a/gr-utils/bindtool/scripts/bind_gr_module.py +++ b/gr-utils/bindtool/scripts/bind_gr_module.py @@ -12,7 +12,7 @@ help='Output directory of generated bindings') parser.add_argument('--prefix', help='Prefix of Installed GNU Radio') parser.add_argument('--src', help='Directory of gnuradio source tree', - default=os.path.dirname(os.path.abspath(__file__))+'/../../..') + default=os.path.dirname(os.path.abspath(__file__)) + '/../../..') parser.add_argument( '--include', help='Additional Include Dirs, comma separated', default='') args = parser.parse_args() @@ -24,9 +24,9 @@ # /usr/include/x86_64-linux-gnu/qt5/QtCore,/usr/include/x86_64-linux-gnu/qt5/QtWidgets,/usr/include/qwt qtgui # To generate UHD requires adding the UHD headers, e.g. -# python3 /share/gnuradio/grpybind/src/gnuradio/gr-utils/python/bindtool/scripts/bind_gr_module.py -# --prefix /share/gnuradio/grpybind -# --include $UHD_PATH,$UHD_PATH/utils,$UHD_PATH/types,$UHD_PATH/transport,$UHD_PATH/usrp_clock,$UHD_PATH/rfnoc +# python3 /share/gnuradio/grpybind/src/gnuradio/gr-utils/python/bindtool/scripts/bind_gr_module.py +# --prefix /share/gnuradio/grpybind +# --include $UHD_PATH,$UHD_PATH/utils,$UHD_PATH/types,$UHD_PATH/transport,$UHD_PATH/usrp_clock,$UHD_PATH/rfnoc # --output_dir /share/tmp/take5 uhd @@ -38,10 +38,10 @@ includes = args.include for name in args.names: if name not in ['gr', 'pmt']: - namespace = ['gr', name.replace("-","_")] + namespace = ['gr', name.replace("-", "_")] module_dir = os.path.abspath( - os.path.join(args.src, 'gr-'+name, 'include')) - prefix_include_root = 'gnuradio/'+name # pmt, gnuradio/digital, etc. + os.path.join(args.src, 'gr-' + name, 'include')) + prefix_include_root = 'gnuradio/' + name # pmt, gnuradio/digital, etc. else: namespace = [name] module_dir = os.path.abspath(os.path.join( diff --git a/gr-utils/bindtool/scripts/bind_intree_file.py b/gr-utils/bindtool/scripts/bind_intree_file.py index 774f1184027..026a702e00e 100644 --- a/gr-utils/bindtool/scripts/bind_intree_file.py +++ b/gr-utils/bindtool/scripts/bind_intree_file.py @@ -14,7 +14,7 @@ help='Output directory of generated bindings') parser.add_argument('--prefix', help='Prefix of Installed GNU Radio') parser.add_argument('--src', help='Directory of gnuradio source tree', - default=os.path.dirname(os.path.abspath(__file__))+'/../../..') + default=os.path.dirname(os.path.abspath(__file__)) + '/../../..') parser.add_argument( '--filename', help="File to be parsed") @@ -41,7 +41,7 @@ if name not in ['gr', 'pmt']: namespace = ['gr', name] - prefix_include_root = 'gnuradio/'+name # pmt, gnuradio/digital, etc. + prefix_include_root = 'gnuradio/' + name # pmt, gnuradio/digital, etc. else: namespace = [name] if name == 'gr': @@ -54,6 +54,7 @@ bg = BindingGenerator(args.prefix, namespace, prefix_include_root, output_dir, addl_includes=','.join(args.include), catch_exceptions=False, write_json_output=False, status_output=args.status, - flag_automatic=True if args.flag_automatic.lower() in ['1','true'] else False, - flag_pygccxml=True if args.flag_pygccxml.lower() in ['1','true'] else False) + flag_automatic=True if args.flag_automatic.lower() in [ + '1', 'true'] else False, + flag_pygccxml=True if args.flag_pygccxml.lower() in ['1', 'true'] else False) bg.gen_file_binding(args.filename) diff --git a/gr-utils/bindtool/scripts/header_utils.py b/gr-utils/bindtool/scripts/header_utils.py index 4071f6fa869..94b16ceb6be 100644 --- a/gr-utils/bindtool/scripts/header_utils.py +++ b/gr-utils/bindtool/scripts/header_utils.py @@ -7,7 +7,7 @@ class PybindHeaderParser: def __init__(self, pathname): try: - with open(pathname,'r') as f: + with open(pathname, 'r') as f: self.file_txt = f.read() except: self.file_txt = "" @@ -42,10 +42,10 @@ def get_header_filename(self): except: return None - def get_header_file_hash(self): try: - m = re.search(r'BINDTOOL_HEADER_FILE_HASH\(([^\s]*)\)', self.file_txt) + m = re.search( + r'BINDTOOL_HEADER_FILE_HASH\(([^\s]*)\)', self.file_txt) if (m): return m.group(1) else: @@ -57,17 +57,19 @@ def get_flags(self): return f'{self.get_flag_automatic()};{self.get_flag_pygccxml()};{self.get_header_filename()};{self.get_header_file_hash()};' - def argParse(): """Parses commandline args.""" - desc='Reads the parameters from the comment block in the pybind files' + desc = 'Reads the parameters from the comment block in the pybind files' parser = ArgumentParser(description=desc) - - parser.add_argument("function", help="Operation to perform on comment block of pybind file", choices=["flag_auto","flag_pygccxml","header_filename","header_file_hash","all"]) - parser.add_argument("pathname", help="Pathname of pybind c++ file to read, e.g. blockname_python.cc") + + parser.add_argument("function", help="Operation to perform on comment block of pybind file", choices=[ + "flag_auto", "flag_pygccxml", "header_filename", "header_file_hash", "all"]) + parser.add_argument( + "pathname", help="Pathname of pybind c++ file to read, e.g. blockname_python.cc") return parser.parse_args() + if __name__ == "__main__": # Parse command line options and set up doxyxml. args = argParse() @@ -81,6 +83,6 @@ def argParse(): elif args.function == "header_filename": print(pbhp.get_header_filename()) elif args.function == "header_file_hash": - print(pbhp.get_header_file_hash()) + print(pbhp.get_header_file_hash()) elif args.function == "all": - print(pbhp.get_flags()) \ No newline at end of file + print(pbhp.get_flags()) diff --git a/gr-utils/blocktool/__main__.py b/gr-utils/blocktool/__main__.py index 6cd8845ae5e..7a59e4af729 100644 --- a/gr-utils/blocktool/__main__.py +++ b/gr-utils/blocktool/__main__.py @@ -3,7 +3,7 @@ # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-2.0-or-later -# +# # """ main function to run the blocktool api from the command line. """ diff --git a/gr-utils/blocktool/cli.py b/gr-utils/blocktool/cli.py index 2f298df4729..295f088d935 100644 --- a/gr-utils/blocktool/cli.py +++ b/gr-utils/blocktool/cli.py @@ -83,7 +83,7 @@ def json_generator(parser, **kwargs): header = parser.filename.split('.')[0] block = parser.modname.split('-')[-1] if kwargs['output']: - json_file = os.path.join('.', block+'_'+header + '.json') + json_file = os.path.join('.', block + '_' + header + '.json') with open(json_file, 'w') as _file: json.dump(parser.parsed_data, _file, indent=4) else: @@ -117,7 +117,7 @@ def parse_directory(**kwargs): json_generator(parse_dir, **kwargs) except: logging.basicConfig(level=logging.DEBUG, - filename=os.path.join('.', dir_name+'_log.out')) + filename=os.path.join('.', dir_name + '_log.out')) logging.exception( 'Log for Exception raised for the header: {}\n'.format(header)) click.secho('Parsing unsuccessful: {}'.format( diff --git a/gr-utils/blocktool/core/comments.py b/gr-utils/blocktool/core/comments.py index 7973165b0d5..2e2a1709dda 100644 --- a/gr-utils/blocktool/core/comments.py +++ b/gr-utils/blocktool/core/comments.py @@ -90,7 +90,7 @@ def read_comments(self): _index = lines.index(line) if _index is not None: - _index = _index+1 + _index = _index + 1 for num in range(_index, len(lines)): if Constants.END_BLOCKTOOL in lines[num]: break @@ -192,7 +192,7 @@ def add_comments(self): if _index is None: with open(self.target_file, 'a') as header: header.write('\n') - header.write('/* '+Constants.BLOCKTOOL + '\n') + header.write('/* ' + Constants.BLOCKTOOL + '\n') header.write('input_signature: ' + parsed_io['input']['signature'] + '\n') header.write('input_min_streams: ' + diff --git a/gr-utils/blocktool/core/iosignature.py b/gr-utils/blocktool/core/iosignature.py index 604772cedd5..23bad17cced 100644 --- a/gr-utils/blocktool/core/iosignature.py +++ b/gr-utils/blocktool/core/iosignature.py @@ -57,10 +57,10 @@ def io_signature(impl_file): for signature in Constants.SIGNATURE_LIST: if signature in io_func[0] and parsed_io['input']['signature'] is None: parsed_io['input']['signature'] = signature - io_func[0] = io_func[0].lstrip(signature+' (') + io_func[0] = io_func[0].lstrip(signature + ' (') if signature in io_func[1] and parsed_io['output']['signature'] is None: parsed_io['output']['signature'] = signature - io_func[1] = io_func[1].lstrip(signature+' (') + io_func[1] = io_func[1].lstrip(signature + ' (') io_elements = [] for _io in io_func: _io = _io.split(',') @@ -151,7 +151,7 @@ def message_port(impl_file): if re.findall(r'"([^"]*)"', port)[0]: input_port.append(re.findall(r'"([^"]*)"', port)[0]) else: - input_port.append(port[port.find('(')+1:port.rfind(')')]) + input_port.append(port[port.find('(') + 1:port.rfind(')')]) _temp_port = ''.join(map(str, input_port)) input_port.clear() input_port.append(_temp_port) @@ -164,7 +164,7 @@ def message_port(impl_file): if re.findall(r'"([^"]*)"', port)[0]: output_port.append(re.findall(r'"([^"]*)"', port)[0]) else: - output_port.append(port[port.find('(')+1:port.rfind(')')]) + output_port.append(port[port.find('(') + 1:port.rfind(')')]) _temp_port = ''.join(map(str, output_port)) output_port.clear() output_port.append(_temp_port) diff --git a/gr-utils/blocktool/core/parseheader.py b/gr-utils/blocktool/core/parseheader.py index a8ef6dadab0..d6babd5f1db 100644 --- a/gr-utils/blocktool/core/parseheader.py +++ b/gr-utils/blocktool/core/parseheader.py @@ -9,6 +9,11 @@ """ Module to generate AST for the headers and parse it """ +from ..core import Constants +from ..core.comments import read_comments, add_comments, exist_comments +from ..core.iosignature import io_signature, message_port +from ..core.base import BlockToolException, BlockTool +import time import os import re import codecs @@ -16,7 +21,6 @@ PYGCCXML_AVAILABLE = False # ugly hack to make pygccxml work with Python >= 3.8 -import time try: time.clock except: @@ -27,10 +31,6 @@ except: pass -from ..core.base import BlockToolException, BlockTool -from ..core.iosignature import io_signature, message_port -from ..core.comments import read_comments, add_comments, exist_comments -from ..core import Constants LOGGER = logging.getLogger(__name__) @@ -79,7 +79,7 @@ def initialize(self): if dirs.path.endswith('lib'): self.impldir = dirs.path self.impl_file = os.path.join(self.impldir, - self.filename.split('.')[0]+'_impl.cc') + self.filename.split('.')[0] + '_impl.cc') def validate(self): """ Override the Blocktool validate function """ @@ -283,11 +283,11 @@ def get_header_info(self): self.parsed_data['member_functions'] = [] query_methods = declarations.access_type_matcher_t('public') functions = main_class.member_functions(function=query_methods, - allow_empty=True, - header_file=self.target_file) + allow_empty=True, + header_file=self.target_file) if functions: for fcn in functions: - if str(fcn.name) not in [main_class.name, '~'+main_class.name, 'make']: + if str(fcn.name) not in [main_class.name, '~' + main_class.name, 'make']: fcn_args = { "name": str(fcn.name), "arguments": [] @@ -299,7 +299,8 @@ def get_header_info(self): "default": argument.default_value } fcn_args['arguments'].append(args.copy()) - self.parsed_data['member_functions'].append(fcn_args.copy()) + self.parsed_data['member_functions'].append( + fcn_args.copy()) except RuntimeError: self.parsed_data['member_functions'] = [] diff --git a/gr-utils/blocktool/core/parseheader_generic.py b/gr-utils/blocktool/core/parseheader_generic.py index c28c6824c77..0e00ba56f8e 100644 --- a/gr-utils/blocktool/core/parseheader_generic.py +++ b/gr-utils/blocktool/core/parseheader_generic.py @@ -9,6 +9,7 @@ """ Module to generate AST for the headers and parse it """ +import time import os import re import codecs @@ -22,7 +23,6 @@ LOGGER = logging.getLogger(__name__) PYGCCXML_AVAILABLE = False # ugly hack to make pygccxml work with Python >= 3.8 -import time try: time.clock except: @@ -35,6 +35,7 @@ from ...modtool.tools import ParserCCBlock from ...modtool.cli import ModToolException + class GenericHeaderParser(BlockTool): """ : Single argument required: file_path @@ -47,7 +48,7 @@ class GenericHeaderParser(BlockTool): name = 'Block Parse Header' description = 'Create a parsed output from a block header file' - def __init__(self, file_path=None, blocktool_comments=False, define_symbols=None, include_paths=None, **kwargs): + def __init__(self, file_path=None, blocktool_comments=False, define_symbols=None, include_paths=None, **kwargs): """ __init__ """ BlockTool.__init__(self, **kwargs) self.parsed_data = {} @@ -63,8 +64,6 @@ def __init__(self, file_path=None, blocktool_comments=False, define_symbols=None file_path = os.path.abspath(file_path) self.target_file = file_path - - self.initialize() self.validate() @@ -84,7 +83,7 @@ def initialize(self): if not os.path.basename(self.module).startswith(Constants.GR): self.module = os.path.abspath( os.path.join(self.module, os.pardir)) - + self.modname = os.path.basename(self.module) self.filename = os.path.basename(self.target_file) self.targetdir = os.path.dirname(self.target_file) @@ -104,9 +103,10 @@ def _get_blockdata(fname_h): fname_h))[0] fname_cc = blockname + '_impl' + '.cc' contains_modulename = blockname.startswith( - self.modname+'_') - blockname = blockname.replace(self.modname+'_', '', 1) - fname_cc = os.path.join(fname_h.split('include')[0],'lib',fname_cc) + self.modname + '_') + blockname = blockname.replace(self.modname + '_', '', 1) + fname_cc = os.path.join(fname_h.split( + 'include')[0], 'lib', fname_cc) return (blockname, fname_cc, contains_modulename) # Go, go, go LOGGER.info("Making GRC bindings for {}...".format(fname_h)) @@ -123,7 +123,7 @@ def _get_blockdata(fname_h): "Can't open some of the files necessary to parse {}.".format(fname_cc)) if contains_modulename: - return (parser.read_params(), parser.read_io_signature(), self.modname+'_'+blockname) + return (parser.read_params(), parser.read_io_signature(), self.modname + '_' + blockname) else: return (parser.read_params(), parser.read_io_signature(), blockname) @@ -171,7 +171,7 @@ def parse_class(self, class_decl): allow_empty=True, recursive=False, header_file=self.target_file) for fcn in functions: - if str(fcn.name) not in [class_decl.name, '~'+class_decl.name]: + if str(fcn.name) not in [class_decl.name, '~' + class_decl.name]: member_functions.append(self.parse_function(fcn)) class_dict['member_functions'] = member_functions @@ -295,17 +295,17 @@ def get_header_info(self, namespace_to_parse): mf_dict = { "name": "make", - "return_type": "::".join(namespace_to_parse + [blockname,"sptr"]), + "return_type": "::".join(namespace_to_parse + [blockname, "sptr"]), "has_static": "1" } - + args = [] - + for p in params: arg_dict = { - "name":p['key'], - "dtype":p['type'], - "default":p['default'] + "name": p['key'], + "dtype": p['type'], + "default": p['default'] } args.append(arg_dict) @@ -341,7 +341,8 @@ def get_header_info(self, namespace_to_parse): raise BlockToolException('namespace cannot be none') self.parsed_data['target_namespace'] = namespace_to_parse - self.parsed_data['namespace'] = self.parse_namespace(main_namespace) + self.parsed_data['namespace'] = self.parse_namespace( + main_namespace) # except RuntimeError: # raise BlockToolException( diff --git a/gr-utils/modtool/cli/add.py b/gr-utils/modtool/cli/add.py index 8078f61a0ae..4a5a4f374cf 100644 --- a/gr-utils/modtool/cli/add.py +++ b/gr-utils/modtool/cli/add.py @@ -43,14 +43,15 @@ def cli(**kwargs): """Adds a block to the out-of-tree module.""" kwargs['cli'] = True self = ModToolAdd(**kwargs) - click.secho("GNU Radio module name identified: " + self.info['modname'], fg='green') + click.secho("GNU Radio module name identified: " + + self.info['modname'], fg='green') get_blockname(self) get_blocktype(self) get_lang(self) info_lang = {'cpp': 'C++', 'python': 'Python'}[self.info['lang']] click.secho(f"Language: {info_lang}", fg='green') - if ((self.skip_subdirs['lib'] and self.info['lang'] == 'cpp') - or (self.skip_subdirs['python'] and self.info['lang'] == 'python')): + if ((self.skip_subdirs['lib'] and self.info['lang'] == 'cpp') or + (self.skip_subdirs['python'] and self.info['lang'] == 'python')): raise ModToolException('Missing or skipping relevant subdir.') click.secho("Block/code identifier: " + self.info['blockname'], fg='green') if not self.license_file: @@ -60,12 +61,13 @@ def cli(**kwargs): get_py_qa(self) get_cpp_qa(self) if self.info['version'] == 'autofoo' and not self.skip_cmakefiles: - click.secho("Warning: Autotools modules are not supported. "+ + click.secho("Warning: Autotools modules are not supported. " + "Files will be created, but Makefiles will not be edited.", fg='yellow') self.skip_cmakefiles = True run(self) + def get_blocktype(self): """ Get the blocktype of the block to be added """ if self.info['blocktype'] is None: @@ -74,7 +76,9 @@ def get_blocktype(self): while self.info['blocktype'] not in self.block_types: self.info['blocktype'] = cli_input("Enter block type: ") if self.info['blocktype'] not in self.block_types: - click.secho('Must be one of ' + str(self.block_types), fg='yellow') + click.secho('Must be one of ' + + str(self.block_types), fg='yellow') + def get_lang(self): """ Get the Programming Language of the block to be added """ @@ -85,20 +89,24 @@ def get_lang(self): if self.info['lang'] == 'c++': self.info['lang'] = 'cpp' + def get_blockname(self): """ Get the blockname""" if not self.info['blockname'] or self.info['blockname'].isspace(): while not self.info['blockname'] or self.info['blockname'].isspace(): - self.info['blockname'] = cli_input("Enter name of block/code (without module name prefix): ") + self.info['blockname'] = cli_input( + "Enter name of block/code (without module name prefix): ") validate_name('block', self.info['blockname']) - self.info['fullblockname'] = self.info['modname'] + '_' + self.info['blockname'] + self.info['fullblockname'] = self.info['modname'] + \ + '_' + self.info['blockname'] fname_grc = self.info['fullblockname'] + '.block.yml' for block in os.scandir('./grc/'): if block.is_file(): s = block.name if s == fname_grc: raise ModToolException('Block Already Present.') - + + def get_copyrightholder(self): """ Get the copyrightholder of the block to be added """ if not self.info['copyrightholder'] or self.info['copyrightholder'].isspace(): @@ -109,31 +117,36 @@ def get_copyrightholder(self): else: copyright_candidates = (user, 'GNU Radio') with SequenceCompleter(copyright_candidates): - self.info['copyrightholder'] = cli_input("Please specify the copyright holder: ") + self.info['copyrightholder'] = cli_input( + "Please specify the copyright holder: ") if not self.info['copyrightholder'] or self.info['copyrightholder'].isspace(): self.info['copyrightholder'] = f'gr-{self.info["modname"]} author' elif self.info['is_component']: click.secho("For GNU Radio components the FSF is added as copyright holder", fg='cyan') + def get_arglist(self): """ Get the argument list of the block to be added """ if self.info['arglist'] is None: self.info['arglist'] = click.prompt(click.style( 'Enter valid argument list, including default arguments: \n', fg='cyan'), - prompt_suffix='', - default='', - show_default=False) + prompt_suffix='', + default='', + show_default=False) + def get_py_qa(self): """ Get a boolean value for addition of py_qa """ if self.add_py_qa is None: if not (self.info['blocktype'] in ('noblock') or self.skip_subdirs['python']): - self.add_py_qa = ask_yes_no(click.style('Add Python QA code?', fg='cyan'), True) + self.add_py_qa = ask_yes_no(click.style( + 'Add Python QA code?', fg='cyan'), True) else: self.add_py_qa = False + def get_cpp_qa(self): """ Get a boolean value for addition of cpp_qa """ if self.add_cc_qa is None: diff --git a/gr-utils/modtool/cli/base.py b/gr-utils/modtool/cli/base.py index 7b8c2237516..19a70e1d45e 100644 --- a/gr-utils/modtool/cli/base.py +++ b/gr-utils/modtool/cli/base.py @@ -26,7 +26,8 @@ class ModToolException(ClickException): """ Exception class for enhanced CLI interface """ - def show(self, file = None): + + def show(self, file=None): """ displays the colored message """ click.secho(f'ModToolException: {self.format_message()}', fg='red') @@ -71,6 +72,7 @@ class ClickHandler(StreamHandler): StreamHandler which overrides some of its functional definitions to add colors to the stream output """ + def emit(self, record): """ Writes message to the stream """ colormap = { @@ -134,7 +136,8 @@ def wrapper(*args, **kwargs): return wrapper -block_name = click.argument('blockname', nargs=1, required=False, metavar="BLOCK_NAME") +block_name = click.argument( + 'blockname', nargs=1, required=False, metavar="BLOCK_NAME") @with_plugins(iter_entry_points('gnuradio.modtool.cli.plugins')) diff --git a/gr-utils/modtool/cli/bind.py b/gr-utils/modtool/cli/bind.py index 9ff401dc6dc..89a980297bc 100644 --- a/gr-utils/modtool/cli/bind.py +++ b/gr-utils/modtool/cli/bind.py @@ -27,14 +27,13 @@ @click.command('bind', short_help=ModToolGenBindings.description) @click.option('-o', '--output', is_flag=True, - help = 'If given, a file with desired output format will be generated') -@click.option('--addl_includes', default = None, - help = 'Comma separated list of additional include directories (default None)') + help='If given, a file with desired output format will be generated') +@click.option('--addl_includes', default=None, + help='Comma separated list of additional include directories (default None)') @click.option('-D', '--define_symbols', multiple=True, default=None, - help = 'Set precompiler defines') -@click.option('-u', '--update-hash-only', is_flag = True, - help = 'If given, only the hash in the binding will be updated') - + help='Set precompiler defines') +@click.option('-u', '--update-hash-only', is_flag=True, + help='If given, only the hash in the binding will be updated') @common_params @block_name def cli(**kwargs): @@ -44,15 +43,18 @@ def cli(**kwargs): """ kwargs['cli'] = True self = ModToolGenBindings(**kwargs) - click.secho("GNU Radio module name identified: " + self.info['modname'], fg='green') + click.secho("GNU Radio module name identified: " + + self.info['modname'], fg='green') get_pattern(self) run(self) + def get_pattern(self): """ Get the regex pattern for block(s) to be parsed """ if self.info['pattern'] is None: block_candidates = get_block_candidates() with SequenceCompleter(block_candidates): - self.info['pattern'] = cli_input('Which blocks do you want to parse? (Regex): ') + self.info['pattern'] = cli_input( + 'Which blocks do you want to parse? (Regex): ') if not self.info['pattern'] or self.info['pattern'].isspace(): self.info['pattern'] = '.' diff --git a/gr-utils/modtool/cli/disable.py b/gr-utils/modtool/cli/disable.py index 136b4e0ee6a..093128f5ce3 100644 --- a/gr-utils/modtool/cli/disable.py +++ b/gr-utils/modtool/cli/disable.py @@ -23,15 +23,18 @@ def cli(**kwargs): """Disable a block (comments out CMake entries for files)""" kwargs['cli'] = True self = ModToolDisable(**kwargs) - click.secho("GNU Radio module name identified: " + self.info['modname'], fg='green') + click.secho("GNU Radio module name identified: " + + self.info['modname'], fg='green') get_pattern(self) run(self) + def get_pattern(self): """ Get the regex pattern for block(s) to be disabled """ if self.info['pattern'] is None: block_candidates = get_block_candidates() with SequenceCompleter(block_candidates): - self.info['pattern'] = cli_input('Which blocks do you want to disable? (Regex): ') + self.info['pattern'] = cli_input( + 'Which blocks do you want to disable? (Regex): ') if not self.info['pattern'] or self.info['pattern'].isspace(): self.info['pattern'] = '.' diff --git a/gr-utils/modtool/cli/makeyaml.py b/gr-utils/modtool/cli/makeyaml.py index c3019cb4fe0..8ea99365ece 100644 --- a/gr-utils/modtool/cli/makeyaml.py +++ b/gr-utils/modtool/cli/makeyaml.py @@ -43,7 +43,8 @@ def cli(**kwargs): if kwargs['blocktool']: kwargs['modtool'] = True if kwargs['blockname'] is None: - raise BlockToolException('Missing argument FILE PATH with blocktool flag') + raise BlockToolException( + 'Missing argument FILE PATH with blocktool flag') kwargs['file_path'] = os.path.abspath(kwargs['blockname']) if os.path.isfile(kwargs['file_path']): parse_yml = BlockHeaderParser(**kwargs) @@ -55,15 +56,18 @@ def cli(**kwargs): raise BlockToolException('Invalid file path.') else: self = ModToolMakeYAML(**kwargs) - click.secho("GNU Radio module name identified: " + self.info['modname'], fg='green') + click.secho("GNU Radio module name identified: " + + self.info['modname'], fg='green') get_pattern(self) run(self) + def get_pattern(self): """ Get the regex pattern for block(s) to be parsed """ if self.info['pattern'] is None: block_candidates = get_block_candidates() with SequenceCompleter(block_candidates): - self.info['pattern'] = cli_input('Which blocks do you want to parse? (Regex): ') + self.info['pattern'] = cli_input( + 'Which blocks do you want to parse? (Regex): ') if not self.info['pattern'] or self.info['pattern'].isspace(): self.info['pattern'] = '.' diff --git a/gr-utils/modtool/cli/newmod.py b/gr-utils/modtool/cli/newmod.py index 80194ff9958..c5d91a95578 100644 --- a/gr-utils/modtool/cli/newmod.py +++ b/gr-utils/modtool/cli/newmod.py @@ -18,6 +18,7 @@ from ..core import ModToolNewModule, validate_name from .base import common_params, run, cli_input, ModToolException + @click.command('newmod', short_help=ModToolNewModule.description) @click.option('--srcdir', help="Source directory for the module template.") @@ -37,15 +38,17 @@ def cli(**kwargs): try: os.stat(self.dir) except OSError: - pass # This is what should happen + pass # This is what should happen else: raise ModToolException('The given directory exists.') if self.srcdir is None: - self.srcdir = os.path.join(gr.prefix(),'share','gnuradio','modtool','templates','gr-newmod') + self.srcdir = os.path.join( + gr.prefix(), 'share', 'gnuradio', 'modtool', 'templates', 'gr-newmod') if not os.path.isdir(self.srcdir): raise ModToolException('Could not find gr-newmod source dir.') run(self) + def get_modname(self): """ Get the name of the new module to be added """ if self.info['modname'] is None: diff --git a/gr-utils/modtool/cli/rename.py b/gr-utils/modtool/cli/rename.py index 0e70867f39f..0909e8b6444 100644 --- a/gr-utils/modtool/cli/rename.py +++ b/gr-utils/modtool/cli/rename.py @@ -31,36 +31,42 @@ def cli(**kwargs): """ kwargs['cli'] = True self = ModToolRename(**kwargs) - click.secho("GNU Radio module name identified: " + self.info['modname'], fg='green') + click.secho("GNU Radio module name identified: " + + self.info['modname'], fg='green') # first make sure the old block name is provided get_oldname(self) - click.secho("Block/code to rename identifier: " + self.info['oldname'], fg='green') - self.info['fulloldname'] = self.info['modname'] + '_' + self.info['oldname'] + click.secho("Block/code to rename identifier: " + + self.info['oldname'], fg='green') + self.info['fulloldname'] = self.info['modname'] + \ + '_' + self.info['oldname'] # now get the new block name get_newname(self) click.secho("Block/code identifier: " + self.info['newname'], fg='green') - self.info['fullnewname'] = self.info['modname'] + '_' + self.info['newname'] + self.info['fullnewname'] = self.info['modname'] + \ + '_' + self.info['newname'] run(self) + def get_oldname(self): """ Get the old block name to be replaced """ block_candidates = get_block_candidates() if self.info['oldname'] is None: with SequenceCompleter(block_candidates): while not self.info['oldname'] or self.info['oldname'].isspace(): - self.info['oldname'] = cli_input("Enter name of block/code to rename "+ + self.info['oldname'] = cli_input("Enter name of block/code to rename " + "(without module name prefix): ") if self.info['oldname'] not in block_candidates: choices = [x for x in block_candidates if self.info['oldname'] in x] if len(choices) > 0: - click.secho("Suggested alternatives: "+str(choices), fg='yellow') + click.secho("Suggested alternatives: " + str(choices), fg='yellow') raise ModToolException("Blockname for renaming does not exists!") validate_name('block', self.info['oldname']) + def get_newname(self): """ Get the new block name """ if self.info['newname'] is None: while not self.info['newname'] or self.info['newname'].isspace(): - self.info['newname'] = cli_input("Enter name of block/code "+ + self.info['newname'] = cli_input("Enter name of block/code " + "(without module name prefix): ") validate_name('block', self.info['newname']) diff --git a/gr-utils/modtool/cli/rm.py b/gr-utils/modtool/cli/rm.py index 30eadb50526..5f86c62f241 100644 --- a/gr-utils/modtool/cli/rm.py +++ b/gr-utils/modtool/cli/rm.py @@ -23,15 +23,18 @@ def cli(**kwargs): """ Remove block (delete files and remove Makefile entries) """ kwargs['cli'] = True self = ModToolRemove(**kwargs) - click.secho("GNU Radio module name identified: " + self.info['modname'], fg='green') + click.secho("GNU Radio module name identified: " + + self.info['modname'], fg='green') get_pattern(self) run(self) + def get_pattern(self): """ Returns the regex pattern for block(s) to be removed """ if self.info['pattern'] is None: block_candidates = get_block_candidates() with SequenceCompleter(block_candidates): - self.info['pattern'] = cli_input('Which blocks do you want to delete? (Regex): ') + self.info['pattern'] = cli_input( + 'Which blocks do you want to delete? (Regex): ') if not self.info['pattern'] or self.info['pattern'].isspace(): self.info['pattern'] = '.' diff --git a/gr-utils/modtool/cli/update.py b/gr-utils/modtool/cli/update.py index 70a7185e7d3..cb45828ed1c 100644 --- a/gr-utils/modtool/cli/update.py +++ b/gr-utils/modtool/cli/update.py @@ -26,10 +26,12 @@ def cli(**kwargs): """ Update the XML bindings to YAML bindings """ kwargs['cli'] = True self = ModToolUpdate(**kwargs) - click.secho("GNU Radio module name identified: " + self.info['modname'], fg='green') + click.secho("GNU Radio module name identified: " + + self.info['modname'], fg='green') get_blockname(self) run(self) + def get_blockname(self): """ Returns the blockname for block to be updated """ if self.info['complete']: @@ -37,11 +39,12 @@ def get_blockname(self): block_candidates = get_xml_candidates() if self.info['blockname'] is None: with SequenceCompleter(block_candidates): - self.info['blockname'] = cli_input('Which block do you wish to update? : ') + self.info['blockname'] = cli_input( + 'Which block do you wish to update? : ') if not self.info['blockname'] or self.info['blockname'].isspace(): raise ModToolException('Block name not specified!') if self.info['blockname'] not in block_candidates: choices = [x for x in block_candidates if self.info['blockname'] in x] if len(choices) > 0: - click.secho("Suggested alternatives: "+str(choices), fg='yellow') + click.secho("Suggested alternatives: " + str(choices), fg='yellow') raise ModToolException("The XML bindings does not exists!") diff --git a/gr-utils/modtool/core/add.py b/gr-utils/modtool/core/add.py index 35988b959c5..47afb990e49 100644 --- a/gr-utils/modtool/core/add.py +++ b/gr-utils/modtool/core/add.py @@ -25,15 +25,16 @@ def clang_format(s): try: - p = subprocess.Popen(["clang-format"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) - out, err = p.communicate(s.encode('utf-8')) - if p.returncode != 0: - print("Failed to run clang-format: %s", err) - return s - return out.decode('utf-8') + p = subprocess.Popen( + ["clang-format"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) + out, err = p.communicate(s.encode('utf-8')) + if p.returncode != 0: + print("Failed to run clang-format: %s", err) + return s + return out.decode('utf-8') except (RuntimeError, FileNotFoundError) as e: - print("Failed to run clang-format: %s", e) - return s + print("Failed to run clang-format: %s", e) + return s class ModToolAdd(ModTool): @@ -41,7 +42,7 @@ class ModToolAdd(ModTool): name = 'add' description = 'Add new block into a module.' block_types = ('sink', 'source', 'sync', 'decimator', 'interpolator', - 'general', 'tagged_stream', 'hier', 'noblock') + 'general', 'tagged_stream', 'hier', 'noblock') language_candidates = ('cpp', 'python', 'c++') def __init__(self, blockname=None, block_type=None, lang=None, copyright=None, @@ -69,24 +70,28 @@ def validate(self): if self.info['lang'] not in self.language_candidates: raise ModToolException('Invalid programming language.') if self.info['blocktype'] == 'tagged_stream' and self.info['lang'] == 'python': - raise ModToolException('Tagged Stream Blocks for Python currently unsupported') + raise ModToolException( + 'Tagged Stream Blocks for Python currently unsupported') if self.info['blockname'] is None: raise ModToolException('Blockname not specified.') validate_name('block', self.info['blockname']) if not isinstance(self.add_py_qa, bool): - raise ModToolException('Expected a boolean value for add_python_qa.') + raise ModToolException( + 'Expected a boolean value for add_python_qa.') if not isinstance(self.add_cc_qa, bool): raise ModToolException('Expected a boolean value for add_cpp_qa.') if not isinstance(self.skip_cmakefiles, bool): - raise ModToolException('Expected a boolean value for skip_cmakefiles.') + raise ModToolException( + 'Expected a boolean value for skip_cmakefiles.') def assign(self): if self.info['lang'] == 'c++': self.info['lang'] = 'cpp' - if ((self.skip_subdirs['lib'] and self.info['lang'] == 'cpp') - or (self.skip_subdirs['python'] and self.info['lang'] == 'python')): + if ((self.skip_subdirs['lib'] and self.info['lang'] == 'cpp') or + (self.skip_subdirs['python'] and self.info['lang'] == 'python')): raise ModToolException('Missing or skipping relevant subdir.') - self.info['fullblockname'] = self.info['modname'] + '_' + self.info['blockname'] + self.info['fullblockname'] = self.info['modname'] + \ + '_' + self.info['blockname'] if not self.license_file: if self.info['copyrightholder'] is None: self.info['copyrightholder'] = '<+YOU OR YOUR COMPANY+>' @@ -105,7 +110,7 @@ def setup_choose_license(self): top directory 3) The default license. """ if self.license_file is not None \ - and os.path.isfile(self.license_file): + and os.path.isfile(self.license_file): with open(self.license_file) as f: return f.read() elif os.path.isfile('LICENSE'): @@ -123,9 +128,9 @@ def _write_tpl(self, tpl, path, fname): """ Shorthand for writing a substituted template to a file""" path_to_file = os.path.join(path, fname) logger.info(f"Adding file '{path_to_file}'...") - formatter = lambda x: x + def formatter(x): return x if fname.endswith('.cc') or fname.endswith('.h'): - formatter = clang_format + formatter = clang_format with open(path_to_file, 'w') as f: f.write(formatter(render_template(tpl, **self.info))) self.scm.add_files((path_to_file,)) @@ -138,14 +143,14 @@ def run(self): self.assign() has_pybind = ( - self.info['lang'] == 'cpp' - and not self.skip_subdirs['python'] + self.info['lang'] == 'cpp' and + not self.skip_subdirs['python'] ) has_grc = False if self.info['lang'] == 'cpp': self._run_lib() has_grc = has_pybind - else: # Python + else: # Python self._run_python() if self.info['blocktype'] != 'noblock': has_grc = True @@ -159,10 +164,10 @@ def run(self): def _run_cc_qa(self): " Add C++ QA files for 3.7 API if intructed from _run_lib" blockname_ = self.info['blockname'] - fname_qa_h = f'qa_{blockname_}.h' + fname_qa_h = f'qa_{blockname_}.h' fname_qa_cc = f'qa_{blockname_}.cc' self._write_tpl('qa_cpp', 'lib', fname_qa_cc) - self._write_tpl('qa_h', 'lib', fname_qa_h) + self._write_tpl('qa_h', 'lib', fname_qa_h) modname_ = self.info['modname'] if self.skip_cmakefiles: return @@ -191,7 +196,7 @@ def _run_cc_qa_boostutf(self): return try: append_re_line_sequence(self._file['cmlib'], - fr'list\(APPEND test_{modname_}_sources.*\n', + fr'list\(APPEND test_{modname_}_sources.*\n', f'qa_{blockname_}.cc') self.scm.mark_files_updated((self._file['cmlib'],)) except IOError: @@ -210,25 +215,28 @@ def _run_lib(self): fname_h = self.info['blockname'] + '.h' fname_cc = self.info['blockname'] + '.cc' if self.info['blocktype'] in ('source', 'sink', 'sync', 'decimator', - 'interpolator', 'general', 'hier', 'tagged_stream'): + 'interpolator', 'general', 'hier', 'tagged_stream'): fname_cc = self.info['blockname'] + '_impl.cc' - self._write_tpl('block_impl_h', 'lib', self.info['blockname'] + '_impl.h') + self._write_tpl('block_impl_h', 'lib', + self.info['blockname'] + '_impl.h') self._write_tpl('block_impl_cpp', 'lib', fname_cc) - self._write_tpl('block_def_h', self.info['includedir'], fname_h) - else: # Pre-3.7 or autotools - fname_h = self.info['fullblockname'] + '.h' + self._write_tpl('block_def_h', self.info['includedir'], fname_h) + else: # Pre-3.7 or autotools + fname_h = self.info['fullblockname'] + '.h' fname_cc = self.info['fullblockname'] + '.cc' - self._write_tpl('block_h36', self.info['includedir'], fname_h) - self._write_tpl('block_cpp36', 'lib', fname_cc) + self._write_tpl('block_h36', self.info['includedir'], fname_h) + self._write_tpl('block_cpp36', 'lib', fname_cc) if self.add_cc_qa: if self.info['version'] == '38': self._run_cc_qa_boostutf() elif self.info['version'] == '37': self._run_cc_qa() elif self.info['version'] == '36': - logger.warning("Warning: C++ QA files not supported for 3.6-style OOTs.") + logger.warning( + "Warning: C++ QA files not supported for 3.6-style OOTs.") elif self.info['version'] == 'autofoo': - logger.warning("Warning: C++ QA files not supported for autotools.") + logger.warning( + "Warning: C++ QA files not supported for autotools.") if not self.skip_cmakefiles: ed = CMakeFileEditor(self._file['cmlib']) cmake_list_var = '[a-z]*_?' + self.info['modname'] + '_sources' @@ -236,35 +244,39 @@ def _run_lib(self): ed.append_value('add_library', fname_cc) ed.write() ed = CMakeFileEditor(self._file['cminclude']) - ed.append_value('install', fname_h, to_ignore_end='DESTINATION[^()]+') + ed.append_value('install', fname_h, + to_ignore_end='DESTINATION[^()]+') ed.write() - self.scm.mark_files_updated((self._file['cminclude'], self._file['cmlib'])) + self.scm.mark_files_updated( + (self._file['cminclude'], self._file['cmlib'])) def _run_pybind(self): """ Do everything that needs doing in the python bindings subdir. - - add blockname_python.cc + - add blockname_python.cc - add reference and call to bind_blockname() - include them into CMakeLists.txt """ # Generate bindings cc file fname_cc = self.info['blockname'] + '_python.cc' - fname_pydoc_h = os.path.join('docstrings',self.info['blockname'] + '_pydoc_template.h') + fname_pydoc_h = os.path.join( + 'docstrings', self.info['blockname'] + '_pydoc_template.h') # Update python_bindings.cc ed = CPPFileEditor(self._file['ccpybind']) - ed.append_value('// BINDING_FUNCTION_PROTOTYPES(', '// ) END BINDING_FUNCTION_PROTOTYPES', - 'void bind_' + self.info['blockname'] + '(py::module& m);') - ed.append_value('// BINDING_FUNCTION_CALLS(', '// ) END BINDING_FUNCTION_CALLS', - 'bind_' + self.info['blockname'] + '(m);') + ed.append_value('// BINDING_FUNCTION_PROTOTYPES(', '// ) END BINDING_FUNCTION_PROTOTYPES', + 'void bind_' + self.info['blockname'] + '(py::module& m);') + ed.append_value('// BINDING_FUNCTION_CALLS(', '// ) END BINDING_FUNCTION_CALLS', + 'bind_' + self.info['blockname'] + '(m);') ed.write() self.scm.mark_files_updated((self._file['ccpybind'])) - bg = BindingGenerator(prefix=gr.prefix(), namespace=['gr',self.info['modname']], prefix_include_root=self.info['modname']) + bg = BindingGenerator(prefix=gr.prefix(), namespace=[ + 'gr', self.info['modname']], prefix_include_root=self.info['modname']) block_base = "" if self.info['blocktype'] in ('source', 'sink', 'sync', 'decimator', - 'interpolator', 'general', 'hier', 'tagged_stream'): + 'interpolator', 'general', 'hier', 'tagged_stream'): block_base = code_generator.GRTYPELIST[self.info['blocktype']] import hashlib @@ -289,7 +301,7 @@ def _run_pybind(self): "member_functions": [ { "name": "make", - "return_type": "::".join(("gr",self.info['modname'],self.info['blockname'],"sptr")), + "return_type": "::".join(("gr", self.info['modname'], self.info['blockname'], "sptr")), "has_static": "1", "arguments": [] } @@ -312,15 +324,15 @@ def _run_pybind(self): } } # def gen_pybind_cc(self, header_info, base_name): - pydoc_txt = bg.gen_pydoc_h(header_info,self.info['blockname']) - path_to_file = os.path.join('python','bindings', fname_pydoc_h) + pydoc_txt = bg.gen_pydoc_h(header_info, self.info['blockname']) + path_to_file = os.path.join('python', 'bindings', fname_pydoc_h) logger.info("Adding file '{}'...".format(path_to_file)) with open(path_to_file, 'w') as f: f.write(pydoc_txt) self.scm.add_files((path_to_file,)) - cc_txt = bg.gen_pybind_cc(header_info,self.info['blockname']) - path_to_file = os.path.join('python','bindings', fname_cc) + cc_txt = bg.gen_pybind_cc(header_info, self.info['blockname']) + path_to_file = os.path.join('python', 'bindings', fname_cc) logger.info("Adding file '{}'...".format(path_to_file)) with open(path_to_file, 'w') as f: f.write(cc_txt) @@ -328,8 +340,10 @@ def _run_pybind(self): if not self.skip_cmakefiles: ed = CMakeFileEditor(self._file['cmpybind']) - cmake_list_var = 'APPEND {}_python_files'.format(self.info['modname']) - ed.append_value('list', fname_cc, to_ignore_start=cmake_list_var, to_ignore_end='python_bindings.cc') + cmake_list_var = 'APPEND {}_python_files'.format( + self.info['modname']) + ed.append_value('list', fname_cc, to_ignore_start=cmake_list_var, + to_ignore_end='python_bindings.cc') ed.write() self.scm.mark_files_updated((self._file['cmpybind'])) @@ -342,13 +356,14 @@ def _run_python_qa(self): fname_py_qa = 'qa_' + self.info['blockname'] + '.py' self._write_tpl('qa_python', self.info['pydir'], fname_py_qa) os.chmod(os.path.join(self.info['pydir'], fname_py_qa), 0o755) - self.scm.mark_files_updated((os.path.join(self.info['pydir'], fname_py_qa),)) + self.scm.mark_files_updated( + (os.path.join(self.info['pydir'], fname_py_qa),)) if self.skip_cmakefiles or CMakeFileEditor(self._file['cmpython']).check_for_glob('qa_*.py'): return logger.info(f'Editing {self.info["pydir"]}/CMakeLists.txt...') with open(self._file['cmpython'], 'a') as f: f.write( - 'GR_ADD_TEST(qa_%s ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/%s)\n' % \ + 'GR_ADD_TEST(qa_%s ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/%s)\n' % (self.info['blockname'], fname_py_qa)) self.scm.mark_files_updated((self._file['cmpython'],)) @@ -369,7 +384,8 @@ def _run_python(self): if self.skip_cmakefiles: return ed = CMakeFileEditor(self._file['cmpython']) - ed.append_value('GR_PYTHON_INSTALL', fname_py, to_ignore_end='DESTINATION[^()]+') + ed.append_value('GR_PYTHON_INSTALL', fname_py, + to_ignore_end='DESTINATION[^()]+') ed.write() self.scm.mark_files_updated((self._file['cmpython'],)) @@ -385,6 +401,7 @@ def _run_grc(self): if self.skip_cmakefiles or ed.check_for_glob('*.yml'): return logger.info("Editing grc/CMakeLists.txt...") - ed.append_value('install', fname_grc, to_ignore_end='DESTINATION[^()]+') + ed.append_value('install', fname_grc, + to_ignore_end='DESTINATION[^()]+') ed.write() self.scm.mark_files_updated((self._file['cmgrc'],)) diff --git a/gr-utils/modtool/core/base.py b/gr-utils/modtool/core/base.py index d35bc631567..11a5ff37fe0 100644 --- a/gr-utils/modtool/core/base.py +++ b/gr-utils/modtool/core/base.py @@ -47,7 +47,8 @@ class ModToolException(Exception): def validate_name(kind, name): """ Checks that block, module etc names are alphanumeric. """ if not re.fullmatch('[a-zA-Z0-9_]+', name): - raise ModToolException("Invalid {} name '{}': names can only contain letters, numbers and underscores".format(kind, name)) + raise ModToolException( + "Invalid {} name '{}': names can only contain letters, numbers and underscores".format(kind, name)) class ModTool(object): @@ -101,15 +102,18 @@ def _validate(self): def _assign(self): if not self._check_directory(self.dir): - raise ModToolException('No GNU Radio module found in the given directory.') + raise ModToolException( + 'No GNU Radio module found in the given directory.') if self.info['modname'] is None: self.info['modname'] = get_modname() if self.info['modname'] is None: - raise ModToolException('No GNU Radio module found in the given directory.') + raise ModToolException( + 'No GNU Radio module found in the given directory.') if self.info['version'] == '36' and ( os.path.isdir(os.path.join('include', self.info['modname'])) or - os.path.isdir(os.path.join('include', 'gnuradio', self.info['modname'])) - ): + os.path.isdir(os.path.join( + 'include', 'gnuradio', self.info['modname'])) + ): self.info['version'] = '37' if not os.path.isfile(os.path.join('cmake', 'Modules', 'FindCppUnit.cmake')): self.info['version'] = '38' @@ -130,37 +134,44 @@ def _setup_files(self): self.info['pydir'] = 'python' if os.path.isdir(os.path.join('python', self.info['modname'])): self.info['pydir'] = os.path.join('python', self.info['modname']) - self._file['qalib'] = os.path.join('lib', f'qa_{self.info["modname"]}.cc') - self._file['pyinit'] = os.path.join(self.info['pydir'], '__init__.py') - self._file['cmlib'] = os.path.join('lib', 'CMakeLists.txt') - self._file['cmgrc'] = os.path.join('grc', 'CMakeLists.txt') - self._file['cmpython'] = os.path.join(self.info['pydir'], 'CMakeLists.txt') - self._file['cmpybind'] = os.path.join(self.info['pydir'], 'bindings', 'CMakeLists.txt') - self._file['ccpybind'] = os.path.join(self.info['pydir'], 'bindings', 'python_bindings.cc') + self._file['qalib'] = os.path.join( + 'lib', f'qa_{self.info["modname"]}.cc') + self._file['pyinit'] = os.path.join(self.info['pydir'], '__init__.py') + self._file['cmlib'] = os.path.join('lib', 'CMakeLists.txt') + self._file['cmgrc'] = os.path.join('grc', 'CMakeLists.txt') + self._file['cmpython'] = os.path.join( + self.info['pydir'], 'CMakeLists.txt') + self._file['cmpybind'] = os.path.join( + self.info['pydir'], 'bindings', 'CMakeLists.txt') + self._file['ccpybind'] = os.path.join( + self.info['pydir'], 'bindings', 'python_bindings.cc') if self.info['is_component']: - self.info['includedir'] = os.path.join('include', 'gnuradio', self.info['modname']) + self.info['includedir'] = os.path.join( + 'include', 'gnuradio', self.info['modname']) elif self.info['version'] in ('37', '38'): - self.info['includedir'] = os.path.join('include', self.info['modname']) + self.info['includedir'] = os.path.join( + 'include', self.info['modname']) else: self.info['includedir'] = 'include' - self._file['cminclude'] = os.path.join(self.info['includedir'], 'CMakeLists.txt') - self._file['cmfind'] = os.path.join('cmake', 'Modules', 'howtoConfig.cmake') - + self._file['cminclude'] = os.path.join( + self.info['includedir'], 'CMakeLists.txt') def _setup_scm(self, mode='active'): """ Initialize source control management. """ - self.options = SimpleNamespace(scm_mode = self._scm) + self.options = SimpleNamespace(scm_mode=self._scm) if mode == 'active': - self.scm = SCMRepoFactory(self.options, '.').make_active_scm_manager() + self.scm = SCMRepoFactory( + self.options, '.').make_active_scm_manager() else: - self.scm = SCMRepoFactory(self.options, '.').make_empty_scm_manager() + self.scm = SCMRepoFactory( + self.options, '.').make_empty_scm_manager() if self.scm is None: logger.error("Error: Can't set up SCM.") exit(1) def _check_directory(self, directory): """ Guesses if dir is a valid GNU Radio module directory by looking for - CMakeLists.txt and at least one of the subdirs lib/, and python/ + CMakeLists.txt and at least one of the subdirs lib/, and python/ Changes the directory, if valid. """ has_makefile = False try: @@ -174,10 +185,12 @@ def _check_directory(self, directory): if os.path.isfile(f) and f == 'CMakeLists.txt': with open(f) as filetext: if re.search(r'find_package\(Gnuradio', filetext.read()) is not None: - self.info['version'] = '36' # Might be 37, check that later + # Might be 37, check that later + self.info['version'] = '36' has_makefile = True elif re.search('GR_REGISTER_COMPONENT', filetext.read()) is not None: - self.info['version'] = '36' # Might be 37, check that later + # Might be 37, check that later + self.info['version'] = '36' self.info['is_component'] = True has_makefile = True # TODO search for autofoo diff --git a/gr-utils/modtool/core/bind.py b/gr-utils/modtool/core/bind.py index c83a320c001..d14c963cd9c 100644 --- a/gr-utils/modtool/core/bind.py +++ b/gr-utils/modtool/core/bind.py @@ -9,7 +9,6 @@ """ Module to call bindtool and create Python bindings """ - import os import logging import warnings @@ -29,6 +28,7 @@ logger = logging.getLogger(__name__) + class ModToolGenBindings(ModTool): """ Make YAML file for GRC block bindings """ name = 'bind' @@ -65,14 +65,16 @@ def run(self): blocknames_to_process.append(self.info['blockname']) elif self.info['pattern']: # A regex resembling one or several blocks were given - blocknames_to_process = get_block_names(self.info['pattern'], self.info['modname']) + blocknames_to_process = get_block_names( + self.info['pattern'], self.info['modname']) else: raise ModToolException("No block name or regex was specified!") - files_to_process = [os.path.join(self.dir, self.info['includedir'], f'{blockname}.h') for blockname in blocknames_to_process] + files_to_process = [os.path.join( + self.dir, self.info['includedir'], f'{blockname}.h') for blockname in blocknames_to_process] bg = BindingGenerator(prefix=gr.prefix(), namespace=[ - 'gr', self.info['modname']], prefix_include_root=self.info['modname'], output_dir=os.path.join(self.dir, 'python'), - define_symbols=self.info['define_symbols'], addl_includes=self.info['addl_includes'], update_hash_only=self.info['update_hash_only']) + 'gr', self.info['modname']], prefix_include_root=self.info['modname'], output_dir=os.path.join(self.dir, 'python'), + define_symbols=self.info['define_symbols'], addl_includes=self.info['addl_includes'], update_hash_only=self.info['update_hash_only']) for file_to_process in files_to_process: if self.info['update_hash_only']: bg.fix_file_hash(file_to_process) diff --git a/gr-utils/modtool/core/disable.py b/gr-utils/modtool/core/disable.py index 10ce00f04df..6ef885bb9b2 100644 --- a/gr-utils/modtool/core/disable.py +++ b/gr-utils/modtool/core/disable.py @@ -39,40 +39,50 @@ def run(self): """ Go, go, go! """ def _handle_py_qa(cmake, fname): """ Do stuff for py qa """ - cmake.comment_out_lines('GR_ADD_TEST.*'+fname) + cmake.comment_out_lines('GR_ADD_TEST.*' + fname) self.scm.mark_file_updated(cmake.filename) return True + def _handle_py_mod(cmake, fname): """ Do stuff for py extra files """ try: with open(self._file['pyinit']) as f: initfile = f.read() except IOError: - logger.warning("Could not edit __init__.py, that might be a problem.") + logger.warning( + "Could not edit __init__.py, that might be a problem.") return False pymodname = os.path.splitext(fname)[0] - initfile = re.sub(r'((from|import)\s+\b'+pymodname+r'\b)', r'#\1', initfile) + initfile = re.sub( + r'((from|import)\s+\b' + pymodname + r'\b)', r'#\1', initfile) with open(self._file['pyinit'], 'w') as f: f.write(initfile) self.scm.mark_file_updated(self._file['pyinit']) return False + def _handle_cc_qa(cmake, fname): """ Do stuff for cc qa """ if self.info['version'] == '37': - cmake.comment_out_lines(r'\$\{CMAKE_CURRENT_SOURCE_DIR\}/'+fname) + cmake.comment_out_lines( + r'\$\{CMAKE_CURRENT_SOURCE_DIR\}/' + fname) fname_base = os.path.splitext(fname)[0] - ed = CMakeFileEditor(self._file['qalib']) # Abusing the CMakeFileEditor... - ed.comment_out_lines(fr'#include\s+"{fname_base}.h"', comment_str='//') - ed.comment_out_lines(fr'{fname_base}::suite\(\)', comment_str='//') + # Abusing the CMakeFileEditor... + ed = CMakeFileEditor(self._file['qalib']) + ed.comment_out_lines( + fr'#include\s+"{fname_base}.h"', comment_str='//') + ed.comment_out_lines( + fr'{fname_base}::suite\(\)', comment_str='//') ed.write() self.scm.mark_file_updated(self._file['qalib']) elif self.info['version'] == '38': fname_qa_cc = f'qa_{self.info["blockname"]}.cc' cmake.comment_out_lines(fname_qa_cc) elif self.info['version'] == '36': - cmake.comment_out_lines('add_executable.*'+fname) - cmake.comment_out_lines('target_link_libraries.*'+os.path.splitext(fname)[0]) - cmake.comment_out_lines('GR_ADD_TEST.*'+os.path.splitext(fname)[0]) + cmake.comment_out_lines('add_executable.*' + fname) + cmake.comment_out_lines( + 'target_link_libraries.*' + os.path.splitext(fname)[0]) + cmake.comment_out_lines( + 'GR_ADD_TEST.*' + os.path.splitext(fname)[0]) self.scm.mark_file_updated(cmake.filename) return True @@ -83,9 +93,9 @@ def _handle_cc_qa(cmake, fname): from ..cli import cli_input # List of special rules: 0: subdir, 1: filename re match, 2: callback special_treatments = ( - ('python', r'qa.+py$', _handle_py_qa), - ('python', r'^(?!qa).+py$', _handle_py_mod), - ('lib', r'qa.+\.cc$', _handle_cc_qa) + ('python', r'qa.+py$', _handle_py_qa), + ('python', r'^(?!qa).+py$', _handle_py_mod), + ('lib', r'qa.+\.cc$', _handle_cc_qa) ) for subdir in self._subdirs: if self.skip_subdirs[subdir]: @@ -119,7 +129,8 @@ def _handle_cc_qa(cmake, fname): for fname in filenames: file_disabled = False if not yes: - ans = cli_input(f"Really disable {fname}? [Y/n/a/q]: ").lower().strip() + ans = cli_input( + f"Really disable {fname}? [Y/n/a/q]: ").lower().strip() if ans == 'a': yes = True if ans == 'q': @@ -132,5 +143,7 @@ def _handle_cc_qa(cmake, fname): if not file_disabled: cmake.disable_file(fname) cmake.write() - self.scm.mark_files_updated((os.path.join(subdir, 'CMakeLists.txt'),)) - logger.warning("Careful: 'gr_modtool disable' does not resolve dependencies.") + self.scm.mark_files_updated( + (os.path.join(subdir, 'CMakeLists.txt'),)) + logger.warning( + "Careful: 'gr_modtool disable' does not resolve dependencies.") diff --git a/gr-utils/modtool/core/info.py b/gr-utils/modtool/core/info.py index fd90aef8962..42d5e2452dd 100644 --- a/gr-utils/modtool/core/info.py +++ b/gr-utils/modtool/core/info.py @@ -32,15 +32,18 @@ def run(self): mod_info = dict() mod_info['base_dir'] = self._get_base_dir(self._directory) if mod_info['base_dir'] is None: - raise ModToolException('{}' if self._python_readable else "No module found.") + raise ModToolException( + '{}' if self._python_readable else "No module found.") os.chdir(mod_info['base_dir']) mod_info['modname'] = get_modname() if mod_info['modname'] is None: - raise ModToolException('{}' if self._python_readable else "No module found.") + raise ModToolException( + '{}' if self._python_readable else "No module found.") if self.info['version'] == '36' and ( os.path.isdir(os.path.join('include', mod_info['modname'])) or - os.path.isdir(os.path.join('include', 'gnuradio', mod_info['modname'])) - ): + os.path.isdir(os.path.join( + 'include', 'gnuradio', mod_info['modname'])) + ): self.info['version'] = '37' if not os.path.isfile(os.path.join('cmake', 'Modules', 'FindCppUnit.cmake')): self.info['version'] = '38' @@ -50,7 +53,8 @@ def run(self): mod_info['incdirs'] = [] mod_incl_dir = os.path.join(mod_info['base_dir'], 'include') if os.path.isdir(os.path.join(mod_incl_dir, mod_info['modname'])): - mod_info['incdirs'].append(os.path.join(mod_incl_dir, mod_info['modname'])) + mod_info['incdirs'].append(os.path.join( + mod_incl_dir, mod_info['modname'])) else: mod_info['incdirs'].append(mod_incl_dir) build_dir = self._get_build_dir(mod_info) @@ -100,31 +104,34 @@ def _get_include_dirs(self, mod_info): path_or_internal = {True: 'INTERNAL', False: 'PATH'}['is_component' in list(mod_info.keys())] try: - cmakecache_fid = open(os.path.join(mod_info['build_dir'], 'CMakeCache.txt')) + cmakecache_fid = open(os.path.join( + mod_info['build_dir'], 'CMakeCache.txt')) for line in cmakecache_fid: if line.find(f'GNURADIO_RUNTIME_INCLUDE_DIRS:{path_or_internal}') != -1: - inc_dirs += line.replace(f'GNURADIO_RUNTIME_INCLUDE_DIRS:{path_or_internal}=', '').strip().split(';') + inc_dirs += line.replace( + f'GNURADIO_RUNTIME_INCLUDE_DIRS:{path_or_internal}=', '').strip().split(';') except IOError: pass if not inc_dirs and self._suggested_dirs is not None: - inc_dirs = [os.path.normpath(path) for path in self._suggested_dirs.split(':') if os.path.isdir(path)] + inc_dirs = [os.path.normpath(path) for path in self._suggested_dirs.split( + ':') if os.path.isdir(path)] return inc_dirs def _pretty_print(elf, mod_info): """ Output the module info in human-readable format """ index_names = {'base_dir': 'Base directory', - 'modname': 'Module name', - 'is_component': 'Is GR component', + 'modname': 'Module name', + 'is_component': 'Is GR component', 'build_dir': 'Build directory', 'incdirs': 'Include directories'} for key in list(mod_info.keys()): if key == 'version': version = { - '36': 'pre-3.7', - '37': 'post-3.7', - '38': 'post-3.8', - 'autofoo': 'Autotools (pre-3.5)' - }[mod_info['version']] + '36': 'pre-3.7', + '37': 'post-3.7', + '38': 'post-3.8', + 'autofoo': 'Autotools (pre-3.5)' + }[mod_info['version']] print(f" API version: {version}") else: print('%19s: %s' % (index_names[key], mod_info[key])) diff --git a/gr-utils/modtool/core/makeyaml.py b/gr-utils/modtool/core/makeyaml.py index bd4fd7b535a..a4842844ca0 100644 --- a/gr-utils/modtool/core/makeyaml.py +++ b/gr-utils/modtool/core/makeyaml.py @@ -73,7 +73,8 @@ def run(self): # This portion will be covered by the CLI if not self.cli: self.validate() - logger.warning("Warning: This is an experimental feature. Don't expect any magic.") + logger.warning( + "Warning: This is an experimental feature. Don't expect any magic.") # 1) Go through lib/ if not self.skip_subdirs['lib']: if self.info['version'] in ('37', '38'): @@ -158,7 +159,8 @@ def _make_grc_yaml_from_block_data(self, params, iosig, blockname): ed = CMakeFileEditor(self._file['cmgrc']) if re.search(fname_yml, ed.cfile) is None and not ed.check_for_glob('*.yml'): logger.info("Adding GRC bindings to grc/CMakeLists.txt...") - ed.append_value('install', fname_yml, to_ignore_end='DESTINATION[^()]+') + ed.append_value('install', fname_yml, + to_ignore_end='DESTINATION[^()]+') ed.write() self.scm.mark_files_updated(self._file['cmgrc']) @@ -186,26 +188,30 @@ def _type_translate(p_type, default_v=None): def _get_blockdata(fname_cc): """ Return the block name and the header file name from the .cc file name """ - blockname = os.path.splitext(os.path.basename(fname_cc.replace('_impl.', '.')))[0] + blockname = os.path.splitext(os.path.basename( + fname_cc.replace('_impl.', '.')))[0] fname_h = (blockname + '.h').replace('_impl.', '.') - contains_modulename = blockname.startswith(self.info['modname']+'_') - blockname = blockname.replace(self.info['modname']+'_', '', 1) + contains_modulename = blockname.startswith( + self.info['modname'] + '_') + blockname = blockname.replace(self.info['modname'] + '_', '', 1) return (blockname, fname_h, contains_modulename) # Go, go, go logger.info(f"Making GRC bindings for {fname_cc}...") (blockname, fname_h, contains_modulename) = _get_blockdata(fname_cc) try: parser = ParserCCBlock(fname_cc, - os.path.join(self.info['includedir'], fname_h), + os.path.join( + self.info['includedir'], fname_h), blockname, self.info['version'], _type_translate ) except IOError: - raise ModToolException(f"Can't open some of the files necessary to parse {fname_cc}.") + raise ModToolException( + f"Can't open some of the files necessary to parse {fname_cc}.") if contains_modulename: - return (parser.read_params(), parser.read_io_signature(), self.info['modname']+'_'+blockname) + return (parser.read_params(), parser.read_io_signature(), self.info['modname'] + '_' + blockname) else: return (parser.read_params(), parser.read_io_signature(), blockname) @@ -218,14 +224,14 @@ def yaml_generator(self, **kwargs): block = self.modname.split('-')[-1] label = header.split('_') del label[-1] - yml_file = os.path.join('.', block+'_'+header+'.block.yml') + yml_file = os.path.join('.', block + '_' + header + '.block.yml') _header = (('id', f'{block}_{ header}'), ('label', ' '.join(label).upper()), ('category', f'[{block.capitalize()}]'), ('flags', '[python, cpp]') ) params_list = [ - '${'+s['name']+'}' for s in self.parsed_data['properties'] if self.parsed_data['properties']] + '${' + s['name'] + '}' for s in self.parsed_data['properties'] if self.parsed_data['properties']] str_ = ', '.join(params_list) _templates = [('imports', f'from gnuradio import {block}'), ('make', f'{block}.{ header}({str_})') @@ -237,10 +243,10 @@ def yaml_generator(self, **kwargs): arguments = [] for args in param['arguments_type']: arguments.append(args['name']) - arg_list = ['${'+s+'}' for s in arguments if arguments] + arg_list = ['${' + s + '}' for s in arguments if arguments] arg_ = ', '.join(arg_list) list_callbacks.append( - param['name']+f'({arg_})') + param['name'] + f'({arg_})') callback_key = ('callbacks') callbacks = (callback_key, tuple(list_callbacks)) _templates.append(callbacks) @@ -277,11 +283,11 @@ def yaml_generator(self, **kwargs): elif i_sig is Constants.MAKE2: input_sig['domain'] = 'stream' input_sig['dtype'] = self.parsed_data['io_signature']['input']['sizeof_stream_item' + - str(port+1)] + str(port + 1)] elif i_sig is Constants.MAKE3: input_sig['domain'] = 'stream' input_sig['dtype'] = self.parsed_data['io_signature']['input']['sizeof_stream_item' + - str(port+1)] + str(port + 1)] elif i_sig is Constants.MAKEV: input_sig['domain'] = 'stream' input_sig['dtype'] = self.parsed_data['io_signature']['input']['sizeof_stream_items'] @@ -307,11 +313,11 @@ def yaml_generator(self, **kwargs): elif o_sig is Constants.MAKE2: output_sig['domain'] = 'stream' output_sig['dtype'] = self.parsed_data['io_signature']['output']['sizeof_stream_item' + - str(port+1)] + str(port + 1)] elif o_sig is Constants.MAKE3: output_sig['domain'] = 'stream' output_sig['dtype'] = self.parsed_data['io_signature']['output']['sizeof_stream_item' + - str(port+1)] + str(port + 1)] elif o_sig is Constants.MAKEV: output_sig['domain'] = 'stream' output_sig['dtype'] = self.parsed_data['io_signature']['output']['sizeof_stream_items'] @@ -325,11 +331,12 @@ def yaml_generator(self, **kwargs): output_signature.append(m_output_sig) if output_signature: data['outputs'] = output_signature - + param_ = ', '.join(params_list) _cpp_templates = [('includes', '#include '), ('declarations', '{block}::{ header}::sptr ${{id}}'), - ('make', 'this->${{id}} = {block}::{ header}::make({param_})') + ('make', + 'this->${{id}} = {block}::{ header}::make({param_})') ] if self.parsed_data['methods']: @@ -338,10 +345,10 @@ def yaml_generator(self, **kwargs): arguments = [] for args in param['arguments_type']: arguments.append(args['name']) - arg_list = ['${'+s+'}' for s in arguments if arguments] + arg_list = ['${' + s + '}' for s in arguments if arguments] arg_ = ', '.join(arg_list) list_callbacks.append( - param['name']+f'({arg_})') + param['name'] + f'({arg_})') callback_key = ('callbacks') callbacks = (callback_key, tuple(list_callbacks)) _cpp_templates.append(callbacks) diff --git a/gr-utils/modtool/core/newmod.py b/gr-utils/modtool/core/newmod.py index babebfcde07..5f63825111d 100644 --- a/gr-utils/modtool/core/newmod.py +++ b/gr-utils/modtool/core/newmod.py @@ -20,10 +20,12 @@ logger = logging.getLogger(__name__) + class ModToolNewModule(ModTool): """ Create a new out-of-tree module """ name = 'newmod' description = 'Create new empty module, use add to add blocks.' + def __init__(self, module_name=None, srcdir=None, **kwargs): ModTool.__init__(self, None, module_name, **kwargs) # Don't call ModTool._validate(), that assumes an existing module. @@ -33,7 +35,8 @@ def __init__(self, module_name=None, srcdir=None, **kwargs): def assign(self): self.dir = os.path.join(self.directory, f'gr-{self.info["modname"]}') if self.srcdir is None: - self.srcdir = os.path.join(gr.prefix(),'share','gnuradio','modtool','templates','gr-newmod') + self.srcdir = os.path.join( + gr.prefix(), 'share', 'gnuradio', 'modtool', 'templates', 'gr-newmod') def validate(self): """ Validates the arguments """ @@ -43,11 +46,12 @@ def validate(self): try: os.stat(self.dir) except OSError: - pass # This is what should happen + pass # This is what should happen else: raise ModToolException('The given directory exists.') if not os.path.isdir(self.srcdir): - raise ModToolException('Could not find gr-newmod source dir \'' + self.srcdir + '\'') + raise ModToolException( + 'Could not find gr-newmod source dir \'' + self.srcdir + '\'') def run(self): """ @@ -64,10 +68,10 @@ def run(self): try: shutil.copytree(self.srcdir, self.dir) try: - shutil.copyfile(os.path.join(gr.prefix(), 'share', 'gnuradio', 'clang-format.conf'), - os.path.join(self.dir, '.clang-format')) + shutil.copyfile(os.path.join(gr.prefix(), 'share', 'gnuradio', 'clang-format.conf'), + os.path.join(self.dir, '.clang-format')) except FileNotFoundError as e: - logger.info(f'Failed to copy .clang-format: {e}') + logger.info(f'Failed to copy .clang-format: {e}') os.chdir(self.dir) except OSError: raise ModToolException(f'Could not create directory {self.dir}.') @@ -81,10 +85,14 @@ def run(self): with open(f, 'w') as filetext: filetext.write(s) if filename.find('howto') != -1: - os.rename(f, os.path.join(root, filename.replace('howto', self.info['modname']))) + os.rename(f, os.path.join( + root, filename.replace('howto', self.info['modname']))) if os.path.basename(root) == 'howto': - os.rename(root, os.path.join(os.path.dirname(root), self.info['modname'])) + os.rename(root, os.path.join( + os.path.dirname(root), self.info['modname'])) logger.info("Done.") if self.scm.init_repo(path_to_repo="."): - logger.info("Created repository... you might want to commit before continuing.") - logger.info("Use 'gr_modtool add' to add a new block to this currently empty module.") + logger.info( + "Created repository... you might want to commit before continuing.") + logger.info( + "Use 'gr_modtool add' to add a new block to this currently empty module.") diff --git a/gr-utils/modtool/core/rename.py b/gr-utils/modtool/core/rename.py index edae90389a1..37c7792f647 100644 --- a/gr-utils/modtool/core/rename.py +++ b/gr-utils/modtool/core/rename.py @@ -37,15 +37,16 @@ def validate(self): block_candidates = get_block_candidates() if self.info['oldname'] not in block_candidates: choices = [x for x in block_candidates if self.info['oldname'] in x] - if len(choices)>0: - print("Suggested alternatives: "+str(choices)) + if len(choices) > 0: + print("Suggested alternatives: " + str(choices)) raise ModToolException("Blockname for renaming does not exists!") if not self.info['newname']: raise ModToolException('New blockname (new_name) not specified.') validate_name('new block', self.info['newname']) def assign(self): - self.info['fullnewname'] = self.info['modname'] + '_' + self.info['newname'] + self.info['fullnewname'] = self.info['modname'] + \ + '_' + self.info['newname'] def run(self): """ Go, go, go. """ @@ -56,7 +57,8 @@ def run(self): module = self.info['modname'] oldname = self.info['oldname'] newname = self.info['newname'] - logger.info(f"In module '{module}' rename block '{oldname}' to '{newname}'") + logger.info( + f"In module '{module}' rename block '{oldname}' to '{newname}'") self._run_grc_rename(self.info['modname'], oldname, newname) self._run_python_qa(self.info['modname'], oldname, newname) self._run_python(self.info['modname'], oldname, newname) @@ -72,7 +74,8 @@ def _run_lib(self, module, old, new): hfile = './lib/' + old + '_impl.h' self._run_file_replace(ccfile, old, new) self._run_file_replace(hfile, old, new) - self._run_file_replace(hfile, old.upper(), new.upper()) # take care of include guards + # take care of include guards + self._run_file_replace(hfile, old.upper(), new.upper()) self._run_cmakelists('./lib/', old, new, '_impl.cc') self._run_cmakelists('./lib/', old, new, '_impl.h') self._run_file_rename('./lib/', old, new, '_impl.cc') @@ -99,7 +102,8 @@ def _run_include(self, module, old, new): path = './include/' + module + '/' filename = path + old + '.h' self._run_file_replace(filename, old, new) - self._run_file_replace(filename, old.upper(), new.upper()) # take care of include guards + # take care of include guards + self._run_file_replace(filename, old.upper(), new.upper()) self._run_cmakelists(path, old, new, '.h') self._run_file_rename(path, old, new, '.h') @@ -125,7 +129,8 @@ def _run_pybind(self, module, old, new): # update the hash in the new file import hashlib hasher = hashlib.md5() - header_filename = './include/' + module + '/' + new + '.h' # note this requires _run_pybind to be called after _run_include + # note this requires _run_pybind to be called after _run_include + header_filename = './include/' + module + '/' + new + '.h' with open(header_filename, 'rb') as file_in: buf = file_in.read() hasher.update(buf) @@ -141,7 +146,8 @@ def _run_pybind(self, module, old, new): f.write(file_txt) filename = path + 'python_bindings.cc' - self._run_file_replace(filename, ' bind_' + old + '\\(', ' bind_' + new + '(') + self._run_file_replace(filename, ' bind_' + + old + '\\(', ' bind_' + new + '(') path = './python/bindings/docstrings/' filename = path + old + '_pydoc_template.h' @@ -159,13 +165,16 @@ def _run_python_qa(self, module, old, new): def _run_grc_rename(self, module, old, new): grcfile = './grc/' + module + '_' + old + '.block.yml' self._run_file_replace(grcfile, old, new) - self._run_cmakelists('./grc/', module + '_' + old, module + '_' + new, '.block.yml') - self._run_file_rename('./grc/', module + '_' + old, module + '_' + new, '.block.yml') + self._run_cmakelists('./grc/', module + '_' + old, + module + '_' + new, '.block.yml') + self._run_file_rename('./grc/', module + '_' + old, + module + '_' + new, '.block.yml') def _run_cmakelists(self, path, first, second, suffix): filename = path + 'CMakeLists.txt' # space character and suffix ensures similiarly named blocks are not mixed up - nsubs = self._run_file_replace(filename, ' ' + first + suffix, ' ' + second + suffix) + nsubs = self._run_file_replace( + filename, ' ' + first + suffix, ' ' + second + suffix) if nsubs < 1: logger.info(f"'{first}' wasn't in '{filename}'.") @@ -186,7 +195,8 @@ def _run_file_replace(self, filename, old, new): if not os.path.isfile(filename): return False else: - logger.info(f"In '{filename}' renaming occurrences of '{old}' to '{new}'") + logger.info( + f"In '{filename}' renaming occurrences of '{old}' to '{new}'") with open(filename) as f: cfile = f.read() diff --git a/gr-utils/modtool/core/rm.py b/gr-utils/modtool/core/rm.py index e8f6a74c09b..21bf999d53d 100644 --- a/gr-utils/modtool/core/rm.py +++ b/gr-utils/modtool/core/rm.py @@ -43,6 +43,7 @@ def run(self): self.validate() else: from ..cli import cli_input + def _remove_cc_test_case(filename=None, ed=None): """ Special function that removes the occurrences of a qa*.cc file from the CMakeLists.txt. """ @@ -56,7 +57,7 @@ def _remove_cc_test_case(filename=None, ed=None): fr'^#include "{filename}"\s*$') remove_pattern_from_file(self._file['qalib'], fr'^\s*s->addTest\(gr::{modname_}::{base}::suite\(\)\);\s*$' - ) + ) self.scm.mark_file_updated(self._file['qalib']) elif ext == '.cc': ed.remove_value('list', @@ -68,7 +69,7 @@ def _remove_cc_test_case(filename=None, ed=None): if ext == '.cc': ed.remove_value( 'list', filename, - to_ignore_start=f'APPEND test_{modname_}_sources' ) + to_ignore_start=f'APPEND test_{modname_}_sources') self.scm.mark_file_updated(ed.filename) else: filebase = os.path.splitext(filename)[0] @@ -92,12 +93,16 @@ def _remove_py_test_case(filename=None, ed=None): py_files_deleted = self._run_subdir('python', ('*.py',), ('GR_PYTHON_INSTALL',), cmakeedit_func=_remove_py_test_case) for f in py_files_deleted: - remove_pattern_from_file(self._file['pyinit'], fr'.*import\s+{f[:-3]}.*') - remove_pattern_from_file(self._file['pyinit'], fr'.*from\s+{f[:-3]}\s+import.*\n') + remove_pattern_from_file( + self._file['pyinit'], fr'.*import\s+{f[:-3]}.*') + remove_pattern_from_file( + self._file['pyinit'], fr'.*from\s+{f[:-3]}\s+import.*\n') - pb_files_deleted = self._run_subdir('python/bindings', ('*.cc',), ('list',)) + pb_files_deleted = self._run_subdir( + 'python/bindings', ('*.cc',), ('list',)) - pbdoc_files_deleted = self._run_subdir('python/bindings/docstrings', ('*.h',), ('',)) + pbdoc_files_deleted = self._run_subdir( + 'python/bindings/docstrings', ('*.h',), ('',)) # Update python_bindings.cc blocknames_to_delete = [] @@ -106,22 +111,24 @@ def _remove_py_test_case(filename=None, ed=None): blocknames_to_delete.append(self.info['blockname']) elif self.info['pattern']: # A regex resembling one or several blocks were given - blocknames_to_delete = get_block_names(self.info['pattern'], self.info['modname']) + blocknames_to_delete = get_block_names( + self.info['pattern'], self.info['modname']) else: raise ModToolException("No block name or regex was specified!") for blockname in blocknames_to_delete: ed = CPPFileEditor(self._file['ccpybind']) - ed.remove_value('// BINDING_FUNCTION_PROTOTYPES(', '// ) END BINDING_FUNCTION_PROTOTYPES', - 'void bind_' + blockname + '(py::module& m);') - ed.remove_value('// BINDING_FUNCTION_CALLS(', '// ) END BINDING_FUNCTION_CALLS', - 'bind_' + blockname + '(m);') + ed.remove_value('// BINDING_FUNCTION_PROTOTYPES(', '// ) END BINDING_FUNCTION_PROTOTYPES', + 'void bind_' + blockname + '(py::module& m);') + ed.remove_value('// BINDING_FUNCTION_CALLS(', '// ) END BINDING_FUNCTION_CALLS', + 'bind_' + blockname + '(m);') ed.write() if not self.skip_subdirs['lib']: self._run_subdir('lib', ('*.cc', '*.h'), ('add_library', 'list'), cmakeedit_func=_remove_cc_test_case) if not self.skip_subdirs['include']: - incl_files_deleted = self._run_subdir(self.info['includedir'], ('*.h',), ('install',)) + incl_files_deleted = self._run_subdir( + self.info['includedir'], ('*.h',), ('install',)) if not self.skip_subdirs['grc']: self._run_subdir('grc', ('*.yml',), ('install',)) @@ -173,7 +180,8 @@ def _run_subdir(self, path, globs, makefile_vars, cmakeedit_func=None): for f in files_filt: b = os.path.basename(f) if not yes and self.cli: - ans = cli_input(f"Really delete {f}? [Y/n/a/q]: ").lower().strip() + ans = cli_input( + f"Really delete {f}? [Y/n/a/q]: ").lower().strip() if ans == 'a': yes = True if ans == 'q': @@ -187,7 +195,8 @@ def _run_subdir(self, path, globs, makefile_vars, cmakeedit_func=None): if (os.path.exists(f'{path}/CMakeLists.txt')): ed = CMakeFileEditor(f'{path}/CMakeLists.txt') - logger.info(f"Deleting occurrences of {b} from {path}/CMakeLists.txt...") + logger.info( + f"Deleting occurrences of {b} from {path}/CMakeLists.txt...") for var in makefile_vars: ed.remove_value(var, b) if cmakeedit_func is not None: diff --git a/gr-utils/modtool/core/update.py b/gr-utils/modtool/core/update.py index 73e0060f610..ee8b78179eb 100644 --- a/gr-utils/modtool/core/update.py +++ b/gr-utils/modtool/core/update.py @@ -42,7 +42,6 @@ def __init__(self, blockname=None, complete=False, include_blacklisted=False, ** self.info['complete'] = complete self.info['include_blacklisted'] = include_blacklisted - def validate(self): """ Validates the arguments """ ModTool._validate(self) @@ -52,16 +51,18 @@ def validate(self): raise ModToolException('Block name not specified!') block_candidates = get_xml_candidates() if self.info['blockname'] not in block_candidates: - choices = [x for x in block_candidates if self.info['blockname'] in x] + choices = [ + x for x in block_candidates if self.info['blockname'] in x] if len(choices) > 0: - print("Suggested alternatives: "+str(choices)) + print("Suggested alternatives: " + str(choices)) raise ModToolException("The XML bindings does not exists!") def run(self): from gnuradio.grc.converter import Converter if not self.cli: self.validate() - logger.warning("Warning: This is an experimental feature. Please verify the bindings.") + logger.warning( + "Warning: This is an experimental feature. Please verify the bindings.") module_name = self.info['modname'] path = './grc/' conv = Converter(path, path) @@ -72,10 +73,10 @@ def run(self): for blockname in blocks: xml_file = f"{module_name}_{blockname}.xml" yml_file = f"{module_name}_{blockname}.block.yml" - if not conv.load_block_xml(path+xml_file, self.info["include_blacklisted"]): + if not conv.load_block_xml(path + xml_file, self.info["include_blacklisted"]): continue logger.info(f"Converted {xml_file} to {yml_file}") - os.remove(path+xml_file) + os.remove(path + xml_file) nsubs = self._run_cmakelists(xml_file, yml_file) if nsubs > 1: logger.warning("Changed more than expected for the block '%s' in the CMakeLists.txt. " diff --git a/gr-utils/modtool/templates/gr-newmod/CMakeLists.txt b/gr-utils/modtool/templates/gr-newmod/CMakeLists.txt index c4d05546061..3c15e25e3db 100644 --- a/gr-utils/modtool/templates/gr-newmod/CMakeLists.txt +++ b/gr-utils/modtool/templates/gr-newmod/CMakeLists.txt @@ -51,11 +51,11 @@ if((CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR endif() IF(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - SET(CMAKE_CXX_STANDARD 14) + SET(CMAKE_CXX_STANDARD 17) ELSEIF(CMAKE_CXX_COMPILER_ID MATCHES "Clang") - SET(CMAKE_CXX_STANDARD 14) + SET(CMAKE_CXX_STANDARD 17) ELSEIF(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - SET(CMAKE_CXX_STANDARD 14) + SET(CMAKE_CXX_STANDARD 17) ELSE() message(WARNING "C++ standard could not be set because compiler is not GNU, Clang or MSVC.") ENDIF() @@ -83,7 +83,7 @@ if(NOT CMAKE_MODULES_DIR) endif(NOT CMAKE_MODULES_DIR) set(GR_INCLUDE_DIR include/howto) -set(GR_CMAKE_DIR ${CMAKE_MODULES_DIR}/howto) +set(GR_CMAKE_DIR ${CMAKE_MODULES_DIR}/gnuradio-howto) set(GR_PKG_DATA_DIR ${GR_DATA_DIR}/${CMAKE_PROJECT_NAME}) set(GR_PKG_DOC_DIR ${GR_DOC_DIR}/${CMAKE_PROJECT_NAME}) set(GR_PKG_CONF_DIR ${GR_CONF_DIR}/${CMAKE_PROJECT_NAME}/conf.d) @@ -150,11 +150,3 @@ if(ENABLE_PYTHON) else(ENABLE_PYTHON) message(STATUS "PYTHON and GRC components are disabled") endif(ENABLE_PYTHON) - -######################################################################## -# Install cmake search helper for this library -######################################################################## - -install(FILES cmake/Modules/howtoConfig.cmake - DESTINATION ${CMAKE_MODULES_DIR}/howto -) diff --git a/gr-utils/modtool/templates/gr-newmod/cmake/Modules/howtoConfig.cmake b/gr-utils/modtool/templates/gr-newmod/cmake/Modules/howtoConfig.cmake deleted file mode 100644 index 4f45052a9fd..00000000000 --- a/gr-utils/modtool/templates/gr-newmod/cmake/Modules/howtoConfig.cmake +++ /dev/null @@ -1,32 +0,0 @@ -find_package(PkgConfig) - -PKG_CHECK_MODULES(PC_HOWTO howto) - -FIND_PATH( - HOWTO_INCLUDE_DIRS - NAMES howto/api.h - HINTS $ENV{HOWTO_DIR}/include - ${PC_HOWTO_INCLUDEDIR} - PATHS ${CMAKE_INSTALL_PREFIX}/include - /usr/local/include - /usr/include -) - -FIND_LIBRARY( - HOWTO_LIBRARIES - NAMES gnuradio-howto - HINTS $ENV{HOWTO_DIR}/lib - ${PC_HOWTO_LIBDIR} - PATHS ${CMAKE_INSTALL_PREFIX}/lib - ${CMAKE_INSTALL_PREFIX}/lib64 - /usr/local/lib - /usr/local/lib64 - /usr/lib - /usr/lib64 - ) - -include("${CMAKE_CURRENT_LIST_DIR}/howtoTarget.cmake") - -INCLUDE(FindPackageHandleStandardArgs) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(HOWTO DEFAULT_MSG HOWTO_LIBRARIES HOWTO_INCLUDE_DIRS) -MARK_AS_ADVANCED(HOWTO_LIBRARIES HOWTO_INCLUDE_DIRS) diff --git a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/__init__.py b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/__init__.py index d8ff40daaa5..a50b52f70d8 100644 --- a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/__init__.py +++ b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/__init__.py @@ -55,6 +55,7 @@ from .doxyindex import DoxyIndex, DoxyFunction, DoxyParam, DoxyClass, DoxyFile, DoxyNamespace, DoxyGroup, DoxyFriend, DoxyOther + def _test(): import os this_dir = os.path.dirname(globals()['__file__']) @@ -66,5 +67,6 @@ def _test(): import doctest return doctest.testmod() + if __name__ == "__main__": _test() diff --git a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/base.py b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/base.py index b2c00955cc2..95029293328 100644 --- a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/base.py +++ b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/base.py @@ -83,8 +83,8 @@ def get_cls(self, mem): for cls in self.mem_classes: if cls.can_parse(mem): return cls - raise Exception(("Did not find a class for object '%s'." \ - % (mem.get_name()))) + raise Exception(("Did not find a class for object '%s'." + % (mem.get_name()))) def convert_mem(self, mem): try: diff --git a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/doxyindex.py b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/doxyindex.py index 53e9a63cd5b..56b744660cb 100644 --- a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/doxyindex.py +++ b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/doxyindex.py @@ -18,6 +18,7 @@ from .base import Base from .text import description + class DoxyIndex(Base): """ Parses a doxygen xml directory. @@ -48,7 +49,6 @@ def _parse(self): class DoxyCompMem(Base): - kind = None def __init__(self, *args, **kwargs): @@ -84,9 +84,11 @@ def set_parameters(self, data): class DoxyCompound(DoxyCompMem): pass + class DoxyMember(DoxyCompMem): pass + class DoxyFunction(DoxyMember): __module__ = "gnuradio.utils.doxyxml" @@ -107,9 +109,11 @@ def _parse(self): self._data['params'].append(DoxyParam(prm)) brief_description = property(lambda self: self.data()['brief_description']) - detailed_description = property(lambda self: self.data()['detailed_description']) + detailed_description = property( + lambda self: self.data()['detailed_description']) params = property(lambda self: self.data()['params']) + Base.mem_classes.append(DoxyFunction) @@ -134,9 +138,11 @@ def description(self): return '\n\n'.join(descriptions) brief_description = property(lambda self: self.data()['brief_description']) - detailed_description = property(lambda self: self.data()['detailed_description']) + detailed_description = property( + lambda self: self.data()['detailed_description']) name = property(lambda self: self.data()['declname']) + class DoxyParameterItem(DoxyMember): """A different representation of a parameter in Doxygen.""" @@ -178,9 +184,11 @@ def _parse(self): self.process_memberdefs() brief_description = property(lambda self: self.data()['brief_description']) - detailed_description = property(lambda self: self.data()['detailed_description']) + detailed_description = property( + lambda self: self.data()['detailed_description']) params = property(lambda self: self.data()['params']) + Base.mem_classes.append(DoxyClass) @@ -201,7 +209,9 @@ def _parse(self): self.process_memberdefs() brief_description = property(lambda self: self.data()['brief_description']) - detailed_description = property(lambda self: self.data()['detailed_description']) + detailed_description = property( + lambda self: self.data()['detailed_description']) + Base.mem_classes.append(DoxyFile) @@ -222,6 +232,7 @@ def _parse(self): return self.process_memberdefs() + Base.mem_classes.append(DoxyNamespace) @@ -265,6 +276,7 @@ class DoxyFriend(DoxyMember): kind = 'friend' + Base.mem_classes.append(DoxyFriend) @@ -279,4 +291,5 @@ class DoxyOther(Base): def can_parse(cls, obj): return obj.kind in cls.kinds + Base.mem_classes.append(DoxyOther) diff --git a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/compound.py b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/compound.py index 294f0216e78..321328bcb7e 100644 --- a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/compound.py +++ b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/compound.py @@ -22,13 +22,15 @@ def find(self, details): return self.compounddef.find(details) + supermod.DoxygenType.subclass = DoxygenTypeSub # end class DoxygenTypeSub class compounddefTypeSub(supermod.compounddefType): def __init__(self, kind=None, prot=None, id=None, compoundname='', title='', basecompoundref=None, derivedcompoundref=None, includes=None, includedby=None, incdepgraph=None, invincdepgraph=None, innerdir=None, innerfile=None, innerclass=None, innernamespace=None, innerpage=None, innergroup=None, templateparamlist=None, sectiondef=None, briefdescription=None, detaileddescription=None, inheritancegraph=None, collaborationgraph=None, programlisting=None, location=None, listofallmembers=None): - supermod.compounddefType.__init__(self, kind, prot, id, compoundname, title, basecompoundref, derivedcompoundref, includes, includedby, incdepgraph, invincdepgraph, innerdir, innerfile, innerclass, innernamespace, innerpage, innergroup, templateparamlist, sectiondef, briefdescription, detaileddescription, inheritancegraph, collaborationgraph, programlisting, location, listofallmembers) + supermod.compounddefType.__init__(self, kind, prot, id, compoundname, title, basecompoundref, derivedcompoundref, includes, includedby, incdepgraph, invincdepgraph, innerdir, innerfile, innerclass, + innernamespace, innerpage, innergroup, templateparamlist, sectiondef, briefdescription, detaileddescription, inheritancegraph, collaborationgraph, programlisting, location, listofallmembers) def find(self, details): @@ -48,13 +50,18 @@ def find(self, details): class listofallmembersTypeSub(supermod.listofallmembersType): def __init__(self, member=None): supermod.listofallmembersType.__init__(self, member) + + supermod.listofallmembersType.subclass = listofallmembersTypeSub # end class listofallmembersTypeSub class memberRefTypeSub(supermod.memberRefType): def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope='', name=''): - supermod.memberRefType.__init__(self, virt, prot, refid, ambiguityscope, scope, name) + supermod.memberRefType.__init__( + self, virt, prot, refid, ambiguityscope, scope, name) + + supermod.memberRefType.subclass = memberRefTypeSub # end class memberRefTypeSub @@ -62,6 +69,8 @@ def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope= class compoundRefTypeSub(supermod.compoundRefType): def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): supermod.compoundRefType.__init__(self, mixedclass_, content_) + + supermod.compoundRefType.subclass = compoundRefTypeSub # end class compoundRefTypeSub @@ -69,6 +78,8 @@ def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=No class reimplementTypeSub(supermod.reimplementType): def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): supermod.reimplementType.__init__(self, mixedclass_, content_) + + supermod.reimplementType.subclass = reimplementTypeSub # end class reimplementTypeSub @@ -76,6 +87,8 @@ def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): class incTypeSub(supermod.incType): def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, content_=None): supermod.incType.__init__(self, mixedclass_, content_) + + supermod.incType.subclass = incTypeSub # end class incTypeSub @@ -83,23 +96,26 @@ def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, conten class refTypeSub(supermod.refType): def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): supermod.refType.__init__(self, mixedclass_, content_) + + supermod.refType.subclass = refTypeSub # end class refTypeSub - class refTextTypeSub(supermod.refTextType): def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): supermod.refTextType.__init__(self, mixedclass_, content_) + supermod.refTextType.subclass = refTextTypeSub # end class refTextTypeSub -class sectiondefTypeSub(supermod.sectiondefType): +class sectiondefTypeSub(supermod.sectiondefType): def __init__(self, kind=None, header='', description=None, memberdef=None): - supermod.sectiondefType.__init__(self, kind, header, description, memberdef) + supermod.sectiondefType.__init__( + self, kind, header, description, memberdef) def find(self, details): @@ -116,7 +132,10 @@ def find(self, details): class memberdefTypeSub(supermod.memberdefType): def __init__(self, initonly=None, kind=None, volatile=None, const=None, raise_=None, virt=None, readable=None, prot=None, explicit=None, new=None, final=None, writable=None, add=None, static=None, remove=None, sealed=None, mutable=None, gettable=None, inline=None, settable=None, id=None, templateparamlist=None, type_=None, definition='', argsstring='', name='', read='', write='', bitfield='', reimplements=None, reimplementedby=None, param=None, enumvalue=None, initializer=None, exceptions=None, briefdescription=None, detaileddescription=None, inbodydescription=None, location=None, references=None, referencedby=None): - supermod.memberdefType.__init__(self, initonly, kind, volatile, const, raise_, virt, readable, prot, explicit, new, final, writable, add, static, remove, sealed, mutable, gettable, inline, settable, id, templateparamlist, type_, definition, argsstring, name, read, write, bitfield, reimplements, reimplementedby, param, enumvalue, initializer, exceptions, briefdescription, detaileddescription, inbodydescription, location, references, referencedby) + supermod.memberdefType.__init__(self, initonly, kind, volatile, const, raise_, virt, readable, prot, explicit, new, final, writable, add, static, remove, sealed, mutable, gettable, inline, settable, id, templateparamlist, type_, + definition, argsstring, name, read, write, bitfield, reimplements, reimplementedby, param, enumvalue, initializer, exceptions, briefdescription, detaileddescription, inbodydescription, location, references, referencedby) + + supermod.memberdefType.subclass = memberdefTypeSub # end class memberdefTypeSub @@ -124,6 +143,8 @@ def __init__(self, initonly=None, kind=None, volatile=None, const=None, raise_=N class descriptionTypeSub(supermod.descriptionType): def __init__(self, title='', para=None, sect1=None, internal=None, mixedclass_=None, content_=None): supermod.descriptionType.__init__(self, mixedclass_, content_) + + supermod.descriptionType.subclass = descriptionTypeSub # end class descriptionTypeSub @@ -131,6 +152,8 @@ def __init__(self, title='', para=None, sect1=None, internal=None, mixedclass_=N class enumvalueTypeSub(supermod.enumvalueType): def __init__(self, prot=None, id=None, name='', initializer=None, briefdescription=None, detaileddescription=None, mixedclass_=None, content_=None): supermod.enumvalueType.__init__(self, mixedclass_, content_) + + supermod.enumvalueType.subclass = enumvalueTypeSub # end class enumvalueTypeSub @@ -138,13 +161,18 @@ def __init__(self, prot=None, id=None, name='', initializer=None, briefdescripti class templateparamlistTypeSub(supermod.templateparamlistType): def __init__(self, param=None): supermod.templateparamlistType.__init__(self, param) + + supermod.templateparamlistType.subclass = templateparamlistTypeSub # end class templateparamlistTypeSub class paramTypeSub(supermod.paramType): def __init__(self, type_=None, declname='', defname='', array='', defval=None, briefdescription=None): - supermod.paramType.__init__(self, type_, declname, defname, array, defval, briefdescription) + supermod.paramType.__init__( + self, type_, declname, defname, array, defval, briefdescription) + + supermod.paramType.subclass = paramTypeSub # end class paramTypeSub @@ -152,6 +180,8 @@ def __init__(self, type_=None, declname='', defname='', array='', defval=None, b class linkedTextTypeSub(supermod.linkedTextType): def __init__(self, ref=None, mixedclass_=None, content_=None): supermod.linkedTextType.__init__(self, mixedclass_, content_) + + supermod.linkedTextType.subclass = linkedTextTypeSub # end class linkedTextTypeSub @@ -159,6 +189,8 @@ def __init__(self, ref=None, mixedclass_=None, content_=None): class graphTypeSub(supermod.graphType): def __init__(self, node=None): supermod.graphType.__init__(self, node) + + supermod.graphType.subclass = graphTypeSub # end class graphTypeSub @@ -166,6 +198,8 @@ def __init__(self, node=None): class nodeTypeSub(supermod.nodeType): def __init__(self, id=None, label='', link=None, childnode=None): supermod.nodeType.__init__(self, id, label, link, childnode) + + supermod.nodeType.subclass = nodeTypeSub # end class nodeTypeSub @@ -173,6 +207,8 @@ def __init__(self, id=None, label='', link=None, childnode=None): class childnodeTypeSub(supermod.childnodeType): def __init__(self, relation=None, refid=None, edgelabel=None): supermod.childnodeType.__init__(self, relation, refid, edgelabel) + + supermod.childnodeType.subclass = childnodeTypeSub # end class childnodeTypeSub @@ -180,6 +216,8 @@ def __init__(self, relation=None, refid=None, edgelabel=None): class linkTypeSub(supermod.linkType): def __init__(self, refid=None, external=None, valueOf_=''): supermod.linkType.__init__(self, refid, external) + + supermod.linkType.subclass = linkTypeSub # end class linkTypeSub @@ -187,13 +225,18 @@ def __init__(self, refid=None, external=None, valueOf_=''): class listingTypeSub(supermod.listingType): def __init__(self, codeline=None): supermod.listingType.__init__(self, codeline) + + supermod.listingType.subclass = listingTypeSub # end class listingTypeSub class codelineTypeSub(supermod.codelineType): def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None): - supermod.codelineType.__init__(self, external, lineno, refkind, refid, highlight) + supermod.codelineType.__init__( + self, external, lineno, refkind, refid, highlight) + + supermod.codelineType.subclass = codelineTypeSub # end class codelineTypeSub @@ -201,6 +244,8 @@ def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlig class highlightTypeSub(supermod.highlightType): def __init__(self, class_=None, sp=None, ref=None, mixedclass_=None, content_=None): supermod.highlightType.__init__(self, mixedclass_, content_) + + supermod.highlightType.subclass = highlightTypeSub # end class highlightTypeSub @@ -208,13 +253,18 @@ def __init__(self, class_=None, sp=None, ref=None, mixedclass_=None, content_=No class referenceTypeSub(supermod.referenceType): def __init__(self, endline=None, startline=None, refid=None, compoundref=None, valueOf_='', mixedclass_=None, content_=None): supermod.referenceType.__init__(self, mixedclass_, content_) + + supermod.referenceType.subclass = referenceTypeSub # end class referenceTypeSub class locationTypeSub(supermod.locationType): def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file=None, valueOf_=''): - supermod.locationType.__init__(self, bodystart, line, bodyend, bodyfile, file) + supermod.locationType.__init__( + self, bodystart, line, bodyend, bodyfile, file) + + supermod.locationType.subclass = locationTypeSub # end class locationTypeSub @@ -222,6 +272,8 @@ def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file= class docSect1TypeSub(supermod.docSect1Type): def __init__(self, id=None, title='', para=None, sect2=None, internal=None, mixedclass_=None, content_=None): supermod.docSect1Type.__init__(self, mixedclass_, content_) + + supermod.docSect1Type.subclass = docSect1TypeSub # end class docSect1TypeSub @@ -229,6 +281,8 @@ def __init__(self, id=None, title='', para=None, sect2=None, internal=None, mixe class docSect2TypeSub(supermod.docSect2Type): def __init__(self, id=None, title='', para=None, sect3=None, internal=None, mixedclass_=None, content_=None): supermod.docSect2Type.__init__(self, mixedclass_, content_) + + supermod.docSect2Type.subclass = docSect2TypeSub # end class docSect2TypeSub @@ -236,6 +290,8 @@ def __init__(self, id=None, title='', para=None, sect3=None, internal=None, mixe class docSect3TypeSub(supermod.docSect3Type): def __init__(self, id=None, title='', para=None, sect4=None, internal=None, mixedclass_=None, content_=None): supermod.docSect3Type.__init__(self, mixedclass_, content_) + + supermod.docSect3Type.subclass = docSect3TypeSub # end class docSect3TypeSub @@ -243,6 +299,8 @@ def __init__(self, id=None, title='', para=None, sect4=None, internal=None, mixe class docSect4TypeSub(supermod.docSect4Type): def __init__(self, id=None, title='', para=None, internal=None, mixedclass_=None, content_=None): supermod.docSect4Type.__init__(self, mixedclass_, content_) + + supermod.docSect4Type.subclass = docSect4TypeSub # end class docSect4TypeSub @@ -250,6 +308,8 @@ def __init__(self, id=None, title='', para=None, internal=None, mixedclass_=None class docInternalTypeSub(supermod.docInternalType): def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): supermod.docInternalType.__init__(self, mixedclass_, content_) + + supermod.docInternalType.subclass = docInternalTypeSub # end class docInternalTypeSub @@ -257,6 +317,8 @@ def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): class docInternalS1TypeSub(supermod.docInternalS1Type): def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): supermod.docInternalS1Type.__init__(self, mixedclass_, content_) + + supermod.docInternalS1Type.subclass = docInternalS1TypeSub # end class docInternalS1TypeSub @@ -264,6 +326,8 @@ def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): class docInternalS2TypeSub(supermod.docInternalS2Type): def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): supermod.docInternalS2Type.__init__(self, mixedclass_, content_) + + supermod.docInternalS2Type.subclass = docInternalS2TypeSub # end class docInternalS2TypeSub @@ -271,6 +335,8 @@ def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): class docInternalS3TypeSub(supermod.docInternalS3Type): def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): supermod.docInternalS3Type.__init__(self, mixedclass_, content_) + + supermod.docInternalS3Type.subclass = docInternalS3TypeSub # end class docInternalS3TypeSub @@ -278,6 +344,8 @@ def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): class docInternalS4TypeSub(supermod.docInternalS4Type): def __init__(self, para=None, mixedclass_=None, content_=None): supermod.docInternalS4Type.__init__(self, mixedclass_, content_) + + supermod.docInternalS4Type.subclass = docInternalS4TypeSub # end class docInternalS4TypeSub @@ -285,6 +353,8 @@ def __init__(self, para=None, mixedclass_=None, content_=None): class docURLLinkSub(supermod.docURLLink): def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): supermod.docURLLink.__init__(self, mixedclass_, content_) + + supermod.docURLLink.subclass = docURLLinkSub # end class docURLLinkSub @@ -292,6 +362,8 @@ def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): class docAnchorTypeSub(supermod.docAnchorType): def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): supermod.docAnchorType.__init__(self, mixedclass_, content_) + + supermod.docAnchorType.subclass = docAnchorTypeSub # end class docAnchorTypeSub @@ -299,6 +371,8 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): class docFormulaTypeSub(supermod.docFormulaType): def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): supermod.docFormulaType.__init__(self, mixedclass_, content_) + + supermod.docFormulaType.subclass = docFormulaTypeSub # end class docFormulaTypeSub @@ -306,6 +380,8 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): class docIndexEntryTypeSub(supermod.docIndexEntryType): def __init__(self, primaryie='', secondaryie=''): supermod.docIndexEntryType.__init__(self, primaryie, secondaryie) + + supermod.docIndexEntryType.subclass = docIndexEntryTypeSub # end class docIndexEntryTypeSub @@ -313,6 +389,8 @@ def __init__(self, primaryie='', secondaryie=''): class docListTypeSub(supermod.docListType): def __init__(self, listitem=None): supermod.docListType.__init__(self, listitem) + + supermod.docListType.subclass = docListTypeSub # end class docListTypeSub @@ -320,6 +398,8 @@ def __init__(self, listitem=None): class docListItemTypeSub(supermod.docListItemType): def __init__(self, para=None): supermod.docListItemType.__init__(self, para) + + supermod.docListItemType.subclass = docListItemTypeSub # end class docListItemTypeSub @@ -327,6 +407,8 @@ def __init__(self, para=None): class docSimpleSectTypeSub(supermod.docSimpleSectType): def __init__(self, kind=None, title=None, para=None): supermod.docSimpleSectType.__init__(self, kind, title, para) + + supermod.docSimpleSectType.subclass = docSimpleSectTypeSub # end class docSimpleSectTypeSub @@ -334,6 +416,8 @@ def __init__(self, kind=None, title=None, para=None): class docVarListEntryTypeSub(supermod.docVarListEntryType): def __init__(self, term=None): supermod.docVarListEntryType.__init__(self, term) + + supermod.docVarListEntryType.subclass = docVarListEntryTypeSub # end class docVarListEntryTypeSub @@ -341,6 +425,8 @@ def __init__(self, term=None): class docRefTextTypeSub(supermod.docRefTextType): def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): supermod.docRefTextType.__init__(self, mixedclass_, content_) + + supermod.docRefTextType.subclass = docRefTextTypeSub # end class docRefTextTypeSub @@ -348,6 +434,8 @@ def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedcl class docTableTypeSub(supermod.docTableType): def __init__(self, rows=None, cols=None, row=None, caption=None): supermod.docTableType.__init__(self, rows, cols, row, caption) + + supermod.docTableType.subclass = docTableTypeSub # end class docTableTypeSub @@ -355,6 +443,8 @@ def __init__(self, rows=None, cols=None, row=None, caption=None): class docRowTypeSub(supermod.docRowType): def __init__(self, entry=None): supermod.docRowType.__init__(self, entry) + + supermod.docRowType.subclass = docRowTypeSub # end class docRowTypeSub @@ -362,6 +452,8 @@ def __init__(self, entry=None): class docEntryTypeSub(supermod.docEntryType): def __init__(self, thead=None, para=None): supermod.docEntryType.__init__(self, thead, para) + + supermod.docEntryType.subclass = docEntryTypeSub # end class docEntryTypeSub @@ -369,6 +461,8 @@ def __init__(self, thead=None, para=None): class docHeadingTypeSub(supermod.docHeadingType): def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): supermod.docHeadingType.__init__(self, mixedclass_, content_) + + supermod.docHeadingType.subclass = docHeadingTypeSub # end class docHeadingTypeSub @@ -376,6 +470,8 @@ def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): class docImageTypeSub(supermod.docImageType): def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', mixedclass_=None, content_=None): supermod.docImageType.__init__(self, mixedclass_, content_) + + supermod.docImageType.subclass = docImageTypeSub # end class docImageTypeSub @@ -383,6 +479,8 @@ def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', class docDotFileTypeSub(supermod.docDotFileType): def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): supermod.docDotFileType.__init__(self, mixedclass_, content_) + + supermod.docDotFileType.subclass = docDotFileTypeSub # end class docDotFileTypeSub @@ -390,6 +488,8 @@ def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): class docTocItemTypeSub(supermod.docTocItemType): def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): supermod.docTocItemType.__init__(self, mixedclass_, content_) + + supermod.docTocItemType.subclass = docTocItemTypeSub # end class docTocItemTypeSub @@ -397,6 +497,8 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): class docTocListTypeSub(supermod.docTocListType): def __init__(self, tocitem=None): supermod.docTocListType.__init__(self, tocitem) + + supermod.docTocListType.subclass = docTocListTypeSub # end class docTocListTypeSub @@ -404,6 +506,8 @@ def __init__(self, tocitem=None): class docLanguageTypeSub(supermod.docLanguageType): def __init__(self, langid=None, para=None): supermod.docLanguageType.__init__(self, langid, para) + + supermod.docLanguageType.subclass = docLanguageTypeSub # end class docLanguageTypeSub @@ -411,13 +515,18 @@ def __init__(self, langid=None, para=None): class docParamListTypeSub(supermod.docParamListType): def __init__(self, kind=None, parameteritem=None): supermod.docParamListType.__init__(self, kind, parameteritem) + + supermod.docParamListType.subclass = docParamListTypeSub # end class docParamListTypeSub class docParamListItemSub(supermod.docParamListItem): def __init__(self, parameternamelist=None, parameterdescription=None): - supermod.docParamListItem.__init__(self, parameternamelist, parameterdescription) + supermod.docParamListItem.__init__( + self, parameternamelist, parameterdescription) + + supermod.docParamListItem.subclass = docParamListItemSub # end class docParamListItemSub @@ -425,6 +534,8 @@ def __init__(self, parameternamelist=None, parameterdescription=None): class docParamNameListSub(supermod.docParamNameList): def __init__(self, parametername=None): supermod.docParamNameList.__init__(self, parametername) + + supermod.docParamNameList.subclass = docParamNameListSub # end class docParamNameListSub @@ -432,6 +543,8 @@ def __init__(self, parametername=None): class docParamNameSub(supermod.docParamName): def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): supermod.docParamName.__init__(self, mixedclass_, content_) + + supermod.docParamName.subclass = docParamNameSub # end class docParamNameSub @@ -439,6 +552,8 @@ def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): class docXRefSectTypeSub(supermod.docXRefSectType): def __init__(self, id=None, xreftitle=None, xrefdescription=None): supermod.docXRefSectType.__init__(self, id, xreftitle, xrefdescription) + + supermod.docXRefSectType.subclass = docXRefSectTypeSub # end class docXRefSectTypeSub @@ -446,6 +561,8 @@ def __init__(self, id=None, xreftitle=None, xrefdescription=None): class docCopyTypeSub(supermod.docCopyType): def __init__(self, link=None, para=None, sect1=None, internal=None): supermod.docCopyType.__init__(self, link, para, sect1, internal) + + supermod.docCopyType.subclass = docCopyTypeSub # end class docCopyTypeSub @@ -453,9 +570,12 @@ def __init__(self, link=None, para=None, sect1=None, internal=None): class docCharTypeSub(supermod.docCharType): def __init__(self, char=None, valueOf_=''): supermod.docCharType.__init__(self, char) + + supermod.docCharType.subclass = docCharTypeSub # end class docCharTypeSub + class docParaTypeSub(supermod.docParaType): def __init__(self, char=None, valueOf_=''): supermod.docParaType.__init__(self, char) @@ -469,7 +589,7 @@ def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == "ref": @@ -492,7 +612,6 @@ def buildChildren(self, child_, nodeName_): # end class docParaTypeSub - def parse(inFilename): doc = minidom.parse(inFilename) rootNode = doc.documentElement diff --git a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/compoundsuper.py b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/compoundsuper.py index 05c49281fe9..40f548aab02 100644 --- a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/compoundsuper.py +++ b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/compoundsuper.py @@ -24,12 +24,16 @@ class GeneratedsSuper(object): def format_string(self, input_data, input_name=''): return input_data + def format_integer(self, input_data, input_name=''): return '%d' % input_data + def format_float(self, input_data, input_name=''): return '%f' % input_data + def format_double(self, input_data, input_name=''): return '%e' % input_data + def format_boolean(self, input_data, input_name=''): return '%s' % input_data @@ -41,9 +45,9 @@ def format_boolean(self, input_data, input_name=''): ## from IPython.Shell import IPShellEmbed ## args = '' -## ipshell = IPShellEmbed(args, +# ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') +# exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: @@ -59,10 +63,12 @@ def format_boolean(self, input_data, input_name=''): # Support/utility functions. # + def showIndent(outfile, level): for idx in range(level): outfile.write(' ') + def quote_xml(inStr): s1 = (isinstance(inStr, str) and inStr or '%s' % inStr) @@ -71,6 +77,7 @@ def quote_xml(inStr): s1 = s1.replace('>', '>') return s1 + def quote_attrib(inStr): s1 = (isinstance(inStr, str) and inStr or '%s' % inStr) @@ -86,6 +93,7 @@ def quote_attrib(inStr): s1 = '"%s"' % s1 return s1 + def quote_python(inStr): s1 = inStr if s1.find("'") == -1: @@ -117,26 +125,33 @@ class MixedContainer(object): TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 + def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value + def getCategory(self): return self.category + def getContenttype(self, content_type): return self.content_type + def getValue(self): return self.value + def getName(self): return self.name + def export(self, outfile, level, name, namespace): if self.category == MixedContainer.CategoryText: outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex - self.value.export(outfile, level, namespace,name) + self.value.export(outfile, level, namespace, name) + def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: outfile.write('<%s>%s' % (self.name, self.value, self.name)) @@ -148,19 +163,20 @@ def exportSimple(self, outfile, level, name): outfile.write('<%s>%f' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: outfile.write('<%s>%g' % (self.name, self.value, self.name)) + def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) + outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % + (self.category, self.content_type, self.name, self.value)) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) + outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % + (self.category, self.content_type, self.name, self.value)) else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s",\n' % \ - (self.category, self.content_type, self.name,)) + outfile.write('MixedContainer(%d, %d, "%s",\n' % + (self.category, self.content_type, self.name,)) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) outfile.write(')\n') @@ -171,6 +187,7 @@ def __init__(self, name='', data_type='', container=0): self.name = name self.data_type = data_type self.container = container + def set_name(self, name): self.name = name def get_name(self): return self.name def set_data_type(self, data_type): self.data_type = data_type @@ -186,9 +203,11 @@ def get_container(self): return self.container class DoxygenType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, version=None, compounddef=None): self.version = version self.compounddef = compounddef + def factory(*args_, **kwargs_): if DoxygenType.subclass: return DoxygenType.subclass(*args_, **kwargs_) @@ -199,6 +218,7 @@ def get_compounddef(self): return self.compounddef def set_compounddef(self, compounddef): self.compounddef = compounddef def get_version(self): return self.version def set_version(self, version): self.version = version + def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -210,27 +230,34 @@ def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='DoxygenType'): outfile.write(' version=%s' % (quote_attrib(self.version), )) + def exportChildren(self, outfile, level, namespace_='', name_='DoxygenType'): if self.compounddef: - self.compounddef.export(outfile, level, namespace_, name_='compounddef') + self.compounddef.export( + outfile, level, namespace_, name_='compounddef') + def hasContent_(self): if ( self.compounddef is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='DoxygenType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.version is not None: showIndent(outfile, level) outfile.write('version = "%s",\n' % (self.version,)) + def exportLiteralChildren(self, outfile, level, name_): if self.compounddef: showIndent(outfile, level) @@ -238,18 +265,21 @@ def exportLiteralChildren(self, outfile, level, name_): self.compounddef.exportLiteral(outfile, level, name_='compounddef') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('version'): self.version = attrs.get('version').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'compounddef': + nodeName_ == 'compounddef': obj_ = compounddefType.factory() obj_.build(child_) self.set_compounddef(obj_) @@ -259,6 +289,7 @@ def buildChildren(self, child_, nodeName_): class compounddefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, prot=None, id=None, compoundname=None, title=None, basecompoundref=None, derivedcompoundref=None, includes=None, includedby=None, incdepgraph=None, invincdepgraph=None, innerdir=None, innerfile=None, innerclass=None, innernamespace=None, innerpage=None, innergroup=None, templateparamlist=None, sectiondef=None, briefdescription=None, detaileddescription=None, inheritancegraph=None, collaborationgraph=None, programlisting=None, location=None, listofallmembers=None): self.kind = kind self.prot = prot @@ -319,6 +350,7 @@ def __init__(self, kind=None, prot=None, id=None, compoundname=None, title=None, self.programlisting = programlisting self.location = location self.listofallmembers = listofallmembers + def factory(*args_, **kwargs_): if compounddefType.subclass: return compounddefType.subclass(*args_, **kwargs_) @@ -330,13 +362,23 @@ def set_compoundname(self, compoundname): self.compoundname = compoundname def get_title(self): return self.title def set_title(self, title): self.title = title def get_basecompoundref(self): return self.basecompoundref - def set_basecompoundref(self, basecompoundref): self.basecompoundref = basecompoundref + def set_basecompoundref( + self, basecompoundref): self.basecompoundref = basecompoundref + def add_basecompoundref(self, value): self.basecompoundref.append(value) - def insert_basecompoundref(self, index, value): self.basecompoundref[index] = value + def insert_basecompoundref( + self, index, value): self.basecompoundref[index] = value + def get_derivedcompoundref(self): return self.derivedcompoundref - def set_derivedcompoundref(self, derivedcompoundref): self.derivedcompoundref = derivedcompoundref - def add_derivedcompoundref(self, value): self.derivedcompoundref.append(value) - def insert_derivedcompoundref(self, index, value): self.derivedcompoundref[index] = value + + def set_derivedcompoundref( + self, derivedcompoundref): self.derivedcompoundref = derivedcompoundref + + def add_derivedcompoundref( + self, value): self.derivedcompoundref.append(value) + def insert_derivedcompoundref( + self, index, value): self.derivedcompoundref[index] = value + def get_includes(self): return self.includes def set_includes(self, includes): self.includes = includes def add_includes(self, value): self.includes.append(value) @@ -348,7 +390,9 @@ def insert_includedby(self, index, value): self.includedby[index] = value def get_incdepgraph(self): return self.incdepgraph def set_incdepgraph(self, incdepgraph): self.incdepgraph = incdepgraph def get_invincdepgraph(self): return self.invincdepgraph - def set_invincdepgraph(self, invincdepgraph): self.invincdepgraph = invincdepgraph + def set_invincdepgraph( + self, invincdepgraph): self.invincdepgraph = invincdepgraph + def get_innerdir(self): return self.innerdir def set_innerdir(self, innerdir): self.innerdir = innerdir def add_innerdir(self, value): self.innerdir.append(value) @@ -362,9 +406,13 @@ def set_innerclass(self, innerclass): self.innerclass = innerclass def add_innerclass(self, value): self.innerclass.append(value) def insert_innerclass(self, index, value): self.innerclass[index] = value def get_innernamespace(self): return self.innernamespace - def set_innernamespace(self, innernamespace): self.innernamespace = innernamespace + def set_innernamespace( + self, innernamespace): self.innernamespace = innernamespace + def add_innernamespace(self, value): self.innernamespace.append(value) - def insert_innernamespace(self, index, value): self.innernamespace[index] = value + def insert_innernamespace( + self, index, value): self.innernamespace[index] = value + def get_innerpage(self): return self.innerpage def set_innerpage(self, innerpage): self.innerpage = innerpage def add_innerpage(self, value): self.innerpage.append(value) @@ -374,35 +422,51 @@ def set_innergroup(self, innergroup): self.innergroup = innergroup def add_innergroup(self, value): self.innergroup.append(value) def insert_innergroup(self, index, value): self.innergroup[index] = value def get_templateparamlist(self): return self.templateparamlist - def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist + def set_templateparamlist( + self, templateparamlist): self.templateparamlist = templateparamlist + def get_sectiondef(self): return self.sectiondef def set_sectiondef(self, sectiondef): self.sectiondef = sectiondef def add_sectiondef(self, value): self.sectiondef.append(value) def insert_sectiondef(self, index, value): self.sectiondef[index] = value def get_briefdescription(self): return self.briefdescription - def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription + def set_briefdescription( + self, briefdescription): self.briefdescription = briefdescription + def get_detaileddescription(self): return self.detaileddescription - def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription + def set_detaileddescription( + self, detaileddescription): self.detaileddescription = detaileddescription + def get_inheritancegraph(self): return self.inheritancegraph - def set_inheritancegraph(self, inheritancegraph): self.inheritancegraph = inheritancegraph + def set_inheritancegraph( + self, inheritancegraph): self.inheritancegraph = inheritancegraph + def get_collaborationgraph(self): return self.collaborationgraph - def set_collaborationgraph(self, collaborationgraph): self.collaborationgraph = collaborationgraph + def set_collaborationgraph( + self, collaborationgraph): self.collaborationgraph = collaborationgraph + def get_programlisting(self): return self.programlisting - def set_programlisting(self, programlisting): self.programlisting = programlisting + def set_programlisting( + self, programlisting): self.programlisting = programlisting + def get_location(self): return self.location def set_location(self, location): self.location = location def get_listofallmembers(self): return self.listofallmembers - def set_listofallmembers(self, listofallmembers): self.listofallmembers = listofallmembers + def set_listofallmembers( + self, listofallmembers): self.listofallmembers = listofallmembers + def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='compounddefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='compounddefType') + self.exportAttributes(outfile, level, namespace_, + name_='compounddefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -410,32 +474,41 @@ def export(self, outfile, level, namespace_='', name_='compounddefType', namespa outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='compounddefType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='compounddefType'): if self.compoundname is not None: showIndent(outfile, level) - outfile.write('<%scompoundname>%s\n' % (namespace_, self.format_string(quote_xml(self.compoundname).encode(ExternalEncoding), input_name='compoundname'), namespace_)) + outfile.write('<%scompoundname>%s\n' % (namespace_, self.format_string( + quote_xml(self.compoundname).encode(ExternalEncoding), input_name='compoundname'), namespace_)) if self.title is not None: showIndent(outfile, level) - outfile.write('<%stitle>%s\n' % (namespace_, self.format_string(quote_xml(self.title).encode(ExternalEncoding), input_name='title'), namespace_)) + outfile.write('<%stitle>%s\n' % (namespace_, self.format_string( + quote_xml(self.title).encode(ExternalEncoding), input_name='title'), namespace_)) for basecompoundref_ in self.basecompoundref: - basecompoundref_.export(outfile, level, namespace_, name_='basecompoundref') + basecompoundref_.export( + outfile, level, namespace_, name_='basecompoundref') for derivedcompoundref_ in self.derivedcompoundref: - derivedcompoundref_.export(outfile, level, namespace_, name_='derivedcompoundref') + derivedcompoundref_.export( + outfile, level, namespace_, name_='derivedcompoundref') for includes_ in self.includes: includes_.export(outfile, level, namespace_, name_='includes') for includedby_ in self.includedby: includedby_.export(outfile, level, namespace_, name_='includedby') if self.incdepgraph: - self.incdepgraph.export(outfile, level, namespace_, name_='incdepgraph') + self.incdepgraph.export( + outfile, level, namespace_, name_='incdepgraph') if self.invincdepgraph: - self.invincdepgraph.export(outfile, level, namespace_, name_='invincdepgraph') + self.invincdepgraph.export( + outfile, level, namespace_, name_='invincdepgraph') for innerdir_ in self.innerdir: innerdir_.export(outfile, level, namespace_, name_='innerdir') for innerfile_ in self.innerfile: @@ -443,29 +516,38 @@ def exportChildren(self, outfile, level, namespace_='', name_='compounddefType') for innerclass_ in self.innerclass: innerclass_.export(outfile, level, namespace_, name_='innerclass') for innernamespace_ in self.innernamespace: - innernamespace_.export(outfile, level, namespace_, name_='innernamespace') + innernamespace_.export( + outfile, level, namespace_, name_='innernamespace') for innerpage_ in self.innerpage: innerpage_.export(outfile, level, namespace_, name_='innerpage') for innergroup_ in self.innergroup: innergroup_.export(outfile, level, namespace_, name_='innergroup') if self.templateparamlist: - self.templateparamlist.export(outfile, level, namespace_, name_='templateparamlist') + self.templateparamlist.export( + outfile, level, namespace_, name_='templateparamlist') for sectiondef_ in self.sectiondef: sectiondef_.export(outfile, level, namespace_, name_='sectiondef') if self.briefdescription: - self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') + self.briefdescription.export( + outfile, level, namespace_, name_='briefdescription') if self.detaileddescription: - self.detaileddescription.export(outfile, level, namespace_, name_='detaileddescription') + self.detaileddescription.export( + outfile, level, namespace_, name_='detaileddescription') if self.inheritancegraph: - self.inheritancegraph.export(outfile, level, namespace_, name_='inheritancegraph') + self.inheritancegraph.export( + outfile, level, namespace_, name_='inheritancegraph') if self.collaborationgraph: - self.collaborationgraph.export(outfile, level, namespace_, name_='collaborationgraph') + self.collaborationgraph.export( + outfile, level, namespace_, name_='collaborationgraph') if self.programlisting: - self.programlisting.export(outfile, level, namespace_, name_='programlisting') + self.programlisting.export( + outfile, level, namespace_, name_='programlisting') if self.location: self.location.export(outfile, level, namespace_, name_='location') if self.listofallmembers: - self.listofallmembers.export(outfile, level, namespace_, name_='listofallmembers') + self.listofallmembers.export( + outfile, level, namespace_, name_='listofallmembers') + def hasContent_(self): if ( self.compoundname is not None or @@ -491,15 +573,17 @@ def hasContent_(self): self.programlisting is not None or self.location is not None or self.listofallmembers is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='compounddefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) @@ -510,9 +594,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('compoundname=%s,\n' % quote_python(self.compoundname).encode(ExternalEncoding)) + outfile.write('compoundname=%s,\n' % quote_python( + self.compoundname).encode(ExternalEncoding)) if self.title: showIndent(outfile, level) outfile.write('title=model_.xsd_string(\n') @@ -525,7 +611,8 @@ def exportLiteralChildren(self, outfile, level, name_): for basecompoundref in self.basecompoundref: showIndent(outfile, level) outfile.write('model_.basecompoundref(\n') - basecompoundref.exportLiteral(outfile, level, name_='basecompoundref') + basecompoundref.exportLiteral( + outfile, level, name_='basecompoundref') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -537,7 +624,8 @@ def exportLiteralChildren(self, outfile, level, name_): for derivedcompoundref in self.derivedcompoundref: showIndent(outfile, level) outfile.write('model_.derivedcompoundref(\n') - derivedcompoundref.exportLiteral(outfile, level, name_='derivedcompoundref') + derivedcompoundref.exportLiteral( + outfile, level, name_='derivedcompoundref') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -576,7 +664,8 @@ def exportLiteralChildren(self, outfile, level, name_): if self.invincdepgraph: showIndent(outfile, level) outfile.write('invincdepgraph=model_.graphType(\n') - self.invincdepgraph.exportLiteral(outfile, level, name_='invincdepgraph') + self.invincdepgraph.exportLiteral( + outfile, level, name_='invincdepgraph') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) @@ -621,7 +710,8 @@ def exportLiteralChildren(self, outfile, level, name_): for innernamespace in self.innernamespace: showIndent(outfile, level) outfile.write('model_.innernamespace(\n') - innernamespace.exportLiteral(outfile, level, name_='innernamespace') + innernamespace.exportLiteral( + outfile, level, name_='innernamespace') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -654,7 +744,8 @@ def exportLiteralChildren(self, outfile, level, name_): if self.templateparamlist: showIndent(outfile, level) outfile.write('templateparamlist=model_.templateparamlistType(\n') - self.templateparamlist.exportLiteral(outfile, level, name_='templateparamlist') + self.templateparamlist.exportLiteral( + outfile, level, name_='templateparamlist') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) @@ -672,31 +763,36 @@ def exportLiteralChildren(self, outfile, level, name_): if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') - self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') + self.briefdescription.exportLiteral( + outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') if self.detaileddescription: showIndent(outfile, level) outfile.write('detaileddescription=model_.descriptionType(\n') - self.detaileddescription.exportLiteral(outfile, level, name_='detaileddescription') + self.detaileddescription.exportLiteral( + outfile, level, name_='detaileddescription') showIndent(outfile, level) outfile.write('),\n') if self.inheritancegraph: showIndent(outfile, level) outfile.write('inheritancegraph=model_.graphType(\n') - self.inheritancegraph.exportLiteral(outfile, level, name_='inheritancegraph') + self.inheritancegraph.exportLiteral( + outfile, level, name_='inheritancegraph') showIndent(outfile, level) outfile.write('),\n') if self.collaborationgraph: showIndent(outfile, level) outfile.write('collaborationgraph=model_.graphType(\n') - self.collaborationgraph.exportLiteral(outfile, level, name_='collaborationgraph') + self.collaborationgraph.exportLiteral( + outfile, level, name_='collaborationgraph') showIndent(outfile, level) outfile.write('),\n') if self.programlisting: showIndent(outfile, level) outfile.write('programlisting=model_.listingType(\n') - self.programlisting.exportLiteral(outfile, level, name_='programlisting') + self.programlisting.exportLiteral( + outfile, level, name_='programlisting') showIndent(outfile, level) outfile.write('),\n') if self.location: @@ -708,15 +804,18 @@ def exportLiteralChildren(self, outfile, level, name_): if self.listofallmembers: showIndent(outfile, level) outfile.write('listofallmembers=model_.listofallmembersType(\n') - self.listofallmembers.exportLiteral(outfile, level, name_='listofallmembers') + self.listofallmembers.exportLiteral( + outfile, level, name_='listofallmembers') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value @@ -724,120 +823,121 @@ def buildAttributes(self, attrs): self.prot = attrs.get('prot').value if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'compoundname': + nodeName_ == 'compoundname': compoundname_ = '' for text__content_ in child_.childNodes: compoundname_ += text__content_.nodeValue self.compoundname = compoundname_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': obj_ = docTitleType.factory() obj_.build(child_) self.set_title(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'basecompoundref': + nodeName_ == 'basecompoundref': obj_ = compoundRefType.factory() obj_.build(child_) self.basecompoundref.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'derivedcompoundref': + nodeName_ == 'derivedcompoundref': obj_ = compoundRefType.factory() obj_.build(child_) self.derivedcompoundref.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'includes': + nodeName_ == 'includes': obj_ = incType.factory() obj_.build(child_) self.includes.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'includedby': + nodeName_ == 'includedby': obj_ = incType.factory() obj_.build(child_) self.includedby.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'incdepgraph': + nodeName_ == 'incdepgraph': obj_ = graphType.factory() obj_.build(child_) self.set_incdepgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'invincdepgraph': + nodeName_ == 'invincdepgraph': obj_ = graphType.factory() obj_.build(child_) self.set_invincdepgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innerdir': + nodeName_ == 'innerdir': obj_ = refType.factory() obj_.build(child_) self.innerdir.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innerfile': + nodeName_ == 'innerfile': obj_ = refType.factory() obj_.build(child_) self.innerfile.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innerclass': + nodeName_ == 'innerclass': obj_ = refType.factory() obj_.build(child_) self.innerclass.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innernamespace': + nodeName_ == 'innernamespace': obj_ = refType.factory() obj_.build(child_) self.innernamespace.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innerpage': + nodeName_ == 'innerpage': obj_ = refType.factory() obj_.build(child_) self.innerpage.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'innergroup': + nodeName_ == 'innergroup': obj_ = refType.factory() obj_.build(child_) self.innergroup.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'templateparamlist': + nodeName_ == 'templateparamlist': obj_ = templateparamlistType.factory() obj_.build(child_) self.set_templateparamlist(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sectiondef': + nodeName_ == 'sectiondef': obj_ = sectiondefType.factory() obj_.build(child_) self.sectiondef.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'briefdescription': + nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'detaileddescription': + nodeName_ == 'detaileddescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_detaileddescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'inheritancegraph': + nodeName_ == 'inheritancegraph': obj_ = graphType.factory() obj_.build(child_) self.set_inheritancegraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'collaborationgraph': + nodeName_ == 'collaborationgraph': obj_ = graphType.factory() obj_.build(child_) self.set_collaborationgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'programlisting': + nodeName_ == 'programlisting': obj_ = listingType.factory() obj_.build(child_) self.set_programlisting(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'location': + nodeName_ == 'location': obj_ = locationType.factory() obj_.build(child_) self.set_location(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'listofallmembers': + nodeName_ == 'listofallmembers': obj_ = listofallmembersType.factory() obj_.build(child_) self.set_listofallmembers(obj_) @@ -847,11 +947,13 @@ def buildChildren(self, child_, nodeName_): class listofallmembersType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, member=None): if member is None: self.member = [] else: self.member = member + def factory(*args_, **kwargs_): if listofallmembersType.subclass: return listofallmembersType.subclass(*args_, **kwargs_) @@ -862,10 +964,12 @@ def get_member(self): return self.member def set_member(self, member): self.member = member def add_member(self, value): self.member.append(value) def insert_member(self, index, value): self.member[index] = value + def export(self, outfile, level, namespace_='', name_='listofallmembersType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='listofallmembersType') + self.exportAttributes(outfile, level, namespace_, + name_='listofallmembersType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -873,25 +977,31 @@ def export(self, outfile, level, namespace_='', name_='listofallmembersType', na outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='listofallmembersType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='listofallmembersType'): for member_ in self.member: member_.export(outfile, level, namespace_, name_='member') + def hasContent_(self): if ( self.member is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='listofallmembersType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('member=[\n') @@ -905,17 +1015,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'member': + nodeName_ == 'member': obj_ = memberRefType.factory() obj_.build(child_) self.member.append(obj_) @@ -925,6 +1038,7 @@ def buildChildren(self, child_, nodeName_): class memberRefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope=None, name=None): self.virt = virt self.prot = prot @@ -932,6 +1046,7 @@ def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope= self.ambiguityscope = ambiguityscope self.scope = scope self.name = name + def factory(*args_, **kwargs_): if memberRefType.subclass: return memberRefType.subclass(*args_, **kwargs_) @@ -949,11 +1064,15 @@ def set_prot(self, prot): self.prot = prot def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_ambiguityscope(self): return self.ambiguityscope - def set_ambiguityscope(self, ambiguityscope): self.ambiguityscope = ambiguityscope + + def set_ambiguityscope( + self, ambiguityscope): self.ambiguityscope = ambiguityscope + def export(self, outfile, level, namespace_='', name_='memberRefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='memberRefType') + self.exportAttributes(outfile, level, namespace_, + name_='memberRefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -961,35 +1080,44 @@ def export(self, outfile, level, namespace_='', name_='memberRefType', namespace outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='memberRefType'): if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.ambiguityscope is not None: - outfile.write(' ambiguityscope=%s' % (self.format_string(quote_attrib(self.ambiguityscope).encode(ExternalEncoding), input_name='ambiguityscope'), )) + outfile.write(' ambiguityscope=%s' % (self.format_string(quote_attrib( + self.ambiguityscope).encode(ExternalEncoding), input_name='ambiguityscope'), )) + def exportChildren(self, outfile, level, namespace_='', name_='memberRefType'): if self.scope is not None: showIndent(outfile, level) - outfile.write('<%sscope>%s\n' % (namespace_, self.format_string(quote_xml(self.scope).encode(ExternalEncoding), input_name='scope'), namespace_)) + outfile.write('<%sscope>%s\n' % (namespace_, self.format_string( + quote_xml(self.scope).encode(ExternalEncoding), input_name='scope'), namespace_)) if self.name is not None: showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + outfile.write('<%sname>%s\n' % (namespace_, self.format_string( + quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + def hasContent_(self): if ( self.scope is not None or self.name is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='memberRefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.virt is not None: showIndent(outfile, level) @@ -1003,17 +1131,22 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.ambiguityscope is not None: showIndent(outfile, level) outfile.write('ambiguityscope = %s,\n' % (self.ambiguityscope,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('scope=%s,\n' % quote_python(self.scope).encode(ExternalEncoding)) + outfile.write('scope=%s,\n' % quote_python( + self.scope).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) + outfile.write('name=%s,\n' % quote_python( + self.name).encode(ExternalEncoding)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('virt'): self.virt = attrs.get('virt').value @@ -1023,15 +1156,16 @@ def buildAttributes(self, attrs): self.refid = attrs.get('refid').value if attrs.get('ambiguityscope'): self.ambiguityscope = attrs.get('ambiguityscope').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'scope': + nodeName_ == 'scope': scope_ = '' for text__content_ in child_.childNodes: scope_ += text__content_.nodeValue self.scope = scope_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue @@ -1042,8 +1176,10 @@ def buildChildren(self, child_, nodeName_): class scope(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if scope.subclass: return scope.subclass(*args_, **kwargs_) @@ -1052,6 +1188,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='scope', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1063,33 +1200,40 @@ def export(self, outfile, level, namespace_='', name_='scope', namespacedef_='') outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='scope'): pass + def exportChildren(self, outfile, level, namespace_='', name_='scope'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='scope'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1097,21 +1241,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class scope class name(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if name.subclass: return name.subclass(*args_, **kwargs_) @@ -1120,6 +1268,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='name', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1131,33 +1280,40 @@ def export(self, outfile, level, namespace_='', name_='name', namespacedef_=''): outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='name'): pass + def exportChildren(self, outfile, level, namespace_='', name_='name'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='name'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1165,19 +1321,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class name class compoundRefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.virt = virt self.prot = prot @@ -1190,6 +1349,7 @@ def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=No self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if compoundRefType.subclass: return compoundRefType.subclass(*args_, **kwargs_) @@ -1204,40 +1364,48 @@ def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='compoundRefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='compoundRefType') + self.exportAttributes(outfile, level, namespace_, + name_='compoundRefType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='compoundRefType'): if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='compoundRefType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='compoundRefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.virt is not None: showIndent(outfile, level) @@ -1248,9 +1416,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1258,6 +1428,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('virt'): self.virt = attrs.get('virt').value @@ -1265,21 +1436,23 @@ def buildAttributes(self, attrs): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class compoundRefType class reimplementType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid if mixedclass_ is None: @@ -1290,6 +1463,7 @@ def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if reimplementType.subclass: return reimplementType.subclass(*args_, **kwargs_) @@ -1300,43 +1474,53 @@ def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='reimplementType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='reimplementType') + self.exportAttributes(outfile, level, namespace_, + name_='reimplementType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='reimplementType'): if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='reimplementType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='reimplementType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1344,24 +1528,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class reimplementType class incType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.local = local self.refid = refid @@ -1373,6 +1560,7 @@ def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, conten self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if incType.subclass: return incType.subclass(*args_, **kwargs_) @@ -1385,6 +1573,7 @@ def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='incType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1392,31 +1581,37 @@ def export(self, outfile, level, namespace_='', name_='incType', namespacedef_=' outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='incType'): if self.local is not None: outfile.write(' local=%s' % (quote_attrib(self.local), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='incType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='incType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.local is not None: showIndent(outfile, level) @@ -1424,9 +1619,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1434,26 +1631,29 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('local'): self.local = attrs.get('local').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class incType class refType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.prot = prot self.refid = refid @@ -1465,6 +1665,7 @@ def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if refType.subclass: return refType.subclass(*args_, **kwargs_) @@ -1477,6 +1678,7 @@ def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='refType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1484,31 +1686,37 @@ def export(self, outfile, level, namespace_='', name_='refType', namespacedef_=' outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='refType'): if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='refType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='refType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.prot is not None: showIndent(outfile, level) @@ -1516,9 +1724,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1526,26 +1736,29 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class refType class refTextType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid self.kindref = kindref @@ -1558,6 +1771,7 @@ def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedcl self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if refTextType.subclass: return refTextType.subclass(*args_, **kwargs_) @@ -1572,6 +1786,7 @@ def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='refTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -1579,33 +1794,40 @@ def export(self, outfile, level, namespace_='', name_='refTextType', namespacede outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='refTextType'): if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.kindref is not None: outfile.write(' kindref=%s' % (quote_attrib(self.kindref), )) if self.external is not None: - outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) + outfile.write(' external=%s' % (self.format_string(quote_attrib( + self.external).encode(ExternalEncoding), input_name='external'), )) + def exportChildren(self, outfile, level, namespace_='', name_='refTextType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='refTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) @@ -1616,9 +1838,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -1626,6 +1850,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value @@ -1633,21 +1858,23 @@ def buildAttributes(self, attrs): self.kindref = attrs.get('kindref').value if attrs.get('external'): self.external = attrs.get('external').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class refTextType class sectiondefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, header=None, description=None, memberdef=None): self.kind = kind self.header = header @@ -1656,6 +1883,7 @@ def __init__(self, kind=None, header=None, description=None, memberdef=None): self.memberdef = [] else: self.memberdef = memberdef + def factory(*args_, **kwargs_): if sectiondefType.subclass: return sectiondefType.subclass(*args_, **kwargs_) @@ -1672,10 +1900,12 @@ def add_memberdef(self, value): self.memberdef.append(value) def insert_memberdef(self, index, value): self.memberdef[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind + def export(self, outfile, level, namespace_='', name_='sectiondefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='sectiondefType') + self.exportAttributes(outfile, level, namespace_, + name_='sectiondefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -1683,38 +1913,47 @@ def export(self, outfile, level, namespace_='', name_='sectiondefType', namespac outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='sectiondefType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) + def exportChildren(self, outfile, level, namespace_='', name_='sectiondefType'): if self.header is not None: showIndent(outfile, level) - outfile.write('<%sheader>%s\n' % (namespace_, self.format_string(quote_xml(self.header).encode(ExternalEncoding), input_name='header'), namespace_)) + outfile.write('<%sheader>%s\n' % (namespace_, self.format_string( + quote_xml(self.header).encode(ExternalEncoding), input_name='header'), namespace_)) if self.description: - self.description.export(outfile, level, namespace_, name_='description') + self.description.export( + outfile, level, namespace_, name_='description') for memberdef_ in self.memberdef: memberdef_.export(outfile, level, namespace_, name_='memberdef') + def hasContent_(self): if ( self.header is not None or self.description is not None or self.memberdef is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='sectiondefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('header=%s,\n' % quote_python(self.header).encode(ExternalEncoding)) + outfile.write('header=%s,\n' % quote_python( + self.header).encode(ExternalEncoding)) if self.description: showIndent(outfile, level) outfile.write('description=model_.descriptionType(\n') @@ -1733,29 +1972,32 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'header': + nodeName_ == 'header': header_ = '' for text__content_ in child_.childNodes: header_ += text__content_.nodeValue self.header = header_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'description': + nodeName_ == 'description': obj_ = descriptionType.factory() obj_.build(child_) self.set_description(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'memberdef': + nodeName_ == 'memberdef': obj_ = memberdefType.factory() obj_.build(child_) self.memberdef.append(obj_) @@ -1765,6 +2007,7 @@ def buildChildren(self, child_, nodeName_): class memberdefType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, initonly=None, kind=None, volatile=None, const=None, raisexx=None, virt=None, readable=None, prot=None, explicit=None, new=None, final=None, writable=None, add=None, static=None, remove=None, sealed=None, mutable=None, gettable=None, inline=None, settable=None, id=None, templateparamlist=None, type_=None, definition=None, argsstring=None, name=None, read=None, write=None, bitfield=None, reimplements=None, reimplementedby=None, param=None, enumvalue=None, initializer=None, exceptions=None, briefdescription=None, detaileddescription=None, inbodydescription=None, location=None, references=None, referencedby=None): self.initonly = initonly self.kind = kind @@ -1825,6 +2068,7 @@ def __init__(self, initonly=None, kind=None, volatile=None, const=None, raisexx= self.referencedby = [] else: self.referencedby = referencedby + def factory(*args_, **kwargs_): if memberdefType.subclass: return memberdefType.subclass(*args_, **kwargs_) @@ -1832,7 +2076,9 @@ def factory(*args_, **kwargs_): return memberdefType(*args_, **kwargs_) factory = staticmethod(factory) def get_templateparamlist(self): return self.templateparamlist - def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist + def set_templateparamlist( + self, templateparamlist): self.templateparamlist = templateparamlist + def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_definition(self): return self.definition @@ -1850,11 +2096,17 @@ def set_bitfield(self, bitfield): self.bitfield = bitfield def get_reimplements(self): return self.reimplements def set_reimplements(self, reimplements): self.reimplements = reimplements def add_reimplements(self, value): self.reimplements.append(value) - def insert_reimplements(self, index, value): self.reimplements[index] = value + def insert_reimplements( + self, index, value): self.reimplements[index] = value + def get_reimplementedby(self): return self.reimplementedby - def set_reimplementedby(self, reimplementedby): self.reimplementedby = reimplementedby + def set_reimplementedby( + self, reimplementedby): self.reimplementedby = reimplementedby + def add_reimplementedby(self, value): self.reimplementedby.append(value) - def insert_reimplementedby(self, index, value): self.reimplementedby[index] = value + def insert_reimplementedby( + self, index, value): self.reimplementedby[index] = value + def get_param(self): return self.param def set_param(self, param): self.param = param def add_param(self, value): self.param.append(value) @@ -1868,11 +2120,17 @@ def set_initializer(self, initializer): self.initializer = initializer def get_exceptions(self): return self.exceptions def set_exceptions(self, exceptions): self.exceptions = exceptions def get_briefdescription(self): return self.briefdescription - def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription + def set_briefdescription( + self, briefdescription): self.briefdescription = briefdescription + def get_detaileddescription(self): return self.detaileddescription - def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription + def set_detaileddescription( + self, detaileddescription): self.detaileddescription = detaileddescription + def get_inbodydescription(self): return self.inbodydescription - def set_inbodydescription(self, inbodydescription): self.inbodydescription = inbodydescription + def set_inbodydescription( + self, inbodydescription): self.inbodydescription = inbodydescription + def get_location(self): return self.location def set_location(self, location): self.location = location def get_references(self): return self.references @@ -1882,7 +2140,9 @@ def insert_references(self, index, value): self.references[index] = value def get_referencedby(self): return self.referencedby def set_referencedby(self, referencedby): self.referencedby = referencedby def add_referencedby(self, value): self.referencedby.append(value) - def insert_referencedby(self, index, value): self.referencedby[index] = value + def insert_referencedby( + self, index, value): self.referencedby[index] = value + def get_initonly(self): return self.initonly def set_initonly(self, initonly): self.initonly = initonly def get_kind(self): return self.kind @@ -1925,10 +2185,12 @@ def get_settable(self): return self.settable def set_settable(self, settable): self.settable = settable def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='memberdefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='memberdefType') + self.exportAttributes(outfile, level, namespace_, + name_='memberdefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -1936,6 +2198,7 @@ def export(self, outfile, level, namespace_='', name_='memberdefType', namespace outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='memberdefType'): if self.initonly is not None: outfile.write(' initonly=%s' % (quote_attrib(self.initonly), )) @@ -1978,54 +2241,73 @@ def exportAttributes(self, outfile, level, namespace_='', name_='memberdefType') if self.settable is not None: outfile.write(' settable=%s' % (quote_attrib(self.settable), )) if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='memberdefType'): if self.templateparamlist: - self.templateparamlist.export(outfile, level, namespace_, name_='templateparamlist') + self.templateparamlist.export( + outfile, level, namespace_, name_='templateparamlist') if self.type_: self.type_.export(outfile, level, namespace_, name_='type') if self.definition is not None: showIndent(outfile, level) - outfile.write('<%sdefinition>%s\n' % (namespace_, self.format_string(quote_xml(self.definition).encode(ExternalEncoding), input_name='definition'), namespace_)) + outfile.write('<%sdefinition>%s\n' % (namespace_, self.format_string( + quote_xml(self.definition).encode(ExternalEncoding), input_name='definition'), namespace_)) if self.argsstring is not None: showIndent(outfile, level) - outfile.write('<%sargsstring>%s\n' % (namespace_, self.format_string(quote_xml(self.argsstring).encode(ExternalEncoding), input_name='argsstring'), namespace_)) + outfile.write('<%sargsstring>%s\n' % (namespace_, self.format_string( + quote_xml(self.argsstring).encode(ExternalEncoding), input_name='argsstring'), namespace_)) if self.name is not None: showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + outfile.write('<%sname>%s\n' % (namespace_, self.format_string( + quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) if self.read is not None: showIndent(outfile, level) - outfile.write('<%sread>%s\n' % (namespace_, self.format_string(quote_xml(self.read).encode(ExternalEncoding), input_name='read'), namespace_)) + outfile.write('<%sread>%s\n' % (namespace_, self.format_string( + quote_xml(self.read).encode(ExternalEncoding), input_name='read'), namespace_)) if self.write is not None: showIndent(outfile, level) - outfile.write('<%swrite>%s\n' % (namespace_, self.format_string(quote_xml(self.write).encode(ExternalEncoding), input_name='write'), namespace_)) + outfile.write('<%swrite>%s\n' % (namespace_, self.format_string( + quote_xml(self.write).encode(ExternalEncoding), input_name='write'), namespace_)) if self.bitfield is not None: showIndent(outfile, level) - outfile.write('<%sbitfield>%s\n' % (namespace_, self.format_string(quote_xml(self.bitfield).encode(ExternalEncoding), input_name='bitfield'), namespace_)) + outfile.write('<%sbitfield>%s\n' % (namespace_, self.format_string( + quote_xml(self.bitfield).encode(ExternalEncoding), input_name='bitfield'), namespace_)) for reimplements_ in self.reimplements: - reimplements_.export(outfile, level, namespace_, name_='reimplements') + reimplements_.export( + outfile, level, namespace_, name_='reimplements') for reimplementedby_ in self.reimplementedby: - reimplementedby_.export(outfile, level, namespace_, name_='reimplementedby') + reimplementedby_.export( + outfile, level, namespace_, name_='reimplementedby') for param_ in self.param: param_.export(outfile, level, namespace_, name_='param') for enumvalue_ in self.enumvalue: enumvalue_.export(outfile, level, namespace_, name_='enumvalue') if self.initializer: - self.initializer.export(outfile, level, namespace_, name_='initializer') + self.initializer.export( + outfile, level, namespace_, name_='initializer') if self.exceptions: - self.exceptions.export(outfile, level, namespace_, name_='exceptions') + self.exceptions.export( + outfile, level, namespace_, name_='exceptions') if self.briefdescription: - self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') + self.briefdescription.export( + outfile, level, namespace_, name_='briefdescription') if self.detaileddescription: - self.detaileddescription.export(outfile, level, namespace_, name_='detaileddescription') + self.detaileddescription.export( + outfile, level, namespace_, name_='detaileddescription') if self.inbodydescription: - self.inbodydescription.export(outfile, level, namespace_, name_='inbodydescription') + self.inbodydescription.export( + outfile, level, namespace_, name_='inbodydescription') if self.location: - self.location.export(outfile, level, namespace_, name_='location', ) + self.location.export( + outfile, level, namespace_, name_='location', ) for references_ in self.references: references_.export(outfile, level, namespace_, name_='references') for referencedby_ in self.referencedby: - referencedby_.export(outfile, level, namespace_, name_='referencedby') + referencedby_.export( + outfile, level, namespace_, name_='referencedby') + def hasContent_(self): if ( self.templateparamlist is not None or @@ -2048,15 +2330,17 @@ def hasContent_(self): self.location is not None or self.references is not None or self.referencedby is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='memberdefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.initonly is not None: showIndent(outfile, level) @@ -2121,11 +2405,13 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): if self.templateparamlist: showIndent(outfile, level) outfile.write('templateparamlist=model_.templateparamlistType(\n') - self.templateparamlist.exportLiteral(outfile, level, name_='templateparamlist') + self.templateparamlist.exportLiteral( + outfile, level, name_='templateparamlist') showIndent(outfile, level) outfile.write('),\n') if self.type_: @@ -2135,17 +2421,23 @@ def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) - outfile.write('definition=%s,\n' % quote_python(self.definition).encode(ExternalEncoding)) + outfile.write('definition=%s,\n' % quote_python( + self.definition).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('argsstring=%s,\n' % quote_python(self.argsstring).encode(ExternalEncoding)) + outfile.write('argsstring=%s,\n' % quote_python( + self.argsstring).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) + outfile.write('name=%s,\n' % quote_python( + self.name).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('read=%s,\n' % quote_python(self.read).encode(ExternalEncoding)) + outfile.write('read=%s,\n' % quote_python( + self.read).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('write=%s,\n' % quote_python(self.write).encode(ExternalEncoding)) + outfile.write('write=%s,\n' % quote_python( + self.write).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('bitfield=%s,\n' % quote_python(self.bitfield).encode(ExternalEncoding)) + outfile.write('bitfield=%s,\n' % quote_python( + self.bitfield).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('reimplements=[\n') level += 1 @@ -2164,7 +2456,8 @@ def exportLiteralChildren(self, outfile, level, name_): for reimplementedby in self.reimplementedby: showIndent(outfile, level) outfile.write('model_.reimplementedby(\n') - reimplementedby.exportLiteral(outfile, level, name_='reimplementedby') + reimplementedby.exportLiteral( + outfile, level, name_='reimplementedby') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -2209,19 +2502,22 @@ def exportLiteralChildren(self, outfile, level, name_): if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') - self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') + self.briefdescription.exportLiteral( + outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') if self.detaileddescription: showIndent(outfile, level) outfile.write('detaileddescription=model_.descriptionType(\n') - self.detaileddescription.exportLiteral(outfile, level, name_='detaileddescription') + self.detaileddescription.exportLiteral( + outfile, level, name_='detaileddescription') showIndent(outfile, level) outfile.write('),\n') if self.inbodydescription: showIndent(outfile, level) outfile.write('inbodydescription=model_.descriptionType(\n') - self.inbodydescription.exportLiteral(outfile, level, name_='inbodydescription') + self.inbodydescription.exportLiteral( + outfile, level, name_='inbodydescription') showIndent(outfile, level) outfile.write('),\n') if self.location: @@ -2254,12 +2550,14 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('initonly'): self.initonly = attrs.get('initonly').value @@ -2303,110 +2601,111 @@ def buildAttributes(self, attrs): self.settable = attrs.get('settable').value if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'templateparamlist': + nodeName_ == 'templateparamlist': obj_ = templateparamlistType.factory() obj_.build(child_) self.set_templateparamlist(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'type': + nodeName_ == 'type': obj_ = linkedTextType.factory() obj_.build(child_) self.set_type(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'definition': + nodeName_ == 'definition': definition_ = '' for text__content_ in child_.childNodes: definition_ += text__content_.nodeValue self.definition = definition_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'argsstring': + nodeName_ == 'argsstring': argsstring_ = '' for text__content_ in child_.childNodes: argsstring_ += text__content_.nodeValue self.argsstring = argsstring_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue self.name = name_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'read': + nodeName_ == 'read': read_ = '' for text__content_ in child_.childNodes: read_ += text__content_.nodeValue self.read = read_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'write': + nodeName_ == 'write': write_ = '' for text__content_ in child_.childNodes: write_ += text__content_.nodeValue self.write = write_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'bitfield': + nodeName_ == 'bitfield': bitfield_ = '' for text__content_ in child_.childNodes: bitfield_ += text__content_.nodeValue self.bitfield = bitfield_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'reimplements': + nodeName_ == 'reimplements': obj_ = reimplementType.factory() obj_.build(child_) self.reimplements.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'reimplementedby': + nodeName_ == 'reimplementedby': obj_ = reimplementType.factory() obj_.build(child_) self.reimplementedby.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'param': + nodeName_ == 'param': obj_ = paramType.factory() obj_.build(child_) self.param.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'enumvalue': + nodeName_ == 'enumvalue': obj_ = enumvalueType.factory() obj_.build(child_) self.enumvalue.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'initializer': + nodeName_ == 'initializer': obj_ = linkedTextType.factory() obj_.build(child_) self.set_initializer(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'exceptions': + nodeName_ == 'exceptions': obj_ = linkedTextType.factory() obj_.build(child_) self.set_exceptions(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'briefdescription': + nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'detaileddescription': + nodeName_ == 'detaileddescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_detaileddescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'inbodydescription': + nodeName_ == 'inbodydescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_inbodydescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'location': + nodeName_ == 'location': obj_ = locationType.factory() obj_.build(child_) self.set_location(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'references': + nodeName_ == 'references': obj_ = referenceType.factory() obj_.build(child_) self.references.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'referencedby': + nodeName_ == 'referencedby': obj_ = referenceType.factory() obj_.build(child_) self.referencedby.append(obj_) @@ -2416,8 +2715,10 @@ def buildChildren(self, child_, nodeName_): class definition(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if definition.subclass: return definition.subclass(*args_, **kwargs_) @@ -2426,6 +2727,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='definition', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2437,33 +2739,40 @@ def export(self, outfile, level, namespace_='', name_='definition', namespacedef outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='definition'): pass + def exportChildren(self, outfile, level, namespace_='', name_='definition'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='definition'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2471,21 +2780,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class definition class argsstring(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if argsstring.subclass: return argsstring.subclass(*args_, **kwargs_) @@ -2494,6 +2807,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='argsstring', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2505,33 +2819,40 @@ def export(self, outfile, level, namespace_='', name_='argsstring', namespacedef outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='argsstring'): pass + def exportChildren(self, outfile, level, namespace_='', name_='argsstring'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='argsstring'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2539,21 +2860,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class argsstring class read(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if read.subclass: return read.subclass(*args_, **kwargs_) @@ -2562,6 +2887,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='read', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2573,33 +2899,40 @@ def export(self, outfile, level, namespace_='', name_='read', namespacedef_=''): outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='read'): pass + def exportChildren(self, outfile, level, namespace_='', name_='read'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='read'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2607,21 +2940,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class read class write(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if write.subclass: return write.subclass(*args_, **kwargs_) @@ -2630,6 +2967,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='write', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2641,33 +2979,40 @@ def export(self, outfile, level, namespace_='', name_='write', namespacedef_='') outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='write'): pass + def exportChildren(self, outfile, level, namespace_='', name_='write'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='write'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2675,21 +3020,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class write class bitfield(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if bitfield.subclass: return bitfield.subclass(*args_, **kwargs_) @@ -2698,6 +3047,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='bitfield', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -2709,33 +3059,40 @@ def export(self, outfile, level, namespace_='', name_='bitfield', namespacedef_= outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='bitfield'): pass + def exportChildren(self, outfile, level, namespace_='', name_='bitfield'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='bitfield'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -2743,19 +3100,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class bitfield class descriptionType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, title=None, para=None, sect1=None, internal=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -2765,6 +3125,7 @@ def __init__(self, title=None, para=None, sect1=None, internal=None, mixedclass_ self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if descriptionType.subclass: return descriptionType.subclass(*args_, **kwargs_) @@ -2783,35 +3144,43 @@ def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal + def export(self, outfile, level, namespace_='', name_='descriptionType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='descriptionType') + self.exportAttributes(outfile, level, namespace_, + name_='descriptionType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='descriptionType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='descriptionType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect1 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='descriptionType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -2837,46 +3206,49 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect1': + nodeName_ == 'sect1': childobj_ = docSect1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect1', childobj_) + MixedContainer.TypeNone, 'sect1', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class descriptionType @@ -2884,6 +3256,7 @@ def buildChildren(self, child_, nodeName_): class enumvalueType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, prot=None, id=None, name=None, initializer=None, briefdescription=None, detaileddescription=None, mixedclass_=None, content_=None): self.prot = prot self.id = id @@ -2895,6 +3268,7 @@ def __init__(self, prot=None, id=None, name=None, initializer=None, briefdescrip self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if enumvalueType.subclass: return enumvalueType.subclass(*args_, **kwargs_) @@ -2906,43 +3280,55 @@ def set_name(self, name): self.name = name def get_initializer(self): return self.initializer def set_initializer(self, initializer): self.initializer = initializer def get_briefdescription(self): return self.briefdescription - def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription + def set_briefdescription( + self, briefdescription): self.briefdescription = briefdescription + def get_detaileddescription(self): return self.detaileddescription - def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription + def set_detaileddescription( + self, detaileddescription): self.detaileddescription = detaileddescription + def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='enumvalueType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='enumvalueType') + self.exportAttributes(outfile, level, namespace_, + name_='enumvalueType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='enumvalueType'): if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='enumvalueType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.name is not None or self.initializer is not None or self.briefdescription is not None or self.detaileddescription is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='enumvalueType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.prot is not None: showIndent(outfile, level) @@ -2950,6 +3336,7 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -2975,51 +3362,54 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': value_ = [] for text_ in child_.childNodes: value_.append(text_.nodeValue) valuestr_ = ''.join(value_) obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'name', valuestr_) + MixedContainer.TypeString, 'name', valuestr_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'initializer': + nodeName_ == 'initializer': childobj_ = linkedTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'initializer', childobj_) + MixedContainer.TypeNone, 'initializer', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'briefdescription': + nodeName_ == 'briefdescription': childobj_ = descriptionType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'briefdescription', childobj_) + MixedContainer.TypeNone, 'briefdescription', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'detaileddescription': + nodeName_ == 'detaileddescription': childobj_ = descriptionType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'detaileddescription', childobj_) + MixedContainer.TypeNone, 'detaileddescription', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class enumvalueType @@ -3027,11 +3417,13 @@ def buildChildren(self, child_, nodeName_): class templateparamlistType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, param=None): if param is None: self.param = [] else: self.param = param + def factory(*args_, **kwargs_): if templateparamlistType.subclass: return templateparamlistType.subclass(*args_, **kwargs_) @@ -3042,10 +3434,12 @@ def get_param(self): return self.param def set_param(self, param): self.param = param def add_param(self, value): self.param.append(value) def insert_param(self, index, value): self.param[index] = value + def export(self, outfile, level, namespace_='', name_='templateparamlistType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='templateparamlistType') + self.exportAttributes(outfile, level, namespace_, + name_='templateparamlistType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -3053,25 +3447,31 @@ def export(self, outfile, level, namespace_='', name_='templateparamlistType', n outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='templateparamlistType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='templateparamlistType'): for param_ in self.param: param_.export(outfile, level, namespace_, name_='param') + def hasContent_(self): if ( self.param is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='templateparamlistType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('param=[\n') @@ -3085,17 +3485,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'param': + nodeName_ == 'param': obj_ = paramType.factory() obj_.build(child_) self.param.append(obj_) @@ -3105,6 +3508,7 @@ def buildChildren(self, child_, nodeName_): class paramType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, type_=None, declname=None, defname=None, array=None, defval=None, briefdescription=None): self.type_ = type_ self.declname = declname @@ -3112,6 +3516,7 @@ def __init__(self, type_=None, declname=None, defname=None, array=None, defval=N self.array = array self.defval = defval self.briefdescription = briefdescription + def factory(*args_, **kwargs_): if paramType.subclass: return paramType.subclass(*args_, **kwargs_) @@ -3129,7 +3534,10 @@ def set_array(self, array): self.array = array def get_defval(self): return self.defval def set_defval(self, defval): self.defval = defval def get_briefdescription(self): return self.briefdescription - def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription + + def set_briefdescription( + self, briefdescription): self.briefdescription = briefdescription + def export(self, outfile, level, namespace_='', name_='paramType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3141,24 +3549,31 @@ def export(self, outfile, level, namespace_='', name_='paramType', namespacedef_ outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='paramType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='paramType'): if self.type_: self.type_.export(outfile, level, namespace_, name_='type') if self.declname is not None: showIndent(outfile, level) - outfile.write('<%sdeclname>%s\n' % (namespace_, self.format_string(quote_xml(self.declname).encode(ExternalEncoding), input_name='declname'), namespace_)) + outfile.write('<%sdeclname>%s\n' % (namespace_, self.format_string( + quote_xml(self.declname).encode(ExternalEncoding), input_name='declname'), namespace_)) if self.defname is not None: showIndent(outfile, level) - outfile.write('<%sdefname>%s\n' % (namespace_, self.format_string(quote_xml(self.defname).encode(ExternalEncoding), input_name='defname'), namespace_)) + outfile.write('<%sdefname>%s\n' % (namespace_, self.format_string( + quote_xml(self.defname).encode(ExternalEncoding), input_name='defname'), namespace_)) if self.array is not None: showIndent(outfile, level) - outfile.write('<%sarray>%s\n' % (namespace_, self.format_string(quote_xml(self.array).encode(ExternalEncoding), input_name='array'), namespace_)) + outfile.write('<%sarray>%s\n' % (namespace_, self.format_string( + quote_xml(self.array).encode(ExternalEncoding), input_name='array'), namespace_)) if self.defval: self.defval.export(outfile, level, namespace_, name_='defval') if self.briefdescription: - self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') + self.briefdescription.export( + outfile, level, namespace_, name_='briefdescription') + def hasContent_(self): if ( self.type_ is not None or @@ -3167,17 +3582,20 @@ def hasContent_(self): self.array is not None or self.defval is not None or self.briefdescription is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='paramType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): if self.type_: showIndent(outfile, level) @@ -3186,11 +3604,14 @@ def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) - outfile.write('declname=%s,\n' % quote_python(self.declname).encode(ExternalEncoding)) + outfile.write('declname=%s,\n' % quote_python( + self.declname).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('defname=%s,\n' % quote_python(self.defname).encode(ExternalEncoding)) + outfile.write('defname=%s,\n' % quote_python( + self.defname).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('array=%s,\n' % quote_python(self.array).encode(ExternalEncoding)) + outfile.write('array=%s,\n' % quote_python( + self.array).encode(ExternalEncoding)) if self.defval: showIndent(outfile, level) outfile.write('defval=model_.linkedTextType(\n') @@ -3200,48 +3621,52 @@ def exportLiteralChildren(self, outfile, level, name_): if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') - self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') + self.briefdescription.exportLiteral( + outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'type': + nodeName_ == 'type': obj_ = linkedTextType.factory() obj_.build(child_) self.set_type(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'declname': + nodeName_ == 'declname': declname_ = '' for text__content_ in child_.childNodes: declname_ += text__content_.nodeValue self.declname = declname_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'defname': + nodeName_ == 'defname': defname_ = '' for text__content_ in child_.childNodes: defname_ += text__content_.nodeValue self.defname = defname_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'array': + nodeName_ == 'array': array_ = '' for text__content_ in child_.childNodes: array_ += text__content_.nodeValue self.array = array_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'defval': + nodeName_ == 'defval': obj_ = linkedTextType.factory() obj_.build(child_) self.set_defval(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'briefdescription': + nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) @@ -3251,8 +3676,10 @@ def buildChildren(self, child_, nodeName_): class declname(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if declname.subclass: return declname.subclass(*args_, **kwargs_) @@ -3261,6 +3688,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='declname', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3272,33 +3700,40 @@ def export(self, outfile, level, namespace_='', name_='declname', namespacedef_= outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='declname'): pass + def exportChildren(self, outfile, level, namespace_='', name_='declname'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='declname'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3306,21 +3741,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class declname class defname(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if defname.subclass: return defname.subclass(*args_, **kwargs_) @@ -3329,6 +3768,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='defname', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3340,33 +3780,40 @@ def export(self, outfile, level, namespace_='', name_='defname', namespacedef_=' outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='defname'): pass + def exportChildren(self, outfile, level, namespace_='', name_='defname'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='defname'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3374,21 +3821,25 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class defname class array(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if array.subclass: return array.subclass(*args_, **kwargs_) @@ -3397,6 +3848,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='array', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3408,33 +3860,40 @@ def export(self, outfile, level, namespace_='', name_='array', namespacedef_='') outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='array'): pass + def exportChildren(self, outfile, level, namespace_='', name_='array'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='array'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3442,19 +3901,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class array class linkedTextType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, ref=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -3464,6 +3926,7 @@ def __init__(self, ref=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if linkedTextType.subclass: return linkedTextType.subclass(*args_, **kwargs_) @@ -3474,32 +3937,40 @@ def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def add_ref(self, value): self.ref.append(value) def insert_ref(self, index, value): self.ref[index] = value + def export(self, outfile, level, namespace_='', name_='linkedTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='linkedTextType') + self.exportAttributes(outfile, level, namespace_, + name_='linkedTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='linkedTextType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='linkedTextType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.ref is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='linkedTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -3507,25 +3978,28 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'ref': + nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'ref', childobj_) + MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class linkedTextType @@ -3533,11 +4007,13 @@ def buildChildren(self, child_, nodeName_): class graphType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, node=None): if node is None: self.node = [] else: self.node = node + def factory(*args_, **kwargs_): if graphType.subclass: return graphType.subclass(*args_, **kwargs_) @@ -3548,6 +4024,7 @@ def get_node(self): return self.node def set_node(self, node): self.node = node def add_node(self, value): self.node.append(value) def insert_node(self, index, value): self.node[index] = value + def export(self, outfile, level, namespace_='', name_='graphType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3559,25 +4036,31 @@ def export(self, outfile, level, namespace_='', name_='graphType', namespacedef_ outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='graphType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='graphType'): for node_ in self.node: node_.export(outfile, level, namespace_, name_='node') + def hasContent_(self): if ( self.node is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='graphType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('node=[\n') @@ -3591,17 +4074,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'node': + nodeName_ == 'node': obj_ = nodeType.factory() obj_.build(child_) self.node.append(obj_) @@ -3611,6 +4097,7 @@ def buildChildren(self, child_, nodeName_): class nodeType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, label=None, link=None, childnode=None): self.id = id self.label = label @@ -3619,6 +4106,7 @@ def __init__(self, id=None, label=None, link=None, childnode=None): self.childnode = [] else: self.childnode = childnode + def factory(*args_, **kwargs_): if nodeType.subclass: return nodeType.subclass(*args_, **kwargs_) @@ -3635,6 +4123,7 @@ def add_childnode(self, value): self.childnode.append(value) def insert_childnode(self, index, value): self.childnode[index] = value def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='nodeType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3646,38 +4135,47 @@ def export(self, outfile, level, namespace_='', name_='nodeType', namespacedef_= outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='nodeType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='nodeType'): if self.label is not None: showIndent(outfile, level) - outfile.write('<%slabel>%s\n' % (namespace_, self.format_string(quote_xml(self.label).encode(ExternalEncoding), input_name='label'), namespace_)) + outfile.write('<%slabel>%s\n' % (namespace_, self.format_string( + quote_xml(self.label).encode(ExternalEncoding), input_name='label'), namespace_)) if self.link: self.link.export(outfile, level, namespace_, name_='link') for childnode_ in self.childnode: childnode_.export(outfile, level, namespace_, name_='childnode') + def hasContent_(self): if ( self.label is not None or self.link is not None or self.childnode is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='nodeType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('label=%s,\n' % quote_python(self.label).encode(ExternalEncoding)) + outfile.write('label=%s,\n' % quote_python( + self.label).encode(ExternalEncoding)) if self.link: showIndent(outfile, level) outfile.write('link=model_.linkType(\n') @@ -3696,29 +4194,32 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'label': + nodeName_ == 'label': label_ = '' for text__content_ in child_.childNodes: label_ += text__content_.nodeValue self.label = label_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'link': + nodeName_ == 'link': obj_ = linkType.factory() obj_.build(child_) self.set_link(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'childnode': + nodeName_ == 'childnode': obj_ = childnodeType.factory() obj_.build(child_) self.childnode.append(obj_) @@ -3728,8 +4229,10 @@ def buildChildren(self, child_, nodeName_): class label(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if label.subclass: return label.subclass(*args_, **kwargs_) @@ -3738,6 +4241,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='label', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3749,33 +4253,40 @@ def export(self, outfile, level, namespace_='', name_='label', namespacedef_='') outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='label'): pass + def exportChildren(self, outfile, level, namespace_='', name_='label'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='label'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3783,19 +4294,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class label class childnodeType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, relation=None, refid=None, edgelabel=None): self.relation = relation self.refid = refid @@ -3803,6 +4317,7 @@ def __init__(self, relation=None, refid=None, edgelabel=None): self.edgelabel = [] else: self.edgelabel = edgelabel + def factory(*args_, **kwargs_): if childnodeType.subclass: return childnodeType.subclass(*args_, **kwargs_) @@ -3817,10 +4332,12 @@ def get_relation(self): return self.relation def set_relation(self, relation): self.relation = relation def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid + def export(self, outfile, level, namespace_='', name_='childnodeType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='childnodeType') + self.exportAttributes(outfile, level, namespace_, + name_='childnodeType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -3828,27 +4345,34 @@ def export(self, outfile, level, namespace_='', name_='childnodeType', namespace outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='childnodeType'): if self.relation is not None: outfile.write(' relation=%s' % (quote_attrib(self.relation), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='childnodeType'): for edgelabel_ in self.edgelabel: showIndent(outfile, level) - outfile.write('<%sedgelabel>%s\n' % (namespace_, self.format_string(quote_xml(edgelabel_).encode(ExternalEncoding), input_name='edgelabel'), namespace_)) + outfile.write('<%sedgelabel>%s\n' % (namespace_, self.format_string( + quote_xml(edgelabel_).encode(ExternalEncoding), input_name='edgelabel'), namespace_)) + def hasContent_(self): if ( self.edgelabel is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='childnodeType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.relation is not None: showIndent(outfile, level) @@ -3856,30 +4380,35 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('edgelabel=[\n') level += 1 for edgelabel in self.edgelabel: showIndent(outfile, level) - outfile.write('%s,\n' % quote_python(edgelabel).encode(ExternalEncoding)) + outfile.write('%s,\n' % quote_python( + edgelabel).encode(ExternalEncoding)) level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('relation'): self.relation = attrs.get('relation').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'edgelabel': + nodeName_ == 'edgelabel': edgelabel_ = '' for text__content_ in child_.childNodes: edgelabel_ += text__content_.nodeValue @@ -3890,8 +4419,10 @@ def buildChildren(self, child_, nodeName_): class edgelabel(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if edgelabel.subclass: return edgelabel.subclass(*args_, **kwargs_) @@ -3900,6 +4431,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='edgelabel', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3911,33 +4443,40 @@ def export(self, outfile, level, namespace_='', name_='edgelabel', namespacedef_ outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='edgelabel'): pass + def exportChildren(self, outfile, level, namespace_='', name_='edgelabel'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='edgelabel'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -3945,23 +4484,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class edgelabel class linkType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, refid=None, external=None, valueOf_=''): self.refid = refid self.external = external self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if linkType.subclass: return linkType.subclass(*args_, **kwargs_) @@ -3974,6 +4517,7 @@ def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='linkType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -3985,31 +4529,38 @@ def export(self, outfile, level, namespace_='', name_='linkType', namespacedef_= outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='linkType'): if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.external is not None: - outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) + outfile.write(' external=%s' % (self.format_string(quote_attrib( + self.external).encode(ExternalEncoding), input_name='external'), )) + def exportChildren(self, outfile, level, namespace_='', name_='linkType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='linkType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) @@ -4017,9 +4568,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -4027,27 +4580,31 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('external'): self.external = attrs.get('external').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class linkType class listingType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, codeline=None): if codeline is None: self.codeline = [] else: self.codeline = codeline + def factory(*args_, **kwargs_): if listingType.subclass: return listingType.subclass(*args_, **kwargs_) @@ -4058,6 +4615,7 @@ def get_codeline(self): return self.codeline def set_codeline(self, codeline): self.codeline = codeline def add_codeline(self, value): self.codeline.append(value) def insert_codeline(self, index, value): self.codeline[index] = value + def export(self, outfile, level, namespace_='', name_='listingType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4069,25 +4627,31 @@ def export(self, outfile, level, namespace_='', name_='listingType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='listingType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='listingType'): for codeline_ in self.codeline: codeline_.export(outfile, level, namespace_, name_='codeline') + def hasContent_(self): if ( self.codeline is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='listingType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('codeline=[\n') @@ -4101,17 +4665,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'codeline': + nodeName_ == 'codeline': obj_ = codelineType.factory() obj_.build(child_) self.codeline.append(obj_) @@ -4121,6 +4688,7 @@ def buildChildren(self, child_, nodeName_): class codelineType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None): self.external = external self.lineno = lineno @@ -4130,6 +4698,7 @@ def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlig self.highlight = [] else: self.highlight = highlight + def factory(*args_, **kwargs_): if codelineType.subclass: return codelineType.subclass(*args_, **kwargs_) @@ -4148,6 +4717,7 @@ def get_refkind(self): return self.refkind def set_refkind(self, refkind): self.refkind = refkind def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid + def export(self, outfile, level, namespace_='', name_='codelineType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4159,30 +4729,37 @@ def export(self, outfile, level, namespace_='', name_='codelineType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='codelineType'): if self.external is not None: outfile.write(' external=%s' % (quote_attrib(self.external), )) if self.lineno is not None: - outfile.write(' lineno="%s"' % self.format_integer(self.lineno, input_name='lineno')) + outfile.write(' lineno="%s"' % self.format_integer( + self.lineno, input_name='lineno')) if self.refkind is not None: outfile.write(' refkind=%s' % (quote_attrib(self.refkind), )) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='codelineType'): for highlight_ in self.highlight: highlight_.export(outfile, level, namespace_, name_='highlight') + def hasContent_(self): if ( self.highlight is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='codelineType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) @@ -4196,6 +4773,7 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('highlight=[\n') @@ -4209,12 +4787,14 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('external'): self.external = attrs.get('external').value @@ -4227,9 +4807,10 @@ def buildAttributes(self, attrs): self.refkind = attrs.get('refkind').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'highlight': + nodeName_ == 'highlight': obj_ = highlightType.factory() obj_.build(child_) self.highlight.append(obj_) @@ -4239,6 +4820,7 @@ def buildChildren(self, child_, nodeName_): class highlightType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, classxx=None, sp=None, ref=None, mixedclass_=None, content_=None): self.classxx = classxx if mixedclass_ is None: @@ -4249,6 +4831,7 @@ def __init__(self, classxx=None, sp=None, ref=None, mixedclass_=None, content_=N self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if highlightType.subclass: return highlightType.subclass(*args_, **kwargs_) @@ -4265,36 +4848,44 @@ def add_ref(self, value): self.ref.append(value) def insert_ref(self, index, value): self.ref[index] = value def get_class(self): return self.classxx def set_class(self, classxx): self.classxx = classxx + def export(self, outfile, level, namespace_='', name_='highlightType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='highlightType') + self.exportAttributes(outfile, level, namespace_, + name_='highlightType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='highlightType'): if self.classxx is not None: outfile.write(' class=%s' % (quote_attrib(self.classxx), )) + def exportChildren(self, outfile, level, namespace_='', name_='highlightType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.sp is not None or self.ref is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='highlightType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.classxx is not None: showIndent(outfile, level) outfile.write('classxx = "%s",\n' % (self.classxx,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -4308,35 +4899,38 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('class'): self.classxx = attrs.get('class').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sp': + nodeName_ == 'sp': value_ = [] for text_ in child_.childNodes: value_.append(text_.nodeValue) valuestr_ = ''.join(value_) obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'sp', valuestr_) + MixedContainer.TypeString, 'sp', valuestr_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'ref': + nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'ref', childobj_) + MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class highlightType @@ -4344,8 +4938,10 @@ def buildChildren(self, child_, nodeName_): class sp(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if sp.subclass: return sp.subclass(*args_, **kwargs_) @@ -4354,6 +4950,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='sp', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4365,33 +4962,40 @@ def export(self, outfile, level, namespace_='', name_='sp', namespacedef_=''): outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='sp'): pass + def exportChildren(self, outfile, level, namespace_='', name_='sp'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='sp'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -4399,19 +5003,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class sp class referenceType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, endline=None, startline=None, refid=None, compoundref=None, valueOf_='', mixedclass_=None, content_=None): self.endline = endline self.startline = startline @@ -4425,6 +5032,7 @@ def __init__(self, endline=None, startline=None, refid=None, compoundref=None, v self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if referenceType.subclass: return referenceType.subclass(*args_, **kwargs_) @@ -4441,42 +5049,53 @@ def get_compoundref(self): return self.compoundref def set_compoundref(self, compoundref): self.compoundref = compoundref def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='referenceType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='referenceType') + self.exportAttributes(outfile, level, namespace_, + name_='referenceType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='referenceType'): if self.endline is not None: - outfile.write(' endline="%s"' % self.format_integer(self.endline, input_name='endline')) + outfile.write(' endline="%s"' % self.format_integer( + self.endline, input_name='endline')) if self.startline is not None: - outfile.write(' startline="%s"' % self.format_integer(self.startline, input_name='startline')) + outfile.write(' startline="%s"' % self.format_integer( + self.startline, input_name='startline')) if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.compoundref is not None: - outfile.write(' compoundref=%s' % (self.format_string(quote_attrib(self.compoundref).encode(ExternalEncoding), input_name='compoundref'), )) + outfile.write(' compoundref=%s' % (self.format_string(quote_attrib( + self.compoundref).encode(ExternalEncoding), input_name='compoundref'), )) + def exportChildren(self, outfile, level, namespace_='', name_='referenceType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='referenceType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.endline is not None: showIndent(outfile, level) @@ -4490,9 +5109,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.compoundref is not None: showIndent(outfile, level) outfile.write('compoundref = %s,\n' % (self.compoundref,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -4500,6 +5121,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('endline'): try: @@ -4515,21 +5137,23 @@ def buildAttributes(self, attrs): self.refid = attrs.get('refid').value if attrs.get('compoundref'): self.compoundref = attrs.get('compoundref').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class referenceType class locationType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file=None, valueOf_=''): self.bodystart = bodystart self.line = line @@ -4537,6 +5161,7 @@ def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file= self.bodyfile = bodyfile self.file = file self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if locationType.subclass: return locationType.subclass(*args_, **kwargs_) @@ -4555,6 +5180,7 @@ def get_file(self): return self.file def set_file(self, file): self.file = file def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='locationType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4566,37 +5192,47 @@ def export(self, outfile, level, namespace_='', name_='locationType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='locationType'): if self.bodystart is not None: - outfile.write(' bodystart="%s"' % self.format_integer(self.bodystart, input_name='bodystart')) + outfile.write(' bodystart="%s"' % self.format_integer( + self.bodystart, input_name='bodystart')) if self.line is not None: - outfile.write(' line="%s"' % self.format_integer(self.line, input_name='line')) + outfile.write(' line="%s"' % self.format_integer( + self.line, input_name='line')) if self.bodyend is not None: - outfile.write(' bodyend="%s"' % self.format_integer(self.bodyend, input_name='bodyend')) + outfile.write(' bodyend="%s"' % self.format_integer( + self.bodyend, input_name='bodyend')) if self.bodyfile is not None: - outfile.write(' bodyfile=%s' % (self.format_string(quote_attrib(self.bodyfile).encode(ExternalEncoding), input_name='bodyfile'), )) + outfile.write(' bodyfile=%s' % (self.format_string(quote_attrib( + self.bodyfile).encode(ExternalEncoding), input_name='bodyfile'), )) if self.file is not None: - outfile.write(' file=%s' % (self.format_string(quote_attrib(self.file).encode(ExternalEncoding), input_name='file'), )) + outfile.write(' file=%s' % (self.format_string(quote_attrib( + self.file).encode(ExternalEncoding), input_name='file'), )) + def exportChildren(self, outfile, level, namespace_='', name_='locationType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='locationType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.bodystart is not None: showIndent(outfile, level) @@ -4613,9 +5249,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.file is not None: showIndent(outfile, level) outfile.write('file = %s,\n' % (self.file,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -4623,6 +5261,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('bodystart'): try: @@ -4643,17 +5282,19 @@ def buildAttributes(self, attrs): self.bodyfile = attrs.get('bodyfile').value if attrs.get('file'): self.file = attrs.get('file').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class locationType class docSect1Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, title=None, para=None, sect2=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -4664,6 +5305,7 @@ def __init__(self, id=None, title=None, para=None, sect2=None, internal=None, mi self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docSect1Type.subclass: return docSect1Type.subclass(*args_, **kwargs_) @@ -4684,6 +5326,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docSect1Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4691,31 +5334,38 @@ def export(self, outfile, level, namespace_='', name_='docSect1Type', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docSect1Type'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSect1Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect2 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSect1Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -4741,47 +5391,50 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect2': + nodeName_ == 'sect2': childobj_ = docSect2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect2', childobj_) + MixedContainer.TypeNone, 'sect2', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalS1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect1Type @@ -4789,6 +5442,7 @@ def buildChildren(self, child_, nodeName_): class docSect2Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, title=None, para=None, sect3=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -4799,6 +5453,7 @@ def __init__(self, id=None, title=None, para=None, sect3=None, internal=None, mi self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docSect2Type.subclass: return docSect2Type.subclass(*args_, **kwargs_) @@ -4819,6 +5474,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docSect2Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4826,31 +5482,38 @@ def export(self, outfile, level, namespace_='', name_='docSect2Type', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docSect2Type'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSect2Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect3 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSect2Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -4876,47 +5539,50 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect3': + nodeName_ == 'sect3': childobj_ = docSect3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect3', childobj_) + MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalS2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect2Type @@ -4924,6 +5590,7 @@ def buildChildren(self, child_, nodeName_): class docSect3Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, title=None, para=None, sect4=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -4934,6 +5601,7 @@ def __init__(self, id=None, title=None, para=None, sect4=None, internal=None, mi self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docSect3Type.subclass: return docSect3Type.subclass(*args_, **kwargs_) @@ -4954,6 +5622,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docSect3Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -4961,31 +5630,38 @@ def export(self, outfile, level, namespace_='', name_='docSect3Type', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docSect3Type'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSect3Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect4 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSect3Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5011,47 +5687,50 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect4': + nodeName_ == 'sect4': childobj_ = docSect4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect4', childobj_) + MixedContainer.TypeNone, 'sect4', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalS3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect3Type @@ -5059,6 +5738,7 @@ def buildChildren(self, child_, nodeName_): class docSect4Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, title=None, para=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -5069,6 +5749,7 @@ def __init__(self, id=None, title=None, para=None, internal=None, mixedclass_=No self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docSect4Type.subclass: return docSect4Type.subclass(*args_, **kwargs_) @@ -5085,6 +5766,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docSect4Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -5092,30 +5774,37 @@ def export(self, outfile, level, namespace_='', name_='docSect4Type', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docSect4Type'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSect4Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.title is not None or self.para is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSect4Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5135,40 +5824,43 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'title', childobj_) + MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': childobj_ = docInternalS4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'internal', childobj_) + MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect4Type @@ -5176,6 +5868,7 @@ def buildChildren(self, child_, nodeName_): class docInternalType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5185,6 +5878,7 @@ def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalType.subclass: return docInternalType.subclass(*args_, **kwargs_) @@ -5199,33 +5893,41 @@ def get_sect1(self): return self.sect1 def set_sect1(self, sect1): self.sect1 = sect1 def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalType') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None or self.sect1 is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5239,32 +5941,35 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect1': + nodeName_ == 'sect1': childobj_ = docSect1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect1', childobj_) + MixedContainer.TypeNone, 'sect1', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalType @@ -5272,6 +5977,7 @@ def buildChildren(self, child_, nodeName_): class docInternalS1Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5281,6 +5987,7 @@ def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalS1Type.subclass: return docInternalS1Type.subclass(*args_, **kwargs_) @@ -5295,33 +6002,41 @@ def get_sect2(self): return self.sect2 def set_sect2(self, sect2): self.sect2 = sect2 def add_sect2(self, value): self.sect2.append(value) def insert_sect2(self, index, value): self.sect2[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalS1Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalS1Type') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalS1Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS1Type'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalS1Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None or self.sect2 is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalS1Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5335,32 +6050,35 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect2': + nodeName_ == 'sect2': childobj_ = docSect2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect2', childobj_) + MixedContainer.TypeNone, 'sect2', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS1Type @@ -5368,6 +6086,7 @@ def buildChildren(self, child_, nodeName_): class docInternalS2Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5377,6 +6096,7 @@ def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalS2Type.subclass: return docInternalS2Type.subclass(*args_, **kwargs_) @@ -5391,33 +6111,41 @@ def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalS2Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalS2Type') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalS2Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS2Type'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalS2Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None or self.sect3 is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalS2Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5431,32 +6159,35 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect3': + nodeName_ == 'sect3': childobj_ = docSect3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect3', childobj_) + MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS2Type @@ -5464,6 +6195,7 @@ def buildChildren(self, child_, nodeName_): class docInternalS3Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5473,6 +6205,7 @@ def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalS3Type.subclass: return docInternalS3Type.subclass(*args_, **kwargs_) @@ -5487,33 +6220,41 @@ def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalS3Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalS3Type') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalS3Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS3Type'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalS3Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None or self.sect3 is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalS3Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5527,32 +6268,35 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect3': + nodeName_ == 'sect3': childobj_ = docSect4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'sect3', childobj_) + MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS3Type @@ -5560,6 +6304,7 @@ def buildChildren(self, child_, nodeName_): class docInternalS4Type(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5569,6 +6314,7 @@ def __init__(self, para=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docInternalS4Type.subclass: return docInternalS4Type.subclass(*args_, **kwargs_) @@ -5579,32 +6325,40 @@ def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value + def export(self, outfile, level, namespace_='', name_='docInternalS4Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docInternalS4Type') + self.exportAttributes(outfile, level, namespace_, + name_='docInternalS4Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS4Type'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docInternalS4Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docInternalS4Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -5612,25 +6366,28 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'para', childobj_) + MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS4Type @@ -5638,6 +6395,7 @@ def buildChildren(self, child_, nodeName_): class docTitleType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5647,6 +6405,7 @@ def __init__(self, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docTitleType.subclass: return docTitleType.subclass(*args_, **kwargs_) @@ -5655,6 +6414,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docTitleType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -5662,33 +6422,40 @@ def export(self, outfile, level, namespace_='', name_='docTitleType', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docTitleType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docTitleType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docTitleType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -5696,23 +6463,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docTitleType class docParaType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5722,6 +6492,7 @@ def __init__(self, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docParaType.subclass: return docParaType.subclass(*args_, **kwargs_) @@ -5730,6 +6501,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docParaType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -5737,33 +6509,40 @@ def export(self, outfile, level, namespace_='', name_='docParaType', namespacede outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docParaType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docParaType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParaType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -5771,23 +6550,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docParaType class docMarkupType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -5797,6 +6579,7 @@ def __init__(self, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docMarkupType.subclass: return docMarkupType.subclass(*args_, **kwargs_) @@ -5805,40 +6588,49 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docMarkupType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docMarkupType') + self.exportAttributes(outfile, level, namespace_, + name_='docMarkupType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docMarkupType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docMarkupType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docMarkupType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -5846,23 +6638,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docMarkupType class docURLLink(GeneratedsSuper): subclass = None superclass = None + def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): self.url = url if mixedclass_ is None: @@ -5873,6 +6668,7 @@ def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docURLLink.subclass: return docURLLink.subclass(*args_, **kwargs_) @@ -5883,6 +6679,7 @@ def get_url(self): return self.url def set_url(self, url): self.url = url def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docURLLink', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -5890,36 +6687,44 @@ def export(self, outfile, level, namespace_='', name_='docURLLink', namespacedef outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docURLLink'): if self.url is not None: - outfile.write(' url=%s' % (self.format_string(quote_attrib(self.url).encode(ExternalEncoding), input_name='url'), )) + outfile.write(' url=%s' % (self.format_string(quote_attrib( + self.url).encode(ExternalEncoding), input_name='url'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docURLLink'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docURLLink'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.url is not None: showIndent(outfile, level) outfile.write('url = %s,\n' % (self.url,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -5927,24 +6732,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('url'): self.url = attrs.get('url').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docURLLink class docAnchorType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -5955,6 +6763,7 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docAnchorType.subclass: return docAnchorType.subclass(*args_, **kwargs_) @@ -5965,43 +6774,53 @@ def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docAnchorType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docAnchorType') + self.exportAttributes(outfile, level, namespace_, + name_='docAnchorType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docAnchorType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docAnchorType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docAnchorType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -6009,24 +6828,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docAnchorType class docFormulaType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -6037,6 +6859,7 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docFormulaType.subclass: return docFormulaType.subclass(*args_, **kwargs_) @@ -6047,43 +6870,53 @@ def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docFormulaType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docFormulaType') + self.exportAttributes(outfile, level, namespace_, + name_='docFormulaType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docFormulaType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docFormulaType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docFormulaType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -6091,27 +6924,31 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docFormulaType class docIndexEntryType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, primaryie=None, secondaryie=None): self.primaryie = primaryie self.secondaryie = secondaryie + def factory(*args_, **kwargs_): if docIndexEntryType.subclass: return docIndexEntryType.subclass(*args_, **kwargs_) @@ -6122,10 +6959,12 @@ def get_primaryie(self): return self.primaryie def set_primaryie(self, primaryie): self.primaryie = primaryie def get_secondaryie(self): return self.secondaryie def set_secondaryie(self, secondaryie): self.secondaryie = secondaryie + def export(self, outfile, level, namespace_='', name_='docIndexEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docIndexEntryType') + self.exportAttributes(outfile, level, namespace_, + name_='docIndexEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6133,52 +6972,65 @@ def export(self, outfile, level, namespace_='', name_='docIndexEntryType', names outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docIndexEntryType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docIndexEntryType'): if self.primaryie is not None: showIndent(outfile, level) - outfile.write('<%sprimaryie>%s\n' % (namespace_, self.format_string(quote_xml(self.primaryie).encode(ExternalEncoding), input_name='primaryie'), namespace_)) + outfile.write('<%sprimaryie>%s\n' % (namespace_, self.format_string( + quote_xml(self.primaryie).encode(ExternalEncoding), input_name='primaryie'), namespace_)) if self.secondaryie is not None: showIndent(outfile, level) - outfile.write('<%ssecondaryie>%s\n' % (namespace_, self.format_string(quote_xml(self.secondaryie).encode(ExternalEncoding), input_name='secondaryie'), namespace_)) + outfile.write('<%ssecondaryie>%s\n' % (namespace_, self.format_string( + quote_xml(self.secondaryie).encode(ExternalEncoding), input_name='secondaryie'), namespace_)) + def hasContent_(self): if ( self.primaryie is not None or self.secondaryie is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docIndexEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('primaryie=%s,\n' % quote_python(self.primaryie).encode(ExternalEncoding)) + outfile.write('primaryie=%s,\n' % quote_python( + self.primaryie).encode(ExternalEncoding)) showIndent(outfile, level) - outfile.write('secondaryie=%s,\n' % quote_python(self.secondaryie).encode(ExternalEncoding)) + outfile.write('secondaryie=%s,\n' % quote_python( + self.secondaryie).encode(ExternalEncoding)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'primaryie': + nodeName_ == 'primaryie': primaryie_ = '' for text__content_ in child_.childNodes: primaryie_ += text__content_.nodeValue self.primaryie = primaryie_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'secondaryie': + nodeName_ == 'secondaryie': secondaryie_ = '' for text__content_ in child_.childNodes: secondaryie_ += text__content_.nodeValue @@ -6189,11 +7041,13 @@ def buildChildren(self, child_, nodeName_): class docListType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, listitem=None): if listitem is None: self.listitem = [] else: self.listitem = listitem + def factory(*args_, **kwargs_): if docListType.subclass: return docListType.subclass(*args_, **kwargs_) @@ -6204,6 +7058,7 @@ def get_listitem(self): return self.listitem def set_listitem(self, listitem): self.listitem = listitem def add_listitem(self, value): self.listitem.append(value) def insert_listitem(self, index, value): self.listitem[index] = value + def export(self, outfile, level, namespace_='', name_='docListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -6215,25 +7070,31 @@ def export(self, outfile, level, namespace_='', name_='docListType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docListType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docListType'): for listitem_ in self.listitem: listitem_.export(outfile, level, namespace_, name_='listitem') + def hasContent_(self): if ( self.listitem is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('listitem=[\n') @@ -6247,17 +7108,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'listitem': + nodeName_ == 'listitem': obj_ = docListItemType.factory() obj_.build(child_) self.listitem.append(obj_) @@ -6267,11 +7131,13 @@ def buildChildren(self, child_, nodeName_): class docListItemType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, para=None): if para is None: self.para = [] else: self.para = para + def factory(*args_, **kwargs_): if docListItemType.subclass: return docListItemType.subclass(*args_, **kwargs_) @@ -6282,10 +7148,12 @@ def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value + def export(self, outfile, level, namespace_='', name_='docListItemType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docListItemType') + self.exportAttributes(outfile, level, namespace_, + name_='docListItemType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6293,25 +7161,31 @@ def export(self, outfile, level, namespace_='', name_='docListItemType', namespa outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docListItemType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docListItemType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') + def hasContent_(self): if ( self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docListItemType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') @@ -6325,17 +7199,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) @@ -6345,6 +7222,7 @@ def buildChildren(self, child_, nodeName_): class docSimpleSectType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, title=None, para=None): self.kind = kind self.title = title @@ -6352,6 +7230,7 @@ def __init__(self, kind=None, title=None, para=None): self.para = [] else: self.para = para + def factory(*args_, **kwargs_): if docSimpleSectType.subclass: return docSimpleSectType.subclass(*args_, **kwargs_) @@ -6366,10 +7245,12 @@ def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind + def export(self, outfile, level, namespace_='', name_='docSimpleSectType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docSimpleSectType') + self.exportAttributes(outfile, level, namespace_, + name_='docSimpleSectType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6377,31 +7258,37 @@ def export(self, outfile, level, namespace_='', name_='docSimpleSectType', names outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docSimpleSectType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) + def exportChildren(self, outfile, level, namespace_='', name_='docSimpleSectType'): if self.title: self.title.export(outfile, level, namespace_, name_='title') for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') + def hasContent_(self): if ( self.title is not None or self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docSimpleSectType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) + def exportLiteralChildren(self, outfile, level, name_): if self.title: showIndent(outfile, level) @@ -6421,23 +7308,26 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'title': + nodeName_ == 'title': obj_ = docTitleType.factory() obj_.build(child_) self.set_title(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) @@ -6447,8 +7337,10 @@ def buildChildren(self, child_, nodeName_): class docVarListEntryType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, term=None): self.term = term + def factory(*args_, **kwargs_): if docVarListEntryType.subclass: return docVarListEntryType.subclass(*args_, **kwargs_) @@ -6457,10 +7349,12 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def get_term(self): return self.term def set_term(self, term): self.term = term + def export(self, outfile, level, namespace_='', name_='docVarListEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docVarListEntryType') + self.exportAttributes(outfile, level, namespace_, + name_='docVarListEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6468,25 +7362,31 @@ def export(self, outfile, level, namespace_='', name_='docVarListEntryType', nam outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docVarListEntryType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docVarListEntryType'): if self.term: self.term.export(outfile, level, namespace_, name_='term', ) + def hasContent_(self): if ( self.term is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docVarListEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): if self.term: showIndent(outfile, level) @@ -6494,17 +7394,20 @@ def exportLiteralChildren(self, outfile, level, name_): self.term.exportLiteral(outfile, level, name_='term') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'term': + nodeName_ == 'term': obj_ = docTitleType.factory() obj_.build(child_) self.set_term(obj_) @@ -6514,8 +7417,10 @@ def buildChildren(self, child_, nodeName_): class docVariableListType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if docVariableListType.subclass: return docVariableListType.subclass(*args_, **kwargs_) @@ -6524,10 +7429,12 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docVariableListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docVariableListType') + self.exportAttributes(outfile, level, namespace_, + name_='docVariableListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -6535,33 +7442,40 @@ def export(self, outfile, level, namespace_='', name_='docVariableListType', nam outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docVariableListType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docVariableListType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docVariableListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -6569,19 +7483,22 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docVariableListType class docRefTextType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid self.kindref = kindref @@ -6594,6 +7511,7 @@ def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedcl self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docRefTextType.subclass: return docRefTextType.subclass(*args_, **kwargs_) @@ -6608,40 +7526,49 @@ def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docRefTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docRefTextType') + self.exportAttributes(outfile, level, namespace_, + name_='docRefTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docRefTextType'): if self.refid is not None: - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.kindref is not None: outfile.write(' kindref=%s' % (quote_attrib(self.kindref), )) if self.external is not None: - outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) + outfile.write(' external=%s' % (self.format_string(quote_attrib( + self.external).encode(ExternalEncoding), input_name='external'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docRefTextType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docRefTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) @@ -6652,9 +7579,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -6662,6 +7591,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value @@ -6669,21 +7599,23 @@ def buildAttributes(self, attrs): self.kindref = attrs.get('kindref').value if attrs.get('external'): self.external = attrs.get('external').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docRefTextType class docTableType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, rows=None, cols=None, row=None, caption=None): self.rows = rows self.cols = cols @@ -6692,6 +7624,7 @@ def __init__(self, rows=None, cols=None, row=None, caption=None): else: self.row = row self.caption = caption + def factory(*args_, **kwargs_): if docTableType.subclass: return docTableType.subclass(*args_, **kwargs_) @@ -6708,6 +7641,7 @@ def get_rows(self): return self.rows def set_rows(self, rows): self.rows = rows def get_cols(self): return self.cols def set_cols(self, cols): self.cols = cols + def export(self, outfile, level, namespace_='', name_='docTableType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -6719,29 +7653,36 @@ def export(self, outfile, level, namespace_='', name_='docTableType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docTableType'): if self.rows is not None: - outfile.write(' rows="%s"' % self.format_integer(self.rows, input_name='rows')) + outfile.write(' rows="%s"' % self.format_integer( + self.rows, input_name='rows')) if self.cols is not None: - outfile.write(' cols="%s"' % self.format_integer(self.cols, input_name='cols')) + outfile.write(' cols="%s"' % self.format_integer( + self.cols, input_name='cols')) + def exportChildren(self, outfile, level, namespace_='', name_='docTableType'): for row_ in self.row: row_.export(outfile, level, namespace_, name_='row') if self.caption: self.caption.export(outfile, level, namespace_, name_='caption') + def hasContent_(self): if ( self.row is not None or self.caption is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docTableType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.rows is not None: showIndent(outfile, level) @@ -6749,6 +7690,7 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.cols is not None: showIndent(outfile, level) outfile.write('cols = %s,\n' % (self.cols,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('row=[\n') @@ -6768,12 +7710,14 @@ def exportLiteralChildren(self, outfile, level, name_): self.caption.exportLiteral(outfile, level, name_='caption') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('rows'): try: @@ -6785,14 +7729,15 @@ def buildAttributes(self, attrs): self.cols = int(attrs.get('cols').value) except ValueError as exp: raise ValueError('Bad integer attribute (cols): %s' % exp) + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'row': + nodeName_ == 'row': obj_ = docRowType.factory() obj_.build(child_) self.row.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'caption': + nodeName_ == 'caption': obj_ = docCaptionType.factory() obj_.build(child_) self.set_caption(obj_) @@ -6802,11 +7747,13 @@ def buildChildren(self, child_, nodeName_): class docRowType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, entry=None): if entry is None: self.entry = [] else: self.entry = entry + def factory(*args_, **kwargs_): if docRowType.subclass: return docRowType.subclass(*args_, **kwargs_) @@ -6817,6 +7764,7 @@ def get_entry(self): return self.entry def set_entry(self, entry): self.entry = entry def add_entry(self, value): self.entry.append(value) def insert_entry(self, index, value): self.entry[index] = value + def export(self, outfile, level, namespace_='', name_='docRowType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -6828,25 +7776,31 @@ def export(self, outfile, level, namespace_='', name_='docRowType', namespacedef outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docRowType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docRowType'): for entry_ in self.entry: entry_.export(outfile, level, namespace_, name_='entry') + def hasContent_(self): if ( self.entry is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docRowType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('entry=[\n') @@ -6860,17 +7814,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'entry': + nodeName_ == 'entry': obj_ = docEntryType.factory() obj_.build(child_) self.entry.append(obj_) @@ -6880,12 +7837,14 @@ def buildChildren(self, child_, nodeName_): class docEntryType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, thead=None, para=None): self.thead = thead if para is None: self.para = [] else: self.para = para + def factory(*args_, **kwargs_): if docEntryType.subclass: return docEntryType.subclass(*args_, **kwargs_) @@ -6898,6 +7857,7 @@ def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_thead(self): return self.thead def set_thead(self, thead): self.thead = thead + def export(self, outfile, level, namespace_='', name_='docEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -6909,28 +7869,34 @@ def export(self, outfile, level, namespace_='', name_='docEntryType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docEntryType'): if self.thead is not None: outfile.write(' thead=%s' % (quote_attrib(self.thead), )) + def exportChildren(self, outfile, level, namespace_='', name_='docEntryType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') + def hasContent_(self): if ( self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.thead is not None: showIndent(outfile, level) outfile.write('thead = "%s",\n' % (self.thead,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') @@ -6944,18 +7910,21 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('thead'): self.thead = attrs.get('thead').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) @@ -6965,6 +7934,7 @@ def buildChildren(self, child_, nodeName_): class docCaptionType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer @@ -6974,6 +7944,7 @@ def __init__(self, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docCaptionType.subclass: return docCaptionType.subclass(*args_, **kwargs_) @@ -6982,40 +7953,49 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docCaptionType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docCaptionType') + self.exportAttributes(outfile, level, namespace_, + name_='docCaptionType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docCaptionType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docCaptionType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docCaptionType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7023,23 +8003,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docCaptionType class docHeadingType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): self.level = level if mixedclass_ is None: @@ -7050,6 +8033,7 @@ def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docHeadingType.subclass: return docHeadingType.subclass(*args_, **kwargs_) @@ -7060,43 +8044,53 @@ def get_level(self): return self.level def set_level(self, level): self.level = level def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docHeadingType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docHeadingType') + self.exportAttributes(outfile, level, namespace_, + name_='docHeadingType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docHeadingType'): if self.level is not None: - outfile.write(' level="%s"' % self.format_integer(self.level, input_name='level')) + outfile.write(' level="%s"' % self.format_integer( + self.level, input_name='level')) + def exportChildren(self, outfile, level, namespace_='', name_='docHeadingType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docHeadingType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.level is not None: showIndent(outfile, level) outfile.write('level = %s,\n' % (self.level,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7104,27 +8098,30 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('level'): try: self.level = int(attrs.get('level').value) except ValueError as exp: raise ValueError('Bad integer attribute (level): %s' % exp) + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docHeadingType class docImageType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', mixedclass_=None, content_=None): self.width = width self.type_ = type_ @@ -7138,6 +8135,7 @@ def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docImageType.subclass: return docImageType.subclass(*args_, **kwargs_) @@ -7154,6 +8152,7 @@ def get_height(self): return self.height def set_height(self, height): self.height = height def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docImageType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -7161,35 +8160,43 @@ def export(self, outfile, level, namespace_='', name_='docImageType', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docImageType'): if self.width is not None: - outfile.write(' width=%s' % (self.format_string(quote_attrib(self.width).encode(ExternalEncoding), input_name='width'), )) + outfile.write(' width=%s' % (self.format_string(quote_attrib( + self.width).encode(ExternalEncoding), input_name='width'), )) if self.type_ is not None: outfile.write(' type=%s' % (quote_attrib(self.type_), )) if self.name is not None: - outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) + outfile.write(' name=%s' % (self.format_string(quote_attrib( + self.name).encode(ExternalEncoding), input_name='name'), )) if self.height is not None: - outfile.write(' height=%s' % (self.format_string(quote_attrib(self.height).encode(ExternalEncoding), input_name='height'), )) + outfile.write(' height=%s' % (self.format_string(quote_attrib( + self.height).encode(ExternalEncoding), input_name='height'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docImageType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docImageType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.width is not None: showIndent(outfile, level) @@ -7203,9 +8210,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.height is not None: showIndent(outfile, level) outfile.write('height = %s,\n' % (self.height,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7213,6 +8222,7 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('width'): self.width = attrs.get('width').value @@ -7222,21 +8232,23 @@ def buildAttributes(self, attrs): self.name = attrs.get('name').value if attrs.get('height'): self.height = attrs.get('height').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docImageType class docDotFileType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): self.name = name if mixedclass_ is None: @@ -7247,6 +8259,7 @@ def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docDotFileType.subclass: return docDotFileType.subclass(*args_, **kwargs_) @@ -7257,43 +8270,53 @@ def get_name(self): return self.name def set_name(self, name): self.name = name def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docDotFileType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docDotFileType') + self.exportAttributes(outfile, level, namespace_, + name_='docDotFileType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docDotFileType'): if self.name is not None: - outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) + outfile.write(' name=%s' % (self.format_string(quote_attrib( + self.name).encode(ExternalEncoding), input_name='name'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docDotFileType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docDotFileType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.name is not None: showIndent(outfile, level) outfile.write('name = %s,\n' % (self.name,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7301,24 +8324,27 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('name'): self.name = attrs.get('name').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docDotFileType class docTocItemType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: @@ -7329,6 +8355,7 @@ def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docTocItemType.subclass: return docTocItemType.subclass(*args_, **kwargs_) @@ -7339,43 +8366,53 @@ def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docTocItemType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docTocItemType') + self.exportAttributes(outfile, level, namespace_, + name_='docTocItemType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docTocItemType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docTocItemType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docTocItemType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -7383,29 +8420,33 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docTocItemType class docTocListType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, tocitem=None): if tocitem is None: self.tocitem = [] else: self.tocitem = tocitem + def factory(*args_, **kwargs_): if docTocListType.subclass: return docTocListType.subclass(*args_, **kwargs_) @@ -7416,10 +8457,12 @@ def get_tocitem(self): return self.tocitem def set_tocitem(self, tocitem): self.tocitem = tocitem def add_tocitem(self, value): self.tocitem.append(value) def insert_tocitem(self, index, value): self.tocitem[index] = value + def export(self, outfile, level, namespace_='', name_='docTocListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docTocListType') + self.exportAttributes(outfile, level, namespace_, + name_='docTocListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7427,25 +8470,31 @@ def export(self, outfile, level, namespace_='', name_='docTocListType', namespac outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docTocListType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docTocListType'): for tocitem_ in self.tocitem: tocitem_.export(outfile, level, namespace_, name_='tocitem') + def hasContent_(self): if ( self.tocitem is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docTocListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('tocitem=[\n') @@ -7459,17 +8508,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'tocitem': + nodeName_ == 'tocitem': obj_ = docTocItemType.factory() obj_.build(child_) self.tocitem.append(obj_) @@ -7479,12 +8531,14 @@ def buildChildren(self, child_, nodeName_): class docLanguageType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, langid=None, para=None): self.langid = langid if para is None: self.para = [] else: self.para = para + def factory(*args_, **kwargs_): if docLanguageType.subclass: return docLanguageType.subclass(*args_, **kwargs_) @@ -7497,10 +8551,12 @@ def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_langid(self): return self.langid def set_langid(self, langid): self.langid = langid + def export(self, outfile, level, namespace_='', name_='docLanguageType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docLanguageType') + self.exportAttributes(outfile, level, namespace_, + name_='docLanguageType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7508,28 +8564,35 @@ def export(self, outfile, level, namespace_='', name_='docLanguageType', namespa outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docLanguageType'): if self.langid is not None: - outfile.write(' langid=%s' % (self.format_string(quote_attrib(self.langid).encode(ExternalEncoding), input_name='langid'), )) + outfile.write(' langid=%s' % (self.format_string(quote_attrib( + self.langid).encode(ExternalEncoding), input_name='langid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docLanguageType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') + def hasContent_(self): if ( self.para is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docLanguageType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.langid is not None: showIndent(outfile, level) outfile.write('langid = %s,\n' % (self.langid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') @@ -7543,18 +8606,21 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('langid'): self.langid = attrs.get('langid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) @@ -7564,12 +8630,14 @@ def buildChildren(self, child_, nodeName_): class docParamListType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, parameteritem=None): self.kind = kind if parameteritem is None: self.parameteritem = [] else: self.parameteritem = parameteritem + def factory(*args_, **kwargs_): if docParamListType.subclass: return docParamListType.subclass(*args_, **kwargs_) @@ -7577,15 +8645,21 @@ def factory(*args_, **kwargs_): return docParamListType(*args_, **kwargs_) factory = staticmethod(factory) def get_parameteritem(self): return self.parameteritem - def set_parameteritem(self, parameteritem): self.parameteritem = parameteritem + def set_parameteritem( + self, parameteritem): self.parameteritem = parameteritem + def add_parameteritem(self, value): self.parameteritem.append(value) - def insert_parameteritem(self, index, value): self.parameteritem[index] = value + def insert_parameteritem( + self, index, value): self.parameteritem[index] = value + def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind + def export(self, outfile, level, namespace_='', name_='docParamListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docParamListType') + self.exportAttributes(outfile, level, namespace_, + name_='docParamListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7593,28 +8667,35 @@ def export(self, outfile, level, namespace_='', name_='docParamListType', namesp outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docParamListType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) + def exportChildren(self, outfile, level, namespace_='', name_='docParamListType'): for parameteritem_ in self.parameteritem: - parameteritem_.export(outfile, level, namespace_, name_='parameteritem') + parameteritem_.export( + outfile, level, namespace_, name_='parameteritem') + def hasContent_(self): if ( self.parameteritem is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParamListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parameteritem=[\n') @@ -7628,18 +8709,21 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'parameteritem': + nodeName_ == 'parameteritem': obj_ = docParamListItem.factory() obj_.build(child_) self.parameteritem.append(obj_) @@ -7649,12 +8733,14 @@ def buildChildren(self, child_, nodeName_): class docParamListItem(GeneratedsSuper): subclass = None superclass = None + def __init__(self, parameternamelist=None, parameterdescription=None): if parameternamelist is None: self.parameternamelist = [] else: self.parameternamelist = parameternamelist self.parameterdescription = parameterdescription + def factory(*args_, **kwargs_): if docParamListItem.subclass: return docParamListItem.subclass(*args_, **kwargs_) @@ -7662,15 +8748,25 @@ def factory(*args_, **kwargs_): return docParamListItem(*args_, **kwargs_) factory = staticmethod(factory) def get_parameternamelist(self): return self.parameternamelist - def set_parameternamelist(self, parameternamelist): self.parameternamelist = parameternamelist - def add_parameternamelist(self, value): self.parameternamelist.append(value) - def insert_parameternamelist(self, index, value): self.parameternamelist[index] = value + + def set_parameternamelist( + self, parameternamelist): self.parameternamelist = parameternamelist + + def add_parameternamelist( + self, value): self.parameternamelist.append(value) + def insert_parameternamelist( + self, index, value): self.parameternamelist[index] = value + def get_parameterdescription(self): return self.parameterdescription - def set_parameterdescription(self, parameterdescription): self.parameterdescription = parameterdescription + + def set_parameterdescription( + self, parameterdescription): self.parameterdescription = parameterdescription + def export(self, outfile, level, namespace_='', name_='docParamListItem', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docParamListItem') + self.exportAttributes(outfile, level, namespace_, + name_='docParamListItem') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7678,28 +8774,36 @@ def export(self, outfile, level, namespace_='', name_='docParamListItem', namesp outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docParamListItem'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docParamListItem'): for parameternamelist_ in self.parameternamelist: - parameternamelist_.export(outfile, level, namespace_, name_='parameternamelist') + parameternamelist_.export( + outfile, level, namespace_, name_='parameternamelist') if self.parameterdescription: - self.parameterdescription.export(outfile, level, namespace_, name_='parameterdescription', ) + self.parameterdescription.export( + outfile, level, namespace_, name_='parameterdescription', ) + def hasContent_(self): if ( self.parameternamelist is not None or self.parameterdescription is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParamListItem'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parameternamelist=[\n') @@ -7707,7 +8811,8 @@ def exportLiteralChildren(self, outfile, level, name_): for parameternamelist in self.parameternamelist: showIndent(outfile, level) outfile.write('model_.parameternamelist(\n') - parameternamelist.exportLiteral(outfile, level, name_='parameternamelist') + parameternamelist.exportLiteral( + outfile, level, name_='parameternamelist') showIndent(outfile, level) outfile.write('),\n') level -= 1 @@ -7716,25 +8821,29 @@ def exportLiteralChildren(self, outfile, level, name_): if self.parameterdescription: showIndent(outfile, level) outfile.write('parameterdescription=model_.descriptionType(\n') - self.parameterdescription.exportLiteral(outfile, level, name_='parameterdescription') + self.parameterdescription.exportLiteral( + outfile, level, name_='parameterdescription') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'parameternamelist': + nodeName_ == 'parameternamelist': obj_ = docParamNameList.factory() obj_.build(child_) self.parameternamelist.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'parameterdescription': + nodeName_ == 'parameterdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_parameterdescription(obj_) @@ -7744,11 +8853,13 @@ def buildChildren(self, child_, nodeName_): class docParamNameList(GeneratedsSuper): subclass = None superclass = None + def __init__(self, parametername=None): if parametername is None: self.parametername = [] else: self.parametername = parametername + def factory(*args_, **kwargs_): if docParamNameList.subclass: return docParamNameList.subclass(*args_, **kwargs_) @@ -7756,13 +8867,19 @@ def factory(*args_, **kwargs_): return docParamNameList(*args_, **kwargs_) factory = staticmethod(factory) def get_parametername(self): return self.parametername - def set_parametername(self, parametername): self.parametername = parametername + def set_parametername( + self, parametername): self.parametername = parametername + def add_parametername(self, value): self.parametername.append(value) - def insert_parametername(self, index, value): self.parametername[index] = value + + def insert_parametername( + self, index, value): self.parametername[index] = value + def export(self, outfile, level, namespace_='', name_='docParamNameList', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docParamNameList') + self.exportAttributes(outfile, level, namespace_, + name_='docParamNameList') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7770,25 +8887,32 @@ def export(self, outfile, level, namespace_='', name_='docParamNameList', namesp outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docParamNameList'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docParamNameList'): for parametername_ in self.parametername: - parametername_.export(outfile, level, namespace_, name_='parametername') + parametername_.export( + outfile, level, namespace_, name_='parametername') + def hasContent_(self): if ( self.parametername is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParamNameList'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parametername=[\n') @@ -7802,17 +8926,20 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'parametername': + nodeName_ == 'parametername': obj_ = docParamName.factory() obj_.build(child_) self.parametername.append(obj_) @@ -7822,6 +8949,7 @@ def buildChildren(self, child_, nodeName_): class docParamName(GeneratedsSuper): subclass = None superclass = None + def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): self.direction = direction if mixedclass_ is None: @@ -7832,6 +8960,7 @@ def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): self.content_ = [] else: self.content_ = content_ + def factory(*args_, **kwargs_): if docParamName.subclass: return docParamName.subclass(*args_, **kwargs_) @@ -7842,6 +8971,7 @@ def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def get_direction(self): return self.direction def set_direction(self, direction): self.direction = direction + def export(self, outfile, level, namespace_='', name_='docParamName', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -7849,28 +8979,34 @@ def export(self, outfile, level, namespace_='', name_='docParamName', namespaced outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('\n' % (namespace_, name_)) + def exportAttributes(self, outfile, level, namespace_='', name_='docParamName'): if self.direction is not None: outfile.write(' direction=%s' % (quote_attrib(self.direction), )) + def exportChildren(self, outfile, level, namespace_='', name_='docParamName'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) + def hasContent_(self): if ( self.ref is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docParamName'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.direction is not None: showIndent(outfile, level) outfile.write('direction = "%s",\n' % (self.direction,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') @@ -7878,26 +9014,29 @@ def exportLiteralChildren(self, outfile, level, name_): item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('direction'): self.direction = attrs.get('direction').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'ref': + nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'ref', childobj_) + MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.nodeValue) + MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docParamName @@ -7905,6 +9044,7 @@ def buildChildren(self, child_, nodeName_): class docXRefSectType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, id=None, xreftitle=None, xrefdescription=None): self.id = id if xreftitle is None: @@ -7912,6 +9052,7 @@ def __init__(self, id=None, xreftitle=None, xrefdescription=None): else: self.xreftitle = xreftitle self.xrefdescription = xrefdescription + def factory(*args_, **kwargs_): if docXRefSectType.subclass: return docXRefSectType.subclass(*args_, **kwargs_) @@ -7923,13 +9064,17 @@ def set_xreftitle(self, xreftitle): self.xreftitle = xreftitle def add_xreftitle(self, value): self.xreftitle.append(value) def insert_xreftitle(self, index, value): self.xreftitle[index] = value def get_xrefdescription(self): return self.xrefdescription - def set_xrefdescription(self, xrefdescription): self.xrefdescription = xrefdescription + def set_xrefdescription( + self, xrefdescription): self.xrefdescription = xrefdescription + def get_id(self): return self.id def set_id(self, id): self.id = id + def export(self, outfile, level, namespace_='', name_='docXRefSectType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) - self.exportAttributes(outfile, level, namespace_, name_='docXRefSectType') + self.exportAttributes(outfile, level, namespace_, + name_='docXRefSectType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) @@ -7937,66 +9082,80 @@ def export(self, outfile, level, namespace_='', name_='docXRefSectType', namespa outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docXRefSectType'): if self.id is not None: - outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) + outfile.write(' id=%s' % (self.format_string(quote_attrib( + self.id).encode(ExternalEncoding), input_name='id'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docXRefSectType'): for xreftitle_ in self.xreftitle: showIndent(outfile, level) - outfile.write('<%sxreftitle>%s\n' % (namespace_, self.format_string(quote_xml(xreftitle_).encode(ExternalEncoding), input_name='xreftitle'), namespace_)) + outfile.write('<%sxreftitle>%s\n' % (namespace_, self.format_string( + quote_xml(xreftitle_).encode(ExternalEncoding), input_name='xreftitle'), namespace_)) if self.xrefdescription: - self.xrefdescription.export(outfile, level, namespace_, name_='xrefdescription', ) + self.xrefdescription.export( + outfile, level, namespace_, name_='xrefdescription', ) + def hasContent_(self): if ( self.xreftitle is not None or self.xrefdescription is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docXRefSectType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('xreftitle=[\n') level += 1 for xreftitle in self.xreftitle: showIndent(outfile, level) - outfile.write('%s,\n' % quote_python(xreftitle).encode(ExternalEncoding)) + outfile.write('%s,\n' % quote_python( + xreftitle).encode(ExternalEncoding)) level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.xrefdescription: showIndent(outfile, level) outfile.write('xrefdescription=model_.descriptionType(\n') - self.xrefdescription.exportLiteral(outfile, level, name_='xrefdescription') + self.xrefdescription.exportLiteral( + outfile, level, name_='xrefdescription') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'xreftitle': + nodeName_ == 'xreftitle': xreftitle_ = '' for text__content_ in child_.childNodes: xreftitle_ += text__content_.nodeValue self.xreftitle.append(xreftitle_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'xrefdescription': + nodeName_ == 'xrefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_xrefdescription(obj_) @@ -8006,6 +9165,7 @@ def buildChildren(self, child_, nodeName_): class docCopyType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, link=None, para=None, sect1=None, internal=None): self.link = link if para is None: @@ -8017,6 +9177,7 @@ def __init__(self, link=None, para=None, sect1=None, internal=None): else: self.sect1 = sect1 self.internal = internal + def factory(*args_, **kwargs_): if docCopyType.subclass: return docCopyType.subclass(*args_, **kwargs_) @@ -8035,6 +9196,7 @@ def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_link(self): return self.link def set_link(self, link): self.link = link + def export(self, outfile, level, namespace_='', name_='docCopyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -8046,9 +9208,12 @@ def export(self, outfile, level, namespace_='', name_='docCopyType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docCopyType'): if self.link is not None: - outfile.write(' link=%s' % (self.format_string(quote_attrib(self.link).encode(ExternalEncoding), input_name='link'), )) + outfile.write(' link=%s' % (self.format_string(quote_attrib( + self.link).encode(ExternalEncoding), input_name='link'), )) + def exportChildren(self, outfile, level, namespace_='', name_='docCopyType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') @@ -8056,24 +9221,28 @@ def exportChildren(self, outfile, level, namespace_='', name_='docCopyType'): sect1_.export(outfile, level, namespace_, name_='sect1') if self.internal: self.internal.export(outfile, level, namespace_, name_='internal') + def hasContent_(self): if ( self.para is not None or self.sect1 is not None or self.internal is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docCopyType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.link is not None: showIndent(outfile, level) outfile.write('link = %s,\n' % (self.link,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') @@ -8105,28 +9274,31 @@ def exportLiteralChildren(self, outfile, level, name_): self.internal.exportLiteral(outfile, level, name_='internal') showIndent(outfile, level) outfile.write('),\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('link'): self.link = attrs.get('link').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'para': + nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'sect1': + nodeName_ == 'sect1': obj_ = docSect1Type.factory() obj_.build(child_) self.sect1.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'internal': + nodeName_ == 'internal': obj_ = docInternalType.factory() obj_.build(child_) self.set_internal(obj_) @@ -8136,9 +9308,11 @@ def buildChildren(self, child_, nodeName_): class docCharType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, char=None, valueOf_=''): self.char = char self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if docCharType.subclass: return docCharType.subclass(*args_, **kwargs_) @@ -8149,6 +9323,7 @@ def get_char(self): return self.char def set_char(self, char): self.char = char def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docCharType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -8160,36 +9335,43 @@ def export(self, outfile, level, namespace_='', name_='docCharType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docCharType'): if self.char is not None: outfile.write(' char=%s' % (quote_attrib(self.char), )) + def exportChildren(self, outfile, level, namespace_='', name_='docCharType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docCharType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.char is not None: showIndent(outfile, level) outfile.write('char = "%s",\n' % (self.char,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -8197,22 +9379,26 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('char'): self.char = attrs.get('char').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docCharType class docEmptyType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if docEmptyType.subclass: return docEmptyType.subclass(*args_, **kwargs_) @@ -8221,6 +9407,7 @@ def factory(*args_, **kwargs_): factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ + def export(self, outfile, level, namespace_='', name_='docEmptyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -8232,33 +9419,40 @@ def export(self, outfile, level, namespace_='', name_='docEmptyType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='docEmptyType'): pass + def exportChildren(self, outfile, level, namespace_='', name_='docEmptyType'): - if self.valueOf_.find('![CDATA')>-1: - value=quote_xml('%s' % self.valueOf_) - value=value.replace('![CDATA','') + if self.valueOf_.find('![CDATA') > -1: + value = quote_xml('%s' % self.valueOf_) + value = value.replace('![CDATA', '') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) + def hasContent_(self): if ( self.valueOf_ is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='docEmptyType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) @@ -8266,13 +9460,15 @@ def build(self, node_): for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: - self.valueOf_ += '![CDATA['+child_.nodeValue+']]' + self.valueOf_ += '![CDATA[' + child_.nodeValue + ']]' # end class docEmptyType @@ -8282,6 +9478,7 @@ def buildChildren(self, child_, nodeName_): -s Use the SAX parser, not the minidom parser. """ + def usage(): print(USAGE_TEXT) sys.exit(1) @@ -8296,7 +9493,7 @@ def parse(inFileName): doc = None sys.stdout.write('\n') rootObj.export(sys.stdout, 0, name_="doxygen", - namespacedef_='') + namespacedef_='') return rootObj @@ -8309,7 +9506,7 @@ def parseString(inString): doc = None sys.stdout.write('\n') rootObj.export(sys.stdout, 0, name_="doxygen", - namespacedef_='') + namespacedef_='') return rootObj @@ -8338,4 +9535,4 @@ def main(): if __name__ == '__main__': main() #import pdb - #pdb.run('main()') + # pdb.run('main()') diff --git a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/index.py b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/index.py index 8a817e15f13..7ffbdf191ac 100644 --- a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/index.py +++ b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/index.py @@ -12,6 +12,7 @@ from . import indexsuper as supermod + class DoxygenTypeSub(supermod.DoxygenType): def __init__(self, version=None, compound=None): supermod.DoxygenType.__init__(self, version, compound) @@ -32,6 +33,7 @@ def find_compounds_and_members(self, details): return results + supermod.DoxygenType.subclass = DoxygenTypeSub # end class DoxygenTypeSub @@ -53,6 +55,7 @@ def find_members(self, details): return results + supermod.CompoundType.subclass = CompoundTypeSub # end class CompoundTypeSub @@ -62,6 +65,7 @@ class MemberTypeSub(supermod.MemberType): def __init__(self, kind=None, refid=None, name=''): supermod.MemberType.__init__(self, kind, refid, name) + supermod.MemberType.subclass = MemberTypeSub # end class MemberTypeSub diff --git a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/indexsuper.py b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/indexsuper.py index cc2c1124182..b30e062ae7d 100644 --- a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/indexsuper.py +++ b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/generated/indexsuper.py @@ -24,12 +24,16 @@ class GeneratedsSuper(object): def format_string(self, input_data, input_name=''): return input_data + def format_integer(self, input_data, input_name=''): return '%d' % input_data + def format_float(self, input_data, input_name=''): return '%f' % input_data + def format_double(self, input_data, input_name=''): return '%e' % input_data + def format_boolean(self, input_data, input_name=''): return '%s' % input_data @@ -41,9 +45,9 @@ def format_boolean(self, input_data, input_name=''): ## from IPython.Shell import IPShellEmbed ## args = '' -## ipshell = IPShellEmbed(args, +# ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') +# exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: @@ -59,10 +63,12 @@ def format_boolean(self, input_data, input_name=''): # Support/utility functions. # + def showIndent(outfile, level): for idx in range(level): outfile.write(' ') + def quote_xml(inStr): s1 = (isinstance(inStr, str) and inStr or '%s' % inStr) @@ -71,6 +77,7 @@ def quote_xml(inStr): s1 = s1.replace('>', '>') return s1 + def quote_attrib(inStr): s1 = (isinstance(inStr, str) and inStr or '%s' % inStr) @@ -86,6 +93,7 @@ def quote_attrib(inStr): s1 = '"%s"' % s1 return s1 + def quote_python(inStr): s1 = inStr if s1.find("'") == -1: @@ -117,26 +125,33 @@ class MixedContainer(object): TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 + def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value + def getCategory(self): return self.category + def getContenttype(self, content_type): return self.content_type + def getValue(self): return self.value + def getName(self): return self.name + def export(self, outfile, level, name, namespace): if self.category == MixedContainer.CategoryText: outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex - self.value.export(outfile, level, namespace,name) + self.value.export(outfile, level, namespace, name) + def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: outfile.write('<%s>%s' % (self.name, self.value, self.name)) @@ -148,19 +163,20 @@ def exportSimple(self, outfile, level, name): outfile.write('<%s>%f' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: outfile.write('<%s>%g' % (self.name, self.value, self.name)) + def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) + outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % + (self.category, self.content_type, self.name, self.value)) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) + outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % + (self.category, self.content_type, self.name, self.value)) else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s",\n' % \ - (self.category, self.content_type, self.name,)) + outfile.write('MixedContainer(%d, %d, "%s",\n' % + (self.category, self.content_type, self.name,)) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) outfile.write(')\n') @@ -171,6 +187,7 @@ def __init__(self, name='', data_type='', container=0): self.name = name self.data_type = data_type self.container = container + def set_name(self, name): self.name = name def get_name(self): return self.name def set_data_type(self, data_type): self.data_type = data_type @@ -186,12 +203,14 @@ def get_container(self): return self.container class DoxygenType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, version=None, compound=None): self.version = version if compound is None: self.compound = [] else: self.compound = compound + def factory(*args_, **kwargs_): if DoxygenType.subclass: return DoxygenType.subclass(*args_, **kwargs_) @@ -204,6 +223,7 @@ def add_compound(self, value): self.compound.append(value) def insert_compound(self, index, value): self.compound[index] = value def get_version(self): return self.version def set_version(self, version): self.version = version + def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -215,27 +235,34 @@ def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacede outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='DoxygenType'): - outfile.write(' version=%s' % (self.format_string(quote_attrib(self.version).encode(ExternalEncoding), input_name='version'), )) + outfile.write(' version=%s' % (self.format_string(quote_attrib( + self.version).encode(ExternalEncoding), input_name='version'), )) + def exportChildren(self, outfile, level, namespace_='', name_='DoxygenType'): for compound_ in self.compound: compound_.export(outfile, level, namespace_, name_='compound') + def hasContent_(self): if ( self.compound is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='DoxygenType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.version is not None: showIndent(outfile, level) outfile.write('version = %s,\n' % (self.version,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('compound=[\n') @@ -249,18 +276,21 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('version'): self.version = attrs.get('version').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'compound': + nodeName_ == 'compound': obj_ = CompoundType.factory() obj_.build(child_) self.compound.append(obj_) @@ -270,6 +300,7 @@ def buildChildren(self, child_, nodeName_): class CompoundType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, refid=None, name=None, member=None): self.kind = kind self.refid = refid @@ -278,6 +309,7 @@ def __init__(self, kind=None, refid=None, name=None, member=None): self.member = [] else: self.member = member + def factory(*args_, **kwargs_): if CompoundType.subclass: return CompoundType.subclass(*args_, **kwargs_) @@ -294,6 +326,7 @@ def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid + def export(self, outfile, level, namespace_='', name_='CompoundType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -305,28 +338,35 @@ def export(self, outfile, level, namespace_='', name_='CompoundType', namespaced outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='CompoundType'): outfile.write(' kind=%s' % (quote_attrib(self.kind), )) - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='CompoundType'): if self.name is not None: showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + outfile.write('<%sname>%s\n' % (namespace_, self.format_string( + quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) for member_ in self.member: member_.export(outfile, level, namespace_, name_='member') + def hasContent_(self): if ( self.name is not None or self.member is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='CompoundType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) @@ -334,9 +374,11 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) + outfile.write('name=%s,\n' % quote_python( + self.name).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('member=[\n') level += 1 @@ -349,26 +391,29 @@ def exportLiteralChildren(self, outfile, level, name_): level -= 1 showIndent(outfile, level) outfile.write('],\n') + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue self.name = name_ elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'member': + nodeName_ == 'member': obj_ = MemberType.factory() obj_.build(child_) self.member.append(obj_) @@ -378,10 +423,12 @@ def buildChildren(self, child_, nodeName_): class MemberType(GeneratedsSuper): subclass = None superclass = None + def __init__(self, kind=None, refid=None, name=None): self.kind = kind self.refid = refid self.name = name + def factory(*args_, **kwargs_): if MemberType.subclass: return MemberType.subclass(*args_, **kwargs_) @@ -394,6 +441,7 @@ def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid + def export(self, outfile, level, namespace_='', name_='MemberType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) @@ -405,25 +453,32 @@ def export(self, outfile, level, namespace_='', name_='MemberType', namespacedef outfile.write('\n' % (namespace_, name_)) else: outfile.write(' />\n') + def exportAttributes(self, outfile, level, namespace_='', name_='MemberType'): outfile.write(' kind=%s' % (quote_attrib(self.kind), )) - outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) + outfile.write(' refid=%s' % (self.format_string(quote_attrib( + self.refid).encode(ExternalEncoding), input_name='refid'), )) + def exportChildren(self, outfile, level, namespace_='', name_='MemberType'): if self.name is not None: showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + outfile.write('<%sname>%s\n' % (namespace_, self.format_string( + quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) + def hasContent_(self): if ( self.name is not None - ): + ): return True else: return False + def exportLiteral(self, outfile, level, name_='MemberType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) @@ -431,23 +486,28 @@ def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) + outfile.write('name=%s,\n' % quote_python( + self.name).encode(ExternalEncoding)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value if attrs.get('refid'): self.refid = attrs.get('refid').value + def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'name': + nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue @@ -461,6 +521,7 @@ def buildChildren(self, child_, nodeName_): -s Use the SAX parser, not the minidom parser. """ + def usage(): print(USAGE_TEXT) sys.exit(1) @@ -475,7 +536,7 @@ def parse(inFileName): doc = None sys.stdout.write('\n') rootObj.export(sys.stdout, 0, name_="doxygenindex", - namespacedef_='') + namespacedef_='') return rootObj @@ -488,7 +549,7 @@ def parseString(inString): doc = None sys.stdout.write('\n') rootObj.export(sys.stdout, 0, name_="doxygenindex", - namespacedef_='') + namespacedef_='') return rootObj @@ -514,9 +575,7 @@ def main(): usage() - - if __name__ == '__main__': main() #import pdb - #pdb.run('main()') + # pdb.run('main()') diff --git a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/text.py b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/text.py index 8d8c7b43016..dbc7170ab2c 100644 --- a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/text.py +++ b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/text.py @@ -11,6 +11,7 @@ Utilities for extracting text from generated classes. """ + def is_string(txt): if isinstance(txt, str): return True @@ -21,11 +22,13 @@ def is_string(txt): pass return False + def description(obj): if obj is None: return None return description_bit(obj).strip() + def description_bit(obj): if hasattr(obj, 'content'): contents = [description_bit(item) for item in obj.content] @@ -38,7 +41,8 @@ def description_bit(obj): elif is_string(obj): return obj else: - raise Exception('Expecting a string or something with content, content_ or value attribute') + raise Exception( + 'Expecting a string or something with content, content_ or value attribute') # If this bit is a paragraph then add one some line breaks. if hasattr(obj, 'name') and obj.name == 'para': result += "\n\n" diff --git a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/update_pydoc.py b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/update_pydoc.py index dd2fba79f28..b65e168ae53 100644 --- a/gr-utils/modtool/templates/gr-newmod/docs/doxygen/update_pydoc.py +++ b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/update_pydoc.py @@ -16,16 +16,23 @@ """ -import os, sys, time, glob, re, json +import os +import sys +import time +import glob +import re +import json from argparse import ArgumentParser from doxyxml import DoxyIndex, DoxyClass, DoxyFriend, DoxyFunction, DoxyFile from doxyxml import DoxyOther, base + def py_name(name): bits = name.split('_') return '_'.join(bits[1:]) + def make_name(name): bits = name.split('_') return bits[0] + '_make_' + '_'.join(bits[1:]) @@ -50,6 +57,7 @@ def includes(cls, item): is_a_block = di.has_member(friendname, DoxyFunction) return is_a_block + class Block2(object): """ Checks if doxyxml produced objects correspond to a new style @@ -63,7 +71,8 @@ def includes(cls, item): # Check for a parsing error. if item.error(): return False - is_a_block2 = item.has_member('make', DoxyFunction) and item.has_member('sptr', DoxyOther) + is_a_block2 = item.has_member( + 'make', DoxyFunction) and item.has_member('sptr', DoxyOther) return is_a_block2 @@ -94,6 +103,7 @@ def combine_descriptions(obj): description.append(dd) return utoascii('\n\n'.join(description)).strip() + def format_params(parameteritems): output = ['Args:'] template = ' {0} : {1}' @@ -101,7 +111,10 @@ def format_params(parameteritems): output.append(template.format(pi.name, pi.description)) return '\n'.join(output) + entry_templ = '%feature("docstring") {name} "{docstring}"' + + def make_entry(obj, name=None, templ="{description}", description=None, params=[]): """ Create a docstring key/value pair, where the key is the object name. @@ -114,9 +127,9 @@ def make_entry(obj, name=None, templ="{description}", description=None, params=[ used as the description instead of extracting it from obj. """ if name is None: - name=obj.name() - if hasattr(obj,'_parse_data') and hasattr(obj._parse_data,'definition'): - name=obj._parse_data.definition.split(' ')[-1] + name = obj.name() + if hasattr(obj, '_parse_data') and hasattr(obj._parse_data, 'definition'): + name = obj._parse_data.definition.split(' ')[-1] if "operator " in name: return '' if description is None: @@ -174,9 +187,10 @@ def make_block_entry(di, block): output = {} output.update(make_class_entry(block, description=super_description)) output.update(make_entry(make_func, description=super_description, - params=block.params)) + params=block.params)) return output + def make_block2_entry(di, block): """ Create class and function docstrings of a new style gnuradio block @@ -186,19 +200,21 @@ def make_block2_entry(di, block): class_description = combine_descriptions(block) make_func = block.get_member('make', DoxyFunction) make_description = combine_descriptions(make_func) - description = class_description + "\n\nConstructor Specific Documentation:\n\n" + make_description + description = class_description + \ + "\n\nConstructor Specific Documentation:\n\n" + make_description # Associate the combined description with the class and # the make function. output = {} output.update(make_class_entry( - block, description=description, - ignored_methods=['make'], params=make_func.params)) + block, description=description, + ignored_methods=['make'], params=make_func.params)) makename = block.name() + '::make' output.update(make_entry( - make_func, name=makename, description=description, - params=make_func.params)) + make_func, name=makename, description=description, + params=make_func.params)) return output + def get_docstrings_dict(di, custom_output=None): output = {} @@ -218,19 +234,21 @@ def get_docstrings_dict(di, custom_output=None): make_funcs.add(make_func.name()) output.update(make_block_entry(di, block)) except block.ParsingError: - sys.stderr.write('Parsing error for block {0}\n'.format(block.name())) + sys.stderr.write( + 'Parsing error for block {0}\n'.format(block.name())) raise for block in blocks2: try: make_func = block.get_member('make', DoxyFunction) - make_func_name = block.name() +'::make' + make_func_name = block.name() + '::make' # Don't want to risk writing to output twice. if make_func_name not in make_funcs: make_funcs.add(make_func_name) output.update(make_block2_entry(di, block)) except block.ParsingError: - sys.stderr.write('Parsing error for block {0}\n'.format(block.name())) + sys.stderr.write( + 'Parsing error for block {0}\n'.format(block.name())) raise # Create docstrings for functions @@ -241,7 +259,8 @@ def get_docstrings_dict(di, custom_output=None): try: output.update(make_entry(f)) except f.ParsingError: - sys.stderr.write('Parsing error for function {0}\n'.format(f.name())) + sys.stderr.write( + 'Parsing error for function {0}\n'.format(f.name())) # Create docstrings for classes block_names = [block.name() for block in blocks] @@ -259,22 +278,24 @@ def get_docstrings_dict(di, custom_output=None): return output + def sub_docstring_in_pydoc_h(pydoc_files, docstrings_dict, output_dir, filter_str=None): if filter_str: - docstrings_dict = {k: v for k, v in docstrings_dict.items() if k.startswith(filter_str)} + docstrings_dict = { + k: v for k, v in docstrings_dict.items() if k.startswith(filter_str)} - with open(os.path.join(output_dir,'docstring_status'),'w') as status_file: + with open(os.path.join(output_dir, 'docstring_status'), 'w') as status_file: for pydoc_file in pydoc_files: if filter_str: - filter_str2 = "::".join((filter_str,os.path.split(pydoc_file)[-1].split('_pydoc_template.h')[0])) - docstrings_dict2 = {k: v for k, v in docstrings_dict.items() if k.startswith(filter_str2)} + filter_str2 = "::".join((filter_str, os.path.split( + pydoc_file)[-1].split('_pydoc_template.h')[0])) + docstrings_dict2 = { + k: v for k, v in docstrings_dict.items() if k.startswith(filter_str2)} else: docstrings_dict2 = docstrings_dict - - - file_in = open(pydoc_file,'r').read() + file_in = open(pydoc_file, 'r').read() for key, value in docstrings_dict2.items(): file_in_tmp = file_in try: @@ -282,37 +303,44 @@ def sub_docstring_in_pydoc_h(pydoc_files, docstrings_dict, output_dir, filter_st # if 'gr' in doc_key: # doc_key.remove('gr') doc_key = '_'.join(doc_key) - regexp = r'(__doc_{} =\sR\"doc\()[^)]*(\)doc\")'.format(doc_key) + regexp = r'(__doc_{} =\sR\"doc\()[^)]*(\)doc\")'.format( + doc_key) regexp = re.compile(regexp, re.MULTILINE) - (file_in, nsubs) = regexp.subn(r'\1'+value+r'\2', file_in, count=1) + (file_in, nsubs) = regexp.subn( + r'\1' + value + r'\2', file_in, count=1) if nsubs == 1: status_file.write("PASS: " + pydoc_file + "\n") except KeyboardInterrupt: raise KeyboardInterrupt - except: # be permissive, TODO log, but just leave the docstring blank + except: # be permissive, TODO log, but just leave the docstring blank status_file.write("FAIL: " + pydoc_file + "\n") file_in = file_in_tmp - output_pathname = os.path.join(output_dir, os.path.basename(pydoc_file).replace('_template.h','.h')) - with open(output_pathname,'w') as file_out: + output_pathname = os.path.join(output_dir, os.path.basename( + pydoc_file).replace('_template.h', '.h')) + with open(output_pathname, 'w') as file_out: file_out.write(file_in) + def copy_docstring_templates(pydoc_files, output_dir): - with open(os.path.join(output_dir,'docstring_status'),'w') as status_file: + with open(os.path.join(output_dir, 'docstring_status'), 'w') as status_file: for pydoc_file in pydoc_files: - file_in = open(pydoc_file,'r').read() - output_pathname = os.path.join(output_dir, os.path.basename(pydoc_file).replace('_template.h','.h')) - with open(output_pathname,'w') as file_out: + file_in = open(pydoc_file, 'r').read() + output_pathname = os.path.join(output_dir, os.path.basename( + pydoc_file).replace('_template.h', '.h')) + with open(output_pathname, 'w') as file_out: file_out.write(file_in) status_file.write("DONE") + def argParse(): """Parses commandline args.""" - desc='Scrape the doxygen generated xml for docstrings to insert into python bindings' + desc = 'Scrape the doxygen generated xml for docstrings to insert into python bindings' parser = ArgumentParser(description=desc) - parser.add_argument("function", help="Operation to perform on docstrings", choices=["scrape","sub","copy"]) + parser.add_argument("function", help="Operation to perform on docstrings", choices=[ + "scrape", "sub", "copy"]) parser.add_argument("--xml_path") parser.add_argument("--bindings_dir") @@ -322,6 +350,7 @@ def argParse(): return parser.parse_args() + if __name__ == "__main__": # Parse command line options and set up doxyxml. args = argParse() @@ -333,8 +362,11 @@ def argParse(): elif args.function.lower() == 'sub': with open(args.json_path, 'r') as fp: docstrings_dict = json.load(fp) - pydoc_files = glob.glob(os.path.join(args.bindings_dir,'*_pydoc_template.h')) - sub_docstring_in_pydoc_h(pydoc_files, docstrings_dict, args.output_dir, args.filter) + pydoc_files = glob.glob(os.path.join( + args.bindings_dir, '*_pydoc_template.h')) + sub_docstring_in_pydoc_h( + pydoc_files, docstrings_dict, args.output_dir, args.filter) elif args.function.lower() == 'copy': - pydoc_files = glob.glob(os.path.join(args.bindings_dir,'*_pydoc_template.h')) + pydoc_files = glob.glob(os.path.join( + args.bindings_dir, '*_pydoc_template.h')) copy_docstring_templates(pydoc_files, args.output_dir) diff --git a/gr-utils/modtool/templates/gr-newmod/python/CMakeLists.txt b/gr-utils/modtool/templates/gr-newmod/python/CMakeLists.txt index 69214defdd4..72f5726b810 100644 --- a/gr-utils/modtool/templates/gr-newmod/python/CMakeLists.txt +++ b/gr-utils/modtool/templates/gr-newmod/python/CMakeLists.txt @@ -31,3 +31,11 @@ GR_PYTHON_INSTALL( include(GrTest) set(GR_TEST_TARGET_DEPS gnuradio-howto) + +# Create a package directory that tests can import. It includes everything +# from `python/`. +add_custom_target( + copy_module_for_tests ALL + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_BINARY_DIR}/test_modules/howto/ +) diff --git a/gr-utils/modtool/templates/gr-newmod/python/bindings/CMakeLists.txt b/gr-utils/modtool/templates/gr-newmod/python/bindings/CMakeLists.txt index 94e5b555348..2e7ec4df147 100644 --- a/gr-utils/modtool/templates/gr-newmod/python/bindings/CMakeLists.txt +++ b/gr-utils/modtool/templates/gr-newmod/python/bindings/CMakeLists.txt @@ -36,4 +36,12 @@ GR_PYBIND_MAKE_OOT(howto gr::howto "${howto_python_files}") +# copy in bindings .so file for use in QA test module +add_custom_target( + copy_bindings_for_tests ALL + COMMAND + ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_BINARY_DIR}/*.so" + ${CMAKE_BINARY_DIR}/test_modules/howto/ + DEPENDS howto_python) + install(TARGETS howto_python DESTINATION ${GR_PYTHON_DIR}/howto COMPONENT pythonapi) diff --git a/gr-utils/modtool/templates/gr-newmod/python/bindings/bind_oot_file.py b/gr-utils/modtool/templates/gr-newmod/python/bindings/bind_oot_file.py index 9673ceb68d5..5bc3ff63e24 100644 --- a/gr-utils/modtool/templates/gr-newmod/python/bindings/bind_oot_file.py +++ b/gr-utils/modtool/templates/gr-newmod/python/bindings/bind_oot_file.py @@ -14,13 +14,13 @@ help='Output directory of generated bindings') parser.add_argument('--prefix', help='Prefix of Installed GNU Radio') parser.add_argument('--src', help='Directory of gnuradio source tree', - default=os.path.dirname(os.path.abspath(__file__))+'/../../..') + default=os.path.dirname(os.path.abspath(__file__)) + '/../../..') parser.add_argument( '--filename', help="File to be parsed") parser.add_argument( - '--defines', help='Set additional defines for precompiler',default=(), nargs='*') + '--defines', help='Set additional defines for precompiler', default=(), nargs='*') parser.add_argument( '--include', help='Additional Include Dirs, separated', default=(), nargs='*') diff --git a/gr-utils/modtool/templates/gr-newmod/python/bindings/header_utils.py b/gr-utils/modtool/templates/gr-newmod/python/bindings/header_utils.py index 2150a76a25a..7c26fe022b3 100644 --- a/gr-utils/modtool/templates/gr-newmod/python/bindings/header_utils.py +++ b/gr-utils/modtool/templates/gr-newmod/python/bindings/header_utils.py @@ -6,7 +6,7 @@ class PybindHeaderParser: def __init__(self, pathname): - with open(pathname,'r') as f: + with open(pathname, 'r') as f: self.file_txt = f.read() def get_flag_automatic(self): @@ -49,17 +49,19 @@ def get_flags(self): return f'{self.get_flag_automatic()};{self.get_flag_pygccxml()};{self.get_header_filename()};{self.get_header_file_hash()};' - def argParse(): """Parses commandline args.""" - desc='Reads the parameters from the comment block in the pybind files' + desc = 'Reads the parameters from the comment block in the pybind files' parser = ArgumentParser(description=desc) - parser.add_argument("function", help="Operation to perform on comment block of pybind file", choices=["flag_auto","flag_pygccxml","header_filename","header_file_hash","all"]) - parser.add_argument("pathname", help="Pathname of pybind c++ file to read, e.g. blockname_python.cc") + parser.add_argument("function", help="Operation to perform on comment block of pybind file", choices=[ + "flag_auto", "flag_pygccxml", "header_filename", "header_file_hash", "all"]) + parser.add_argument( + "pathname", help="Pathname of pybind c++ file to read, e.g. blockname_python.cc") return parser.parse_args() + if __name__ == "__main__": # Parse command line options and set up doxyxml. args = argParse() diff --git a/gr-utils/modtool/templates/templates.py b/gr-utils/modtool/templates/templates.py index 57e1ff600a3..5c94f4c214b 100644 --- a/gr-utils/modtool/templates/templates.py +++ b/gr-utils/modtool/templates/templates.py @@ -389,7 +389,7 @@ def forecast(self, noutput_items, ninputs): # ninputs is the number of input connections # setup size of input_items[i] for work call # the required number of input items is returned - # in a list where each element represents the + # in a list where each element represents the # number of required items for each input ninput_items_required = [noutput_items] * ninputs return ninput_items_required @@ -583,7 +583,7 @@ def test_001_descriptive_test_name(self): file_format: 1 ''' -## Old stuff +# Old stuff # C++ file of a GR block Templates['block_cpp36'] = '''/* -*- c++ -*- */ ${str_to_fancyc_comment(license)} diff --git a/gr-utils/modtool/tests/test_modtool.py b/gr-utils/modtool/tests/test_modtool.py index dd510b831ba..4f7944f695b 100644 --- a/gr-utils/modtool/tests/test_modtool.py +++ b/gr-utils/modtool/tests/test_modtool.py @@ -20,7 +20,7 @@ except: skip_pylint_test = True -try: # for debugging, full path must be given +try: # for debugging, full path must be given from gnuradio.modtool.core import ModToolNewModule from gnuradio.modtool.core import ModToolAdd from gnuradio.modtool.core import ModToolDisable @@ -35,15 +35,18 @@ from modtool.core import ModToolException from modtool.core import ModToolMakeYAML from modtool.core import ModToolRename - from modtool.core import ModToolRemove + from modtool.core import ModToolRemove + class TestModToolCore(unittest.TestCase): """ The tests for the modtool core """ + def __init__(self, *args, **kwargs): super(TestModToolCore, self).__init__(*args, **kwargs) self.f_add = False self.f_newmod = False - self.srcdir = path.abspath(path.join(path.dirname(path.realpath(__file__)), '../templates/gr-newmod')) + self.srcdir = path.abspath(path.join(path.dirname( + path.realpath(__file__)), '../templates/gr-newmod')) @classmethod def setUpClass(cls): @@ -59,7 +62,7 @@ def setUp(self): """ create a new module and block before every test """ try: warnings.simplefilter("ignore", ResourceWarning) - args = {'module_name':'howto', + args = {'module_name': 'howto', 'directory': self.test_dir, 'srcdir': self.srcdir} ModToolNewModule(**args).run() @@ -67,8 +70,8 @@ def setUp(self): self.f_newmod = True else: try: - args = {'blockname':'square_ff', 'block_type':'general', - 'lang':'cpp', 'directory': self.test_dir + '/gr-howto', + args = {'blockname': 'square_ff', 'block_type': 'general', + 'lang': 'cpp', 'directory': self.test_dir + '/gr-howto', 'add_python_qa': True} ModToolAdd(**args).run() except (TypeError, ModToolException): @@ -78,7 +81,7 @@ def tearDown(self): """ removes the created module """ # Required, else the new-module directory command # in setup will throw exception after first test - ## cannot remove if directory is not created + # cannot remove if directory is not created if not self.f_newmod: rmdir = self.test_dir + '/gr-howto' shutil.rmtree(rmdir) @@ -86,8 +89,8 @@ def tearDown(self): def test_newmod(self): """ Tests for the API function newmod """ ## Tests for proper exceptions ## - test_dict = { 'directory': self.test_dir, - 'srcdir': self.srcdir} + test_dict = {'directory': self.test_dir, + 'srcdir': self.srcdir} # module name not specified self.assertRaises(ModToolException, ModToolNewModule(**test_dict).run) test_dict['module_name'] = 'howto' @@ -110,7 +113,7 @@ def test_newmod(self): self.assertTrue(path.exists(path.join(module_dir, 'CMakeLists.txt'))) ## The check for object instantiation ## - test_obj = ModToolNewModule(srcdir = self.srcdir) + test_obj = ModToolNewModule(srcdir=self.srcdir) # module name not specified with self.assertRaises(ModToolException) as context_manager: test_obj.run() @@ -120,9 +123,10 @@ def test_newmod(self): self.assertRaises(ModToolException, test_obj.run) test_obj.info['modname'] = 'test1' test_obj.run() - self.assertTrue(path.isdir(self.test_dir+'/gr-test1')) - self.assertTrue(path.isdir(self.test_dir+'/gr-test1/lib')) - self.assertTrue(path.exists(self.test_dir+'/gr-test1/CMakeLists.txt')) + self.assertTrue(path.isdir(self.test_dir + '/gr-test1')) + self.assertTrue(path.isdir(self.test_dir + '/gr-test1/lib')) + self.assertTrue(path.exists( + self.test_dir + '/gr-test1/CMakeLists.txt')) @unittest.skipIf(skip_pylint_test, 'pylint dependency missing, skip test') def test_pylint_newmod(self): @@ -131,15 +135,17 @@ def test_pylint_newmod(self): ## pylint tests ## python_dir = path.join(module_dir, 'python') py_module = path.join(python_dir, 'mul_ff.py') - (pylint_stdout, pylint_stderr) = py_run(py_module+' --errors-only --disable=E0602', return_std=True) + (pylint_stdout, pylint_stderr) = py_run(py_module + + ' --errors-only --disable=E0602', return_std=True) print(pylint_stdout.getvalue(), end='') py_module = path.join(python_dir, 'qa_mul_ff.py') - (pylint_stdout, pylint_stderr) = py_run(py_module+' --errors-only', return_std=True) + (pylint_stdout, pylint_stderr) = py_run( + py_module + ' --errors-only', return_std=True) print(pylint_stdout.getvalue(), end='') def test_add(self): """ Tests for the API function add """ - ## skip tests if newmod command wasn't successful + # skip tests if newmod command wasn't successful if self.f_newmod: raise unittest.SkipTest("setUp for API function 'add' failed") module_dir = path.join(self.test_dir, 'gr-howto') @@ -176,10 +182,14 @@ def test_add(self): ## Some tests for checking the created directory, sub-directories and files ## test_dict['skip_lib'] = False ModToolAdd(**test_dict).run() - self.assertTrue(path.exists(path.join(module_dir, 'lib', 'qa_add_ff.cc'))) - self.assertTrue(path.exists(path.join(module_dir, 'lib', 'add_ff_impl.cc'))) - self.assertTrue(path.exists(path.join(module_dir, 'grc', 'howto_add_ff.block.yml'))) - self.assertTrue(path.exists(path.join(module_dir, 'include', 'howto', 'add_ff.h'))) + self.assertTrue(path.exists( + path.join(module_dir, 'lib', 'qa_add_ff.cc'))) + self.assertTrue(path.exists( + path.join(module_dir, 'lib', 'add_ff_impl.cc'))) + self.assertTrue(path.exists( + path.join(module_dir, 'grc', 'howto_add_ff.block.yml'))) + self.assertTrue(path.exists( + path.join(module_dir, 'include', 'howto', 'add_ff.h'))) ## The check for object instantiation ## test_obj = ModToolAdd() @@ -193,14 +203,17 @@ def test_add(self): test_obj.info['blockname'] = 'mul_ff' test_obj.add_py_qa = True test_obj.run() - self.assertTrue(path.exists(path.join(module_dir, 'python', 'mul_ff.py'))) - self.assertTrue(path.exists(path.join(module_dir, 'python', 'qa_mul_ff.py'))) - self.assertTrue(path.exists(path.join(module_dir, 'grc', 'howto_mul_ff.block.yml'))) + self.assertTrue(path.exists( + path.join(module_dir, 'python', 'mul_ff.py'))) + self.assertTrue(path.exists( + path.join(module_dir, 'python', 'qa_mul_ff.py'))) + self.assertTrue(path.exists( + path.join(module_dir, 'grc', 'howto_mul_ff.block.yml'))) @unittest.skipIf(skip_pylint_test, 'pylint dependency missing, skip test') def test_pylint_add(self): """ Pylint tests for API function add """ - ## skip tests if newmod command wasn't successful + # skip tests if newmod command wasn't successful if self.f_newmod: raise unittest.SkipTest("setUp for API function 'add' failed") module_dir = path.join(self.test_dir, 'gr-howto') @@ -217,16 +230,20 @@ def test_pylint_add(self): test_obj.info['blockname'] = 'mul_ff' test_obj.add_py_qa = True test_obj.run() - self.assertTrue(path.exists(path.join(module_dir, 'python', 'mul_ff.py'))) - self.assertTrue(path.exists(path.join(module_dir, 'python', 'qa_mul_ff.py'))) + self.assertTrue(path.exists( + path.join(module_dir, 'python', 'mul_ff.py'))) + self.assertTrue(path.exists( + path.join(module_dir, 'python', 'qa_mul_ff.py'))) ## pylint tests ## python_dir = path.join(module_dir, 'python') py_module = path.join(python_dir, 'mul_ff.py') - (pylint_stdout, pylint_stderr) = py_run(py_module+' --errors-only --disable=E0602', return_std=True) + (pylint_stdout, pylint_stderr) = py_run(py_module + + ' --errors-only --disable=E0602', return_std=True) print(pylint_stdout.getvalue(), end='') py_module = path.join(python_dir, 'qa_mul_ff.py') - (pylint_stdout, pylint_stderr) = py_run(py_module+' --errors-only', return_std=True) + (pylint_stdout, pylint_stderr) = py_run( + py_module + ' --errors-only', return_std=True) print(pylint_stdout.getvalue(), end='') def test_rename(self): @@ -247,7 +264,8 @@ def test_rename(self): test_dict['new_name'] = '//#' # Invalid new block name! expected_message = "Invalid new block name '//#': names can only contain letters, numbers and underscores" - self.assertRaisesRegex(ModToolException, expected_message, ModToolRename(**test_dict).run) + self.assertRaisesRegex( + ModToolException, expected_message, ModToolRename(**test_dict).run) test_dict['new_name'] = 'non-alpha-chars-like-hyphen-are-not-allowed' # Invalid new block name! @@ -260,20 +278,28 @@ def test_rename(self): ## Some tests for checking the renamed files ## test_dict['new_name'] = 'div_ff' ModToolRename(**test_dict).run() - self.assertTrue(path.exists(path.join(module_dir, 'lib', 'div_ff_impl.h'))) - self.assertTrue(path.exists(path.join(module_dir, 'lib', 'div_ff_impl.cc'))) - self.assertTrue(path.exists(path.join(module_dir, 'python', 'qa_div_ff.py'))) - self.assertTrue(path.exists(path.join(module_dir, 'grc', 'howto_div_ff.block.yml'))) + self.assertTrue(path.exists( + path.join(module_dir, 'lib', 'div_ff_impl.h'))) + self.assertTrue(path.exists( + path.join(module_dir, 'lib', 'div_ff_impl.cc'))) + self.assertTrue(path.exists( + path.join(module_dir, 'python', 'qa_div_ff.py'))) + self.assertTrue(path.exists( + path.join(module_dir, 'grc', 'howto_div_ff.block.yml'))) ## The check for object instantiation ## test_obj = ModToolRename() test_obj.info['oldname'] = 'div_ff' test_obj.info['newname'] = 'sub_ff' test_obj.run() - self.assertTrue(path.exists(path.join(module_dir, 'lib', 'sub_ff_impl.h'))) - self.assertTrue(path.exists(path.join(module_dir, 'lib', 'sub_ff_impl.cc'))) - self.assertTrue(path.exists(path.join(module_dir, 'python', 'qa_sub_ff.py'))) - self.assertTrue(path.exists(path.join(module_dir, 'grc', 'howto_sub_ff.block.yml'))) + self.assertTrue(path.exists( + path.join(module_dir, 'lib', 'sub_ff_impl.h'))) + self.assertTrue(path.exists( + path.join(module_dir, 'lib', 'sub_ff_impl.cc'))) + self.assertTrue(path.exists( + path.join(module_dir, 'python', 'qa_sub_ff.py'))) + self.assertTrue(path.exists( + path.join(module_dir, 'grc', 'howto_sub_ff.block.yml'))) def test_remove(self): """ Tests for the API function remove """ @@ -289,18 +315,26 @@ def test_remove(self): ## Some tests to check blocks are not removed with different blocknames ## test_dict['blockname'] = 'div_ff' ModToolRemove(**test_dict).run() - self.assertTrue(path.exists(path.join(module_dir, 'lib', 'square_ff_impl.h'))) - self.assertTrue(path.exists(path.join(module_dir, 'lib', 'square_ff_impl.cc'))) - self.assertTrue(path.exists(path.join(module_dir, 'python', 'qa_square_ff.py'))) - self.assertTrue(path.exists(path.join(module_dir, 'grc', 'howto_square_ff.block.yml'))) + self.assertTrue(path.exists( + path.join(module_dir, 'lib', 'square_ff_impl.h'))) + self.assertTrue(path.exists( + path.join(module_dir, 'lib', 'square_ff_impl.cc'))) + self.assertTrue(path.exists( + path.join(module_dir, 'python', 'qa_square_ff.py'))) + self.assertTrue(path.exists( + path.join(module_dir, 'grc', 'howto_square_ff.block.yml'))) ## Some tests for checking the non-existence of removed files ## test_dict['blockname'] = 'square_ff' ModToolRemove(**test_dict).run() - self.assertTrue(not path.exists(path.join(module_dir, 'lib', 'square_ff_impl.h'))) - self.assertTrue(not path.exists(path.join(module_dir, 'lib', 'square_ff_impl.cc'))) - self.assertTrue(not path.exists(path.join(module_dir, 'python', 'qa_square_ff.py'))) - self.assertTrue(not path.exists(path.join(module_dir, 'grc', 'howto_square_ff.block.yml'))) + self.assertTrue(not path.exists( + path.join(module_dir, 'lib', 'square_ff_impl.h'))) + self.assertTrue(not path.exists( + path.join(module_dir, 'lib', 'square_ff_impl.cc'))) + self.assertTrue(not path.exists( + path.join(module_dir, 'python', 'qa_square_ff.py'))) + self.assertTrue(not path.exists( + path.join(module_dir, 'grc', 'howto_square_ff.block.yml'))) def test_makeyaml(self): """ Tests for the API function makeyaml """ @@ -332,5 +366,6 @@ def test_disable(self): test_dict['blockname'] = 'square_ff' ModToolDisable(**test_dict).run() + if __name__ == '__main__': unittest.main() diff --git a/gr-utils/modtool/tools/cmakefile_editor.py b/gr-utils/modtool/tools/cmakefile_editor.py index ce97b959193..5632eef2540 100644 --- a/gr-utils/modtool/tools/cmakefile_editor.py +++ b/gr-utils/modtool/tools/cmakefile_editor.py @@ -17,6 +17,7 @@ class CMakeFileEditor(object): """A tool for editing CMakeLists.txt files. """ + def __init__(self, filename, separator='\n ', indent=' '): self.filename = filename with open(filename, 'r') as f: @@ -60,10 +61,10 @@ def remove_value(self, entry, value, to_ignore_start='', to_ignore_end=''): else: regexp = r'^\s*({entry}\(\s*{to_ignore_start}[^()]*?\s+){value}\s*([^()]*{to_ignore_end}\s*\))' regexp = regexp.format( - entry=entry, - to_ignore_start=to_ignore_start, - value=value, - to_ignore_end=to_ignore_end, + entry=entry, + to_ignore_start=to_ignore_start, + value=value, + to_ignore_end=to_ignore_end, ) regexp = re.compile(regexp, re.MULTILINE) (self.cfile, nsubs) = re.subn(regexp, r'\1\2', self.cfile, count=1) @@ -83,7 +84,8 @@ def write(self): def remove_double_newlines(self): """Simply clear double newlines from the file buffer.""" - self.cfile = re.compile('\n\n\n+', re.MULTILINE).sub('\n\n', self.cfile) + self.cfile = re.compile( + '\n\n\n+', re.MULTILINE).sub('\n\n', self.cfile) def find_filenames_match(self, regex): """ Find the filenames that match a certain regex @@ -112,27 +114,30 @@ def disable_file(self, fname): for line in self.cfile.splitlines(): if len(line.strip()) == 0 or line.strip()[0] == '#': continue - if re.search(r'\b'+fname+r'\b', line): + if re.search(r'\b' + fname + r'\b', line): if re.match(fname, line.lstrip()): starts_line = True break comment_out_re = r'#\1' + '\n' + self.indent if not starts_line: comment_out_re = r'\n' + self.indent + comment_out_re - (self.cfile, nsubs) = re.subn(r'(\b'+fname+r'\b)\s*', comment_out_re, self.cfile) + (self.cfile, nsubs) = re.subn( + r'(\b' + fname + r'\b)\s*', comment_out_re, self.cfile) if nsubs == 0: - logger.warning(f"Warning: A replacement failed when commenting out {fname}. Check the CMakeFile.txt manually.") + logger.warning( + f"Warning: A replacement failed when commenting out {fname}. Check the CMakeFile.txt manually.") elif nsubs > 1: - logger.warning(f"Warning: Replaced {fname} {nsubs} times (instead of once). Check the CMakeFile.txt manually.") + logger.warning( + f"Warning: Replaced {fname} {nsubs} times (instead of once). Check the CMakeFile.txt manually.") def comment_out_lines(self, pattern, comment_str='#'): """ Comments out all lines that match with pattern """ for line in self.cfile.splitlines(): if re.search(pattern, line): - self.cfile = self.cfile.replace(line, comment_str+line) + self.cfile = self.cfile.replace(line, comment_str + line) def check_for_glob(self, globstr): """ Returns true if a glob as in globstr is found in the cmake file """ str_ = globstr.replace('*', r'\*') glob_re = fr'GLOB\s[a-z_]+\s"{str_}"' - return re.search(glob_re, self.cfile, flags=re.MULTILINE|re.IGNORECASE) is not None + return re.search(glob_re, self.cfile, flags=re.MULTILINE | re.IGNORECASE) is not None diff --git a/gr-utils/modtool/tools/code_generator.py b/gr-utils/modtool/tools/code_generator.py index 7c6addd69fe..d491d7b56c5 100644 --- a/gr-utils/modtool/tools/code_generator.py +++ b/gr-utils/modtool/tools/code_generator.py @@ -29,6 +29,7 @@ 'noblock': '' } + def render_template(tpl_id, **kwargs): """ Return the parsed and rendered template given by tpl_id """ # Choose template @@ -46,4 +47,3 @@ def render_template(tpl_id, **kwargs): kwargs['include_dir_prefix'] = kwargs['modname'] # Render and return return tpl.render(**kwargs) - diff --git a/gr-utils/modtool/tools/cppfile_editor.py b/gr-utils/modtool/tools/cppfile_editor.py index 418547c9b75..5b44bc3dbfc 100644 --- a/gr-utils/modtool/tools/cppfile_editor.py +++ b/gr-utils/modtool/tools/cppfile_editor.py @@ -17,6 +17,7 @@ class CPPFileEditor(object): """A tool for editing CMakeLists.txt files. """ + def __init__(self, filename, separator='\n ', indent=' '): self.filename = filename with open(filename, 'r') as f: @@ -35,36 +36,43 @@ def __init__(self, filename, separator='\n ', indent=' '): def append_value(self, start_tag, end_tag, value): """ Add a value to an entry. """ cfile_lines = self.cfile.splitlines() - start_line_idx = [cfile_lines.index(s) for s in cfile_lines if start_tag in s][0] - end_line_idx = [cfile_lines.index(s) for s in cfile_lines if end_tag in s][0] + start_line_idx = [cfile_lines.index( + s) for s in cfile_lines if start_tag in s][0] + end_line_idx = [cfile_lines.index(s) + for s in cfile_lines if end_tag in s][0] - self.cfile = '\n'.join((cfile_lines[0:end_line_idx]+[self.indent + value]+cfile_lines[end_line_idx:])) + self.cfile = '\n'.join( + (cfile_lines[0:end_line_idx] + [self.indent + value] + cfile_lines[end_line_idx:])) return 1 - def remove_value(self, start_tag, end_tag, value): - + cfile_lines = self.cfile.splitlines() try: - start_line_idx = [cfile_lines.index(s) for s in cfile_lines if start_tag in s][0] - end_line_idx = [cfile_lines.index(s) for s in cfile_lines if end_tag in s][0] + start_line_idx = [cfile_lines.index( + s) for s in cfile_lines if start_tag in s][0] + end_line_idx = [cfile_lines.index( + s) for s in cfile_lines if end_tag in s][0] except: logger.warning("Could not find start or end tags in search") return 0 - try: - lines_between_tags = cfile_lines[(start_line_idx+1):end_line_idx] - remove_index = [lines_between_tags.index(s) for s in cfile_lines if value in s][0] + try: + lines_between_tags = cfile_lines[(start_line_idx + 1):end_line_idx] + remove_index = [lines_between_tags.index( + s) for s in cfile_lines if value in s][0] lines_between_tags.pop(remove_index) except: return 0 - self.cfile = '\n'.join((cfile_lines[0:(start_line_idx+1)]+lines_between_tags+cfile_lines[end_line_idx:])) + self.cfile = '\n'.join((cfile_lines[0:( + start_line_idx + 1)] + lines_between_tags + cfile_lines[end_line_idx:])) return 1 def delete_entry(self, entry, value_pattern=''): """Remove an entry from the current buffer.""" - regexp = r'{}\s*\([^()]*{}[^()]*\)[^\n]*\n'.format(entry, value_pattern) + regexp = r'{}\s*\([^()]*{}[^()]*\)[^\n]*\n'.format(entry, + value_pattern) regexp = re.compile(regexp, re.MULTILINE) (self.cfile, nsubs) = re.subn(regexp, '', self.cfile, count=1) return nsubs @@ -76,7 +84,8 @@ def write(self): def remove_double_newlines(self): """Simply clear double newlines from the file buffer.""" - self.cfile = re.compile('\n\n\n+', re.MULTILINE).sub('\n\n', self.cfile) + self.cfile = re.compile( + '\n\n\n+', re.MULTILINE).sub('\n\n', self.cfile) def find_filenames_match(self, regex): """ Find the filenames that match a certain regex @@ -105,26 +114,29 @@ def disable_file(self, fname): for line in self.cfile.splitlines(): if len(line.strip()) == 0 or line.strip()[0] == '#': continue - if re.search(r'\b'+fname+r'\b', line): + if re.search(r'\b' + fname + r'\b', line): if re.match(fname, line.lstrip()): starts_line = True break comment_out_re = r'#\1' + '\n' + self.indent if not starts_line: comment_out_re = r'\n' + self.indent + comment_out_re - (self.cfile, nsubs) = re.subn(r'(\b'+fname+r'\b)\s*', comment_out_re, self.cfile) + (self.cfile, nsubs) = re.subn( + r'(\b' + fname + r'\b)\s*', comment_out_re, self.cfile) if nsubs == 0: - logger.warning("Warning: A replacement failed when commenting out {}. Check the CMakeFile.txt manually.".format(fname)) + logger.warning( + "Warning: A replacement failed when commenting out {}. Check the CMakeFile.txt manually.".format(fname)) elif nsubs > 1: - logger.warning("Warning: Replaced {} {} times (instead of once). Check the CMakeFile.txt manually.".format(fname, nsubs)) + logger.warning( + "Warning: Replaced {} {} times (instead of once). Check the CMakeFile.txt manually.".format(fname, nsubs)) def comment_out_lines(self, pattern, comment_str='#'): """ Comments out all lines that match with pattern """ for line in self.cfile.splitlines(): if re.search(pattern, line): - self.cfile = self.cfile.replace(line, comment_str+line) + self.cfile = self.cfile.replace(line, comment_str + line) def check_for_glob(self, globstr): """ Returns true if a glob as in globstr is found in the cmake file """ glob_re = r'GLOB\s[a-z_]+\s"{}"'.format(globstr.replace('*', r'\*')) - return re.search(glob_re, self.cfile, flags=re.MULTILINE|re.IGNORECASE) is not None + return re.search(glob_re, self.cfile, flags=re.MULTILINE | re.IGNORECASE) is not None diff --git a/gr-utils/modtool/tools/grc_yaml_generator.py b/gr-utils/modtool/tools/grc_yaml_generator.py index 188b917d1f4..2ecee8ca763 100644 --- a/gr-utils/modtool/tools/grc_yaml_generator.py +++ b/gr-utils/modtool/tools/grc_yaml_generator.py @@ -23,6 +23,7 @@ ## setup dumper for dumping OrderedDict ## _mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG + def dict_representer(dumper, data): """ Representer to represent special OrderedDict """ return dumper.represent_dict(data.items()) @@ -32,24 +33,27 @@ def dict_constructor(loader, node): """ Construct an OrderedDict for dumping """ return OrderedDict(loader.construct_pairs(node)) + Dumper.add_representer(OrderedDict, dict_representer) Loader.add_constructor(_mapping_tag, dict_constructor) class GRCYAMLGenerator(object): """ Create and write the YAML bindings for a GRC block. """ + def __init__(self, modname=None, blockname=None, doc=None, params=None, iosig=None): """docstring for __init__""" - params_list = ['${'+s['key']+'}' for s in params if s['in_constructor']] + params_list = [ + '${' + s['key'] + '}' for s in params if s['in_constructor']] # Can't make a dict 'cause order matters str_ = ', '.join(params_list) self._header = (('id', f'{modname}_{blockname}'), ('label', blockname.replace('_', ' ')), (f'category', f'[{modname.capitalize()}]') - ) + ) self._templates = (('imports', f'import {modname}'), ('make', f'{modname}.{blockname}({str_})') - ) + ) self.params = params self.iosig = iosig self.doc = doc @@ -97,13 +101,13 @@ def make_yaml(self): if is_number(vlen): s_obj['vlen'] = vlen else: - s_obj['vlen'] = '${ '+vlen+' }' - if i == len(iosig[inout]['type'])-1: + s_obj['vlen'] = '${ ' + vlen + ' }' + if i == len(iosig[inout]['type']) - 1: if not is_number(iosig[inout]['max_ports']): s_obj['multiplicity'] = iosig[inout]['max_ports'] elif len(iosig[inout]['type']) < int(iosig[inout]['max_ports']): s_obj['multiplicity'] = str(int(iosig[inout]['max_ports']) - - len(iosig[inout]['type'])+1) + len(iosig[inout]['type']) + 1) if s_type == 'input': inputs.append(s_obj) elif s_type == 'output': diff --git a/gr-utils/modtool/tools/parser_cc_block.py b/gr-utils/modtool/tools/parser_cc_block.py index 1e94147a140..0ef85c0e74d 100644 --- a/gr-utils/modtool/tools/parser_cc_block.py +++ b/gr-utils/modtool/tools/parser_cc_block.py @@ -15,17 +15,20 @@ logger = logging.getLogger(__name__) + def dummy_translator(the_type, default_v=None): """ Doesn't really translate. """ return the_type + class ParserCCBlock(object): """ Class to read blocks written in C++ """ + def __init__(self, filename_cc, filename_h, blockname, version, type_trans=dummy_translator): with open(filename_cc) as f: self.code_cc = f.read() with open(filename_h) as f: - self.code_h = f.read() + self.code_h = f.read() self.blockname = blockname self.type_trans = type_trans self.version = version @@ -40,14 +43,16 @@ def _figure_out_iotype_and_vlen(iosigcall, typestr): logger.error('tbi') raise ValueError return {'type': [_typestr_to_iotype(x) for x in typestr.split(',')], - 'vlen': [_typestr_to_vlen(x) for x in typestr.split(',')] - } + 'vlen': [_typestr_to_vlen(x) for x in typestr.split(',')] + } + def _typestr_to_iotype(typestr): """ Convert a type string (e.g. sizeof(int) * vlen) to the type (e.g. 'int'). """ type_match = re.search(r'sizeof\s*\(([^)]*)\)', typestr) if type_match is None: return self.type_trans('char') return self.type_trans(type_match.group(1)) + def _typestr_to_vlen(typestr): """ From a type identifier, returns the vector length of the block's input/out. E.g., for 'sizeof(int) * 10', it returns 10. For @@ -71,7 +76,8 @@ def _typestr_to_vlen(typestr): r'\s*(?P(\([^\)]*\)|[^)])+)\),\s*' + \ r'(?Pgr::io_signature::make[23v]?)\s*\(\s*(?P[^,]+),\s*(?P[^,]+),' + \ r'\s*(?P(\([^\)]*\)|[^)])+)\)' - iosig_match = re.compile(iosig_regex, re.MULTILINE).search(self.code_cc) + iosig_match = re.compile( + iosig_regex, re.MULTILINE).search(self.code_cc) try: iosig['in'] = _figure_out_iotype_and_vlen(iosig_match.group('incall'), iosig_match.group('intype')) @@ -88,7 +94,6 @@ def _typestr_to_vlen(typestr): logger.error("Error: Can't parse output signature.") return iosig - def read_params(self): """ Read the parameters required to initialize the block """ def _scan_param_list(start_idx): @@ -104,8 +109,8 @@ def _scan_param_list(start_idx): param_list = [] read_state = 'type' in_string = False - parens_count = 0 # Counts () - brackets_count = 0 # Counts <> + parens_count = 0 # Counts () + brackets_count = 0 # Counts <> end_of_list = False this_type = '' this_name = '' @@ -118,12 +123,13 @@ def _scan_param_list(start_idx): if parens_count == 0: if read_state == 'type' and len(this_type): raise ValueError( - 'Found closing parentheses before finishing ' - 'last argument (this is how far I got: {})'.format \ - (str(param_list)) + 'Found closing parentheses before finishing ' + 'last argument (this is how far I got: {})'.format + (str(param_list)) ) if len(this_type): - param_list.append((this_type, this_name, this_defv)) + param_list.append( + (this_type, this_name, this_defv)) end_of_list = True break else: @@ -143,9 +149,9 @@ def _scan_param_list(start_idx): while c[i] in WHITESPACE: i += 1 continue - if this_type == 'const' or this_type == '': # Ignore this + if this_type == 'const' or this_type == '': # Ignore this this_type = '' - elif this_type == 'unsigned': # Continue + elif this_type == 'unsigned': # Continue this_type += ' ' continue else: @@ -161,16 +167,16 @@ def _scan_param_list(start_idx): elif c[i] == '=': if parens_count != 0: raise ValueError( - 'While parsing argument {} ({}): name finished but no closing parentheses.'.format \ - (len(param_list)+1, this_type + ' ' + this_name) + 'While parsing argument {} ({}): name finished but no closing parentheses.'.format + (len(param_list) + 1, this_type + ' ' + this_name) ) read_state = 'defv' i += 1 elif c[i] == ',': if parens_count: raise ValueError( - 'While parsing argument {} ({}): name finished but no closing parentheses.'.format \ - (len(param_list)+1, this_type + ' ' + this_name) + 'While parsing argument {} ({}): name finished but no closing parentheses.'.format + (len(param_list) + 1, this_type + ' ' + this_name) ) read_state = 'defv' else: @@ -180,15 +186,15 @@ def _scan_param_list(start_idx): # Default value if read_state == 'defv': if in_string: - if c[i] == '"' and c[i-1] != '\\': + if c[i] == '"' and c[i - 1] != '\\': in_string = False else: this_defv += c[i] elif c[i] == ',': if parens_count: raise ValueError( - 'While parsing argument {} ({}): default value finished but no closing parentheses.'.format \ - (len(param_list)+1, this_type + ' ' + this_name) + 'While parsing argument {} ({}): default value finished but no closing parentheses.'.format + (len(param_list) + 1, this_type + ' ' + this_name) ) read_state = 'type' param_list.append((this_type, this_name, this_defv)) diff --git a/gr-utils/modtool/tools/scm.py b/gr-utils/modtool/tools/scm.py index a92be88de64..005eb7c1f3f 100644 --- a/gr-utils/modtool/tools/scm.py +++ b/gr-utils/modtool/tools/scm.py @@ -22,15 +22,20 @@ # GitPython is a bit too unstable currently HAS_GITPYTHON = False + class InvalidSCMError(Exception): """ Exception for when trying to access a repo of wrong type. """ + def __init__(self): Exception.__init__(self) ### Base class ############################################################### + + class SCMRepository(object): """ Base class to handle interactions with source code management systems. """ handles_scm_type = '*' + def __init__(self, path_to_repo, is_empty=False): self.path_to_repo = path_to_repo self.is_empty = is_empty @@ -84,6 +89,7 @@ def get_gituser(self): ### Git ##################################################################### class GitManagerGitPython(object): """ Manage git through GitPython (preferred way). """ + def __init__(self, path_to_repo, init=False): if init: self.repo = git.Repo.init(path_to_repo, mkdir=False) @@ -108,11 +114,13 @@ def remove_files(self, paths_to_files): class GitManagerShell(object): """ Call the git executable through a shell. """ + def __init__(self, path_to_repo, init=False, git_executable=None): self.path_to_repo = path_to_repo if git_executable is None: try: - self.git_executable = subprocess.check_output('which git', shell=True).strip() + self.git_executable = subprocess.check_output( + 'which git', shell=True).strip() except (OSError, subprocess.CalledProcessError): raise InvalidSCMError try: @@ -127,16 +135,19 @@ def __init__(self, path_to_repo, init=False, git_executable=None): def add_files(self, paths_to_files): """ Adds a tuple of files to the index of the current repository. Does not commit. """ - subprocess.check_output([self.git_executable, 'add'] + list(paths_to_files)) + subprocess.check_output( + [self.git_executable, 'add'] + list(paths_to_files)) def remove_files(self, paths_to_files): """ Removes a tuple of files from the index of the current repository. Does not commit. """ - subprocess.check_output([self.git_executable, 'rm', '--cached'] + list(paths_to_files)) + subprocess.check_output( + [self.git_executable, 'rm', '--cached'] + list(paths_to_files)) class GitRepository(SCMRepository): """ Specific to operating on git repositories. """ handles_scm_type = 'git' + def __init__(self, path_to_repo, is_empty=False): SCMRepository.__init__(self, path_to_repo, is_empty) if not is_empty: @@ -155,7 +166,8 @@ def init_repo(self, path_to_repo=None, add_files=True): If add_file is True, all files in this dir are added to the index. """ SCMRepository.init_repo(self, path_to_repo, add_files) if HAS_GITPYTHON: - self.repo_manager = GitManagerGitPython(self.path_to_repo, init=True) + self.repo_manager = GitManagerGitPython( + self.path_to_repo, init=True) else: self.repo_manager = GitManagerShell(self.path_to_repo, init=True) if add_files: @@ -182,6 +194,7 @@ def is_active(self): ### Factory ################################################################## class SCMRepoFactory(object): """ Factory object to create the correct SCM class from the given options and dir. """ + def __init__(self, options, path_to_repo): self.path_to_repo = path_to_repo self.options = options @@ -195,7 +208,8 @@ def make_active_scm_manager(self): if issubclass(glbl, SCMRepository): the_scm = glbl(self.path_to_repo) if the_scm.is_active(): - logger.info('Found SCM of type:', the_scm.handles_scm_type) + logger.info('Found SCM of type:', + the_scm.handles_scm_type) return the_scm except (TypeError, AttributeError, InvalidSCMError): pass @@ -217,4 +231,3 @@ def make_empty_scm_manager(self, scm_type='git'): if self.options == 'yes': return None return SCMRepository(self.path_to_repo) - diff --git a/gr-utils/modtool/tools/util_functions.py b/gr-utils/modtool/tools/util_functions.py index 52bd01384f7..a5b368e32c8 100644 --- a/gr-utils/modtool/tools/util_functions.py +++ b/gr-utils/modtool/tools/util_functions.py @@ -15,6 +15,7 @@ # None of these must depend on other modtool stuff! + def append_re_line_sequence(filename, linepattern, newline): """ Detects the re 'linepattern' in the file. After its last occurrence, paste 'newline'. If the pattern does not exist, append the new line @@ -31,6 +32,7 @@ def append_re_line_sequence(filename, linepattern, newline): with open(filename, 'w') as f: f.write(newfile) + def remove_pattern_from_file(filename, pattern): """ Remove all occurrences of a given pattern from a file. """ with open(filename, 'r') as f: @@ -39,6 +41,7 @@ def remove_pattern_from_file(filename, pattern): with open(filename, 'w') as f: f.write(pattern.sub('', oldfile)) + def str_to_fancyc_comment(text): """ Return a string as a C formatted comment. """ l_lines = text.splitlines() @@ -54,6 +57,7 @@ def str_to_fancyc_comment(text): outstr += " */\n" return outstr + def str_to_python_comment(text): """ Return a string as a Python formatted comment. """ l_lines = text.splitlines() @@ -69,10 +73,12 @@ def str_to_python_comment(text): outstr += "#\n" return outstr + def strip_default_values(string): """ Strip default values from a C++ argument list. """ return re.sub(' *=[^,)]*', '', string) + def strip_arg_types(string): """" Strip the argument types from a list of arguments. @@ -83,8 +89,9 @@ def strip_arg_types(string): """ string = strip_default_values(string) return ", ".join( - [part.strip().split(' ')[-1] for part in string.split(',')] - ).replace('*','').replace('&','') + [part.strip().split(' ')[-1] for part in string.split(',')] + ).replace('*', '').replace('&', '') + def strip_arg_types_grc(string): """" Strip the argument types from a list of arguments for GRC make tag. @@ -95,6 +102,7 @@ def strip_arg_types_grc(string): string = strip_default_values(string) return ", ".join(['${' + part.strip().split(' ')[-1] + '}' for part in string.split(',')]) + def get_modname(): """ Grep the current module's name from gnuradio.project or CMakeLists.txt """ modname_trans = {'howto-write-a-block': 'howto'} @@ -110,13 +118,15 @@ def get_modname(): cmfile = f.read() regexp = r'(project\s*\(\s*|GR_REGISTER_COMPONENT\(")gr-(?P[a-zA-Z0-9-_]+)(\s*(CXX)?|" ENABLE)' try: - modname = re.search(regexp, cmfile, flags=re.MULTILINE).group('modname').strip() + modname = re.search(regexp, cmfile, flags=re.MULTILINE).group( + 'modname').strip() if modname in list(modname_trans.keys()): modname = modname_trans[modname] return modname except AttributeError: return None + def get_block_names(pattern, modname): """ Return a list of block names belonging to modname that matches the regex pattern. """ blocknames = [] @@ -131,6 +141,7 @@ def get_block_names(pattern, modname): blocknames.append(word.strip('.h')) return blocknames + def is_number(s): """ Return True if the string s contains a number. """ try: @@ -139,6 +150,7 @@ def is_number(s): except ValueError: return False + def ask_yes_no(question, default): """ Asks a binary question. Returns True for yes, False for no. default is given as a boolean. """ @@ -148,6 +160,7 @@ def ask_yes_no(question, default): else: return not default + class SequenceCompleter(object): """ A simple completer function wrapper to be used with readline, e.g. option_iterable = ("search", "seek", "destroy") @@ -165,7 +178,8 @@ def completefunc(self, text, state): if not text and state < len(self._seq): return self._seq[state] if not state: - self._tmp_matches = [candidate for candidate in self._seq if candidate.startswith(text)] + self._tmp_matches = [ + candidate for candidate in self._seq if candidate.startswith(text)] if state < len(self._tmp_matches): return self._tmp_matches[state] diff --git a/gr-utils/plot_tools/gr_plot b/gr-utils/plot_tools/gr_plot index 84601fda02f..14fb3a4c867 100755 --- a/gr-utils/plot_tools/gr_plot +++ b/gr-utils/plot_tools/gr_plot @@ -16,9 +16,9 @@ def main(): args = parser.parse_args() plot_data(None, args.files, args) + if __name__ == "__main__": try: main() except KeyboardInterrupt: pass - diff --git a/gr-utils/plot_tools/gr_plot_const b/gr-utils/plot_tools/gr_plot_const index 18f781e5162..aa4350eb5ca 100755 --- a/gr-utils/plot_tools/gr_plot_const +++ b/gr-utils/plot_tools/gr_plot_const @@ -76,7 +76,8 @@ class draw_constellation: [0.45, 0.01, 0.05, 0.05], frameon=True ) self.button_left = Button(self.button_left_axes, "<") - self.button_left_callback = self.button_left.on_clicked(self.button_left_click) + self.button_left_callback = self.button_left.on_clicked( + self.button_left_click) self.button_right_axes = self.fig.add_axes( [0.50, 0.01, 0.05, 0.05], frameon=True @@ -112,7 +113,8 @@ class draw_constellation: self.imags = numpy.array([i.imag for i in iq]) self.time = numpy.array( - [i * (1 / self.sample_rate) for i in range(len(self.reals))] + [i * (1 / self.sample_rate) + for i in range(len(self.reals))] ) return True else: @@ -126,8 +128,10 @@ class draw_constellation: r = self.get_data() # Subplot for real and imaginary parts of signal - self.sp_iq = self.fig.add_subplot(2, 1, 1, position=[0.075, 0.2, 0.4, 0.6]) - self.sp_iq.set_title(("I&Q"), fontsize=self.title_font_size, fontweight="bold") + self.sp_iq = self.fig.add_subplot( + 2, 1, 1, position=[0.075, 0.2, 0.4, 0.6]) + self.sp_iq.set_title( + ("I&Q"), fontsize=self.title_font_size, fontweight="bold") self.sp_iq.set_xlabel( "Time (s)", fontsize=self.label_font_size, fontweight="bold" ) @@ -139,7 +143,8 @@ class draw_constellation: ) # Subplot for constellation plot - self.sp_const = self.fig.add_subplot(2, 2, 1, position=[0.575, 0.2, 0.4, 0.6]) + self.sp_const = self.fig.add_subplot( + 2, 2, 1, position=[0.575, 0.2, 0.4, 0.6]) self.sp_const.set_title( ("Constellation"), fontsize=self.title_font_size, fontweight="bold" ) @@ -219,8 +224,8 @@ class draw_constellation: curxlim = numpy.array(self.xlim) if newxlim[0] != curxlim[0] or newxlim[1] != curxlim[1]: self.xlim = newxlim - r = self.reals[int(ceil(self.xlim[0])) : int(ceil(self.xlim[1]))] - i = self.imags[int(ceil(self.xlim[0])) : int(ceil(self.xlim[1]))] + r = self.reals[int(ceil(self.xlim[0])): int(ceil(self.xlim[1]))] + i = self.imags[int(ceil(self.xlim[0])): int(ceil(self.xlim[1]))] self.plot_const[0].set_data(r, i) self.sp_const.axis([-2, 2, -2, 2]) @@ -297,7 +302,8 @@ def find(item_in, list_search): def main(): description = "Takes a GNU Radio complex binary file and displays the I&Q data versus time and the constellation plot (I vs. Q). You can set the block size to specify how many points to read in at a time and the start position in the file. By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples." - parser = ArgumentParser(conflict_handler="resolve", description=description) + parser = ArgumentParser(conflict_handler="resolve", + description=description) parser.add_argument( "-B", "--block", @@ -319,7 +325,8 @@ def main(): default=1.0, help="Set the sampler rate of the data [default=%(default)r]", ) - parser.add_argument("file", metavar="FILE", help="Input file with complex samples") + parser.add_argument("file", metavar="FILE", + help="Input file with complex samples") args = parser.parse_args() dc = draw_constellation(args.file, args) diff --git a/gr-utils/plot_tools/gr_plot_fft b/gr-utils/plot_tools/gr_plot_fft index 9851c080072..e57eb234d1b 100755 --- a/gr-utils/plot_tools/gr_plot_fft +++ b/gr-utils/plot_tools/gr_plot_fft @@ -13,12 +13,14 @@ from gnuradio.plot_fft_base import plot_fft_base # This is a wrapper program for plot_fft_base. It handles any data # type and defaults to complex64. + def main(): parser = plot_fft_base.setup_options() args = parser.parse_args() plot_fft_base(None, args.file, args) + if __name__ == "__main__": try: main() diff --git a/gr-utils/plot_tools/gr_plot_iq b/gr-utils/plot_tools/gr_plot_iq index ba3838c0817..77833ee2562 100755 --- a/gr-utils/plot_tools/gr_plot_iq +++ b/gr-utils/plot_tools/gr_plot_iq @@ -79,7 +79,8 @@ class draw_iq: [0.45, 0.01, 0.05, 0.05], frameon=True ) self.button_left = Button(self.button_left_axes, "<") - self.button_left_callback = self.button_left.on_clicked(self.button_left_click) + self.button_left_callback = self.button_left.on_clicked( + self.button_left_click) self.button_right_axes = self.fig.add_axes( [0.50, 0.01, 0.05, 0.05], frameon=True @@ -119,15 +120,18 @@ class draw_iq: self.get_data() # Subplot for real and imaginary parts of signal - self.sp_iq = self.fig.add_subplot(2, 1, 1, position=[0.075, 0.14, 0.85, 0.67]) - self.sp_iq.set_title(("I&Q"), fontsize=self.title_font_size, fontweight="bold") + self.sp_iq = self.fig.add_subplot( + 2, 1, 1, position=[0.075, 0.14, 0.85, 0.67]) + self.sp_iq.set_title( + ("I&Q"), fontsize=self.title_font_size, fontweight="bold") self.sp_iq.set_xlabel( "Time (s)", fontsize=self.label_font_size, fontweight="bold" ) self.sp_iq.set_ylabel( "Amplitude (V)", fontsize=self.label_font_size, fontweight="bold" ) - self.plot_iq = plot(self.time, self.reals, "bo-", self.time, self.imags, "ro-") + self.plot_iq = plot(self.time, self.reals, "bo-", + self.time, self.imags, "ro-") self.sp_iq.set_ylim( [ 1.5 * min([self.reals.min(), self.imags.min()]), @@ -189,7 +193,8 @@ def find(item_in, list_search): def main(): description = "Takes a GNU Radio complex binary file and displays the I&Q data versus time. You can set the block size to specify how many points to read in at a time and the start position in the file. By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples." - parser = ArgumentParser(conflict_handler="resolve", description=description) + parser = ArgumentParser(conflict_handler="resolve", + description=description) parser.add_argument( "-B", "--block", @@ -211,7 +216,8 @@ def main(): default=1.0, help="Set the sampler rate of the data [default=%(default)r]", ) - parser.add_argument("file", metavar="FILE", help="Input file with complex samples") + parser.add_argument("file", metavar="FILE", + help="Input file with complex samples") args = parser.parse_args() diff --git a/gr-utils/plot_tools/gr_plot_psd b/gr-utils/plot_tools/gr_plot_psd index 9576eeac9b5..f8c75bfe52a 100755 --- a/gr-utils/plot_tools/gr_plot_psd +++ b/gr-utils/plot_tools/gr_plot_psd @@ -13,12 +13,14 @@ from gnuradio.plot_psd_base import plot_psd_base # This is a wrapper program for plot_psd_base. It handles any data # type and defaults to complex64. + def main(): parser = plot_psd_base.setup_options() args = parser.parse_args() plot_psd_base(None, args.file, args) + if __name__ == "__main__": try: main() diff --git a/gr-utils/plot_tools/gr_plot_qt b/gr-utils/plot_tools/gr_plot_qt index aada9e0bba4..cd24270ab45 100755 --- a/gr-utils/plot_tools/gr_plot_qt +++ b/gr-utils/plot_tools/gr_plot_qt @@ -28,7 +28,8 @@ except ImportError: print("Could not import from pyqt_plot. Please build with \"pyuic4 pyqt_plot.ui -o pyqt_plot.py\"") raise SystemExit(1) -import sys, os +import sys +import os from optparse import OptionParser from gnuradio import eng_notation @@ -62,8 +63,8 @@ class SpectrogramData(Qwt.QwtRasterData): try: f = int(self.freq.searchsorted(x)) t = int(self.time.searchsorted(y)) - return self.sp[f][t-1] - except AttributeError: # if no file loaded yet + return self.sp[f][t - 1] + except AttributeError: # if no file loaded yet return 0 @@ -88,10 +89,14 @@ class gr_plot_qt(QtGui.QMainWindow): # Set up basic plot attributes self.gui.timePlot.setAxisTitle(self.gui.timePlot.xBottom, "Time (sec)") - self.gui.timePlot.setAxisTitle(self.gui.timePlot.yLeft, "Amplitude (V)") - self.gui.freqPlot.setAxisTitle(self.gui.freqPlot.xBottom, "Frequency (Hz)") - self.gui.freqPlot.setAxisTitle(self.gui.freqPlot.yLeft, "Magnitude (dB)") - self.gui.specPlot.setAxisTitle(self.gui.specPlot.xBottom, "Frequency (Hz)") + self.gui.timePlot.setAxisTitle( + self.gui.timePlot.yLeft, "Amplitude (V)") + self.gui.freqPlot.setAxisTitle( + self.gui.freqPlot.xBottom, "Frequency (Hz)") + self.gui.freqPlot.setAxisTitle( + self.gui.freqPlot.yLeft, "Magnitude (dB)") + self.gui.specPlot.setAxisTitle( + self.gui.specPlot.xBottom, "Frequency (Hz)") self.gui.specPlot.setAxisTitle(self.gui.specPlot.yLeft, "Time (sec)") # Set up FFT size combo box @@ -99,9 +104,11 @@ class gr_plot_qt(QtGui.QMainWindow): "4096", "8192", "16384", "32768"] self.gui.psdFFTComboBox.addItems(self.fftsizes) self.gui.specFFTComboBox.addItems(self.fftsizes) - pos = self.gui.psdFFTComboBox.findText(Qt.QString("%1").arg(self.psdfftsize)) + pos = self.gui.psdFFTComboBox.findText( + Qt.QString("%1").arg(self.psdfftsize)) self.gui.psdFFTComboBox.setCurrentIndex(pos) - pos = self.gui.specFFTComboBox.findText(Qt.QString("%1").arg(self.specfftsize)) + pos = self.gui.specFFTComboBox.findText( + Qt.QString("%1").arg(self.specfftsize)) self.gui.specFFTComboBox.setCurrentIndex(pos) self.connect(self.gui.psdFFTComboBox, @@ -112,10 +119,10 @@ class gr_plot_qt(QtGui.QMainWindow): self.specFFTComboBoxEdit) # Set up color scheme box - self.color_modes = {"Black on White" : self.color_black_on_white, - "White on Black" : self.color_white_on_black, - "Blue on Black" : self.color_blue_on_black, - "Green on Black" : self.color_green_on_black} + self.color_modes = {"Black on White": self.color_black_on_white, + "White on Black": self.color_white_on_black, + "Blue on Black": self.color_blue_on_black, + "Green on Black": self.color_green_on_black} self.gui.colorComboBox.addItems(self.color_modes.keys()) pos = self.gui.colorComboBox.findText("Blue on Black") self.gui.colorComboBox.setCurrentIndex(pos) @@ -123,12 +130,11 @@ class gr_plot_qt(QtGui.QMainWindow): Qt.SIGNAL("activated (const QString&)"), self.colorComboBoxEdit) - # Set up line style combo box - self.line_styles = {"None" : Qwt.QwtSymbol.NoSymbol, - "Circle" : Qwt.QwtSymbol.Ellipse, - "Diamond" : Qwt.QwtSymbol.Rect, - "Triangle" : Qwt.QwtSymbol.Triangle} + self.line_styles = {"None": Qwt.QwtSymbol.NoSymbol, + "Circle": Qwt.QwtSymbol.Ellipse, + "Diamond": Qwt.QwtSymbol.Rect, + "Triangle": Qwt.QwtSymbol.Triangle} self.gui.lineStyleComboBox.addItems(self.line_styles.keys()) pos = self.gui.lineStyleComboBox.findText("None") self.gui.lineStyleComboBox.setCurrentIndex(pos) @@ -220,7 +226,6 @@ class gr_plot_qt(QtGui.QMainWindow): self.rcurve.setSymbol(self.rsym) self.icurve.setSymbol(self.isym) - self.icurve.attach(self.gui.timePlot) self.rcurve.attach(self.gui.timePlot) @@ -264,7 +269,6 @@ class gr_plot_qt(QtGui.QMainWindow): self.gui.styleSizeSpinBox.setRange(1, 20) self.gui.styleSizeSpinBox.setValue(5) - # Connect a signal for when the sample rate changes self.set_sample_rate(self.sample_rate) self.connect(self.gui.sampleRateLineEdit, @@ -279,7 +283,7 @@ class gr_plot_qt(QtGui.QMainWindow): def open_file(self): filename = Qt.QFileDialog.getOpenFileName(self, "Open", ".") if(filename != ""): - #print(filename) + # print(filename) self.initialize(filename) def reload_file(self): @@ -305,8 +309,7 @@ class gr_plot_qt(QtGui.QMainWindow): self.get_psd() self.get_specgram() self.gui.plotHBar.setSliderPosition(0) - self.gui.plotHBar.setMaximum(self.signal_size-self.block_length) - + self.gui.plotHBar.setMaximum(self.signal_size - self.block_length) self.update_time_curves() self.update_psd_curves() @@ -314,26 +317,28 @@ class gr_plot_qt(QtGui.QMainWindow): def init_data_input(self): self.hfile.seek(0, os.SEEK_END) - self.signal_size = self.hfile.tell()/self.sizeof_data + self.signal_size = self.hfile.tell() / self.sizeof_data #print("Sizeof File: ", self.signal_size) self.hfile.seek(0, os.SEEK_SET) def get_data(self, start, end): if(end > start): - self.hfile.seek(start*self.sizeof_data, os.SEEK_SET) + self.hfile.seek(start * self.sizeof_data, os.SEEK_SET) self.position = start try: iq = numpy.fromfile(self.hfile, dtype=self.datatype, - count=end-start) + count=end - start) - if(len(iq) < (end-start)): + if(len(iq) < (end - start)): end = start + len(iq) - self.gui.filePosLengthLineEdit.setText(Qt.QString("%1").arg(len(iq))) + self.gui.filePosLengthLineEdit.setText( + Qt.QString("%1").arg(len(iq))) self.file_length_changed() tstep = 1.0 / self.sample_rate self.iq = iq - self.time = [tstep*(self.position + i) for i in range(len(self.iq))] + self.time = [tstep * (self.position + i) + for i in range(len(self.iq))] self.set_file_pos_box(start, end) except MemoryError: @@ -346,22 +351,22 @@ class gr_plot_qt(QtGui.QMainWindow): winpoints = self.winfunc(self.psdfftsize) iq_psd, freq = mlab.psd(self.iq, Fs=self.sample_rate, NFFT=self.psdfftsize, - noverlap=self.psdfftsize/4.0, + noverlap=self.psdfftsize / 4.0, window=winpoints, scale_by_freq=False) - self.iq_psd = 10.0*numpy.log10(abs(numpy.fft.fftshift(iq_psd))) - self.freq = freq - self.sample_rate/2.0 + self.iq_psd = 10.0 * numpy.log10(abs(numpy.fft.fftshift(iq_psd))) + self.freq = freq - self.sample_rate / 2.0 def get_specgram(self): winpoints = self.winfunc(self.specfftsize) iq_spec, f, t = mlab.specgram(self.iq, Fs=self.sample_rate, NFFT=self.specfftsize, - noverlap=self.specfftsize/4.0, + noverlap=self.specfftsize / 4.0, window=winpoints, scale_by_freq=False) - self.iq_spec = 10.0*numpy.log10(abs(iq_spec)) + self.iq_spec = 10.0 * numpy.log10(abs(iq_spec)) self.spec_f = f self.spec_t = t @@ -421,22 +426,25 @@ class gr_plot_qt(QtGui.QMainWindow): self.gui.filePosStartLineEdit.setText(Qt.QString("%1").arg(start)) self.gui.filePosStopLineEdit.setText(Qt.QString("%1").arg(end)) - self.gui.filePosLengthLineEdit.setText(Qt.QString("%1").arg(end-start)) + self.gui.filePosLengthLineEdit.setText( + Qt.QString("%1").arg(end - start)) self.gui.fileTimeStartLineEdit.setText(Qt.QString("%1").arg(tstart)) self.gui.fileTimeStopLineEdit.setText(Qt.QString("%1").arg(tend)) - self.gui.fileTimeLengthLineEdit.setText(Qt.QString("%1").arg(tend-tstart)) + self.gui.fileTimeLengthLineEdit.setText( + Qt.QString("%1").arg(tend - tstart)) def file_position_changed(self): - start = self.gui.filePosStartLineEdit.text().toInt() - end = self.gui.filePosStopLineEdit.text().toInt() + start = self.gui.filePosStartLineEdit.text().toInt() + end = self.gui.filePosStopLineEdit.text().toInt() if((start[1] == True) and (end[1] == True)): self.cur_start = start[0] self.cur_stop = end[0] tstart = self.cur_start / self.sample_rate tend = self.cur_stop / self.sample_rate - self.gui.fileTimeStartLineEdit.setText(Qt.QString("%1").arg(tstart)) + self.gui.fileTimeStartLineEdit.setText( + Qt.QString("%1").arg(tstart)) self.gui.fileTimeStopLineEdit.setText(Qt.QString("%1").arg(tend)) self.get_data(self.cur_start, self.cur_stop) @@ -452,17 +460,18 @@ class gr_plot_qt(QtGui.QMainWindow): except AttributeError: pass - def file_time_changed(self): tstart = self.gui.fileTimeStartLineEdit.text().toDouble() - tstop = self.gui.fileTimeStopLineEdit.text().toDouble() + tstop = self.gui.fileTimeStopLineEdit.text().toDouble() if((tstart[1] == True) and (tstop[1] == True)): self.cur_start = int(tstart[0] * self.sample_rate) self.cur_stop = int(tstop[0] * self.sample_rate) self.get_data(self.cur_start, self.cur_stop) - self.gui.filePosStartLineEdit.setText(Qt.QString("%1").arg(self.cur_start)) - self.gui.filePosStopLineEdit.setText(Qt.QString("%1").arg(self.cur_stop)) + self.gui.filePosStartLineEdit.setText( + Qt.QString("%1").arg(self.cur_start)) + self.gui.filePosStopLineEdit.setText( + Qt.QString("%1").arg(self.cur_stop)) self.update_time_curves() self.update_psd_curves() @@ -483,7 +492,8 @@ class gr_plot_qt(QtGui.QMainWindow): tstart = self.cur_start / self.sample_rate tend = self.cur_stop / self.sample_rate tlen = self.block_length / self.sample_rate - self.gui.fileTimeStartLineEdit.setText(Qt.QString("%1").arg(tstart)) + self.gui.fileTimeStartLineEdit.setText( + Qt.QString("%1").arg(tstart)) self.gui.fileTimeStopLineEdit.setText(Qt.QString("%1").arg(tend)) self.gui.fileTimeLengthLineEdit.setText(Qt.QString("%1").arg(tlen)) @@ -511,7 +521,8 @@ class gr_plot_qt(QtGui.QMainWindow): tstart = self.cur_start / self.sample_rate tend = self.cur_stop / self.sample_rate tlen = self.block_length / self.sample_rate - self.gui.fileTimeStartLineEdit.setText(Qt.QString("%1").arg(tstart)) + self.gui.fileTimeStartLineEdit.setText( + Qt.QString("%1").arg(tstart)) self.gui.fileTimeStopLineEdit.setText(Qt.QString("%1").arg(tend)) self.gui.fileTimeLengthLineEdit.setText(Qt.QString("%1").arg(tlen)) @@ -526,7 +537,6 @@ class gr_plot_qt(QtGui.QMainWindow): else: self.set_file_pos_box(self.cur_start, self.cur_stop) - def update_time_curves(self): self.icurve.setData(self.time, self.iq.imag) self.rcurve.setData(self.time, self.iq.real) @@ -645,7 +655,6 @@ class gr_plot_qt(QtGui.QMainWindow): self.gui.timePlot.replot() self.gui.freqPlot.replot() - def color_green_on_black(self): green = QtGui.qRgb(0x00, 0xFF, 0x00) red = QtGui.qRgb(0xFF, 0x00, 0x50) @@ -688,11 +697,13 @@ class gr_plot_qt(QtGui.QMainWindow): self.gui.timePlot.replot() self.gui.freqPlot.replot() + def setup_options(): - usage="%prog: [options] (input_filename)" + usage = "%prog: [options] (input_filename)" description = "" - parser = OptionParser(conflict_handler="resolve", usage=usage, description=description) + parser = OptionParser(conflict_handler="resolve", + usage=usage, description=description) parser.add_option("-B", "--block-length", type="int", default=8192, help="Specify the block size [default=%default]") parser.add_option("-s", "--start", type="int", default=0, @@ -706,9 +717,10 @@ def setup_options(): return parser + def main(args): parser = setup_options() - (options, args) = parser.parse_args () + (options, args) = parser.parse_args() if(len(args) == 1): filename = args[0] @@ -719,6 +731,6 @@ def main(args): gplt = gr_plot_qt(app, filename, options) app.exec_() + if __name__ == '__main__': main(sys.argv) - diff --git a/gr-utils/plot_tools/plot_data.py b/gr-utils/plot_tools/plot_data.py index 4a42659514d..18e7ae87e4b 100644 --- a/gr-utils/plot_tools/plot_data.py +++ b/gr-utils/plot_tools/plot_data.py @@ -33,6 +33,7 @@ "int8": numpy.int8, } + class plot_data(object): def __init__(self, datatype, filenames, options): self.hfile = list() @@ -48,7 +49,8 @@ def __init__(self, datatype, filenames, options): self.datatype = datatype if self.datatype is None: self.datatype = datatype_lookup[options.data_type] - self.sizeof_data = self.datatype().nbytes # number of bytes per sample in file + # number of bytes per sample in file + self.sizeof_data = self.datatype().nbytes self.axis_font_size = 16 self.label_font_size = 18 @@ -60,20 +62,25 @@ def __init__(self, datatype, filenames, options): rcParams['xtick.labelsize'] = self.axis_font_size rcParams['ytick.labelsize'] = self.axis_font_size - self.text_file_pos = figtext(0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size) - self.text_block = figtext(0.40, 0.88, ("Block Size: %d" % self.block_length), - weight="heavy", size=self.text_size) - self.text_sr = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate), - weight="heavy", size=self.text_size) + self.text_file_pos = figtext( + 0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size) + self.text_block = figtext(0.40, 0.88, ("Block Size: %d" % self.block_length), + weight="heavy", size=self.text_size) + self.text_sr = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate), + weight="heavy", size=self.text_size) self.make_plots() - self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True) + self.button_left_axes = self.fig.add_axes( + [0.45, 0.01, 0.05, 0.05], frameon=True) self.button_left = Button(self.button_left_axes, "<") - self.button_left_callback = self.button_left.on_clicked(self.button_left_click) + self.button_left_callback = self.button_left.on_clicked( + self.button_left_click) - self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True) + self.button_right_axes = self.fig.add_axes( + [0.50, 0.01, 0.05, 0.05], frameon=True) self.button_right = Button(self.button_right_axes, ">") - self.button_right_callback = self.button_right.on_clicked(self.button_right_click) + self.button_right_callback = self.button_right.on_clicked( + self.button_right_click) self.xlim = self.sp_f.get_xlim() @@ -82,20 +89,27 @@ def __init__(self, datatype, filenames, options): show() def get_data(self, hfile): - self.text_file_pos.set_text("File Position: %d" % (hfile.tell()//self.sizeof_data)) + self.text_file_pos.set_text( + "File Position: %d" % (hfile.tell() // self.sizeof_data)) try: - f = numpy.fromfile(hfile, dtype=self.datatype, count=self.block_length) + f = numpy.fromfile(hfile, dtype=self.datatype, + count=self.block_length) except MemoryError: print("End of File") else: self.f = numpy.array(f) - self.time = numpy.array([i*(1 / self.sample_rate) for i in range(len(self.f))]) + self.time = numpy.array([i * (1 / self.sample_rate) + for i in range(len(self.f))]) def make_plots(self): - self.sp_f = self.fig.add_subplot(2,1,1, position=[0.075, 0.2, 0.875, 0.6]) - self.sp_f.set_title(("Amplitude"), fontsize=self.title_font_size, fontweight="bold") - self.sp_f.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold") - self.sp_f.set_ylabel("Amplitude (V)", fontsize=self.label_font_size, fontweight="bold") + self.sp_f = self.fig.add_subplot( + 2, 1, 1, position=[0.075, 0.2, 0.875, 0.6]) + self.sp_f.set_title( + ("Amplitude"), fontsize=self.title_font_size, fontweight="bold") + self.sp_f.set_xlabel( + "Time (s)", fontsize=self.label_font_size, fontweight="bold") + self.sp_f.set_ylabel( + "Amplitude (V)", fontsize=self.label_font_size, fontweight="bold") self.plot_f = list() maxval = -1e12 @@ -103,7 +117,7 @@ def make_plots(self): for hf in self.hfile: # if specified on the command-line, set file pointer - hf.seek(self.sizeof_data*self.start, 1) + hf.seek(self.sizeof_data * self.start, 1) self.get_data(hf) @@ -112,7 +126,7 @@ def make_plots(self): maxval = max(maxval, self.f.max()) minval = min(minval, self.f.min()) - self.sp_f.set_ylim([1.5*minval, 1.5*maxval]) + self.sp_f.set_ylim([1.5 * minval, 1.5 * maxval]) self.leg = self.sp_f.legend(self.plot_f, self.legend_text) @@ -121,13 +135,13 @@ def make_plots(self): def update_plots(self): maxval = -1e12 minval = 1e12 - for hf,p in zip(self.hfile,self.plot_f): + for hf, p in zip(self.hfile, self.plot_f): self.get_data(hf) p.set_data([self.time, self.f]) maxval = max(maxval, self.f.max()) minval = min(minval, self.f.min()) - self.sp_f.set_ylim([1.5*minval, 1.5*maxval]) + self.sp_f.set_ylim([1.5 * minval, 1.5 * maxval]) draw() @@ -153,31 +167,33 @@ def step_forward(self): def step_backward(self): for hf in self.hfile: # Step back in file position - if(hf.tell() >= 2*self.sizeof_data*self.block_length ): - hf.seek(-2*self.sizeof_data*self.block_length, 1) + if(hf.tell() >= 2 * self.sizeof_data * self.block_length): + hf.seek(-2 * self.sizeof_data * self.block_length, 1) else: - hf.seek(-hf.tell(),1) + hf.seek(-hf.tell(), 1) self.update_plots() @staticmethod def setup_options(): description = "Takes a GNU Radio binary file and displays the samples versus time. You can set the block size to specify how many points to read in at a time and the start position in the file. By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples." - parser = ArgumentParser(conflict_handler="resolve", description=description) + parser = ArgumentParser( + conflict_handler="resolve", description=description) parser.add_argument("-d", "--data-type", default="complex64", - choices=("complex64", "float32", "uint32", "int32", "uint16", - "int16", "uint8", "int8"), - help="Specify the data type [default=%(default)r]") + choices=("complex64", "float32", "uint32", "int32", "uint16", + "int16", "uint8", "int8"), + help="Specify the data type [default=%(default)r]") parser.add_argument("-B", "--block", type=int, default=1000, - help="Specify the block size [default=%(default)r]") + help="Specify the block size [default=%(default)r]") parser.add_argument("-s", "--start", type=int, default=0, - help="Specify where to start in the file [default=%(default)r]") + help="Specify where to start in the file [default=%(default)r]") parser.add_argument("-R", "--sample-rate", type=float, default=1.0, - help="Set the sampler rate of the data [default=%(default)r]") + help="Set the sampler rate of the data [default=%(default)r]") parser.add_argument("files", metavar="FILE", nargs='+', - help="Input file with samples") + help="Input file with samples") return parser + def find(item_in, list_search): try: return list_search.index(item_in) != None diff --git a/gr-utils/plot_tools/plot_fft_base.py b/gr-utils/plot_tools/plot_fft_base.py index 9fa3611e14c..8de668d4c41 100644 --- a/gr-utils/plot_tools/plot_fft_base.py +++ b/gr-utils/plot_tools/plot_fft_base.py @@ -31,7 +31,8 @@ def __init__(self, datatype, filename, options): self.datatype = datatype if self.datatype is None: self.datatype = datatype_lookup[options.data_type] - self.sizeof_data = self.datatype().nbytes # number of bytes per sample in file + # number of bytes per sample in file + self.sizeof_data = self.datatype().nbytes self.axis_font_size = 16 self.label_font_size = 18 @@ -43,21 +44,27 @@ def __init__(self, datatype, filename, options): rcParams['xtick.labelsize'] = self.axis_font_size rcParams['ytick.labelsize'] = self.axis_font_size - self.text_file = figtext(0.10, 0.94, ("File: %s" % filename), weight="heavy", size=self.text_size) - self.text_file_pos = figtext(0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size) - self.text_block = figtext(0.35, 0.88, ("Block Size: %d" % self.block_length), - weight="heavy", size=self.text_size) - self.text_sr = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate), - weight="heavy", size=self.text_size) + self.text_file = figtext( + 0.10, 0.94, ("File: %s" % filename), weight="heavy", size=self.text_size) + self.text_file_pos = figtext( + 0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size) + self.text_block = figtext(0.35, 0.88, ("Block Size: %d" % self.block_length), + weight="heavy", size=self.text_size) + self.text_sr = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate), + weight="heavy", size=self.text_size) self.make_plots() - self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True) + self.button_left_axes = self.fig.add_axes( + [0.45, 0.01, 0.05, 0.05], frameon=True) self.button_left = Button(self.button_left_axes, "<") - self.button_left_callback = self.button_left.on_clicked(self.button_left_click) + self.button_left_callback = self.button_left.on_clicked( + self.button_left_click) - self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True) + self.button_right_axes = self.fig.add_axes( + [0.50, 0.01, 0.05, 0.05], frameon=True) self.button_right = Button(self.button_right_axes, ">") - self.button_right_callback = self.button_right.on_clicked(self.button_right_click) + self.button_right_callback = self.button_right.on_clicked( + self.button_right_click) self.xlim = self.sp_iq.get_xlim() @@ -70,7 +77,8 @@ def get_data(self): self.position = self.hfile.tell() / self.sizeof_data self.text_file_pos.set_text("File Position: %d" % (self.position)) try: - self.iq = numpy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length) + self.iq = numpy.fromfile( + self.hfile, dtype=self.datatype, count=self.block_length) except MemoryError: print("End of File") else: @@ -78,14 +86,16 @@ def get_data(self): tstep = 1.0 / self.sample_rate #self.time = numpy.array([tstep*(self.position + i) for i in range(len(self.iq))]) - self.time = numpy.array([tstep*(i) for i in range(len(self.iq))]) + self.time = numpy.array([tstep * (i) for i in range(len(self.iq))]) self.freq = self.calc_freq(self.time, self.sample_rate) def dofft(self, iq): N = len(iq) - iq_fft = numpy.fft.fftshift(numpy.fft.fft(iq)) # fft and shift axis - iq_fft = 20*numpy.log10(abs((iq_fft+1e-15) / N)) # convert to decibels, adjust power + iq_fft = numpy.fft.fftshift( + numpy.fft.fft(iq)) # fft and shift axis + # convert to decibels, adjust power + iq_fft = 20 * numpy.log10(abs((iq_fft + 1e-15) / N)) # adding 1e-15 (-300 dB) to protect against value errors if an item in iq_fft is 0 return iq_fft @@ -93,29 +103,37 @@ def calc_freq(self, time, sample_rate): N = len(time) Fs = 1.0 / (max(time) - min(time)) Fn = 0.5 * sample_rate - freq = numpy.array([-Fn + i*Fs for i in range(N)]) + freq = numpy.array([-Fn + i * Fs for i in range(N)]) return freq def make_plots(self): # if specified on the command-line, set file pointer - self.hfile.seek(self.sizeof_data*self.start, 1) + self.hfile.seek(self.sizeof_data * self.start, 1) # Subplot for real and imaginary parts of signal - self.sp_iq = self.fig.add_subplot(2,2,1, position=[0.075, 0.2, 0.4, 0.6]) - self.sp_iq.set_title(("I&Q"), fontsize=self.title_font_size, fontweight="bold") - self.sp_iq.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold") - self.sp_iq.set_ylabel("Amplitude (V)", fontsize=self.label_font_size, fontweight="bold") + self.sp_iq = self.fig.add_subplot( + 2, 2, 1, position=[0.075, 0.2, 0.4, 0.6]) + self.sp_iq.set_title( + ("I&Q"), fontsize=self.title_font_size, fontweight="bold") + self.sp_iq.set_xlabel( + "Time (s)", fontsize=self.label_font_size, fontweight="bold") + self.sp_iq.set_ylabel( + "Amplitude (V)", fontsize=self.label_font_size, fontweight="bold") # Subplot for FFT plot - self.sp_fft = self.fig.add_subplot(2,2,2, position=[0.575, 0.2, 0.4, 0.6]) - self.sp_fft.set_title(("FFT"), fontsize=self.title_font_size, fontweight="bold") - self.sp_fft.set_xlabel("Frequency (Hz)", fontsize=self.label_font_size, fontweight="bold") - self.sp_fft.set_ylabel("Power Spectrum (dBm)", fontsize=self.label_font_size, fontweight="bold") + self.sp_fft = self.fig.add_subplot( + 2, 2, 2, position=[0.575, 0.2, 0.4, 0.6]) + self.sp_fft.set_title( + ("FFT"), fontsize=self.title_font_size, fontweight="bold") + self.sp_fft.set_xlabel( + "Frequency (Hz)", fontsize=self.label_font_size, fontweight="bold") + self.sp_fft.set_ylabel("Power Spectrum (dBm)", + fontsize=self.label_font_size, fontweight="bold") self.get_data() - self.plot_iq = self.sp_iq.plot([], 'bo-') # make plot for reals - self.plot_iq += self.sp_iq.plot([], 'ro-') # make plot for imags + self.plot_iq = self.sp_iq.plot([], 'bo-') # make plot for reals + self.plot_iq += self.sp_iq.plot([], 'ro-') # make plot for imags self.draw_time() # draw the plot self.plot_fft = self.sp_fft.plot([], 'bo-') # make plot for FFT @@ -129,13 +147,13 @@ def draw_time(self): self.plot_iq[0].set_data([self.time, reals]) self.plot_iq[1].set_data([self.time, imags]) self.sp_iq.set_xlim(self.time.min(), self.time.max()) - self.sp_iq.set_ylim([1.5*min([reals.min(), imags.min()]), - 1.5*max([reals.max(), imags.max()])]) + self.sp_iq.set_ylim([1.5 * min([reals.min(), imags.min()]), + 1.5 * max([reals.max(), imags.max()])]) def draw_fft(self): self.plot_fft[0].set_data([self.freq, self.iq_fft]) self.sp_fft.set_xlim(self.freq.min(), self.freq.max()) - self.sp_fft.set_ylim([self.iq_fft.min()-10, self.iq_fft.max()+10]) + self.sp_fft.set_ylim([self.iq_fft.min() - 10, self.iq_fft.max() + 10]) def update_plots(self): self.draw_time() @@ -151,18 +169,19 @@ def zoom(self, event): self.xlim = newxlim #xmin = max(0, int(ceil(self.sample_rate*(self.xlim[0] - self.position)))) #xmax = min(int(ceil(self.sample_rate*(self.xlim[1] - self.position))), len(self.iq)) - xmin = max(0, int(ceil(self.sample_rate*(self.xlim[0])))) - xmax = min(int(ceil(self.sample_rate*(self.xlim[1]))), len(self.iq)) + xmin = max(0, int(ceil(self.sample_rate * (self.xlim[0])))) + xmax = min( + int(ceil(self.sample_rate * (self.xlim[1]))), len(self.iq)) - iq = self.iq[xmin : xmax] - time = self.time[xmin : xmax] + iq = self.iq[xmin: xmax] + time = self.time[xmin: xmax] iq_fft = self.dofft(iq) freq = self.calc_freq(time, self.sample_rate) self.plot_fft[0].set_data(freq, iq_fft) self.sp_fft.axis([freq.min(), freq.max(), - iq_fft.min()-10, iq_fft.max()+10]) + iq_fft.min() - 10, iq_fft.max() + 10]) draw() @@ -188,10 +207,10 @@ def step_forward(self): def step_backward(self): # Step back in file position - if(self.hfile.tell() >= 2*self.sizeof_data*self.block_length ): - self.hfile.seek(-2*self.sizeof_data*self.block_length, 1) + if(self.hfile.tell() >= 2 * self.sizeof_data * self.block_length): + self.hfile.seek(-2 * self.sizeof_data * self.block_length, 1) else: - self.hfile.seek(-self.hfile.tell(),1) + self.hfile.seek(-self.hfile.tell(), 1) self.get_data() self.update_plots() @@ -199,33 +218,37 @@ def step_backward(self): def setup_options(): description = "Takes a GNU Radio complex binary file and displays the I&Q data versus time as well as the frequency domain (FFT) plot. The y-axis values are plotted assuming volts as the amplitude of the I&Q streams and converted into dBm in the frequency domain (the 1/N power adjustment out of the FFT is performed internally). The script plots a certain block of data at a time, specified on the command line as -B or --block. This value defaults to 1000. The start position in the file can be set by specifying -s or --start and defaults to 0 (the start of the file). By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time and frequency axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples." - parser = ArgumentParser(conflict_handler="resolve", description=description) + parser = ArgumentParser( + conflict_handler="resolve", description=description) parser.add_argument("-d", "--data-type", default="complex64", - choices=("complex64", "float32", "uint32", "int32", "uint16", - "int16", "uint8", "int8"), - help="Specify the data type [default=%(default)r]") + choices=("complex64", "float32", "uint32", "int32", "uint16", + "int16", "uint8", "int8"), + help="Specify the data type [default=%(default)r]") parser.add_argument("-B", "--block", type=int, default=1000, - help="Specify the block size [default=%(default)r]") + help="Specify the block size [default=%(default)r]") parser.add_argument("-s", "--start", type=int, default=0, - help="Specify where to start in the file [default=%(default)r]") + help="Specify where to start in the file [default=%(default)r]") parser.add_argument("-R", "--sample-rate", type=float, default=1.0, - help="Set the sampler rate of the data [default=%(default)r]") + help="Set the sampler rate of the data [default=%(default)r]") parser.add_argument("file", metavar="FILE", - help="Input file with samples") + help="Input file with samples") return parser + def find(item_in, list_search): try: return list_search.index(item_in) != None except ValueError: return False + def main(): parser = plot_fft_base.setup_options() args = parser.parse_args() plot_fft_base(None, args.file, args) + if __name__ == "__main__": try: main() diff --git a/gr-utils/plot_tools/plot_psd_base.py b/gr-utils/plot_tools/plot_psd_base.py index 3d78af0dd1f..88f86f57252 100644 --- a/gr-utils/plot_tools/plot_psd_base.py +++ b/gr-utils/plot_tools/plot_psd_base.py @@ -35,7 +35,8 @@ def __init__(self, datatype, filename, options): self.datatype = datatype if self.datatype is None: self.datatype = datatype_lookup[options.data_type] - self.sizeof_data = self.datatype().nbytes # number of bytes per sample in file + # number of bytes per sample in file + self.sizeof_data = self.datatype().nbytes self.axis_font_size = 16 self.label_font_size = 18 @@ -47,23 +48,27 @@ def __init__(self, datatype, filename, options): rcParams['xtick.labelsize'] = self.axis_font_size rcParams['ytick.labelsize'] = self.axis_font_size - self.text_file = figtext(0.10, 0.95, ("File: %s" % filename), - weight="heavy", size=self.text_size) + self.text_file = figtext(0.10, 0.95, ("File: %s" % filename), + weight="heavy", size=self.text_size) self.text_file_pos = figtext(0.10, 0.92, "File Position: ", weight="heavy", size=self.text_size) - self.text_block = figtext(0.35, 0.92, ("Block Size: %d" % self.block_length), - weight="heavy", size=self.text_size) - self.text_sr = figtext(0.60, 0.915, ("Sample Rate: %.2f" % self.sample_rate), - weight="heavy", size=self.text_size) + self.text_block = figtext(0.35, 0.92, ("Block Size: %d" % self.block_length), + weight="heavy", size=self.text_size) + self.text_sr = figtext(0.60, 0.915, ("Sample Rate: %.2f" % self.sample_rate), + weight="heavy", size=self.text_size) self.make_plots() - self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True) + self.button_left_axes = self.fig.add_axes( + [0.45, 0.01, 0.05, 0.05], frameon=True) self.button_left = Button(self.button_left_axes, "<") - self.button_left_callback = self.button_left.on_clicked(self.button_left_click) + self.button_left_callback = self.button_left.on_clicked( + self.button_left_click) - self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True) + self.button_right_axes = self.fig.add_axes( + [0.50, 0.01, 0.05, 0.05], frameon=True) self.button_right = Button(self.button_right_axes, ">") - self.button_right_callback = self.button_right.on_clicked(self.button_right_click) + self.button_right_callback = self.button_right.on_clicked( + self.button_right_click) self.xlim = numpy.array(self.sp_iq.get_xlim()) @@ -76,7 +81,8 @@ def get_data(self): self.position = self.hfile.tell() / self.sizeof_data self.text_file_pos.set_text("File Position: %d" % self.position) try: - self.iq = numpy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length) + self.iq = numpy.fromfile( + self.hfile, dtype=self.datatype, count=self.block_length) except MemoryError: print("End of File") return False @@ -86,7 +92,8 @@ def get_data(self): if(len(self.iq) > 0): tstep = 1.0 / self.sample_rate #self.time = numpy.array([tstep*(self.position + i) for i in range(len(self.iq))]) - self.time = numpy.array([tstep*(i) for i in range(len(self.iq))]) + self.time = numpy.array([tstep * (i) + for i in range(len(self.iq))]) self.iq_psd, self.freq = self.dopsd(self.iq) return True @@ -98,48 +105,58 @@ def dopsd(self, iq): ''' Need to do this here and plot later so we can do the fftshift ''' overlap = self.psdfftsize / 4 winfunc = numpy.blackman - psd,freq = mlab.psd(iq, self.psdfftsize, self.sample_rate, - window = lambda d: d*winfunc(self.psdfftsize), - noverlap = overlap) - psd = 10.0*numpy.log10(abs(psd)) + psd, freq = mlab.psd(iq, self.psdfftsize, self.sample_rate, + window=lambda d: d * winfunc(self.psdfftsize), + noverlap=overlap) + psd = 10.0 * numpy.log10(abs(psd)) return (psd, freq) def make_plots(self): # if specified on the command-line, set file pointer - self.hfile.seek(self.sizeof_data*self.start, 1) + self.hfile.seek(self.sizeof_data * self.start, 1) iqdims = [[0.075, 0.2, 0.4, 0.6], [0.075, 0.55, 0.4, 0.3]] psddims = [[0.575, 0.2, 0.4, 0.6], [0.575, 0.55, 0.4, 0.3]] specdims = [0.2, 0.125, 0.6, 0.3] # Subplot for real and imaginary parts of signal - self.sp_iq = self.fig.add_subplot(2,2,1, position=iqdims[self.dospec]) - self.sp_iq.set_title(("I&Q"), fontsize=self.title_font_size, fontweight="bold") - self.sp_iq.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold") - self.sp_iq.set_ylabel("Amplitude (V)", fontsize=self.label_font_size, fontweight="bold") + self.sp_iq = self.fig.add_subplot( + 2, 2, 1, position=iqdims[self.dospec]) + self.sp_iq.set_title( + ("I&Q"), fontsize=self.title_font_size, fontweight="bold") + self.sp_iq.set_xlabel( + "Time (s)", fontsize=self.label_font_size, fontweight="bold") + self.sp_iq.set_ylabel( + "Amplitude (V)", fontsize=self.label_font_size, fontweight="bold") # Subplot for PSD plot - self.sp_psd = self.fig.add_subplot(2,2,2, position=psddims[self.dospec]) - self.sp_psd.set_title(("PSD"), fontsize=self.title_font_size, fontweight="bold") - self.sp_psd.set_xlabel("Frequency (Hz)", fontsize=self.label_font_size, fontweight="bold") - self.sp_psd.set_ylabel("Power Spectrum (dBm)", fontsize=self.label_font_size, fontweight="bold") + self.sp_psd = self.fig.add_subplot( + 2, 2, 2, position=psddims[self.dospec]) + self.sp_psd.set_title( + ("PSD"), fontsize=self.title_font_size, fontweight="bold") + self.sp_psd.set_xlabel( + "Frequency (Hz)", fontsize=self.label_font_size, fontweight="bold") + self.sp_psd.set_ylabel("Power Spectrum (dBm)", + fontsize=self.label_font_size, fontweight="bold") r = self.get_data() - self.plot_iq = self.sp_iq.plot([], 'bo-') # make plot for reals - self.plot_iq += self.sp_iq.plot([], 'ro-') # make plot for imags + self.plot_iq = self.sp_iq.plot([], 'bo-') # make plot for reals + self.plot_iq += self.sp_iq.plot([], 'ro-') # make plot for imags self.draw_time(self.time, self.iq) # draw the plot self.plot_psd = self.sp_psd.plot([], 'b') # make plot for PSD self.draw_psd(self.freq, self.iq_psd) # draw the plot - if self.dospec: # Subplot for spectrogram plot - self.sp_spec = self.fig.add_subplot(2,2,3, position=specdims) - self.sp_spec.set_title(("Spectrogram"), fontsize=self.title_font_size, fontweight="bold") - self.sp_spec.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold") - self.sp_spec.set_ylabel("Frequency (Hz)", fontsize=self.label_font_size, fontweight="bold") + self.sp_spec = self.fig.add_subplot(2, 2, 3, position=specdims) + self.sp_spec.set_title( + ("Spectrogram"), fontsize=self.title_font_size, fontweight="bold") + self.sp_spec.set_xlabel( + "Time (s)", fontsize=self.label_font_size, fontweight="bold") + self.sp_spec.set_ylabel( + "Frequency (Hz)", fontsize=self.label_font_size, fontweight="bold") self.draw_spec(self.time, self.iq) @@ -151,12 +168,12 @@ def draw_time(self, t, iq): self.plot_iq[0].set_data([t, reals]) self.plot_iq[1].set_data([t, imags]) self.sp_iq.set_xlim(t.min(), t.max()) - self.sp_iq.set_ylim([1.5*min([reals.min(), imags.min()]), - 1.5*max([reals.max(), imags.max()])]) + self.sp_iq.set_ylim([1.5 * min([reals.min(), imags.min()]), + 1.5 * max([reals.max(), imags.max()])]) def draw_psd(self, f, p): self.plot_psd[0].set_data([f, p]) - self.sp_psd.set_ylim([p.min()-10, p.max()+10]) + self.sp_psd.set_ylim([p.min() - 10, p.max() + 10]) self.sp_psd.set_xlim([f.min(), f.max()]) def draw_spec(self, t, s): @@ -164,8 +181,8 @@ def draw_spec(self, t, s): winfunc = numpy.blackman self.sp_spec.clear() self.sp_spec.specgram(s, self.specfftsize, self.sample_rate, - window = lambda d: d*winfunc(self.specfftsize), - noverlap = overlap, xextent=[t.min(), t.max()]) + window=lambda d: d * winfunc(self.specfftsize), + noverlap=overlap, xextent=[t.min(), t.max()]) def update_plots(self): self.draw_time(self.time, self.iq) @@ -174,7 +191,8 @@ def update_plots(self): if self.dospec: self.draw_spec(self.time, self.iq) - self.xlim = numpy.array(self.sp_iq.get_xlim()) # so zoom doesn't get called + # so zoom doesn't get called + self.xlim = numpy.array(self.sp_iq.get_xlim()) draw() @@ -184,11 +202,12 @@ def zoom(self, event): if(newxlim[0] != curxlim[0] or newxlim[1] != curxlim[1]): #xmin = max(0, int(ceil(self.sample_rate*(newxlim[0] - self.position)))) #xmax = min(int(ceil(self.sample_rate*(newxlim[1] - self.position))), len(self.iq)) - xmin = max(0, int(ceil(self.sample_rate*(newxlim[0])))) - xmax = min(int(ceil(self.sample_rate*(newxlim[1]))), len(self.iq)) + xmin = max(0, int(ceil(self.sample_rate * (newxlim[0])))) + xmax = min( + int(ceil(self.sample_rate * (newxlim[1]))), len(self.iq)) - iq = numpy.array(self.iq[xmin : xmax]) - time = numpy.array(self.time[xmin : xmax]) + iq = numpy.array(self.iq[xmin: xmax]) + time = numpy.array(self.time[xmin: xmax]) iq_psd, freq = self.dopsd(iq) @@ -220,10 +239,10 @@ def step_forward(self): def step_backward(self): # Step back in file position - if(self.hfile.tell() >= 2*self.sizeof_data*self.block_length ): - self.hfile.seek(-2*self.sizeof_data*self.block_length, 1) + if(self.hfile.tell() >= 2 * self.sizeof_data * self.block_length): + self.hfile.seek(-2 * self.sizeof_data * self.block_length, 1) else: - self.hfile.seek(-self.hfile.tell(),1) + self.hfile.seek(-self.hfile.tell(), 1) r = self.get_data() if(r): self.update_plots() @@ -232,40 +251,44 @@ def step_backward(self): def setup_options(): description = "Takes a GNU Radio binary file (with specified data type using --data-type) and displays the I&Q data versus time as well as the power spectral density (PSD) plot. The y-axis values are plotted assuming volts as the amplitude of the I&Q streams and converted into dBm in the frequency domain (the 1/N power adjustment out of the FFT is performed internally). The script plots a certain block of data at a time, specified on the command line as -B or --block. The start position in the file can be set by specifying -s or --start and defaults to 0 (the start of the file). By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time and frequency axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples. Finally, the size of the FFT to use for the PSD and spectrogram plots can be set independently with --psd-size and --spec-size, respectively. The spectrogram plot does not display by default and is turned on with -S or --enable-spec." - parser = ArgumentParser(conflict_handler="resolve", description=description) + parser = ArgumentParser( + conflict_handler="resolve", description=description) parser.add_argument("-d", "--data-type", default="complex64", - choices=("complex64", "float32", "int32", "uint32", "int16", - "uint16", "int8", "uint8" ), - help="Specify the data type [default=%(default)r]") + choices=("complex64", "float32", "int32", "uint32", "int16", + "uint16", "int8", "uint8"), + help="Specify the data type [default=%(default)r]") parser.add_argument("-B", "--block", type=int, default=8192, - help="Specify the block size [default=%(default)r]") + help="Specify the block size [default=%(default)r]") parser.add_argument("-s", "--start", type=int, default=0, - help="Specify where to start in the file [default=%(default)r]") + help="Specify where to start in the file [default=%(default)r]") parser.add_argument("-R", "--sample-rate", type=eng_float, default=1.0, - help="Set the sampler rate of the data [default=%(default)r]") + help="Set the sampler rate of the data [default=%(default)r]") parser.add_argument("--psd-size", type=int, default=1024, - help="Set the size of the PSD FFT [default=%(default)r]") + help="Set the size of the PSD FFT [default=%(default)r]") parser.add_argument("--spec-size", type=int, default=256, - help="Set the size of the spectrogram FFT [default=%(default)r]") + help="Set the size of the spectrogram FFT [default=%(default)r]") parser.add_argument("-S", "--enable-spec", action="store_true", - help="Turn on plotting the spectrogram [default=%(default)r]") + help="Turn on plotting the spectrogram [default=%(default)r]") parser.add_argument("file", metavar="FILE", - help="Input file with samples") + help="Input file with samples") return parser + def find(item_in, list_search): try: return list_search.index(item_in) != None except ValueError: return False + def main(): parser = plot_psd_base.setup_options() args = parser.parse_args() plot_psd_base(None, args.file, args) + if __name__ == "__main__": try: main() diff --git a/gr-utils/plot_tools/pyqt_filter.py b/gr-utils/plot_tools/pyqt_filter.py index d56e45a056c..3f4ee1e5469 100644 --- a/gr-utils/plot_tools/pyqt_filter.py +++ b/gr-utils/plot_tools/pyqt_filter.py @@ -7,8 +7,10 @@ # # WARNING! All changes made in this file will be lost! +from PyQt5.Qwt import QwtPlot from PyQt5 import QtCore, QtGui + class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") @@ -46,22 +48,27 @@ def setupUi(self, MainWindow): self.filterDesignTypeComboBox.addItem("") self.verticalLayout.addWidget(self.filterDesignTypeComboBox) self.globalParamsLayout = QtGui.QFormLayout() - self.globalParamsLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) + self.globalParamsLayout.setFieldGrowthPolicy( + QtGui.QFormLayout.AllNonFixedFieldsGrow) self.globalParamsLayout.setObjectName("globalParamsLayout") self.sampleRateLabel = QtGui.QLabel(self.filterFrame) self.sampleRateLabel.setMaximumSize(QtCore.QSize(16777215, 30)) self.sampleRateLabel.setObjectName("sampleRateLabel") - self.globalParamsLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.sampleRateLabel) + self.globalParamsLayout.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.sampleRateLabel) self.sampleRateEdit = QtGui.QLineEdit(self.filterFrame) self.sampleRateEdit.setMaximumSize(QtCore.QSize(16777215, 30)) self.sampleRateEdit.setObjectName("sampleRateEdit") - self.globalParamsLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.sampleRateEdit) + self.globalParamsLayout.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.sampleRateEdit) self.filterGainLabel = QtGui.QLabel(self.filterFrame) self.filterGainLabel.setObjectName("filterGainLabel") - self.globalParamsLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.filterGainLabel) + self.globalParamsLayout.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.filterGainLabel) self.filterGainEdit = QtGui.QLineEdit(self.filterFrame) self.filterGainEdit.setObjectName("filterGainEdit") - self.globalParamsLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.filterGainEdit) + self.globalParamsLayout.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.filterGainEdit) self.verticalLayout.addLayout(self.globalParamsLayout) self.filterTypeWidget = QtGui.QStackedWidget(self.filterFrame) self.filterTypeWidget.setObjectName("filterTypeWidget") @@ -71,28 +78,36 @@ def setupUi(self, MainWindow): self.formLayout.setObjectName("formLayout") self.endofLpfPassBandLabel = QtGui.QLabel(self.firlpfPage) self.endofLpfPassBandLabel.setObjectName("endofLpfPassBandLabel") - self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.endofLpfPassBandLabel) + self.formLayout.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.endofLpfPassBandLabel) self.endofLpfPassBandEdit = QtGui.QLineEdit(self.firlpfPage) self.endofLpfPassBandEdit.setObjectName("endofLpfPassBandEdit") - self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.endofLpfPassBandEdit) + self.formLayout.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.endofLpfPassBandEdit) self.startofLpfStopBandLabel = QtGui.QLabel(self.firlpfPage) self.startofLpfStopBandLabel.setObjectName("startofLpfStopBandLabel") - self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.startofLpfStopBandLabel) + self.formLayout.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.startofLpfStopBandLabel) self.startofLpfStopBandEdit = QtGui.QLineEdit(self.firlpfPage) self.startofLpfStopBandEdit.setObjectName("startofLpfStopBandEdit") - self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.startofLpfStopBandEdit) + self.formLayout.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.startofLpfStopBandEdit) self.lpfStopBandAttenLabel = QtGui.QLabel(self.firlpfPage) self.lpfStopBandAttenLabel.setObjectName("lpfStopBandAttenLabel") - self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.lpfStopBandAttenLabel) + self.formLayout.setWidget( + 2, QtGui.QFormLayout.LabelRole, self.lpfStopBandAttenLabel) self.lpfStopBandAttenEdit = QtGui.QLineEdit(self.firlpfPage) self.lpfStopBandAttenEdit.setObjectName("lpfStopBandAttenEdit") - self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.lpfStopBandAttenEdit) + self.formLayout.setWidget( + 2, QtGui.QFormLayout.FieldRole, self.lpfStopBandAttenEdit) self.lpfPassBandRippleEdit = QtGui.QLineEdit(self.firlpfPage) self.lpfPassBandRippleEdit.setObjectName("lpfPassBandRippleEdit") - self.formLayout.setWidget(3, QtGui.QFormLayout.FieldRole, self.lpfPassBandRippleEdit) + self.formLayout.setWidget( + 3, QtGui.QFormLayout.FieldRole, self.lpfPassBandRippleEdit) self.lpfPassBandRippleLabel = QtGui.QLabel(self.firlpfPage) self.lpfPassBandRippleLabel.setObjectName("lpfPassBandRippleLabel") - self.formLayout.setWidget(3, QtGui.QFormLayout.LabelRole, self.lpfPassBandRippleLabel) + self.formLayout.setWidget( + 3, QtGui.QFormLayout.LabelRole, self.lpfPassBandRippleLabel) self.filterTypeWidget.addWidget(self.firlpfPage) self.firbpfPage = QtGui.QWidget() self.firbpfPage.setObjectName("firbpfPage") @@ -100,100 +115,130 @@ def setupUi(self, MainWindow): self.formLayout_2.setObjectName("formLayout_2") self.startofBpfPassBandLabel = QtGui.QLabel(self.firbpfPage) self.startofBpfPassBandLabel.setObjectName("startofBpfPassBandLabel") - self.formLayout_2.setWidget(0, QtGui.QFormLayout.LabelRole, self.startofBpfPassBandLabel) + self.formLayout_2.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.startofBpfPassBandLabel) self.startofBpfPassBandEdit = QtGui.QLineEdit(self.firbpfPage) self.startofBpfPassBandEdit.setObjectName("startofBpfPassBandEdit") - self.formLayout_2.setWidget(0, QtGui.QFormLayout.FieldRole, self.startofBpfPassBandEdit) + self.formLayout_2.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.startofBpfPassBandEdit) self.endofBpfPassBandLabel = QtGui.QLabel(self.firbpfPage) self.endofBpfPassBandLabel.setObjectName("endofBpfPassBandLabel") - self.formLayout_2.setWidget(1, QtGui.QFormLayout.LabelRole, self.endofBpfPassBandLabel) + self.formLayout_2.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.endofBpfPassBandLabel) self.endofBpfPassBandEdit = QtGui.QLineEdit(self.firbpfPage) self.endofBpfPassBandEdit.setObjectName("endofBpfPassBandEdit") - self.formLayout_2.setWidget(1, QtGui.QFormLayout.FieldRole, self.endofBpfPassBandEdit) + self.formLayout_2.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.endofBpfPassBandEdit) self.bpfStopBandAttenEdit = QtGui.QLineEdit(self.firbpfPage) self.bpfStopBandAttenEdit.setObjectName("bpfStopBandAttenEdit") - self.formLayout_2.setWidget(3, QtGui.QFormLayout.FieldRole, self.bpfStopBandAttenEdit) + self.formLayout_2.setWidget( + 3, QtGui.QFormLayout.FieldRole, self.bpfStopBandAttenEdit) self.bpfStopBandAttenLabel = QtGui.QLabel(self.firbpfPage) self.bpfStopBandAttenLabel.setObjectName("bpfStopBandAttenLabel") - self.formLayout_2.setWidget(3, QtGui.QFormLayout.LabelRole, self.bpfStopBandAttenLabel) + self.formLayout_2.setWidget( + 3, QtGui.QFormLayout.LabelRole, self.bpfStopBandAttenLabel) self.bpfTransitionLabel = QtGui.QLabel(self.firbpfPage) self.bpfTransitionLabel.setObjectName("bpfTransitionLabel") - self.formLayout_2.setWidget(2, QtGui.QFormLayout.LabelRole, self.bpfTransitionLabel) + self.formLayout_2.setWidget( + 2, QtGui.QFormLayout.LabelRole, self.bpfTransitionLabel) self.bpfTransitionEdit = QtGui.QLineEdit(self.firbpfPage) self.bpfTransitionEdit.setObjectName("bpfTransitionEdit") - self.formLayout_2.setWidget(2, QtGui.QFormLayout.FieldRole, self.bpfTransitionEdit) + self.formLayout_2.setWidget( + 2, QtGui.QFormLayout.FieldRole, self.bpfTransitionEdit) self.bpfPassBandRippleEdit = QtGui.QLineEdit(self.firbpfPage) self.bpfPassBandRippleEdit.setObjectName("bpfPassBandRippleEdit") - self.formLayout_2.setWidget(4, QtGui.QFormLayout.FieldRole, self.bpfPassBandRippleEdit) + self.formLayout_2.setWidget( + 4, QtGui.QFormLayout.FieldRole, self.bpfPassBandRippleEdit) self.bpfPassBandRippleLabel = QtGui.QLabel(self.firbpfPage) self.bpfPassBandRippleLabel.setObjectName("bpfPassBandRippleLabel") - self.formLayout_2.setWidget(4, QtGui.QFormLayout.LabelRole, self.bpfPassBandRippleLabel) + self.formLayout_2.setWidget( + 4, QtGui.QFormLayout.LabelRole, self.bpfPassBandRippleLabel) self.filterTypeWidget.addWidget(self.firbpfPage) self.firbnfPage = QtGui.QWidget() self.firbnfPage.setObjectName("firbnfPage") self.formLayout_5 = QtGui.QFormLayout(self.firbnfPage) - self.formLayout_5.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_5.setFieldGrowthPolicy( + QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_5.setObjectName("formLayout_5") self.startofBnfStopBandLabel = QtGui.QLabel(self.firbnfPage) self.startofBnfStopBandLabel.setObjectName("startofBnfStopBandLabel") - self.formLayout_5.setWidget(0, QtGui.QFormLayout.LabelRole, self.startofBnfStopBandLabel) + self.formLayout_5.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.startofBnfStopBandLabel) self.startofBnfStopBandEdit = QtGui.QLineEdit(self.firbnfPage) self.startofBnfStopBandEdit.setObjectName("startofBnfStopBandEdit") - self.formLayout_5.setWidget(0, QtGui.QFormLayout.FieldRole, self.startofBnfStopBandEdit) + self.formLayout_5.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.startofBnfStopBandEdit) self.endofBnfStopBandLabel = QtGui.QLabel(self.firbnfPage) self.endofBnfStopBandLabel.setObjectName("endofBnfStopBandLabel") - self.formLayout_5.setWidget(1, QtGui.QFormLayout.LabelRole, self.endofBnfStopBandLabel) + self.formLayout_5.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.endofBnfStopBandLabel) self.endofBnfStopBandEdit = QtGui.QLineEdit(self.firbnfPage) self.endofBnfStopBandEdit.setObjectName("endofBnfStopBandEdit") - self.formLayout_5.setWidget(1, QtGui.QFormLayout.FieldRole, self.endofBnfStopBandEdit) + self.formLayout_5.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.endofBnfStopBandEdit) self.bnfTransitionLabel = QtGui.QLabel(self.firbnfPage) self.bnfTransitionLabel.setObjectName("bnfTransitionLabel") - self.formLayout_5.setWidget(2, QtGui.QFormLayout.LabelRole, self.bnfTransitionLabel) + self.formLayout_5.setWidget( + 2, QtGui.QFormLayout.LabelRole, self.bnfTransitionLabel) self.bnfTransitionEdit = QtGui.QLineEdit(self.firbnfPage) self.bnfTransitionEdit.setObjectName("bnfTransitionEdit") - self.formLayout_5.setWidget(2, QtGui.QFormLayout.FieldRole, self.bnfTransitionEdit) + self.formLayout_5.setWidget( + 2, QtGui.QFormLayout.FieldRole, self.bnfTransitionEdit) self.bnfStopBandAttenLabel = QtGui.QLabel(self.firbnfPage) self.bnfStopBandAttenLabel.setObjectName("bnfStopBandAttenLabel") - self.formLayout_5.setWidget(3, QtGui.QFormLayout.LabelRole, self.bnfStopBandAttenLabel) + self.formLayout_5.setWidget( + 3, QtGui.QFormLayout.LabelRole, self.bnfStopBandAttenLabel) self.bnfStopBandAttenEdit = QtGui.QLineEdit(self.firbnfPage) self.bnfStopBandAttenEdit.setObjectName("bnfStopBandAttenEdit") - self.formLayout_5.setWidget(3, QtGui.QFormLayout.FieldRole, self.bnfStopBandAttenEdit) + self.formLayout_5.setWidget( + 3, QtGui.QFormLayout.FieldRole, self.bnfStopBandAttenEdit) self.bnfPassBandRippleLabel = QtGui.QLabel(self.firbnfPage) self.bnfPassBandRippleLabel.setObjectName("bnfPassBandRippleLabel") - self.formLayout_5.setWidget(4, QtGui.QFormLayout.LabelRole, self.bnfPassBandRippleLabel) + self.formLayout_5.setWidget( + 4, QtGui.QFormLayout.LabelRole, self.bnfPassBandRippleLabel) self.bnfPassBandRippleEdit = QtGui.QLineEdit(self.firbnfPage) self.bnfPassBandRippleEdit.setObjectName("bnfPassBandRippleEdit") - self.formLayout_5.setWidget(4, QtGui.QFormLayout.FieldRole, self.bnfPassBandRippleEdit) + self.formLayout_5.setWidget( + 4, QtGui.QFormLayout.FieldRole, self.bnfPassBandRippleEdit) self.filterTypeWidget.addWidget(self.firbnfPage) self.firhpfPage = QtGui.QWidget() self.firhpfPage.setObjectName("firhpfPage") self.formLayout_3 = QtGui.QFormLayout(self.firhpfPage) - self.formLayout_3.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_3.setFieldGrowthPolicy( + QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_3.setObjectName("formLayout_3") self.endofHpfStopBandLabel = QtGui.QLabel(self.firhpfPage) self.endofHpfStopBandLabel.setObjectName("endofHpfStopBandLabel") - self.formLayout_3.setWidget(0, QtGui.QFormLayout.LabelRole, self.endofHpfStopBandLabel) + self.formLayout_3.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.endofHpfStopBandLabel) self.endofHpfStopBandEdit = QtGui.QLineEdit(self.firhpfPage) self.endofHpfStopBandEdit.setObjectName("endofHpfStopBandEdit") - self.formLayout_3.setWidget(0, QtGui.QFormLayout.FieldRole, self.endofHpfStopBandEdit) + self.formLayout_3.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.endofHpfStopBandEdit) self.startofHpfPassBandLabel = QtGui.QLabel(self.firhpfPage) self.startofHpfPassBandLabel.setObjectName("startofHpfPassBandLabel") - self.formLayout_3.setWidget(1, QtGui.QFormLayout.LabelRole, self.startofHpfPassBandLabel) + self.formLayout_3.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.startofHpfPassBandLabel) self.startofHpfPassBandEdit = QtGui.QLineEdit(self.firhpfPage) self.startofHpfPassBandEdit.setObjectName("startofHpfPassBandEdit") - self.formLayout_3.setWidget(1, QtGui.QFormLayout.FieldRole, self.startofHpfPassBandEdit) + self.formLayout_3.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.startofHpfPassBandEdit) self.hpfStopBandAttenLabel = QtGui.QLabel(self.firhpfPage) self.hpfStopBandAttenLabel.setObjectName("hpfStopBandAttenLabel") - self.formLayout_3.setWidget(2, QtGui.QFormLayout.LabelRole, self.hpfStopBandAttenLabel) + self.formLayout_3.setWidget( + 2, QtGui.QFormLayout.LabelRole, self.hpfStopBandAttenLabel) self.hpfStopBandAttenEdit = QtGui.QLineEdit(self.firhpfPage) self.hpfStopBandAttenEdit.setObjectName("hpfStopBandAttenEdit") - self.formLayout_3.setWidget(2, QtGui.QFormLayout.FieldRole, self.hpfStopBandAttenEdit) + self.formLayout_3.setWidget( + 2, QtGui.QFormLayout.FieldRole, self.hpfStopBandAttenEdit) self.hpfPassBandRippleLabel = QtGui.QLabel(self.firhpfPage) self.hpfPassBandRippleLabel.setObjectName("hpfPassBandRippleLabel") - self.formLayout_3.setWidget(3, QtGui.QFormLayout.LabelRole, self.hpfPassBandRippleLabel) + self.formLayout_3.setWidget( + 3, QtGui.QFormLayout.LabelRole, self.hpfPassBandRippleLabel) self.hpfPassBandRippleEdit = QtGui.QLineEdit(self.firhpfPage) self.hpfPassBandRippleEdit.setObjectName("hpfPassBandRippleEdit") - self.formLayout_3.setWidget(3, QtGui.QFormLayout.FieldRole, self.hpfPassBandRippleEdit) + self.formLayout_3.setWidget( + 3, QtGui.QFormLayout.FieldRole, self.hpfPassBandRippleEdit) self.filterTypeWidget.addWidget(self.firhpfPage) self.rrcPage = QtGui.QWidget() self.rrcPage.setObjectName("rrcPage") @@ -201,22 +246,28 @@ def setupUi(self, MainWindow): self.formLayout_6.setObjectName("formLayout_6") self.rrcSymbolRateLabel = QtGui.QLabel(self.rrcPage) self.rrcSymbolRateLabel.setObjectName("rrcSymbolRateLabel") - self.formLayout_6.setWidget(0, QtGui.QFormLayout.LabelRole, self.rrcSymbolRateLabel) + self.formLayout_6.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.rrcSymbolRateLabel) self.rrcAlphaLabel = QtGui.QLabel(self.rrcPage) self.rrcAlphaLabel.setObjectName("rrcAlphaLabel") - self.formLayout_6.setWidget(1, QtGui.QFormLayout.LabelRole, self.rrcAlphaLabel) + self.formLayout_6.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.rrcAlphaLabel) self.rrcNumTapsLabel = QtGui.QLabel(self.rrcPage) self.rrcNumTapsLabel.setObjectName("rrcNumTapsLabel") - self.formLayout_6.setWidget(2, QtGui.QFormLayout.LabelRole, self.rrcNumTapsLabel) + self.formLayout_6.setWidget( + 2, QtGui.QFormLayout.LabelRole, self.rrcNumTapsLabel) self.rrcSymbolRateEdit = QtGui.QLineEdit(self.rrcPage) self.rrcSymbolRateEdit.setObjectName("rrcSymbolRateEdit") - self.formLayout_6.setWidget(0, QtGui.QFormLayout.FieldRole, self.rrcSymbolRateEdit) + self.formLayout_6.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.rrcSymbolRateEdit) self.rrcAlphaEdit = QtGui.QLineEdit(self.rrcPage) self.rrcAlphaEdit.setObjectName("rrcAlphaEdit") - self.formLayout_6.setWidget(1, QtGui.QFormLayout.FieldRole, self.rrcAlphaEdit) + self.formLayout_6.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.rrcAlphaEdit) self.rrcNumTapsEdit = QtGui.QLineEdit(self.rrcPage) self.rrcNumTapsEdit.setObjectName("rrcNumTapsEdit") - self.formLayout_6.setWidget(2, QtGui.QFormLayout.FieldRole, self.rrcNumTapsEdit) + self.formLayout_6.setWidget( + 2, QtGui.QFormLayout.FieldRole, self.rrcNumTapsEdit) self.filterTypeWidget.addWidget(self.rrcPage) self.gausPage = QtGui.QWidget() self.gausPage.setObjectName("gausPage") @@ -224,40 +275,49 @@ def setupUi(self, MainWindow): self.formLayout_7.setObjectName("formLayout_7") self.gausSymbolRateLabel = QtGui.QLabel(self.gausPage) self.gausSymbolRateLabel.setObjectName("gausSymbolRateLabel") - self.formLayout_7.setWidget(0, QtGui.QFormLayout.LabelRole, self.gausSymbolRateLabel) + self.formLayout_7.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.gausSymbolRateLabel) self.gausSymbolRateEdit = QtGui.QLineEdit(self.gausPage) self.gausSymbolRateEdit.setObjectName("gausSymbolRateEdit") - self.formLayout_7.setWidget(0, QtGui.QFormLayout.FieldRole, self.gausSymbolRateEdit) + self.formLayout_7.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.gausSymbolRateEdit) self.gausBTLabel = QtGui.QLabel(self.gausPage) self.gausBTLabel.setObjectName("gausBTLabel") - self.formLayout_7.setWidget(1, QtGui.QFormLayout.LabelRole, self.gausBTLabel) + self.formLayout_7.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.gausBTLabel) self.gausBTEdit = QtGui.QLineEdit(self.gausPage) self.gausBTEdit.setObjectName("gausBTEdit") - self.formLayout_7.setWidget(1, QtGui.QFormLayout.FieldRole, self.gausBTEdit) + self.formLayout_7.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.gausBTEdit) self.gausNumTapsLabel = QtGui.QLabel(self.gausPage) self.gausNumTapsLabel.setObjectName("gausNumTapsLabel") - self.formLayout_7.setWidget(2, QtGui.QFormLayout.LabelRole, self.gausNumTapsLabel) + self.formLayout_7.setWidget( + 2, QtGui.QFormLayout.LabelRole, self.gausNumTapsLabel) self.gausNumTapsEdit = QtGui.QLineEdit(self.gausPage) self.gausNumTapsEdit.setObjectName("gausNumTapsEdit") - self.formLayout_7.setWidget(2, QtGui.QFormLayout.FieldRole, self.gausNumTapsEdit) + self.formLayout_7.setWidget( + 2, QtGui.QFormLayout.FieldRole, self.gausNumTapsEdit) self.filterTypeWidget.addWidget(self.gausPage) self.verticalLayout.addWidget(self.filterTypeWidget) self.filterPropsBox = QtGui.QGroupBox(self.filterFrame) self.filterPropsBox.setObjectName("filterPropsBox") self.formLayout_8 = QtGui.QFormLayout(self.filterPropsBox) - self.formLayout_8.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_8.setFieldGrowthPolicy( + QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_8.setObjectName("formLayout_8") self.nTapsLabel = QtGui.QLabel(self.filterPropsBox) self.nTapsLabel.setMinimumSize(QtCore.QSize(150, 0)) self.nTapsLabel.setObjectName("nTapsLabel") - self.formLayout_8.setWidget(1, QtGui.QFormLayout.LabelRole, self.nTapsLabel) + self.formLayout_8.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.nTapsLabel) self.nTapsEdit = QtGui.QLabel(self.filterPropsBox) self.nTapsEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.nTapsEdit.setFrameShape(QtGui.QFrame.Box) self.nTapsEdit.setFrameShadow(QtGui.QFrame.Raised) self.nTapsEdit.setText("") self.nTapsEdit.setObjectName("nTapsEdit") - self.formLayout_8.setWidget(1, QtGui.QFormLayout.FieldRole, self.nTapsEdit) + self.formLayout_8.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.nTapsEdit) self.verticalLayout.addWidget(self.filterPropsBox) self.sysParamsBox = QtGui.QGroupBox(self.filterFrame) self.sysParamsBox.setObjectName("sysParamsBox") @@ -265,11 +325,13 @@ def setupUi(self, MainWindow): self.formLayout_4.setObjectName("formLayout_4") self.nfftEdit = QtGui.QLineEdit(self.sysParamsBox) self.nfftEdit.setObjectName("nfftEdit") - self.formLayout_4.setWidget(1, QtGui.QFormLayout.FieldRole, self.nfftEdit) + self.formLayout_4.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.nfftEdit) self.nfftLabel = QtGui.QLabel(self.sysParamsBox) self.nfftLabel.setMinimumSize(QtCore.QSize(150, 0)) self.nfftLabel.setObjectName("nfftLabel") - self.formLayout_4.setWidget(1, QtGui.QFormLayout.LabelRole, self.nfftLabel) + self.formLayout_4.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.nfftLabel) self.verticalLayout.addWidget(self.sysParamsBox) self.designButton = QtGui.QPushButton(self.filterFrame) self.designButton.setMinimumSize(QtCore.QSize(0, 0)) @@ -339,30 +401,51 @@ def setupUi(self, MainWindow): self.retranslateUi(MainWindow) self.filterTypeWidget.setCurrentIndex(5) self.tabGroup.setCurrentIndex(0) - QtCore.QObject.connect(self.action_exit, QtCore.SIGNAL("activated()"), MainWindow.close) + QtCore.QObject.connect(self.action_exit, QtCore.SIGNAL( + "activated()"), MainWindow.close) QtCore.QMetaObject.connectSlotsByName(MainWindow) - MainWindow.setTabOrder(self.filterTypeComboBox, self.filterDesignTypeComboBox) - MainWindow.setTabOrder(self.filterDesignTypeComboBox, self.sampleRateEdit) + MainWindow.setTabOrder(self.filterTypeComboBox, + self.filterDesignTypeComboBox) + MainWindow.setTabOrder( + self.filterDesignTypeComboBox, self.sampleRateEdit) MainWindow.setTabOrder(self.sampleRateEdit, self.filterGainEdit) MainWindow.setTabOrder(self.filterGainEdit, self.endofLpfPassBandEdit) - MainWindow.setTabOrder(self.endofLpfPassBandEdit, self.startofLpfStopBandEdit) - MainWindow.setTabOrder(self.startofLpfStopBandEdit, self.lpfStopBandAttenEdit) - MainWindow.setTabOrder(self.lpfStopBandAttenEdit, self.lpfPassBandRippleEdit) - MainWindow.setTabOrder(self.lpfPassBandRippleEdit, self.startofBpfPassBandEdit) - MainWindow.setTabOrder(self.startofBpfPassBandEdit, self.endofBpfPassBandEdit) - MainWindow.setTabOrder(self.endofBpfPassBandEdit, self.bpfTransitionEdit) - MainWindow.setTabOrder(self.bpfTransitionEdit, self.bpfStopBandAttenEdit) - MainWindow.setTabOrder(self.bpfStopBandAttenEdit, self.bpfPassBandRippleEdit) - MainWindow.setTabOrder(self.bpfPassBandRippleEdit, self.startofBnfStopBandEdit) - MainWindow.setTabOrder(self.startofBnfStopBandEdit, self.endofBnfStopBandEdit) - MainWindow.setTabOrder(self.endofBnfStopBandEdit, self.bnfTransitionEdit) - MainWindow.setTabOrder(self.bnfTransitionEdit, self.bnfStopBandAttenEdit) - MainWindow.setTabOrder(self.bnfStopBandAttenEdit, self.bnfPassBandRippleEdit) - MainWindow.setTabOrder(self.bnfPassBandRippleEdit, self.endofHpfStopBandEdit) - MainWindow.setTabOrder(self.endofHpfStopBandEdit, self.startofHpfPassBandEdit) - MainWindow.setTabOrder(self.startofHpfPassBandEdit, self.hpfStopBandAttenEdit) - MainWindow.setTabOrder(self.hpfStopBandAttenEdit, self.hpfPassBandRippleEdit) - MainWindow.setTabOrder(self.hpfPassBandRippleEdit, self.rrcSymbolRateEdit) + MainWindow.setTabOrder(self.endofLpfPassBandEdit, + self.startofLpfStopBandEdit) + MainWindow.setTabOrder(self.startofLpfStopBandEdit, + self.lpfStopBandAttenEdit) + MainWindow.setTabOrder(self.lpfStopBandAttenEdit, + self.lpfPassBandRippleEdit) + MainWindow.setTabOrder(self.lpfPassBandRippleEdit, + self.startofBpfPassBandEdit) + MainWindow.setTabOrder(self.startofBpfPassBandEdit, + self.endofBpfPassBandEdit) + MainWindow.setTabOrder(self.endofBpfPassBandEdit, + self.bpfTransitionEdit) + MainWindow.setTabOrder(self.bpfTransitionEdit, + self.bpfStopBandAttenEdit) + MainWindow.setTabOrder(self.bpfStopBandAttenEdit, + self.bpfPassBandRippleEdit) + MainWindow.setTabOrder(self.bpfPassBandRippleEdit, + self.startofBnfStopBandEdit) + MainWindow.setTabOrder(self.startofBnfStopBandEdit, + self.endofBnfStopBandEdit) + MainWindow.setTabOrder(self.endofBnfStopBandEdit, + self.bnfTransitionEdit) + MainWindow.setTabOrder(self.bnfTransitionEdit, + self.bnfStopBandAttenEdit) + MainWindow.setTabOrder(self.bnfStopBandAttenEdit, + self.bnfPassBandRippleEdit) + MainWindow.setTabOrder(self.bnfPassBandRippleEdit, + self.endofHpfStopBandEdit) + MainWindow.setTabOrder(self.endofHpfStopBandEdit, + self.startofHpfPassBandEdit) + MainWindow.setTabOrder(self.startofHpfPassBandEdit, + self.hpfStopBandAttenEdit) + MainWindow.setTabOrder(self.hpfStopBandAttenEdit, + self.hpfPassBandRippleEdit) + MainWindow.setTabOrder( + self.hpfPassBandRippleEdit, self.rrcSymbolRateEdit) MainWindow.setTabOrder(self.rrcSymbolRateEdit, self.rrcAlphaEdit) MainWindow.setTabOrder(self.rrcAlphaEdit, self.rrcNumTapsEdit) MainWindow.setTabOrder(self.rrcNumTapsEdit, self.gausSymbolRateEdit) @@ -373,63 +456,118 @@ def setupUi(self, MainWindow): MainWindow.setTabOrder(self.designButton, self.tabGroup) def retranslateUi(self, MainWindow): - MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "GNU Radio Filter Design Tool", None, QtGui.QApplication.UnicodeUTF8)) - self.filterTypeComboBox.setItemText(0, QtGui.QApplication.translate("MainWindow", "Low Pass", None, QtGui.QApplication.UnicodeUTF8)) - self.filterTypeComboBox.setItemText(1, QtGui.QApplication.translate("MainWindow", "Band Pass", None, QtGui.QApplication.UnicodeUTF8)) - self.filterTypeComboBox.setItemText(2, QtGui.QApplication.translate("MainWindow", "Complex Band Pass", None, QtGui.QApplication.UnicodeUTF8)) - self.filterTypeComboBox.setItemText(3, QtGui.QApplication.translate("MainWindow", "Band Notch", None, QtGui.QApplication.UnicodeUTF8)) - self.filterTypeComboBox.setItemText(4, QtGui.QApplication.translate("MainWindow", "High Pass", None, QtGui.QApplication.UnicodeUTF8)) - self.filterTypeComboBox.setItemText(5, QtGui.QApplication.translate("MainWindow", "Root Raised Cosine", None, QtGui.QApplication.UnicodeUTF8)) - self.filterTypeComboBox.setItemText(6, QtGui.QApplication.translate("MainWindow", "Gaussian", None, QtGui.QApplication.UnicodeUTF8)) - self.filterDesignTypeComboBox.setItemText(0, QtGui.QApplication.translate("MainWindow", "Hamming Window", None, QtGui.QApplication.UnicodeUTF8)) - self.filterDesignTypeComboBox.setItemText(1, QtGui.QApplication.translate("MainWindow", "Hann Window", None, QtGui.QApplication.UnicodeUTF8)) - self.filterDesignTypeComboBox.setItemText(2, QtGui.QApplication.translate("MainWindow", "Blackman Window", None, QtGui.QApplication.UnicodeUTF8)) - self.filterDesignTypeComboBox.setItemText(3, QtGui.QApplication.translate("MainWindow", "Rectangular Window", None, QtGui.QApplication.UnicodeUTF8)) - self.filterDesignTypeComboBox.setItemText(4, QtGui.QApplication.translate("MainWindow", "Kaiser Window", None, QtGui.QApplication.UnicodeUTF8)) - self.filterDesignTypeComboBox.setItemText(5, QtGui.QApplication.translate("MainWindow", "Blackman-harris Window", None, QtGui.QApplication.UnicodeUTF8)) - self.filterDesignTypeComboBox.setItemText(6, QtGui.QApplication.translate("MainWindow", "Equiripple", None, QtGui.QApplication.UnicodeUTF8)) - self.sampleRateLabel.setText(QtGui.QApplication.translate("MainWindow", "Sample Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) - self.filterGainLabel.setText(QtGui.QApplication.translate("MainWindow", "Filter Gain", None, QtGui.QApplication.UnicodeUTF8)) - self.endofLpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.startofLpfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.lpfStopBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) - self.lpfPassBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) - self.startofBpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.endofBpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.bpfStopBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) - self.bpfTransitionLabel.setText(QtGui.QApplication.translate("MainWindow", "Transition Width (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.bpfPassBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) - self.startofBnfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.endofBnfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.bnfTransitionLabel.setText(QtGui.QApplication.translate("MainWindow", "Transition Width (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.bnfStopBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) - self.bnfPassBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) - self.endofHpfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.startofHpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) - self.hpfStopBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) - self.hpfPassBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) - self.rrcSymbolRateLabel.setText(QtGui.QApplication.translate("MainWindow", "Symbol Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) - self.rrcAlphaLabel.setText(QtGui.QApplication.translate("MainWindow", "Roll-off Factor", None, QtGui.QApplication.UnicodeUTF8)) - self.rrcNumTapsLabel.setText(QtGui.QApplication.translate("MainWindow", "Number of Taps", None, QtGui.QApplication.UnicodeUTF8)) - self.gausSymbolRateLabel.setText(QtGui.QApplication.translate("MainWindow", "Symbol Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) - self.gausBTLabel.setText(QtGui.QApplication.translate("MainWindow", "Roll-off Factor", None, QtGui.QApplication.UnicodeUTF8)) - self.gausNumTapsLabel.setText(QtGui.QApplication.translate("MainWindow", "Number of Taps", None, QtGui.QApplication.UnicodeUTF8)) - self.filterPropsBox.setTitle(QtGui.QApplication.translate("MainWindow", "Filter Properties", None, QtGui.QApplication.UnicodeUTF8)) - self.nTapsLabel.setText(QtGui.QApplication.translate("MainWindow", "Number of Taps:", None, QtGui.QApplication.UnicodeUTF8)) - self.sysParamsBox.setTitle(QtGui.QApplication.translate("MainWindow", "System Parameters", None, QtGui.QApplication.UnicodeUTF8)) - self.nfftLabel.setText(QtGui.QApplication.translate("MainWindow", "Num FFT points", None, QtGui.QApplication.UnicodeUTF8)) - self.designButton.setText(QtGui.QApplication.translate("MainWindow", "Design", None, QtGui.QApplication.UnicodeUTF8)) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.freqTab), QtGui.QApplication.translate("MainWindow", "Frequency Domain", None, QtGui.QApplication.UnicodeUTF8)) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.timeTab), QtGui.QApplication.translate("MainWindow", "Time Domain", None, QtGui.QApplication.UnicodeUTF8)) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.phaseTab), QtGui.QApplication.translate("MainWindow", "Phase", None, QtGui.QApplication.UnicodeUTF8)) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.groupTab), QtGui.QApplication.translate("MainWindow", "Group Delay", None, QtGui.QApplication.UnicodeUTF8)) - self.menu_File.setTitle(QtGui.QApplication.translate("MainWindow", "&File", None, QtGui.QApplication.UnicodeUTF8)) - self.action_exit.setText(QtGui.QApplication.translate("MainWindow", "E&xit", None, QtGui.QApplication.UnicodeUTF8)) - self.action_save.setText(QtGui.QApplication.translate("MainWindow", "&Save", None, QtGui.QApplication.UnicodeUTF8)) - self.action_save.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+S", None, QtGui.QApplication.UnicodeUTF8)) - self.action_open.setText(QtGui.QApplication.translate("MainWindow", "&Open", None, QtGui.QApplication.UnicodeUTF8)) - self.action_open.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+O", None, QtGui.QApplication.UnicodeUTF8)) + MainWindow.setWindowTitle(QtGui.QApplication.translate( + "MainWindow", "GNU Radio Filter Design Tool", None, QtGui.QApplication.UnicodeUTF8)) + self.filterTypeComboBox.setItemText(0, QtGui.QApplication.translate( + "MainWindow", "Low Pass", None, QtGui.QApplication.UnicodeUTF8)) + self.filterTypeComboBox.setItemText(1, QtGui.QApplication.translate( + "MainWindow", "Band Pass", None, QtGui.QApplication.UnicodeUTF8)) + self.filterTypeComboBox.setItemText(2, QtGui.QApplication.translate( + "MainWindow", "Complex Band Pass", None, QtGui.QApplication.UnicodeUTF8)) + self.filterTypeComboBox.setItemText(3, QtGui.QApplication.translate( + "MainWindow", "Band Notch", None, QtGui.QApplication.UnicodeUTF8)) + self.filterTypeComboBox.setItemText(4, QtGui.QApplication.translate( + "MainWindow", "High Pass", None, QtGui.QApplication.UnicodeUTF8)) + self.filterTypeComboBox.setItemText(5, QtGui.QApplication.translate( + "MainWindow", "Root Raised Cosine", None, QtGui.QApplication.UnicodeUTF8)) + self.filterTypeComboBox.setItemText(6, QtGui.QApplication.translate( + "MainWindow", "Gaussian", None, QtGui.QApplication.UnicodeUTF8)) + self.filterDesignTypeComboBox.setItemText(0, QtGui.QApplication.translate( + "MainWindow", "Hamming Window", None, QtGui.QApplication.UnicodeUTF8)) + self.filterDesignTypeComboBox.setItemText(1, QtGui.QApplication.translate( + "MainWindow", "Hann Window", None, QtGui.QApplication.UnicodeUTF8)) + self.filterDesignTypeComboBox.setItemText(2, QtGui.QApplication.translate( + "MainWindow", "Blackman Window", None, QtGui.QApplication.UnicodeUTF8)) + self.filterDesignTypeComboBox.setItemText(3, QtGui.QApplication.translate( + "MainWindow", "Rectangular Window", None, QtGui.QApplication.UnicodeUTF8)) + self.filterDesignTypeComboBox.setItemText(4, QtGui.QApplication.translate( + "MainWindow", "Kaiser Window", None, QtGui.QApplication.UnicodeUTF8)) + self.filterDesignTypeComboBox.setItemText(5, QtGui.QApplication.translate( + "MainWindow", "Blackman-harris Window", None, QtGui.QApplication.UnicodeUTF8)) + self.filterDesignTypeComboBox.setItemText(6, QtGui.QApplication.translate( + "MainWindow", "Equiripple", None, QtGui.QApplication.UnicodeUTF8)) + self.sampleRateLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Sample Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) + self.filterGainLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Filter Gain", None, QtGui.QApplication.UnicodeUTF8)) + self.endofLpfPassBandLabel.setText(QtGui.QApplication.translate( + "MainWindow", "End of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.startofLpfStopBandLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Start of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.lpfStopBandAttenLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) + self.lpfPassBandRippleLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) + self.startofBpfPassBandLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Start of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.endofBpfPassBandLabel.setText(QtGui.QApplication.translate( + "MainWindow", "End of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.bpfStopBandAttenLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) + self.bpfTransitionLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Transition Width (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.bpfPassBandRippleLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) + self.startofBnfStopBandLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Start of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.endofBnfStopBandLabel.setText(QtGui.QApplication.translate( + "MainWindow", "End of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.bnfTransitionLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Transition Width (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.bnfStopBandAttenLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) + self.bnfPassBandRippleLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) + self.endofHpfStopBandLabel.setText(QtGui.QApplication.translate( + "MainWindow", "End of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.startofHpfPassBandLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Start of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) + self.hpfStopBandAttenLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) + self.hpfPassBandRippleLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) + self.rrcSymbolRateLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Symbol Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) + self.rrcAlphaLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Roll-off Factor", None, QtGui.QApplication.UnicodeUTF8)) + self.rrcNumTapsLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Number of Taps", None, QtGui.QApplication.UnicodeUTF8)) + self.gausSymbolRateLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Symbol Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) + self.gausBTLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Roll-off Factor", None, QtGui.QApplication.UnicodeUTF8)) + self.gausNumTapsLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Number of Taps", None, QtGui.QApplication.UnicodeUTF8)) + self.filterPropsBox.setTitle(QtGui.QApplication.translate( + "MainWindow", "Filter Properties", None, QtGui.QApplication.UnicodeUTF8)) + self.nTapsLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Number of Taps:", None, QtGui.QApplication.UnicodeUTF8)) + self.sysParamsBox.setTitle(QtGui.QApplication.translate( + "MainWindow", "System Parameters", None, QtGui.QApplication.UnicodeUTF8)) + self.nfftLabel.setText(QtGui.QApplication.translate( + "MainWindow", "Num FFT points", None, QtGui.QApplication.UnicodeUTF8)) + self.designButton.setText(QtGui.QApplication.translate( + "MainWindow", "Design", None, QtGui.QApplication.UnicodeUTF8)) + self.tabGroup.setTabText(self.tabGroup.indexOf(self.freqTab), QtGui.QApplication.translate( + "MainWindow", "Frequency Domain", None, QtGui.QApplication.UnicodeUTF8)) + self.tabGroup.setTabText(self.tabGroup.indexOf(self.timeTab), QtGui.QApplication.translate( + "MainWindow", "Time Domain", None, QtGui.QApplication.UnicodeUTF8)) + self.tabGroup.setTabText(self.tabGroup.indexOf(self.phaseTab), QtGui.QApplication.translate( + "MainWindow", "Phase", None, QtGui.QApplication.UnicodeUTF8)) + self.tabGroup.setTabText(self.tabGroup.indexOf(self.groupTab), QtGui.QApplication.translate( + "MainWindow", "Group Delay", None, QtGui.QApplication.UnicodeUTF8)) + self.menu_File.setTitle(QtGui.QApplication.translate( + "MainWindow", "&File", None, QtGui.QApplication.UnicodeUTF8)) + self.action_exit.setText(QtGui.QApplication.translate( + "MainWindow", "E&xit", None, QtGui.QApplication.UnicodeUTF8)) + self.action_save.setText(QtGui.QApplication.translate( + "MainWindow", "&Save", None, QtGui.QApplication.UnicodeUTF8)) + self.action_save.setShortcut(QtGui.QApplication.translate( + "MainWindow", "Ctrl+S", None, QtGui.QApplication.UnicodeUTF8)) + self.action_open.setText(QtGui.QApplication.translate( + "MainWindow", "&Open", None, QtGui.QApplication.UnicodeUTF8)) + self.action_open.setShortcut(QtGui.QApplication.translate( + "MainWindow", "Ctrl+O", None, QtGui.QApplication.UnicodeUTF8)) -#from qwt_plot import QwtPlot -from PyQt5.Qwt import QwtPlot +#from qwt_plot import QwtPlot diff --git a/gr-utils/plot_tools/pyqt_plot.py b/gr-utils/plot_tools/pyqt_plot.py index 2d4df6c5a75..f102fe50e4b 100644 --- a/gr-utils/plot_tools/pyqt_plot.py +++ b/gr-utils/plot_tools/pyqt_plot.py @@ -6,6 +6,7 @@ # # WARNING! All changes made in this file will be lost! +from PyQt5 import Qwt from PyQt5 import QtCore, QtGui try: @@ -16,12 +17,14 @@ def _fromUtf8(s): try: _encoding = QtGui.QApplication.UnicodeUTF8 + def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) + class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) @@ -44,54 +47,73 @@ def setupUi(self, MainWindow): self.filePosStartLineEdit = QtGui.QLineEdit(self.filePosBox) self.filePosStartLineEdit.setMinimumSize(QtCore.QSize(50, 0)) self.filePosStartLineEdit.setMaximumSize(QtCore.QSize(100, 16777215)) - self.filePosStartLineEdit.setObjectName(_fromUtf8("filePosStartLineEdit")) - self.filePosLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.filePosStartLineEdit) + self.filePosStartLineEdit.setObjectName( + _fromUtf8("filePosStartLineEdit")) + self.filePosLayout.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.filePosStartLineEdit) self.filePosStopLabel = QtGui.QLabel(self.filePosBox) self.filePosStopLabel.setObjectName(_fromUtf8("filePosStopLabel")) - self.filePosLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.filePosStopLabel) + self.filePosLayout.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.filePosStopLabel) self.filePosStopLineEdit = QtGui.QLineEdit(self.filePosBox) self.filePosStopLineEdit.setMinimumSize(QtCore.QSize(50, 0)) self.filePosStopLineEdit.setMaximumSize(QtCore.QSize(100, 16777215)) - self.filePosStopLineEdit.setObjectName(_fromUtf8("filePosStopLineEdit")) - self.filePosLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.filePosStopLineEdit) + self.filePosStopLineEdit.setObjectName( + _fromUtf8("filePosStopLineEdit")) + self.filePosLayout.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.filePosStopLineEdit) self.filePosLengthLabel = QtGui.QLabel(self.filePosBox) self.filePosLengthLabel.setObjectName(_fromUtf8("filePosLengthLabel")) - self.filePosLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.filePosLengthLabel) + self.filePosLayout.setWidget( + 2, QtGui.QFormLayout.LabelRole, self.filePosLengthLabel) self.filePosLengthLineEdit = QtGui.QLineEdit(self.filePosBox) self.filePosLengthLineEdit.setMinimumSize(QtCore.QSize(50, 0)) self.filePosLengthLineEdit.setMaximumSize(QtCore.QSize(100, 16777215)) - self.filePosLengthLineEdit.setObjectName(_fromUtf8("filePosLengthLineEdit")) - self.filePosLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.filePosLengthLineEdit) + self.filePosLengthLineEdit.setObjectName( + _fromUtf8("filePosLengthLineEdit")) + self.filePosLayout.setWidget( + 2, QtGui.QFormLayout.FieldRole, self.filePosLengthLineEdit) self.filePosStartLabel = QtGui.QLabel(self.filePosBox) self.filePosStartLabel.setObjectName(_fromUtf8("filePosStartLabel")) - self.filePosLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.filePosStartLabel) + self.filePosLayout.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.filePosStartLabel) self.gridLayout_4.addLayout(self.filePosLayout, 0, 0, 1, 1) self.fileTimeLayout = QtGui.QFormLayout() self.fileTimeLayout.setObjectName(_fromUtf8("fileTimeLayout")) self.fileTimeStartLabel = QtGui.QLabel(self.filePosBox) self.fileTimeStartLabel.setObjectName(_fromUtf8("fileTimeStartLabel")) - self.fileTimeLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.fileTimeStartLabel) + self.fileTimeLayout.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.fileTimeStartLabel) self.fileTimeStartLineEdit = QtGui.QLineEdit(self.filePosBox) self.fileTimeStartLineEdit.setMinimumSize(QtCore.QSize(50, 0)) self.fileTimeStartLineEdit.setMaximumSize(QtCore.QSize(100, 16777215)) - self.fileTimeStartLineEdit.setObjectName(_fromUtf8("fileTimeStartLineEdit")) - self.fileTimeLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.fileTimeStartLineEdit) + self.fileTimeStartLineEdit.setObjectName( + _fromUtf8("fileTimeStartLineEdit")) + self.fileTimeLayout.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.fileTimeStartLineEdit) self.fileTimeStopLabel = QtGui.QLabel(self.filePosBox) self.fileTimeStopLabel.setObjectName(_fromUtf8("fileTimeStopLabel")) - self.fileTimeLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.fileTimeStopLabel) + self.fileTimeLayout.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.fileTimeStopLabel) self.fileTimeStopLineEdit = QtGui.QLineEdit(self.filePosBox) self.fileTimeStopLineEdit.setMinimumSize(QtCore.QSize(50, 0)) self.fileTimeStopLineEdit.setMaximumSize(QtCore.QSize(100, 16777215)) - self.fileTimeStopLineEdit.setObjectName(_fromUtf8("fileTimeStopLineEdit")) - self.fileTimeLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.fileTimeStopLineEdit) + self.fileTimeStopLineEdit.setObjectName( + _fromUtf8("fileTimeStopLineEdit")) + self.fileTimeLayout.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.fileTimeStopLineEdit) self.fileTimeLengthLabel = QtGui.QLabel(self.filePosBox) - self.fileTimeLengthLabel.setObjectName(_fromUtf8("fileTimeLengthLabel")) - self.fileTimeLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.fileTimeLengthLabel) + self.fileTimeLengthLabel.setObjectName( + _fromUtf8("fileTimeLengthLabel")) + self.fileTimeLayout.setWidget( + 2, QtGui.QFormLayout.LabelRole, self.fileTimeLengthLabel) self.fileTimeLengthLineEdit = QtGui.QLineEdit(self.filePosBox) self.fileTimeLengthLineEdit.setMinimumSize(QtCore.QSize(50, 0)) self.fileTimeLengthLineEdit.setMaximumSize(QtCore.QSize(100, 16777215)) - self.fileTimeLengthLineEdit.setObjectName(_fromUtf8("fileTimeLengthLineEdit")) - self.fileTimeLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.fileTimeLengthLineEdit) + self.fileTimeLengthLineEdit.setObjectName( + _fromUtf8("fileTimeLengthLineEdit")) + self.fileTimeLayout.setWidget( + 2, QtGui.QFormLayout.FieldRole, self.fileTimeLengthLineEdit) self.gridLayout_4.addLayout(self.fileTimeLayout, 0, 1, 1, 1) self.gridLayout.addWidget(self.filePosBox, 2, 0, 1, 1) self.displayGroupBox = QtGui.QGroupBox(self.centralwidget) @@ -131,16 +153,19 @@ def setupUi(self, MainWindow): self.sysGroupBox.setMinimumSize(QtCore.QSize(200, 0)) self.sysGroupBox.setObjectName(_fromUtf8("sysGroupBox")) self.formLayout = QtGui.QFormLayout(self.sysGroupBox) - self.formLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout.setFieldGrowthPolicy( + QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout.setObjectName(_fromUtf8("formLayout")) self.sampleRateLabel = QtGui.QLabel(self.sysGroupBox) self.sampleRateLabel.setObjectName(_fromUtf8("sampleRateLabel")) - self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.sampleRateLabel) + self.formLayout.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.sampleRateLabel) self.sampleRateLineEdit = QtGui.QLineEdit(self.sysGroupBox) self.sampleRateLineEdit.setMinimumSize(QtCore.QSize(50, 0)) self.sampleRateLineEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.sampleRateLineEdit.setObjectName(_fromUtf8("sampleRateLineEdit")) - self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.sampleRateLineEdit) + self.formLayout.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.sampleRateLineEdit) self.gridLayout.addWidget(self.sysGroupBox, 2, 1, 1, 1) self.frame = QtGui.QFrame(self.centralwidget) self.frame.setFrameShape(QtGui.QFrame.StyledPanel) @@ -170,16 +195,19 @@ def setupUi(self, MainWindow): self.fftPropBox.setMinimumSize(QtCore.QSize(160, 0)) self.fftPropBox.setObjectName(_fromUtf8("fftPropBox")) self.formLayout_4 = QtGui.QFormLayout(self.fftPropBox) - self.formLayout_4.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) + self.formLayout_4.setFieldGrowthPolicy( + QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_4.setObjectName(_fromUtf8("formLayout_4")) self.psdFFTSizeLabel = QtGui.QLabel(self.fftPropBox) self.psdFFTSizeLabel.setObjectName(_fromUtf8("psdFFTSizeLabel")) - self.formLayout_4.setWidget(0, QtGui.QFormLayout.LabelRole, self.psdFFTSizeLabel) + self.formLayout_4.setWidget( + 0, QtGui.QFormLayout.LabelRole, self.psdFFTSizeLabel) self.psdFFTComboBox = QtGui.QComboBox(self.fftPropBox) self.psdFFTComboBox.setMinimumSize(QtCore.QSize(96, 0)) self.psdFFTComboBox.setMaximumSize(QtCore.QSize(96, 16777215)) self.psdFFTComboBox.setObjectName(_fromUtf8("psdFFTComboBox")) - self.formLayout_4.setWidget(0, QtGui.QFormLayout.FieldRole, self.psdFFTComboBox) + self.formLayout_4.setWidget( + 0, QtGui.QFormLayout.FieldRole, self.psdFFTComboBox) self.psdFFTSizeLabel.raise_() self.psdFFTComboBox.raise_() self.horizontalLayout_2.addWidget(self.fftPropBox) @@ -198,12 +226,14 @@ def setupUi(self, MainWindow): self.formLayout_3.setObjectName(_fromUtf8("formLayout_3")) self.specFFTLabel = QtGui.QLabel(self.groupBox) self.specFFTLabel.setObjectName(_fromUtf8("specFFTLabel")) - self.formLayout_3.setWidget(1, QtGui.QFormLayout.LabelRole, self.specFFTLabel) + self.formLayout_3.setWidget( + 1, QtGui.QFormLayout.LabelRole, self.specFFTLabel) self.specFFTComboBox = QtGui.QComboBox(self.groupBox) self.specFFTComboBox.setMinimumSize(QtCore.QSize(96, 0)) self.specFFTComboBox.setMaximumSize(QtCore.QSize(96, 16777215)) self.specFFTComboBox.setObjectName(_fromUtf8("specFFTComboBox")) - self.formLayout_3.setWidget(1, QtGui.QFormLayout.FieldRole, self.specFFTComboBox) + self.formLayout_3.setWidget( + 1, QtGui.QFormLayout.FieldRole, self.specFFTComboBox) self.horizontalLayout_3.addWidget(self.groupBox) self.specPlot = Qwt5.QwtPlot(self.specTab) self.specPlot.setObjectName(_fromUtf8("specPlot")) @@ -237,35 +267,51 @@ def setupUi(self, MainWindow): self.retranslateUi(MainWindow) self.tabGroup.setCurrentIndex(0) - QtCore.QObject.connect(self.action_exit, QtCore.SIGNAL(_fromUtf8("activated()")), MainWindow.close) + QtCore.QObject.connect(self.action_exit, QtCore.SIGNAL( + _fromUtf8("activated()")), MainWindow.close) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) - self.filePosBox.setTitle(_translate("MainWindow", "File Position", None)) + self.filePosBox.setTitle(_translate( + "MainWindow", "File Position", None)) self.filePosStopLabel.setText(_translate("MainWindow", "Stop", None)) - self.filePosLengthLabel.setText(_translate("MainWindow", "Length", None)) + self.filePosLengthLabel.setText( + _translate("MainWindow", "Length", None)) self.filePosStartLabel.setText(_translate("MainWindow", "Start", None)) - self.fileTimeStartLabel.setText(_translate("MainWindow", "time start (sec)", None)) - self.fileTimeStopLabel.setText(_translate("MainWindow", "time stop (sec)", None)) - self.fileTimeLengthLabel.setText(_translate("MainWindow", "time length (sec)", None)) - self.displayGroupBox.setTitle(_translate("MainWindow", "Display Properties", None)) - self.lineWidthLabel.setText(_translate("MainWindow", "Line Width", None)) - self.lineStyleLabel.setText(_translate("MainWindow", "Line Style", None)) - self.styleSizeLabel.setText(_translate("MainWindow", "Style Size", None)) - self.sysGroupBox.setTitle(_translate("MainWindow", "System Properties", None)) - self.sampleRateLabel.setText(_translate("MainWindow", "Sample Rate", None)) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.timeTab), _translate("MainWindow", "Time Domain", None)) - self.fftPropBox.setTitle(_translate("MainWindow", "FFT Properties", None)) - self.psdFFTSizeLabel.setText(_translate("MainWindow", "FFT Size", None)) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.freqTab), _translate("MainWindow", "Frequency Domain", None)) - self.groupBox.setTitle(_translate("MainWindow", "Spectrogram Properties", None)) + self.fileTimeStartLabel.setText(_translate( + "MainWindow", "time start (sec)", None)) + self.fileTimeStopLabel.setText(_translate( + "MainWindow", "time stop (sec)", None)) + self.fileTimeLengthLabel.setText(_translate( + "MainWindow", "time length (sec)", None)) + self.displayGroupBox.setTitle(_translate( + "MainWindow", "Display Properties", None)) + self.lineWidthLabel.setText( + _translate("MainWindow", "Line Width", None)) + self.lineStyleLabel.setText( + _translate("MainWindow", "Line Style", None)) + self.styleSizeLabel.setText( + _translate("MainWindow", "Style Size", None)) + self.sysGroupBox.setTitle(_translate( + "MainWindow", "System Properties", None)) + self.sampleRateLabel.setText( + _translate("MainWindow", "Sample Rate", None)) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.timeTab), _translate("MainWindow", "Time Domain", None)) + self.fftPropBox.setTitle(_translate( + "MainWindow", "FFT Properties", None)) + self.psdFFTSizeLabel.setText( + _translate("MainWindow", "FFT Size", None)) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.freqTab), _translate("MainWindow", "Frequency Domain", None)) + self.groupBox.setTitle(_translate( + "MainWindow", "Spectrogram Properties", None)) self.specFFTLabel.setText(_translate("MainWindow", "FFT Size", None)) - self.tabGroup.setTabText(self.tabGroup.indexOf(self.specTab), _translate("MainWindow", "Spectrogram", None)) + self.tabGroup.setTabText(self.tabGroup.indexOf( + self.specTab), _translate("MainWindow", "Spectrogram", None)) self.menu_File.setTitle(_translate("MainWindow", "&File", None)) self.action_open.setText(_translate("MainWindow", "&Open", None)) self.action_open.setShortcut(_translate("MainWindow", "Ctrl+O", None)) self.action_exit.setText(_translate("MainWindow", "E&xit", None)) self.action_reload.setText(_translate("MainWindow", "&Reload", None)) - -from PyQt5 import Qwt diff --git a/gr-utils/read_file_metadata/gr_read_file_metadata b/gr-utils/read_file_metadata/gr_read_file_metadata index a3b851b0d02..6bacfac0ae0 100755 --- a/gr-utils/read_file_metadata/gr_read_file_metadata +++ b/gr-utils/read_file_metadata/gr_read_file_metadata @@ -14,6 +14,7 @@ from argparse import ArgumentParser import pmt from gnuradio.blocks import parse_file_metadata + def main(filename, detached=False): handle = open(filename, "rb") @@ -30,7 +31,8 @@ def main(filename, detached=False): try: header = pmt.deserialize_str(header_str) except RuntimeError: - sys.stderr.write("Could not deserialize header: invalid or corrupt data file.\n") + sys.stderr.write( + "Could not deserialize header: invalid or corrupt data file.\n") sys.exit(1) print("HEADER {0}".format(nheaders)) @@ -44,11 +46,13 @@ def main(filename, detached=False): try: extra = pmt.deserialize_str(extra_str) except RuntimeError: - sys.stderr.write("Could not deserialize extras: invalid or corrupt data file.\n") + sys.stderr.write( + "Could not deserialize extras: invalid or corrupt data file.\n") sys.exit(1) print("\nExtra Header:") - extra_info = parse_file_metadata.parse_extra_dict(extra, info, True) + extra_info = parse_file_metadata.parse_extra_dict( + extra, info, True) nheaders += 1 nread += parse_file_metadata.HEADER_LENGTH + info["extra_len"] @@ -61,11 +65,12 @@ def main(filename, detached=False): if __name__ == "__main__": description = "Read in a GNU Radio file with meta data, extracts the header and prints it." - parser = ArgumentParser(conflict_handler="resolve", description=description) + parser = ArgumentParser(conflict_handler="resolve", + description=description) parser.add_argument("-D", "--detached", action="store_true", - help="Used if header is detached.") + help="Used if header is detached.") parser.add_argument("file", metavar="FILE", - help="Input file"); + help="Input file") args = parser.parse_args() main(args.file, args.detached) diff --git a/gr-vocoder/examples/alaw_audio_loopback.py b/gr-vocoder/examples/alaw_audio_loopback.py index 8f759ac092e..5af109b4be3 100644 --- a/gr-vocoder/examples/alaw_audio_loopback.py +++ b/gr-vocoder/examples/alaw_audio_loopback.py @@ -13,6 +13,7 @@ from gnuradio import blocks from gnuradio import vocoder + def build_graph(): tb = gr.top_block() src = audio.source(8000) @@ -26,9 +27,10 @@ def build_graph(): tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb + if __name__ == '__main__': tb = build_graph() tb.start() - input ('Press Enter to exit: ') + input('Press Enter to exit: ') tb.stop() tb.wait() diff --git a/gr-vocoder/examples/codec2_audio_loopback.py b/gr-vocoder/examples/codec2_audio_loopback.py index e49279fc869..930bd8cf8ac 100644 --- a/gr-vocoder/examples/codec2_audio_loopback.py +++ b/gr-vocoder/examples/codec2_audio_loopback.py @@ -14,6 +14,7 @@ from gnuradio import vocoder from gnuradio.vocoder import codec2 + def build_graph(): tb = gr.top_block() src = audio.source(8000) @@ -27,9 +28,10 @@ def build_graph(): tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb + if __name__ == '__main__': tb = build_graph() tb.start() - input ('Press Enter to exit: ') + input('Press Enter to exit: ') tb.stop() tb.wait() diff --git a/gr-vocoder/examples/cvsd_audio_loopback.py b/gr-vocoder/examples/cvsd_audio_loopback.py index aa12eedca02..79fb5e87685 100644 --- a/gr-vocoder/examples/cvsd_audio_loopback.py +++ b/gr-vocoder/examples/cvsd_audio_loopback.py @@ -14,6 +14,7 @@ from gnuradio import filter from gnuradio import vocoder + def build_graph(): sample_rate = 8000 scale_factor = 32000 @@ -37,22 +38,25 @@ def build_graph(): tb.connect(src, src_scale, interp, f2s, enc) tb.connect(enc, dec, s2f, decim, sink_scale, sink) - if 0: # debug + if 0: # debug tb.connect(src, blocks.file_sink(gr.sizeof_float, "source.dat")) - tb.connect(src_scale, blocks.file_sink(gr.sizeof_float, "src_scale.dat")) + tb.connect(src_scale, blocks.file_sink( + gr.sizeof_float, "src_scale.dat")) tb.connect(interp, blocks.file_sink(gr.sizeof_float, "interp.dat")) tb.connect(f2s, blocks.file_sink(gr.sizeof_short, "f2s.dat")) - tb.connect(enc, blocks.file_sink(gr.sizeof_char, "enc.dat")) + tb.connect(enc, blocks.file_sink(gr.sizeof_char, "enc.dat")) tb.connect(dec, blocks.file_sink(gr.sizeof_short, "dec.dat")) tb.connect(s2f, blocks.file_sink(gr.sizeof_float, "s2f.dat")) tb.connect(decim, blocks.file_sink(gr.sizeof_float, "decim.dat")) - tb.connect(sink_scale, blocks.file_sink(gr.sizeof_float, "sink_scale.dat")) + tb.connect(sink_scale, blocks.file_sink( + gr.sizeof_float, "sink_scale.dat")) return tb + if __name__ == '__main__': tb = build_graph() tb.start() - input ('Press Enter to exit: ') + input('Press Enter to exit: ') tb.stop() tb.wait() diff --git a/gr-vocoder/examples/g721_audio_loopback.py b/gr-vocoder/examples/g721_audio_loopback.py index ac9bdc759d9..6b9261edbac 100644 --- a/gr-vocoder/examples/g721_audio_loopback.py +++ b/gr-vocoder/examples/g721_audio_loopback.py @@ -13,6 +13,7 @@ from gnuradio import blocks from gnuradio import vocoder + def build_graph(): tb = gr.top_block() src = audio.source(8000) @@ -26,9 +27,10 @@ def build_graph(): tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb + if __name__ == '__main__': tb = build_graph() tb.start() - input ('Press Enter to exit: ') + input('Press Enter to exit: ') tb.stop() tb.wait() diff --git a/gr-vocoder/examples/g723_24_audio_loopback.py b/gr-vocoder/examples/g723_24_audio_loopback.py index e755f38cd4d..f8c09ccfedd 100644 --- a/gr-vocoder/examples/g723_24_audio_loopback.py +++ b/gr-vocoder/examples/g723_24_audio_loopback.py @@ -13,6 +13,7 @@ from gnuradio import blocks from gnuradio import vocoder + def build_graph(): tb = gr.top_block() src = audio.source(8000) @@ -26,9 +27,10 @@ def build_graph(): tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb + if __name__ == '__main__': tb = build_graph() tb.start() - input ('Press Enter to exit: ') + input('Press Enter to exit: ') tb.stop() tb.wait() diff --git a/gr-vocoder/examples/g723_40_audio_loopback.py b/gr-vocoder/examples/g723_40_audio_loopback.py index fbc10b871c0..742dc8b36af 100644 --- a/gr-vocoder/examples/g723_40_audio_loopback.py +++ b/gr-vocoder/examples/g723_40_audio_loopback.py @@ -13,6 +13,7 @@ from gnuradio import blocks from gnuradio import vocoder + def build_graph(): tb = gr.top_block() src = audio.source(8000) @@ -26,9 +27,10 @@ def build_graph(): tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb + if __name__ == '__main__': tb = build_graph() tb.start() - input ('Press Enter to exit: ') + input('Press Enter to exit: ') tb.stop() tb.wait() diff --git a/gr-vocoder/examples/gsm_audio_loopback.py b/gr-vocoder/examples/gsm_audio_loopback.py index fe6c6bf2ac6..8edf27f87e5 100644 --- a/gr-vocoder/examples/gsm_audio_loopback.py +++ b/gr-vocoder/examples/gsm_audio_loopback.py @@ -13,6 +13,7 @@ from gnuradio import blocks from gnuradio import vocoder + def build_graph(): tb = gr.top_block() src = audio.source(8000) @@ -26,9 +27,10 @@ def build_graph(): tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb + if __name__ == '__main__': tb = build_graph() tb.start() - input ('Press Enter to exit: ') + input('Press Enter to exit: ') tb.stop() tb.wait() diff --git a/gr-vocoder/examples/ulaw_audio_loopback.py b/gr-vocoder/examples/ulaw_audio_loopback.py index 1a3fbd85cf6..fcae71c1c89 100644 --- a/gr-vocoder/examples/ulaw_audio_loopback.py +++ b/gr-vocoder/examples/ulaw_audio_loopback.py @@ -13,6 +13,7 @@ from gnuradio import blocks from gnuradio import vocoder + def build_graph(): tb = gr.top_block() src = audio.source(8000) @@ -26,9 +27,10 @@ def build_graph(): tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb + if __name__ == '__main__': tb = build_graph() tb.start() - input ('Press Enter to exit: ') + input('Press Enter to exit: ') tb.stop() tb.wait() diff --git a/gr-vocoder/python/vocoder/cvsd.py b/gr-vocoder/python/vocoder/cvsd.py index 076031e160a..3ad2e35b7fd 100644 --- a/gr-vocoder/python/vocoder/cvsd.py +++ b/gr-vocoder/python/vocoder/cvsd.py @@ -29,14 +29,15 @@ def __init__(self, resample=8, bw=0.5): ''' gr.hier_block2.__init__(self, "cvsd_encode", - gr.io_signature(1, 1, gr.sizeof_float), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(1, 1, gr.sizeof_char)) # Output signature scale_factor = 32000.0 self.interp = resample src_scale = blocks.multiply_const_ff(scale_factor) - taps = filter.firdes.low_pass(self.interp, self.interp, bw, 2*bw) + taps = filter.firdes.low_pass(self.interp, self.interp, bw, 2 * bw) interp = filter.interp_fir_filter_fff(self.interp, taps) f2s = blocks.float_to_short() enc = vocoder_python.cvsd_encode_sb() @@ -60,15 +61,16 @@ def __init__(self, resample=8, bw=0.5): from 1 to 8. A rate of 8k with a resampling rate of 8 provides a good quality signal. ''' gr.hier_block2.__init__(self, "cvsd_decode", - gr.io_signature(1, 1, gr.sizeof_char), # Input signature - gr.io_signature(1, 1, gr.sizeof_float)) # Output signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_char), + gr.io_signature(1, 1, gr.sizeof_float)) # Output signature scale_factor = 32000.0 self.decim = resample dec = vocoder_python.cvsd_decode_bs() s2f = blocks.short_to_float() - taps = filter.firdes.low_pass(1, 1, bw, 2*bw) + taps = filter.firdes.low_pass(1, 1, bw, 2 * bw) decim = filter.fir_filter_fff(self.decim, taps) sink_scale = blocks.multiply_const_ff(1.0 / scale_factor) diff --git a/gr-vocoder/python/vocoder/qa_cvsd_vocoder.py b/gr-vocoder/python/vocoder/qa_cvsd_vocoder.py index de5ac9f9994..a4df57fdaf6 100644 --- a/gr-vocoder/python/vocoder/qa_cvsd_vocoder.py +++ b/gr-vocoder/python/vocoder/qa_cvsd_vocoder.py @@ -104,7 +104,7 @@ def test01(self): self.tb.connect(src, src_scale, interp, f2s, enc) self.tb.connect(enc, dec, s2f, decim, sink_scale, head, sink) self.tb.run() - print sink.data() + print sink.data() self.assertFloatTuplesAlmostEqual (expected_data, sink.data(), 5) """ diff --git a/gr-zeromq/examples/python/client.py b/gr-zeromq/examples/python/client.py index cabdbebee7b..30a73254e8d 100644 --- a/gr-zeromq/examples/python/client.py +++ b/gr-zeromq/examples/python/client.py @@ -25,6 +25,8 @@ ############################################################################### # GNU Radio top_block ############################################################################### + + class top_block(gr.top_block): def __init__(self, options): gr.top_block.__init__(self) @@ -34,7 +36,7 @@ def __init__(self, options): # socket addresses rpc_adr = "tcp://*:6667" probe_adr = "tcp://*:5557" - source_adr = "tcp://"+self.options.servername+":5555" + source_adr = "tcp://" + self.options.servername + ":5555" # blocks #self.zmq_source = zeromq.req_source(gr.sizeof_float, 1, source_adr) @@ -49,8 +51,8 @@ def __init__(self, options): # ZeroMQ self.rpc_manager = zeromq.rpc_manager() self.rpc_manager.set_reply_socket(rpc_adr) - self.rpc_manager.add_interface("start_fg",self.start_fg) - self.rpc_manager.add_interface("stop_fg",self.stop_fg) + self.rpc_manager.add_interface("start_fg", self.start_fg) + self.rpc_manager.add_interface("stop_fg", self.stop_fg) self.rpc_manager.start_watcher() def start_fg(self): @@ -68,23 +70,29 @@ def stop_fg(self): ############################################################################### # Options Parser ############################################################################### + + def parse_args(): """Argument parser.""" parser = ArgumentParser() parser.add_argument("-s", "--servername", default="localhost", - help="Server hostname") + help="Server hostname") args = parser.parse_args() return args ############################################################################### # Waiter Thread ############################################################################### + + class waiter(Thread): """ To keep the program alive when flowgraph is stopped. """ + def run(self): while keep_running: time.sleep(1) + ############################################################################### # Main ############################################################################### diff --git a/gr-zeromq/examples/python/gui.py b/gr-zeromq/examples/python/gui.py index 3105470ec7b..bbdcb105394 100644 --- a/gr-zeromq/examples/python/gui.py +++ b/gr-zeromq/examples/python/gui.py @@ -19,6 +19,7 @@ from gnuradio import zeromq import signal + class gui(QtGui.QMainWindow): def __init__(self, window_name, options, parent=None): QtGui.QMainWindow.__init__(self, parent) @@ -26,20 +27,23 @@ def __init__(self, window_name, options, parent=None): # give Ctrl+C back to system signal.signal(signal.SIGINT, signal.SIG_DFL) - self.gui = uic.loadUi(os.path.join(os.path.dirname(__file__),'main_window.ui'), self) + self.gui = uic.loadUi(os.path.join( + os.path.dirname(__file__), 'main_window.ui'), self) self.update_timer = Qt.QTimer() # socket addresses - rpc_adr_server = "tcp://"+options.servername+":6666" - rpc_adr_client = "tcp://"+options.clientname+":6667" - probe_adr_server = "tcp://"+options.servername+":5556" - probe_adr_client = "tcp://"+options.clientname+":5557" + rpc_adr_server = "tcp://" + options.servername + ":6666" + rpc_adr_client = "tcp://" + options.clientname + ":6667" + probe_adr_server = "tcp://" + options.servername + ":5556" + probe_adr_client = "tcp://" + options.clientname + ":5557" # ZeroMQ self.probe_manager = zeromq.probe_manager() - self.probe_manager.add_socket(probe_adr_server, 'float32', self.plot_data_server) - self.probe_manager.add_socket(probe_adr_client, 'float32', self.plot_data_client) + self.probe_manager.add_socket( + probe_adr_server, 'float32', self.plot_data_server) + self.probe_manager.add_socket( + probe_adr_client, 'float32', self.plot_data_client) self.rpc_mgr_server = zeromq.rpc_manager() self.rpc_mgr_server.set_request_socket(rpc_adr_server) @@ -69,18 +73,29 @@ def __init__(self, window_name, options, parent=None): grid_server.attach(self.gui.qwtPlotServer) grid_client.attach(self.gui.qwtPlotClient) - #Signals - self.connect(self.update_timer, QtCore.SIGNAL("timeout()"), self.probe_manager.watcher) - self.connect(self.gui.pushButtonRunServer, QtCore.SIGNAL("clicked()"), self.start_fg_server) - self.connect(self.gui.pushButtonStopServer, QtCore.SIGNAL("clicked()"), self.stop_fg_server) - self.connect(self.gui.pushButtonRunClient, QtCore.SIGNAL("clicked()"), self.start_fg_client) - self.connect(self.gui.pushButtonStopClient, QtCore.SIGNAL("clicked()"), self.stop_fg_client) - self.connect(self.gui.comboBox, QtCore.SIGNAL("currentIndexChanged(QString)"), self.set_waveform) - self.connect(self.gui.spinBox, QtCore.SIGNAL("valueChanged(int)"), self.set_gain) - self.shortcut_start = QtGui.QShortcut(Qt.QKeySequence("Ctrl+S"), self.gui) - self.shortcut_stop = QtGui.QShortcut(Qt.QKeySequence("Ctrl+C"), self.gui) - self.shortcut_exit = QtGui.QShortcut(Qt.QKeySequence("Ctrl+D"), self.gui) - self.connect(self.shortcut_exit, QtCore.SIGNAL("activated()"), self.gui.close) + # Signals + self.connect(self.update_timer, QtCore.SIGNAL( + "timeout()"), self.probe_manager.watcher) + self.connect(self.gui.pushButtonRunServer, QtCore.SIGNAL( + "clicked()"), self.start_fg_server) + self.connect(self.gui.pushButtonStopServer, + QtCore.SIGNAL("clicked()"), self.stop_fg_server) + self.connect(self.gui.pushButtonRunClient, QtCore.SIGNAL( + "clicked()"), self.start_fg_client) + self.connect(self.gui.pushButtonStopClient, + QtCore.SIGNAL("clicked()"), self.stop_fg_client) + self.connect(self.gui.comboBox, QtCore.SIGNAL( + "currentIndexChanged(QString)"), self.set_waveform) + self.connect(self.gui.spinBox, QtCore.SIGNAL( + "valueChanged(int)"), self.set_gain) + self.shortcut_start = QtGui.QShortcut( + Qt.QKeySequence("Ctrl+S"), self.gui) + self.shortcut_stop = QtGui.QShortcut( + Qt.QKeySequence("Ctrl+C"), self.gui) + self.shortcut_exit = QtGui.QShortcut( + Qt.QKeySequence("Ctrl+D"), self.gui) + self.connect(self.shortcut_exit, QtCore.SIGNAL( + "activated()"), self.gui.close) # start update timer self.update_timer.start(30) @@ -99,7 +114,7 @@ def stop_fg_client(self): # plot the data from the queues def plot_data(self, plot, samples): - self.x = list(range(0,len(samples),1)) + self.x = list(range(0, len(samples), 1)) self.y = samples # clear the previous points from the plot plot.clear() @@ -117,24 +132,26 @@ def plot_data_client(self, samples): self.plot_data(self.gui.qwtPlotClient, samples) def set_waveform(self, waveform_str): - self.rpc_mgr_server.request("set_waveform",[str(waveform_str)]) + self.rpc_mgr_server.request("set_waveform", [str(waveform_str)]) def set_gain(self, gain): self.rpc_set_gain(gain) def rpc_set_gain(self, gain): - self.rpc_mgr_server.request("set_k",[gain]) + self.rpc_mgr_server.request("set_k", [gain]) ############################################################################### # Options Parser ############################################################################### + + def parse_args(): """Options parser.""" parser = ArgumentParser() parser.add_argument("-s", "--servername", default="localhost", - help="Server hostname") + help="Server hostname") parser.add_argument("-c", "--clientname", default="localhost", - help="Server hostname") + help="Server hostname") args = parser.parse_args() return args @@ -148,4 +165,3 @@ def parse_args(): qapp.main_window = gui("Remote GNU Radio GUI", args) qapp.main_window.show() qapp.exec_() - diff --git a/gr-zeromq/examples/python/server.py b/gr-zeromq/examples/python/server.py index 24b9484cbe9..3721fba163d 100644 --- a/gr-zeromq/examples/python/server.py +++ b/gr-zeromq/examples/python/server.py @@ -40,7 +40,8 @@ def __init__(self, options): self.samp_rate = samp_rate = 48200 # blocks - self.gr_sig_source = analog.sig_source_f(samp_rate, analog.GR_SIN_WAVE , 1000, 1, 0) + self.gr_sig_source = analog.sig_source_f( + samp_rate, analog.GR_SIN_WAVE, 1000, 1, 0) self.throttle = blocks.throttle(gr.sizeof_float, samp_rate) self.mult = blocks.multiply_const_ff(1) #self.zmq_sink = zeromq.rep_sink(gr.sizeof_float, 1, sink_adr) @@ -51,17 +52,19 @@ def __init__(self, options): #self.null_sink = blocks.null_sink(gr.sizeof_float) # connects - self.connect(self.gr_sig_source, self.mult, self.throttle, self.zmq_sink) + self.connect(self.gr_sig_source, self.mult, + self.throttle, self.zmq_sink) self.connect(self.throttle, self.zmq_probe) # ZeroMQ self.rpc_manager = zeromq.rpc_manager() self.rpc_manager.set_reply_socket(rpc_adr) - self.rpc_manager.add_interface("start_fg",self.start_fg) - self.rpc_manager.add_interface("stop_fg",self.stop_fg) - self.rpc_manager.add_interface("set_waveform",self.set_waveform) - self.rpc_manager.add_interface("set_k",self.mult.set_k) - self.rpc_manager.add_interface("get_sample_rate",self.throttle.sample_rate) + self.rpc_manager.add_interface("start_fg", self.start_fg) + self.rpc_manager.add_interface("stop_fg", self.stop_fg) + self.rpc_manager.add_interface("set_waveform", self.set_waveform) + self.rpc_manager.add_interface("set_k", self.mult.set_k) + self.rpc_manager.add_interface( + "get_sample_rate", self.throttle.sample_rate) self.rpc_manager.start_watcher() def start_fg(self): @@ -77,23 +80,26 @@ def stop_fg(self): self.wait() def set_waveform(self, waveform_str): - waveform = {'Constant' : analog.GR_CONST_WAVE, - 'Sine' : analog.GR_SIN_WAVE, - 'Cosine' : analog.GR_COS_WAVE, - 'Square' : analog.GR_SQR_WAVE, - 'Triangle' : analog.GR_TRI_WAVE, - 'Saw Tooth' : analog.GR_SAW_WAVE}[waveform_str] + waveform = {'Constant': analog.GR_CONST_WAVE, + 'Sine': analog.GR_SIN_WAVE, + 'Cosine': analog.GR_COS_WAVE, + 'Square': analog.GR_SQR_WAVE, + 'Triangle': analog.GR_TRI_WAVE, + 'Saw Tooth': analog.GR_SAW_WAVE}[waveform_str] self.gr_sig_source.set_waveform(waveform) ############################################################################### # Options Parser ############################################################################### + + def parse_args(): """Argument parser.""" parser = ArgumentParser() args = parser.parse_args() return args + ############################################################################### # Main ############################################################################### diff --git a/gr-zeromq/python/zeromq/probe_manager.py b/gr-zeromq/python/zeromq/probe_manager.py index 0cdc2c54585..98ee3bb8fb7 100644 --- a/gr-zeromq/python/zeromq/probe_manager.py +++ b/gr-zeromq/python/zeromq/probe_manager.py @@ -11,6 +11,7 @@ import zmq import numpy + class probe_manager(object): def __init__(self): self.zmq_context = zmq.Context() diff --git a/gr-zeromq/python/zeromq/rpc_manager.py b/gr-zeromq/python/zeromq/rpc_manager.py index 389214bb413..ba7a0ac86dc 100644 --- a/gr-zeromq/python/zeromq/rpc_manager.py +++ b/gr-zeromq/python/zeromq/rpc_manager.py @@ -58,7 +58,7 @@ def watcher(self): self.rep_socket.send(pmt.serialize_str(pmt.to_pmt(reply))) def start_watcher(self): - self.watcher_thread = threading.Thread(target=self.watcher,args=()) + self.watcher_thread = threading.Thread(target=self.watcher, args=()) self.watcher_thread.daemon = True self.watcher_thread.start() @@ -69,7 +69,7 @@ def stop_watcher(self): def request(self, id_str, args=None): socks = dict(self.poller_req_out.poll(10)) if socks.get(self.req_socket) == zmq.POLLOUT: - self.req_socket.send(pmt.serialize_str(pmt.to_pmt((id_str,args)))) + self.req_socket.send(pmt.serialize_str(pmt.to_pmt((id_str, args)))) socks = dict(self.poller_req_in.poll(10)) if socks.get(self.req_socket) == zmq.POLLIN: reply = pmt.to_python(pmt.deserialize_str(self.req_socket.recv())) diff --git a/grc/compiler.py b/grc/compiler.py index 2478055daf4..e0f51e51d30 100755 --- a/grc/compiler.py +++ b/grc/compiler.py @@ -38,7 +38,8 @@ def main(args=None): name='GNU Radio Companion Compiler', prefs=gr.prefs(), version=gr.version(), - version_parts=(gr.major_version(), gr.api_version(), gr.minor_version()) + version_parts=(gr.major_version(), + gr.api_version(), gr.minor_version()) ) platform.build_library() diff --git a/grc/converter/block.py b/grc/converter/block.py index 369e709286d..ceddfc7615d 100644 --- a/grc/converter/block.py +++ b/grc/converter/block.py @@ -94,7 +94,8 @@ def convert_block_xml(node): data['asserts'] = [converter.to_python_dec(check_node.text) for check_node in node.iterfind('check')] or no_value - data['templates'] = convert_templates(node, converter.to_mako, block_id) or no_value + data['templates'] = convert_templates( + node, converter.to_mako, block_id) or no_value docs = node.findtext('doc') if docs: @@ -103,7 +104,8 @@ def convert_block_xml(node): data['file_format'] = current_file_format - data = OrderedDict((key, value) for key, value in data.items() if value is not no_value) + data = OrderedDict((key, value) + for key, value in data.items() if value is not no_value) auto_hide_params_for_item_sizes(data) return data @@ -116,8 +118,10 @@ def auto_hide_params_for_item_sizes(data): for key in ['dtype', 'multiplicity']: item_size_templates.append(str(port.get(key, ''))) vlen_templates.append(str(port.get('vlen', ''))) - item_size_templates = ' '.join(value for value in item_size_templates if '${' in value) - vlen_templates = ' '.join(value for value in vlen_templates if '${' in value) + item_size_templates = ' '.join( + value for value in item_size_templates if '${' in value) + vlen_templates = ' '.join( + value for value in vlen_templates if '${' in value) for param in data.get('parameters', []): if param['id'] in item_size_templates: @@ -135,7 +139,8 @@ def convert_templates(node, convert, block_id=''): imports = yaml.MultiLineString(imports) templates['imports'] = imports or no_value - templates['var_make'] = convert(node.findtext('var_make') or '') or no_value + templates['var_make'] = convert( + node.findtext('var_make') or '') or no_value make = convert(node.findtext('make') or '') if make: @@ -160,8 +165,10 @@ def convert_param_xml(node, convert): param['dtype'] = convert(node.findtext('type') or '') param['default'] = node.findtext('value') or no_value - options = yaml.ListFlowing(on.findtext('key') for on in node.iterfind('option')) - option_labels = yaml.ListFlowing(on.findtext('name') for on in node.iterfind('option')) + options = yaml.ListFlowing(on.findtext('key') + for on in node.iterfind('option')) + option_labels = yaml.ListFlowing(on.findtext( + 'name') for on in node.iterfind('option')) param['options'] = options or no_value if not all(str(o).title() == l for o, l in zip(options, option_labels)): param['option_labels'] = option_labels @@ -192,7 +199,8 @@ def convert_port_xml(node, convert): else: port['dtype'] = dtype vlen = node.findtext('vlen') - port['vlen'] = int(vlen) if vlen and vlen.isdigit() else convert(vlen) or no_value + port['vlen'] = int(vlen) if vlen and vlen.isdigit( + ) else convert(vlen) or no_value port['multiplicity'] = convert(node.findtext('nports')) or no_value port['optional'] = bool(node.findtext('optional')) or no_value @@ -207,4 +215,5 @@ def check_mako_template(block_id, expr): try: Template(expr) except Exception as error: - print(block_id, expr, type(error), error, '', sep='\n', file=sys.stderr) + print(block_id, expr, type(error), error, + '', sep='\n', file=sys.stderr) diff --git a/grc/converter/cheetah_converter.py b/grc/converter/cheetah_converter.py index 62220812c62..778b9c9ac1d 100644 --- a/grc/converter/cheetah_converter.py +++ b/grc/converter/cheetah_converter.py @@ -18,7 +18,8 @@ r'(?P[_a-zA-Z][_a-zA-Z0-9]*(?:\.[_a-zA-Z][_a-zA-Z0-9]*)?)(?P\(\))?' r'(?(d1)\)|(?(d2)\}|(?(d3)\]|)))$' ) -cheetah_inline_if = re.compile(r'#if (?P.*) then (?P.*?) ?else (?P.*?) ?(#|$)') +cheetah_inline_if = re.compile( + r'#if (?P.*) then (?P.*?) ?else (?P.*?) ?(#|$)') class Python(object): @@ -116,7 +117,8 @@ def convert_simple(self, expr, spec=Python): return spec.type(out) def convert_hard(self, expr, spec=Python): - lines = '\n'.join(self.convert_hard_line(line, spec) for line in expr.split('\n')) + lines = '\n'.join(self.convert_hard_line(line, spec) + for line in expr.split('\n')) if spec == Mako: # no line-continuation before a mako control structure lines = re.sub(r'\\\n(\s*%)', r'\n\1', lines) @@ -220,7 +222,8 @@ def extra_close(): out.append(char) delim_to_find = False - elif delim_to_find and char in ')]}' and extra_close(): # end of substitution + # end of substitution + elif delim_to_find and char in ')]}' and extra_close(): out.append(spec.end) out.append(char) delim_to_find = False @@ -235,7 +238,8 @@ def extra_close(): out = ''.join(out) # fix: eval stuff - out = re.sub(r'(?P' + r'|'.join(self.extended) + r')\(\)', r'\g', out) + out = re.sub(r'(?P' + r'|'.join(self.extended) + + r')\(\)', r'\g', out) self.stats['hard'] += 1 return spec.type(out) diff --git a/grc/converter/main.py b/grc/converter/main.py index c5da997407b..5eb80a504fd 100644 --- a/grc/converter/main.py +++ b/grc/converter/main.py @@ -50,7 +50,8 @@ def run(self, force=False): self._force = force try: - logger.debug("Loading block cache from: {}".format(self.cache_file)) + logger.debug( + "Loading block cache from: {}".format(self.cache_file)) with open(self.cache_file, encoding='utf-8') as cache_file: self.cache = byteify(json.load(cache_file)) except (IOError, ValueError): @@ -108,7 +109,8 @@ def load_block_xml(self, xml_file, force=False): def load_category_tree_xml(self, xml_file): """Validate and parse category tree file and add it to list""" - module_name = path.basename(xml_file)[:-len('block_tree.xml')].rstrip('._-') + module_name = path.basename( + xml_file)[:-len('block_tree.xml')].rstrip('._-') yml_file = path.join(self.output_dir, module_name + '.tree.yml') if not self.needs_conversion(xml_file, yml_file): @@ -142,7 +144,8 @@ def iter_files_in_block_path(self, suffix='.xml'): if name.endswith(suffix): yield path.join(root, name) else: - logger.warning('Invalid entry in search path: {}'.format(block_path)) + logger.warning( + 'Invalid entry in search path: {}'.format(block_path)) def byteify(data): diff --git a/grc/converter/xml.py b/grc/converter/xml.py index a3c4cb457a7..fab97f93bc5 100644 --- a/grc/converter/xml.py +++ b/grc/converter/xml.py @@ -53,7 +53,7 @@ def load_stdlib(filename, document_type_def=None): if isinstance(filename, str): with open(filename, 'rb') as xml_file: data = xml_file.read().decode('utf-8') - else: # Already opened + else: # Already opened data = filename.read().decode('utf-8') try: diff --git a/grc/core/Config.py b/grc/core/Config.py index 73cc1358613..374a3f2316a 100644 --- a/grc/core/Config.py +++ b/grc/core/Config.py @@ -17,13 +17,16 @@ class Config(object): license = __doc__.strip() website = 'https://www.gnuradio.org/' - hier_block_lib_dir = os.environ.get('GRC_HIER_PATH', Constants.DEFAULT_HIER_BLOCK_LIB_DIR) + hier_block_lib_dir = os.environ.get( + 'GRC_HIER_PATH', Constants.DEFAULT_HIER_BLOCK_LIB_DIR) def __init__(self, version, version_parts=None, name=None, prefs=None): self._gr_prefs = prefs if prefs else DummyPrefs() self.version = version - self.version_parts = version_parts or version[1:].split('-', 1)[0].split('.')[:3] - self.enabled_components = self._gr_prefs.get_string('grc', 'enabled_components', '') + self.version_parts = version_parts or version[1:].split( + '-', 1)[0].split('.')[:3] + self.enabled_components = self._gr_prefs.get_string( + 'grc', 'enabled_components', '') if name: self.name = name diff --git a/grc/core/Connection.py b/grc/core/Connection.py index b1c7196e3d1..a341abe72ae 100644 --- a/grc/core/Connection.py +++ b/grc/core/Connection.py @@ -96,12 +96,14 @@ def validate(self): if source_dtype != sink_dtype and source_dtype not in ALIASES_OF.get( sink_dtype, set() ): - self.add_error_message('Source IO type "{}" does not match sink IO type "{}".'.format(source_dtype, sink_dtype)) + self.add_error_message('Source IO type "{}" does not match sink IO type "{}".'.format( + source_dtype, sink_dtype)) source_size = self.source_port.item_size sink_size = self.sink_port.item_size if source_size != sink_size: - self.add_error_message('Source IO size "{}" does not match sink IO size "{}".'.format(source_size, sink_size)) + self.add_error_message( + 'Source IO size "{}" does not match sink IO size "{}".'.format(source_size, sink_size)) ############################################## # Import/Export Methods diff --git a/grc/core/Constants.py b/grc/core/Constants.py index 953676ffdec..93adec26be2 100644 --- a/grc/core/Constants.py +++ b/grc/core/Constants.py @@ -41,7 +41,7 @@ # File creation modes TOP_BLOCK_FILE_MODE = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | \ - stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH + stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH HIER_BLOCK_FILE_MODE = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH PARAM_TYPE_NAMES = { @@ -50,7 +50,7 @@ 'complex_vector', 'real_vector', 'float_vector', 'int_vector', 'hex', 'string', 'bool', 'file_open', 'file_save', 'dir_select', '_multiline', '_multiline_python_external', - 'id', 'stream_id','name', + 'id', 'stream_id', 'name', 'gui_hint', 'import', } @@ -89,31 +89,31 @@ GRC_COLOR_WHITE = '#FFFFFF' CORE_TYPES = ( # name, key, sizeof, color - ('Complex Float 64', 'fc64', 16, GRC_COLOR_BROWN), - ('Complex Float 32', 'fc32', 8, GRC_COLOR_BLUE), - ('Complex Integer 64', 'sc64', 16, GRC_COLOR_LIGHT_GREEN), - ('Complex Integer 32', 'sc32', 8, GRC_COLOR_GREEN), - ('Complex Integer 16', 'sc16', 4, GRC_COLOR_AMBER), - ('Complex Integer 8', 'sc8', 2, GRC_COLOR_PURPLE), - ('Float 64', 'f64', 8, GRC_COLOR_CYAN), - ('Float 32', 'f32', 4, GRC_COLOR_ORANGE), - ('Integer 64', 's64', 8, GRC_COLOR_LIME), - ('Integer 32', 's32', 4, GRC_COLOR_TEAL), - ('Integer 16', 's16', 2, GRC_COLOR_YELLOW), - ('Integer 8', 's8', 1, GRC_COLOR_PURPLE_A400), - ('Bits (unpacked byte)', 'bit', 1, GRC_COLOR_PURPLE_A100), - ('Async Message', 'message', 0, GRC_COLOR_GREY), - ('Bus Connection', 'bus', 0, GRC_COLOR_WHITE), - ('Wildcard', '', 0, GRC_COLOR_WHITE), + ('Complex Float 64', 'fc64', 16, GRC_COLOR_BROWN), + ('Complex Float 32', 'fc32', 8, GRC_COLOR_BLUE), + ('Complex Integer 64', 'sc64', 16, GRC_COLOR_LIGHT_GREEN), + ('Complex Integer 32', 'sc32', 8, GRC_COLOR_GREEN), + ('Complex Integer 16', 'sc16', 4, GRC_COLOR_AMBER), + ('Complex Integer 8', 'sc8', 2, GRC_COLOR_PURPLE), + ('Float 64', 'f64', 8, GRC_COLOR_CYAN), + ('Float 32', 'f32', 4, GRC_COLOR_ORANGE), + ('Integer 64', 's64', 8, GRC_COLOR_LIME), + ('Integer 32', 's32', 4, GRC_COLOR_TEAL), + ('Integer 16', 's16', 2, GRC_COLOR_YELLOW), + ('Integer 8', 's8', 1, GRC_COLOR_PURPLE_A400), + ('Bits (unpacked byte)', 'bit', 1, GRC_COLOR_PURPLE_A100), + ('Async Message', 'message', 0, GRC_COLOR_GREY), + ('Bus Connection', 'bus', 0, GRC_COLOR_WHITE), + ('Wildcard', '', 0, GRC_COLOR_WHITE), ) ALIAS_TYPES = { 'complex': (8, GRC_COLOR_BLUE), - 'float': (4, GRC_COLOR_ORANGE), - 'int': (4, GRC_COLOR_TEAL), - 'short': (2, GRC_COLOR_YELLOW), - 'byte': (1, GRC_COLOR_PURPLE_A400), - 'bits': (1, GRC_COLOR_PURPLE_A100), + 'float': (4, GRC_COLOR_ORANGE), + 'int': (4, GRC_COLOR_TEAL), + 'short': (2, GRC_COLOR_YELLOW), + 'byte': (1, GRC_COLOR_PURPLE_A400), + 'bits': (1, GRC_COLOR_PURPLE_A100), } ALIASES_OF = { @@ -135,4 +135,5 @@ } TYPE_TO_SIZEOF = {key: sizeof for name, key, sizeof, color in CORE_TYPES} -TYPE_TO_SIZEOF.update((key, sizeof) for key, (sizeof, _) in ALIAS_TYPES.items()) +TYPE_TO_SIZEOF.update((key, sizeof) + for key, (sizeof, _) in ALIAS_TYPES.items()) diff --git a/grc/core/FlowGraph.py b/grc/core/FlowGraph.py index ad42371bb8d..ae567d003da 100644 --- a/grc/core/FlowGraph.py +++ b/grc/core/FlowGraph.py @@ -68,7 +68,8 @@ def get_variables(self): Returns: a sorted list of variable blocks in order of dependency (indep -> dep) """ - variables = [block for block in self.iter_enabled_blocks() if block.is_variable] + variables = [block for block in self.iter_enabled_blocks() + if block.is_variable] return expr_utils.sort_objects(variables, attrgetter('name'), methodcaller('get_var_make')) def get_parameters(self): @@ -78,7 +79,8 @@ def get_parameters(self): Returns: a list of parameterized variables """ - parameters = [b for b in self.iter_enabled_blocks() if b.key == 'parameter'] + parameters = [b for b in self.iter_enabled_blocks() + if b.key == 'parameter'] return parameters def get_snippets(self): @@ -126,7 +128,8 @@ def get_monitors(self): """ Get a list of all ControlPort monitors """ - monitors = [b for b in self.iter_enabled_blocks() if 'ctrlport_monitor' in b.key] + monitors = [b for b in self.iter_enabled_blocks() + if 'ctrlport_monitor' in b.key] return monitors def get_python_modules(self): @@ -189,7 +192,8 @@ def get_run_command(self, file_path, split=False): filename=shlex.quote(file_path)) return shlex.split(run_command) if split else run_command except Exception as e: - raise ValueError("Can't parse run command {!r}: {}".format(run_command, e)) + raise ValueError( + "Can't parse run command {!r}: {}".format(run_command, e)) def get_imported_names(self): """ @@ -241,7 +245,8 @@ def renew_namespace(self): # this is ok behavior, unfortunately we could be hiding other import bugs pass except Exception: - log.exception('Failed to evaluate import expression "{0}"'.format(expr), exc_info=True) + log.exception('Failed to evaluate import expression "{0}"'.format( + expr), exc_info=True) pass self.imported_names = list(namespace.keys()) @@ -252,17 +257,20 @@ def renew_namespace(self): exec(expr, module.__dict__) namespace[id] = module except Exception: - log.exception('Failed to evaluate expression in module {0}'.format(id), exc_info=True) + log.exception( + 'Failed to evaluate expression in module {0}'.format(id), exc_info=True) pass # Load parameters np = {} # params don't know each other for parameter_block in self.get_parameters(): try: - value = eval(parameter_block.params['value'].to_code(), namespace) + value = eval( + parameter_block.params['value'].to_code(), namespace) np[parameter_block.name] = value except Exception: - log.exception('Failed to evaluate parameter block {0}'.format(parameter_block.name), exc_info=True) + log.exception('Failed to evaluate parameter block {0}'.format( + parameter_block.name), exc_info=True) pass namespace.update(np) # Merge param namespace @@ -273,13 +281,16 @@ def renew_namespace(self): for variable_block in self.get_variables(): try: variable_block.rewrite() - value = eval(variable_block.value, namespace, variable_block.namespace) + value = eval(variable_block.value, namespace, + variable_block.namespace) namespace[variable_block.name] = value - self.namespace.update(namespace) # rewrite on subsequent blocks depends on an updated self.namespace - except TypeError: #Type Errors may happen, but that doesn't matter as they are displayed in the gui + # rewrite on subsequent blocks depends on an updated self.namespace + self.namespace.update(namespace) + except TypeError: # Type Errors may happen, but that doesn't matter as they are displayed in the gui pass except Exception: - log.exception('Failed to evaluate variable block {0}'.format(variable_block.name), exc_info=True) + log.exception('Failed to evaluate variable block {0}'.format( + variable_block.name), exc_info=True) pass self._eval_cache.clear() @@ -397,7 +408,8 @@ def _build_depending_hier_block(self, block_id): cwd=self.grc_file_path ) if file_path: # grc file found. load and get block - self.parent_platform.load_and_generate_flow_graph(file_path, hier_only=True) + self.parent_platform.load_and_generate_flow_graph( + file_path, hier_only=True) return self.new_block(block_id) # can be None def import_data(self, data): @@ -424,7 +436,8 @@ def import_data(self, data): block = ( self.new_block(block_id) or self._build_depending_hier_block(block_id) or - self.new_block(block_id='_dummy', missing_block_id=block_id, **block_data) + self.new_block(block_id='_dummy', + missing_block_id=block_id, **block_data) ) block.import_data(**block_data) @@ -443,7 +456,8 @@ def verify_and_get_port(key, block, dir): if block.is_dummy_block: port = block.add_missing_port(key, dir) else: - raise LookupError('%s key %r not in %s block keys' % (dir, key, dir)) + raise LookupError( + '%s key %r not in %s block keys' % (dir, key, dir)) return port had_connect_errors = False @@ -461,8 +475,10 @@ def verify_and_get_port(key, block, dir): src_port_id, snk_port_id, source_block, sink_block) # build the connection - source_port = verify_and_get_port(src_port_id, source_block, 'source') - sink_port = verify_and_get_port(snk_port_id, sink_block, 'sink') + source_port = verify_and_get_port( + src_port_id, source_block, 'source') + sink_port = verify_and_get_port( + snk_port_id, sink_block, 'sink') self.connect(source_port, sink_port) @@ -478,7 +494,8 @@ def verify_and_get_port(key, block, dir): # Flowgraph errors depending on disabled blocks are not displayed # in the error dialog box # So put a message into the Property window of the dummy block - block.add_error_message('Block id "{}" not found.'.format(block.key)) + block.add_error_message( + 'Block id "{}" not found.'.format(block.key)) self.rewrite() # global rewrite return had_connect_errors diff --git a/grc/core/Messages.py b/grc/core/Messages.py index e6297d98c8b..778a6baaab4 100644 --- a/grc/core/Messages.py +++ b/grc/core/Messages.py @@ -5,7 +5,6 @@ # - import traceback import sys @@ -43,6 +42,7 @@ def send(message): for messenger in MESSENGERS_LIST: messenger(_indent + message) + # register stdout by default register_messenger(sys.stdout.write) @@ -117,7 +117,8 @@ def send_fail_save(file_path): def send_fail_connection(msg=''): - send('>>> Error: Cannot create connection.\n' + ('\t{}\n'.format(msg) if msg else '')) + send('>>> Error: Cannot create connection.\n' + + ('\t{}\n'.format(msg) if msg else '')) def send_fail_load_preferences(prefs_file_path): diff --git a/grc/core/__init__.py b/grc/core/__init__.py index 8b137891791..e69de29bb2d 100644 --- a/grc/core/__init__.py +++ b/grc/core/__init__.py @@ -1 +0,0 @@ - diff --git a/grc/core/blocks/__init__.py b/grc/core/blocks/__init__.py index a80121e8bf5..cc5297ece41 100644 --- a/grc/core/blocks/__init__.py +++ b/grc/core/blocks/__init__.py @@ -21,6 +21,7 @@ def register_build_in(cls): build_ins[cls.key] = cls return cls + from .dummy import DummyBlock from .embedded_python import EPyBlock, EPyModule from .virtual import VirtualSink, VirtualSource diff --git a/grc/core/blocks/_build.py b/grc/core/blocks/_build.py index 40155fc84f3..91ebef1a420 100644 --- a/grc/core/blocks/_build.py +++ b/grc/core/blocks/_build.py @@ -79,7 +79,8 @@ def build_ports(ports_raw, direction): port_id = port.setdefault('id', str(next(stream_port_ids))) if port_id in port_ids: - raise Exception('Port id "{}" already exists in {}s'.format(port_id, direction)) + raise Exception( + 'Port id "{}" already exists in {}s'.format(port_id, direction)) port_ids.add(port_id) ports.append(port) @@ -137,16 +138,19 @@ def _single_mako_expr(value, block_id): return None value = value.strip() if not (value.startswith('${') and value.endswith('}')): - raise ValueError('{} is not a mako substitution in {}'.format(value, block_id)) + raise ValueError( + '{} is not a mako substitution in {}'.format(value, block_id)) return value[2:-1].strip() def _validate_option_attributes(param_data, block_id): if param_data['dtype'] != 'enum': - send_warning('{} - option_attributes are for enums only, ignoring'.format(block_id)) + send_warning( + '{} - option_attributes are for enums only, ignoring'.format(block_id)) del param_data['option_attributes'] else: for key in list(param_data['option_attributes'].keys()): if key in dir(str): del param_data['option_attributes'][key] - send_warning('{} - option_attribute "{}" overrides str, ignoring'.format(block_id, key)) + send_warning( + '{} - option_attribute "{}" overrides str, ignoring'.format(block_id, key)) diff --git a/grc/core/blocks/_templates.py b/grc/core/blocks/_templates.py index 37775cea1d7..8ed69c6eac9 100644 --- a/grc/core/blocks/_templates.py +++ b/grc/core/blocks/_templates.py @@ -16,12 +16,15 @@ # The utils dict contains convenience functions # that can be called from any template + + def no_quotes(string, fallback=None): if len(string) > 2: if str(string)[0] + str(string)[-1] in ("''", '""'): return str(string)[1:-1] return str(fallback if fallback else string) + utils = {'no_quotes': no_quotes} diff --git a/grc/core/blocks/block.py b/grc/core/blocks/block.py index 86c408f6171..89f96f96c89 100644 --- a/grc/core/blocks/block.py +++ b/grc/core/blocks/block.py @@ -22,6 +22,7 @@ from ..base import Element from ..utils.descriptors import lazy_property + def _get_elem(iterable, key): items = list(iterable) for item in items: @@ -39,7 +40,7 @@ class Block(Element): key = '' label = '' category = [] - vtype = '' # This is only used for variables when we want C++ output + vtype = '' # This is only used for variables when we want C++ output flags = Flags('') documentation = {'': ''} @@ -67,13 +68,16 @@ def __init__(self, parent): if self.key == 'options': self.params['id'].hide = 'part' - self.sinks = [port_factory(parent=self, **params) for params in self.inputs_data] - self.sources = [port_factory(parent=self, **params) for params in self.outputs_data] + self.sinks = [port_factory(parent=self, **params) + for params in self.inputs_data] + self.sources = [port_factory(parent=self, **params) + for params in self.outputs_data] self.active_sources = [] # on rewrite self.active_sinks = [] # on rewrite - self.states = {'state': True, 'bus_source': False, 'bus_sink': False, 'bus_structure': None} + self.states = {'state': True, 'bus_source': False, + 'bus_sink': False, 'bus_structure': None} self.block_namespace = {} self.deprecated = self.is_deprecated() @@ -81,7 +85,8 @@ def __init__(self, parent): # This is a workaround to allow embedded python blocks/modules to load as there is # currently 'cpp' in the flags by default caused by the other built-in blocks if hasattr(self, 'cpp_templates'): - self.orig_cpp_templates = self.cpp_templates # The original template, in case we have to edit it when transpiling to C++ + # The original template, in case we have to edit it when transpiling to C++ + self.orig_cpp_templates = self.cpp_templates self.current_bus_structure = {'source': None, 'sink': None} @@ -100,8 +105,8 @@ def get_bus_structure(self, direction): except: return None - # region Rewrite_and_Validation + def rewrite(self): """ Add and remove ports to adjust for the nports. @@ -125,7 +130,8 @@ def rekey(ports): self.update_bus_logic() # disconnect hidden ports - self.parent_flowgraph.disconnect(*[p for p in self.ports() if p.hidden]) + self.parent_flowgraph.disconnect( + *[p for p in self.ports() if p.hidden]) self.active_sources = [p for p in self.sources if not p.hidden] self.active_sinks = [p for p in self.sinks if not p.hidden] @@ -142,11 +148,12 @@ def rekey(ports): # this is ok behavior, unfortunately we could be hiding other import bugs pass except Exception: - self.add_error_message(f'Failed to evaluate import expression {imports!r}') + self.add_error_message( + f'Failed to evaluate import expression {imports!r}') def update_bus_logic(self): ############################### - ## Bus Logic + # Bus Logic ############################### for direc in {'source', 'sink'}: @@ -170,13 +177,12 @@ def update_bus_logic(self): removed_bus_connections.append(c) ports.remove(port) - if (bus_state): struct = self.form_bus_structure(direc) self.current_bus_structure[direc] = struct # Hide ports that are not part of the bus structure - #TODO: Blocks where it is desired to only have a subset + # TODO: Blocks where it is desired to only have a subset # of ports included in the bus still has some issues for idx, port in enumerate(ports): if any([idx in bus for bus in self.current_bus_structure[direc]]): @@ -187,19 +193,20 @@ def update_bus_logic(self): # Add the Bus Ports to the list of ports for i in range(len(struct)): # self.sinks = [port_factory(parent=self, **params) for params in self.inputs_data] - port = self.parent.parent.make_port(self, direction=direc, id=str(len(ports)), label='bus', dtype='bus', bus_struct=struct[i]) + port = self.parent.parent.make_port(self, direction=direc, id=str( + len(ports)), label='bus', dtype='bus', bus_struct=struct[i]) ports.append(port) for (saved_port, connection) in zip(removed_bus_ports, removed_bus_connections): if port.key == saved_port.key: - self.parent_flowgraph.connections.remove(connection) + self.parent_flowgraph.connections.remove( + connection) if saved_port.is_source: connection.source_port = port if saved_port.is_sink: connection.sink_port = port self.parent_flowgraph.connections.add(connection) - else: self.current_bus_structure[direc] = None @@ -209,8 +216,6 @@ def update_bus_logic(self): port.hidden = port.stored_hidden_state port.stored_hidden_state = None - - def _rewrite_nports(self, ports): for port in ports: if hasattr(port, 'master_port'): # Not a master port and no left-over clones @@ -218,7 +223,7 @@ def _rewrite_nports(self, ports): port.vlen = port.master_port.vlen continue nports = port.multiplicity - for clone in port.clones[nports-1:]: + for clone in port.clones[nports - 1:]: # Remove excess connections self.parent_flowgraph.disconnect(clone) port.remove_clone(clone) @@ -245,9 +250,11 @@ def _run_asserts(self): for expr in self.asserts: try: if not self.evaluate(expr): - self.add_error_message('Assertion "{}" failed.'.format(expr)) + self.add_error_message( + 'Assertion "{}" failed.'.format(expr)) except Exception: - self.add_error_message('Assertion "{}" did not evaluate.'.format(expr)) + self.add_error_message( + 'Assertion "{}" did not evaluate.'.format(expr)) def _validate_generate_mode_compat(self): """check if this is a GUI block and matches the selected generate option""" @@ -261,7 +268,8 @@ def check_generate_mode(label, flag, valid_options): self.add_error_message("Can't generate this block in mode: {} ".format( repr(current_generate_option))) - check_generate_mode('QT GUI', Flags.NEED_QT_GUI, ('qt_gui', 'hb_qt_gui')) + check_generate_mode('QT GUI', Flags.NEED_QT_GUI, + ('qt_gui', 'hb_qt_gui')) def _validate_output_language_compat(self): """check if this block supports the selected output language""" @@ -269,19 +277,23 @@ def _validate_output_language_compat(self): if current_output_language == 'cpp': if 'cpp' not in self.flags: - self.add_error_message("This block does not support C++ output.") + self.add_error_message( + "This block does not support C++ output.") if self.key == 'parameter': if not self.params['type'].value: - self.add_error_message("C++ output requires you to choose a parameter type.") + self.add_error_message( + "C++ output requires you to choose a parameter type.") def _validate_var_value(self): """or variables check the value (only if var_value is used)""" if self.is_variable and self.value != 'value': try: - self.parent_flowgraph.evaluate(self.value, local_namespace=self.namespace) + self.parent_flowgraph.evaluate( + self.value, local_namespace=self.namespace) except Exception as err: - self.add_error_message('Value "{}" cannot be evaluated:\n{}'.format(self.value, err)) + self.add_error_message( + 'Value "{}" cannot be evaluated:\n{}'.format(self.value, err)) # endregion # region Properties @@ -458,7 +470,7 @@ def get_type(element, _vtype): # For container types we must also determine the type of the template parameter(s) return 'std::vector<' + get_type(str(evaluated[0]), type(evaluated[0])) + '>' - except IndexError: # empty list + except IndexError: # empty list return 'std::vector' if _vtype == dict: @@ -466,9 +478,9 @@ def get_type(element, _vtype): # For container types we must also determine the type of the template parameter(s) key = list(evaluated)[0] val = list(evaluated.values())[0] - return 'std::map<' + get_type(str(key), type(key)) + ', ' + get_type(str(val), type(val)) +'>' + return 'std::map<' + get_type(str(key), type(key)) + ', ' + get_type(str(val), type(val)) + '>' - except IndexError: # empty dict + except IndexError: # empty dict return 'std::map' else: @@ -480,12 +492,12 @@ def get_type(element, _vtype): # The r-value for these types must be transformed to create legal C++ syntax. if self.vtype in ['bool', 'gr_complex'] or 'std::map' in self.vtype or 'std::vector' in self.vtype: evaluated = ast.literal_eval(value) - self.cpp_templates['var_make'] = self.cpp_templates['var_make'].replace('${value}', self.get_cpp_value(evaluated)) + self.cpp_templates['var_make'] = self.cpp_templates['var_make'].replace( + '${value}', self.get_cpp_value(evaluated)) if 'string' in self.vtype: self.cpp_templates['includes'].append('#include ') - def get_cpp_value(self, pyval): if type(pyval) == int or type(pyval) == float: @@ -494,8 +506,10 @@ def get_cpp_value(self, pyval): # Check for PI and replace with C++ constant pi_re = r'^(math|numpy|np|scipy|sp)\.pi$' if re.match(pi_re, str(pyval)): - val_str = re.sub(pi_re, 'boost::math::constants::pi()', val_str) - self.cpp_templates['includes'].append('#include ') + val_str = re.sub( + pi_re, 'boost::math::constants::pi()', val_str) + self.cpp_templates['includes'].append( + '#include ') return str(pyval) @@ -503,7 +517,8 @@ def get_cpp_value(self, pyval): return str(pyval)[0].lower() + str(pyval)[1:] elif type(pyval) == complex: - self.cpp_templates['includes'].append('#include ') + self.cpp_templates['includes'].append( + '#include ') evaluated = ast.literal_eval(str(pyval).strip()) return '{' + str(evaluated.real) + ', ' + str(evaluated.imag) + '}' @@ -523,7 +538,8 @@ def get_cpp_value(self, pyval): self.cpp_templates['includes'].append('#include ') val_str = '{' for key in pyval: - val_str += '{' + self.get_cpp_value(key) + ', ' + self.get_cpp_value(pyval[key]) + '}, ' + val_str += '{' + self.get_cpp_value(key) + \ + ', ' + self.get_cpp_value(pyval[key]) + '}, ' if len(val_str) > 1: # truncate to trim superfluous ', ' from the end @@ -535,7 +551,6 @@ def get_cpp_value(self, pyval): self.cpp_templates['includes'].append('#include ') return '"' + pyval + '"' - def is_virtual_sink(self): return self.key == 'virtual_sink' @@ -561,8 +576,8 @@ def is_deprecated(self): print(exception.message) return False - # Block bypassing + def get_bypassed(self): """ Check if the block is bypassed @@ -618,7 +633,8 @@ def get_source(self, key): @property def namespace(self): # update block namespace - self.block_namespace.update({key:param.get_evaluated() for key, param in self.params.items()}) + self.block_namespace.update( + {key: param.get_evaluated() for key, param in self.params.items()}) return self.block_namespace @property @@ -721,7 +737,7 @@ def form_bus_structure(self, direc): struct = [range(len(ports))] # struct = list(range(len(ports))) - #TODO for more complicated port structures, this code is needed but not working yet + # TODO for more complicated port structures, this code is needed but not working yet if any([p.multiplicity for p in ports]): structlet = [] last = 0 @@ -736,8 +752,8 @@ def form_bus_structure(self, direc): continue if p.multiplicity > 1: - cnt = p.multiplicity-1 - structlet.append([idx+j for j in range(p.multiplicity)]) + cnt = p.multiplicity - 1 + structlet.append([idx + j for j in range(p.multiplicity)]) else: structlet.append([idx]) diff --git a/grc/core/blocks/dummy.py b/grc/core/blocks/dummy.py index 5cdc05a9dfc..8147eededb9 100644 --- a/grc/core/blocks/dummy.py +++ b/grc/core/blocks/dummy.py @@ -9,6 +9,7 @@ from ._build import build_params + @register_build_in class DummyBlock(Block): @@ -19,12 +20,14 @@ class DummyBlock(Block): def __init__(self, parent, missing_block_id, parameters, **_): self.key = missing_block_id - self.parameters_data = build_params([], False, False, self.flags, self.key) + self.parameters_data = build_params( + [], False, False, self.flags, self.key) super(DummyBlock, self).__init__(parent=parent) param_factory = self.parent_platform.make_param for param_id in parameters: - self.params.setdefault(param_id, param_factory(parent=self, id=param_id, dtype='string')) + self.params.setdefault(param_id, param_factory( + parent=self, id=param_id, dtype='string')) def is_valid(self): return False diff --git a/grc/core/blocks/embedded_python.py b/grc/core/blocks/embedded_python.py index 051ba70317b..893dcda9488 100644 --- a/grc/core/blocks/embedded_python.py +++ b/grc/core/blocks/embedded_python.py @@ -122,7 +122,8 @@ def rewrite(self): self.label = blk_io.name or blk_io.cls self.documentation = {'': blk_io.doc} - self.module_name = "{}_{}".format(self.parent_flowgraph.get_option("id"), self.name) + self.module_name = "{}_{}".format( + self.parent_flowgraph.get_option("id"), self.name) self.templates['imports'] = 'import {} as {} # embedded python block'.format( self.module_name, self.name) self.templates['make'] = '{mod}.{cls}({args})'.format( @@ -131,7 +132,7 @@ def rewrite(self): args=', '.join('{0}=${{ {0} }}'.format(key) for key, _ in blk_io.params)) self.templates['callbacks'] = [ '{0} = ${{ {0} }}'.format(attr) for attr in blk_io.callbacks - ] + ] self._update_params(blk_io.params) self._update_ports('in', self.sinks, blk_io.sinks, 'sink') @@ -195,7 +196,8 @@ def _update_ports(self, label, ports, port_specs, direction): def validate(self): super(EPyBlock, self).validate() if self._epy_reload_error: - self.params['_source_code'].add_error_message(str(self._epy_reload_error)) + self.params['_source_code'].add_error_message( + str(self._epy_reload_error)) @register_build_in @@ -240,6 +242,7 @@ def __init__(self, flow_graph, **kwargs): def rewrite(self): super(EPyModule, self).rewrite() - self.module_name = "{}_{}".format(self.parent_flowgraph.get_option("id"), self.name) + self.module_name = "{}_{}".format( + self.parent_flowgraph.get_option("id"), self.name) self.templates['imports'] = 'import {} as {} # embedded python module'.format( self.module_name, self.name) diff --git a/grc/core/blocks/virtual.py b/grc/core/blocks/virtual.py index 9d1387dbbb4..34e0feb34b9 100644 --- a/grc/core/blocks/virtual.py +++ b/grc/core/blocks/virtual.py @@ -21,7 +21,8 @@ class VirtualSink(Block): flags.set('cpp') parameters_data = build_params( - params_raw=[dict(label='Stream ID', id='stream_id', dtype='stream_id')], + params_raw=[ + dict(label='Stream ID', id='stream_id', dtype='stream_id')], have_inputs=False, have_outputs=False, flags=flags, block_id=key ) inputs_data = [dict(domain='stream', dtype='', direction='sink', id="0")] @@ -45,10 +46,12 @@ class VirtualSource(Block): flags.set('cpp') parameters_data = build_params( - params_raw=[dict(label='Stream ID', id='stream_id', dtype='stream_id')], + params_raw=[ + dict(label='Stream ID', id='stream_id', dtype='stream_id')], have_inputs=False, have_outputs=False, flags=flags, block_id=key ) - outputs_data = [dict(domain='stream', dtype='', direction='source', id="0")] + outputs_data = [dict(domain='stream', dtype='', + direction='source', id="0")] def __init__(self, parent, **kwargs): super(VirtualSource, self).__init__(parent, **kwargs) diff --git a/grc/core/cache.py b/grc/core/cache.py index ab2cc4465bb..59daa4b5cef 100644 --- a/grc/core/cache.py +++ b/grc/core/cache.py @@ -16,7 +16,7 @@ class Cache(object): - def __init__(self, filename, version = None): + def __init__(self, filename, version=None): self.cache_file = filename self.version = version self.cache = {} @@ -57,7 +57,7 @@ def get_or_load(self, filename): if modtime <= self._converter_mtime: try: cached = self.cache[filename] - if int(cached["cached-at"]+0.5) >= modtime: + if int(cached["cached-at"] + 0.5) >= modtime: return cached["data"] logger.info(f"Cache for {filename} outdated, loading yaml") except KeyError: diff --git a/grc/core/errors.py b/grc/core/errors.py index 59f3e0c4360..0b9aefccb76 100644 --- a/grc/core/errors.py +++ b/grc/core/errors.py @@ -5,7 +5,6 @@ # - class GRCError(Exception): """Generic error class""" diff --git a/grc/core/generator/FlowGraphProxy.py b/grc/core/generator/FlowGraphProxy.py index 38d44e5b131..dad36c9240c 100644 --- a/grc/core/generator/FlowGraphProxy.py +++ b/grc/core/generator/FlowGraphProxy.py @@ -8,6 +8,7 @@ from ..utils import expr_utils from operator import methodcaller, attrgetter + class FlowGraphProxy(object): # TODO: move this in a refactored Generator def __init__(self, fg): @@ -59,8 +60,8 @@ def get_hier_block_io(self, direction): 'label': str(pad.params['label'].get_evaluated()), 'type': str(pad.params['type'].get_evaluated()), 'vlen': str(pad.params['vlen'].get_value()), - 'size': type_param.options.attributes[type_param.get_value()]['size'], - 'cpp_size': type_param.options.attributes[type_param.get_value()]['cpp_size'], + 'size': type_param.options.attributes[type_param.get_value()]['size'], + 'cpp_size': type_param.options.attributes[type_param.get_value()]['cpp_size'], 'optional': bool(pad.params['optional'].get_evaluated()), } num_ports = pad.params['num_streams'].get_evaluated() @@ -127,7 +128,8 @@ def get_cpp_variables(self): Returns: a sorted list of variable blocks in order of dependency (indep -> dep) """ - variables = [block for block in self.iter_enabled_blocks() if block.is_variable] + variables = [block for block in self.iter_enabled_blocks() + if block.is_variable] return expr_utils.sort_objects(variables, attrgetter('name'), methodcaller('get_cpp_var_make')) def includes(self): @@ -157,6 +159,7 @@ def packages(self): """ return [block.cpp_templates.render('packages') for block in self.iter_enabled_blocks() if not (block.is_virtual_sink() or block.is_virtual_source())] + def get_hier_block_io(flow_graph, direction, domain=None): """ Get a list of io ports for this flow graph. @@ -172,7 +175,7 @@ def get_hier_block_io(flow_graph, direction, domain=None): 'label': str(pad.params['label'].get_evaluated()), 'type': str(pad.params['type'].get_evaluated()), 'vlen': str(pad.params['vlen'].get_value()), - 'size': type_param.options.attributes[type_param.get_value()]['size'], + 'size': type_param.options.attributes[type_param.get_value()]['size'], 'optional': bool(pad.params['optional'].get_evaluated()), } num_ports = pad.params['num_streams'].get_evaluated() diff --git a/grc/core/generator/Generator.py b/grc/core/generator/Generator.py index 3f1831cc1bf..8932419249e 100644 --- a/grc/core/generator/Generator.py +++ b/grc/core/generator/Generator.py @@ -5,7 +5,6 @@ # - from .hier_block import HierBlockGenerator, QtHierBlockGenerator from .top_block import TopBlockGenerator from .cpp_top_block import CppTopBlockGenerator diff --git a/grc/core/generator/cpp_hier_block.py b/grc/core/generator/cpp_hier_block.py index 67f001568c6..688af19348b 100644 --- a/grc/core/generator/cpp_hier_block.py +++ b/grc/core/generator/cpp_hier_block.py @@ -8,6 +8,7 @@ from .. import Constants from ..io import yaml + class CppHierBlockGenerator(CppTopBlockGenerator): """Extends the top block generator to also generate a block YML file""" @@ -27,7 +28,8 @@ def __init__(self, flow_graph, file_path): os.mkdir(hier_block_lib_dir) self._mode = Constants.HIER_BLOCK_FILE_MODE - self.file_path = os.path.join(hier_block_lib_dir, self._flow_graph.get_option('id')) + self.file_path = os.path.join( + hier_block_lib_dir, self._flow_graph.get_option('id')) self.file_path_yml = self.file_path + '.block.yml' def write(self): @@ -55,7 +57,6 @@ def write(self): # Windows only supports S_IREAD and S_IWRITE, other flags are ignored os.chmod(self.file_path_yml, self._mode) - def _build_block_n_from_flow_graph_io(self): """ Generate a block YML nested data from the flow graph IO @@ -136,7 +137,8 @@ def var_or_value(name): t_cpp = data['cpp_templates'] = collections.OrderedDict() t_cpp['includes'] = [] - t_cpp['includes'].append('#include "{id}/{id}.hpp"'.format(id=self._flow_graph.get_option('id'))) + t_cpp['includes'].append( + '#include "{id}/{id}.hpp"'.format(id=self._flow_graph.get_option('id'))) # Make data if parameters: @@ -147,7 +149,8 @@ def var_or_value(name): ), ) else: - t_cpp['make'] = 'this->${{id}} = {cls}_sptr(make_{cls}());'.format(cls=block_id) + t_cpp['make'] = 'this->${{id}} = {cls}_sptr(make_{cls}());'.format( + cls=block_id) t_cpp['declarations'] = '{cls}_sptr ${{id}};'.format(cls=block_id) # Callback data @@ -206,7 +209,8 @@ def get_hier_block_io(flow_graph, direction, domain=None): Returns a list of dicts with: type, label, vlen, size, optional """ - pads = flow_graph.get_pad_sources() if direction == 'inputs' else flow_graph.get_pad_sinks() + pads = flow_graph.get_pad_sources( + ) if direction == 'inputs' else flow_graph.get_pad_sinks() for pad in pads: for port in (pad.sources if direction == 'inputs' else pad.sinks): diff --git a/grc/core/generator/cpp_top_block.py b/grc/core/generator/cpp_top_block.py index ee9dc1a314a..3ee712553fa 100644 --- a/grc/core/generator/cpp_top_block.py +++ b/grc/core/generator/cpp_top_block.py @@ -38,7 +38,8 @@ def __init__(self, flow_graph, output_dir): """ self._flow_graph = FlowGraphProxy(flow_graph) - self._generate_options = self._flow_graph.get_option('generate_options') + self._generate_options = self._flow_graph.get_option( + 'generate_options') self._mode = TOP_BLOCK_FILE_MODE # Handle the case where the directory is read-only @@ -48,25 +49,26 @@ def __init__(self, flow_graph, output_dir): filename = self._flow_graph.get_option('id') self.file_path = os.path.join(output_dir, filename) self.output_dir = output_dir - + def _warnings(self): throttling_blocks = [b for b in self._flow_graph.get_enabled_blocks() - if b.flags.throttle] + if b.flags.throttle] if not throttling_blocks and not self._generate_options.startswith('hb'): Messages.send_warning("This flow graph may not have flow control: " - "no audio or RF hardware blocks found. " - "Add a Misc->Throttle block to your flow " - "graph to avoid CPU congestion.") + "no audio or RF hardware blocks found. " + "Add a Misc->Throttle block to your flow " + "graph to avoid CPU congestion.") if len(throttling_blocks) > 1: keys = set([b.key for b in throttling_blocks]) if len(keys) > 1 and 'blocks_throttle' in keys: Messages.send_warning("This flow graph contains a throttle " - "block and another rate limiting block, " - "e.g. a hardware source or sink. " - "This is usually undesired. Consider " - "removing the throttle block.") + "block and another rate limiting block, " + "e.g. a hardware source or sink. " + "This is usually undesired. Consider " + "removing the throttle block.") - deprecated_block_keys = {b.name for b in self._flow_graph.get_enabled_blocks() if b.flags.deprecated} + deprecated_block_keys = { + b.name for b in self._flow_graph.get_enabled_blocks() if b.flags.deprecated} for key in deprecated_block_keys: Messages.send_warning("The block {!r} is deprecated.".format(key)) @@ -76,7 +78,8 @@ def write(self): fg = self._flow_graph platform = fg.parent - self.title = fg.get_option('title') or fg.get_option('id').replace('_', ' ').title() + self.title = fg.get_option('title') or fg.get_option( + 'id').replace('_', ' ').title() variables = fg.get_cpp_variables() parameters = fg.get_parameters() monitors = fg.get_monitors() @@ -119,7 +122,8 @@ def _build_cpp_source_code_from_template(self): Returns: a string of C++ code """ - file_path = self.file_path + '/' + self._flow_graph.get_option('id') + '.cpp' + file_path = self.file_path + '/' + \ + self._flow_graph.get_option('id') + '.cpp' output = [] @@ -132,12 +136,12 @@ def _build_cpp_source_code_from_template(self): **self.namespace ) # strip trailing white-space - flow_graph_code = "\n".join(line.rstrip() for line in flow_graph_code.split("\n")) + flow_graph_code = "\n".join(line.rstrip() + for line in flow_graph_code.split("\n")) output.append((file_path, flow_graph_code)) return output - def _build_cpp_header_code_from_template(self): """ Convert the flow graph to a C++ header file. @@ -145,7 +149,8 @@ def _build_cpp_header_code_from_template(self): Returns: a string of C++ code """ - file_path = self.file_path + '/' + self._flow_graph.get_option('id') + '.hpp' + file_path = self.file_path + '/' + \ + self._flow_graph.get_option('id') + '.hpp' output = [] @@ -158,7 +163,8 @@ def _build_cpp_header_code_from_template(self): **self.namespace ) # strip trailing white-space - flow_graph_code = "\n".join(line.rstrip() for line in flow_graph_code.split("\n")) + flow_graph_code = "\n".join(line.rstrip() + for line in flow_graph_code.split("\n")) output.append((file_path, flow_graph_code)) return output @@ -175,7 +181,7 @@ def _build_cmake_code_from_template(self): cmake_tuples = [] cmake_opt = self._flow_graph.get_option("cmake_opt") - cmake_opt = " " + cmake_opt # To make sure we get rid of the "-D"s when splitting + cmake_opt = " " + cmake_opt # To make sure we get rid of the "-D"s when splitting for opt_string in cmake_opt.split(" -D"): opt_string = opt_string.strip() @@ -196,7 +202,8 @@ def _build_cmake_code_from_template(self): **self.namespace ) # strip trailing white-space - flow_graph_code = "\n".join(line.rstrip() for line in flow_graph_code.split("\n")) + flow_graph_code = "\n".join(line.rstrip() + for line in flow_graph_code.split("\n")) output.append((file_path, flow_graph_code)) return output @@ -255,7 +262,8 @@ def _blocks(self): def _get_block_sort_text(block): code = block.cpp_templates.render('declarations') try: - code += block.params['gui_hint'].get_value() # Newer gui markup w/ qtgui + # Newer gui markup w/ qtgui + code += block.params['gui_hint'].get_value() except: pass return code @@ -265,7 +273,8 @@ def _get_block_sort_text(block): if b.enabled and not (b.get_bypassed() or b.is_import or b in parameters or b.key == 'options' or b.is_virtual_source() or b.is_virtual_sink()) ] - blocks = expr_utils.sort_objects(blocks, operator.attrgetter('name'), _get_block_sort_text) + blocks = expr_utils.sort_objects( + blocks, operator.attrgetter('name'), _get_block_sort_text) blocks_make = [] for block in blocks: translations = block.cpp_templates.render('translations') @@ -279,7 +288,8 @@ def _get_block_sort_text(block): {r"gr\.sizeof_([\w_]+)": r"sizeof(\1)"} ) for key in translations: - make = re.sub(key.replace("\\\\", "\\"), translations[key], make) + make = re.sub(key.replace("\\\\", "\\"), + translations[key], make) declarations = declarations.replace(key, translations[key]) if make: blocks_make.append((block, make, declarations)) @@ -293,7 +303,8 @@ def _variable_types(self): fg = self._flow_graph variables = fg.get_cpp_variables() - type_translation = {'complex': 'gr_complex', 'real': 'double', 'float': 'float', 'int': 'int', 'complex_vector': 'std::vector', 'real_vector': 'std::vector', 'float_vector': 'std::vector', 'int_vector': 'std::vector', 'string': 'std::string', 'bool': 'bool'} + type_translation = {'complex': 'gr_complex', 'real': 'double', 'float': 'float', 'int': 'int', 'complex_vector': 'std::vector', + 'real_vector': 'std::vector', 'float_vector': 'std::vector', 'int_vector': 'std::vector', 'string': 'std::string', 'bool': 'bool'} # If the type is explcitly specified, translate to the corresponding C++ type for var in list(variables): if var.params['value'].dtype != 'raw': @@ -304,26 +315,28 @@ def _variable_types(self): # Create an executable fragment of code containing all 'raw' variables in # order to infer the lvalue types. # - # Note that this differs from using ast.literal_eval() as literal_eval evaluates one - # variable at a time. The code fragment below evaluates all variables together which + # Note that this differs from using ast.literal_eval() as literal_eval evaluates one + # variable at a time. The code fragment below evaluates all variables together which # allows the variables to reference each other (i.e. a = b * c). prog = 'def get_decl_types():\n' prog += '\tvar_types = {}\n' for var in variables: - prog += '\t' + str(var.params['id'].value) + '=' + str(var.params['value'].value) + '\n' - prog += '\tvar_types = {}\n'; + prog += '\t' + str(var.params['id'].value) + \ + '=' + str(var.params['value'].value) + '\n' + prog += '\tvar_types = {}\n' for var in variables: - prog += '\tvar_types[\'' + str(var.params['id'].value) + '\'] = type(' + str(var.params['id'].value) + ')\n' + prog += '\tvar_types[\'' + str(var.params['id'].value) + \ + '\'] = type(' + str(var.params['id'].value) + ')\n' prog += '\treturn var_types' # Execute the code fragment in a separate namespace and retrieve the lvalue types var_types = {} namespace = {} try: - exec(prog, namespace) - var_types = namespace['get_decl_types']() + exec(prog, namespace) + var_types = namespace['get_decl_types']() except Exception as excp: - print('Failed to get parameter lvalue types: %s' %(excp)) + print('Failed to get parameter lvalue types: %s' % (excp)) # Format the rvalue of each variable expression for var in variables: @@ -334,20 +347,22 @@ def _parameter_types(self): parameters = fg.get_parameters() for param in parameters: - type_translation = {'eng_float' : 'double', 'intx' : 'int', 'str' : 'std::string', 'complex': 'gr_complex'}; + type_translation = {'eng_float': 'double', 'intx': 'int', + 'str': 'std::string', 'complex': 'gr_complex'} param.vtype = type_translation[param.params['type'].value] if param.vtype == 'gr_complex': - evaluated = ast.literal_eval(param.params['value'].value.strip()) - cpp_cmplx = '{' + str(evaluated.real) + ', ' + str(evaluated.imag) + '}' + evaluated = ast.literal_eval( + param.params['value'].value.strip()) + cpp_cmplx = '{' + str(evaluated.real) + \ + ', ' + str(evaluated.imag) + '}' # Update the 'var_make' entry in the cpp_templates dictionary d = param.cpp_templates cpp_expr = d['var_make'].replace('${value}', cpp_cmplx) - d.update({'var_make':cpp_expr}) + d.update({'var_make': cpp_expr}) param.cpp_templates = d - def _callbacks(self): fg = self._flow_graph variables = fg.get_cpp_variables() @@ -361,16 +376,19 @@ def _callbacks(self): callbacks_all = [] for block in fg.iter_enabled_blocks(): if not (block.is_virtual_sink() or block.is_virtual_source()): - callbacks_all.extend(expr_utils.expr_replace(cb, replace_dict) for cb in block.get_cpp_callbacks()) + callbacks_all.extend(expr_utils.expr_replace( + cb, replace_dict) for cb in block.get_cpp_callbacks()) # Map var id to callbacks def uses_var_id(callback): used = expr_utils.get_variable_dependencies(callback, [var_id]) - return used and ('this->' + var_id in callback) # callback might contain var_id itself + # callback might contain var_id itself + return used and ('this->' + var_id in callback) callbacks = {} for var_id in var_ids: - callbacks[var_id] = [callback for callback in callbacks_all if uses_var_id(callback)] + callbacks[var_id] = [ + callback for callback in callbacks_all if uses_var_id(callback)] return callbacks @@ -402,14 +420,17 @@ def make_port_sig(port): # Get the virtual blocks and resolve their connections connection_factory = fg.parent_platform.Connection - virtual_source_connections = [c for c in connections if isinstance(c.source_block, blocks.VirtualSource)] + virtual_source_connections = [c for c in connections if isinstance( + c.source_block, blocks.VirtualSource)] for connection in virtual_source_connections: sink = connection.sink_port for source in connection.source_port.resolve_virtual_source(): - resolved = connection_factory(fg.orignal_flowgraph, source, sink) + resolved = connection_factory( + fg.orignal_flowgraph, source, sink) connections.append(resolved) - virtual_connections = [c for c in connections if (isinstance(c.source_block, blocks.VirtualSource) or isinstance(c.sink_block, blocks.VirtualSink))] + virtual_connections = [c for c in connections if (isinstance( + c.source_block, blocks.VirtualSource) or isinstance(c.sink_block, blocks.VirtualSink))] for connection in virtual_connections: # Remove the virtual connection connections.remove(connection) @@ -423,7 +444,8 @@ def make_port_sig(port): for block in bypassed_blocks: # Get the upstream connection (off of the sink ports) # Use *connections* not get_connections() - source_connection = [c for c in connections if c.sink_port == block.sinks[0]] + source_connection = [ + c for c in connections if c.sink_port == block.sinks[0]] # The source connection should never have more than one element. assert (len(source_connection) == 1) @@ -435,7 +457,8 @@ def make_port_sig(port): if not sink.enabled: # Ignore disabled connections continue - connection = connection_factory(fg.orignal_flowgraph, source_port, sink.sink_port) + connection = connection_factory( + fg.orignal_flowgraph, source_port, sink.sink_port) connections.append(connection) # Remove this sink connection connections.remove(sink) @@ -451,7 +474,8 @@ def by_domain_and_blocks(c): template = templates[con.type] if con.source_port.dtype != 'bus': - code = template.render(make_port_sig=make_port_sig, source=con.source_port, sink=con.sink_port) + code = template.render( + make_port_sig=make_port_sig, source=con.source_port, sink=con.sink_port) if not self._generate_options.startswith('hb'): code = 'this->tb->' + code rendered.append(code) @@ -470,7 +494,8 @@ def by_domain_and_blocks(c): hidden_portb = portb.parent.sinks[port_num] connection = fg.parent_platform.Connection( parent=self, source=hidden_porta, sink=hidden_portb) - code = template.render(make_port_sig=make_port_sig, source=hidden_porta, sink=hidden_portb) + code = template.render( + make_port_sig=make_port_sig, source=hidden_porta, sink=hidden_portb) if not self._generate_options.startswith('hb'): code = 'this->tb->' + code rendered.append(code) diff --git a/grc/core/generator/hier_block.py b/grc/core/generator/hier_block.py index d609a50ff9b..0985437ed4b 100644 --- a/grc/core/generator/hier_block.py +++ b/grc/core/generator/hier_block.py @@ -128,7 +128,6 @@ def var_or_value(name): 'set_{key}(${{ {key} }})'.format(key=param_block.name) for param_block in parameters ] - # Documentation data['documentation'] = "\n".join(field for field in ( self._flow_graph.get_option('author'), @@ -178,7 +177,8 @@ def get_hier_block_io(flow_graph, direction, domain=None): Returns a list of blocks """ - pads = flow_graph.get_pad_sources() if direction == 'inputs' else flow_graph.get_pad_sinks() + pads = flow_graph.get_pad_sources( + ) if direction == 'inputs' else flow_graph.get_pad_sinks() for pad in pads: for port in (pad.sources if direction == 'inputs' else pad.sinks): diff --git a/grc/core/generator/top_block.py b/grc/core/generator/top_block.py index 275921da51d..2abfd0fbb4b 100644 --- a/grc/core/generator/top_block.py +++ b/grc/core/generator/top_block.py @@ -30,7 +30,8 @@ def __init__(self, flow_graph, output_dir): """ self._flow_graph = FlowGraphProxy(flow_graph) - self._generate_options = self._flow_graph.get_option('generate_options') + self._generate_options = self._flow_graph.get_option( + 'generate_options') self._mode = TOP_BLOCK_FILE_MODE # Handle the case where the directory is read-only @@ -58,7 +59,8 @@ def _warnings(self): "This is usually undesired. Consider " "removing the throttle block.") - deprecated_block_keys = {b.name for b in self._flow_graph.get_enabled_blocks() if b.flags.deprecated} + deprecated_block_keys = { + b.name for b in self._flow_graph.get_enabled_blocks() if b.flags.deprecated} for key in deprecated_block_keys: Messages.send_warning("The block {!r} is deprecated.".format(key)) @@ -67,7 +69,8 @@ def write(self): self._warnings() fg = self._flow_graph - self.title = fg.get_option('title') or fg.get_option('id').replace('_', ' ').title() + self.title = fg.get_option('title') or fg.get_option( + 'id').replace('_', ' ').title() variables = fg.get_variables() parameters = fg.get_parameters() monitors = fg.get_monitors() @@ -97,7 +100,8 @@ def _build_python_code_from_template(self): fg = self._flow_graph platform = fg.parent - title = fg.get_option('title') or fg.get_option('id').replace('_', ' ').title() + title = fg.get_option('title') or fg.get_option( + 'id').replace('_', ' ').title() variables = fg.get_variables() parameters = fg.get_parameters() monitors = fg.get_monitors() @@ -110,7 +114,8 @@ def _build_python_code_from_template(self): else: continue - file_path = os.path.join(self.output_dir, block.module_name + ".py") + file_path = os.path.join( + self.output_dir, block.module_name + ".py") output.append((file_path, src)) self.namespace = { @@ -131,7 +136,8 @@ def _build_python_code_from_template(self): **self.namespace ) # strip trailing white-space - flow_graph_code = "\n".join(line.rstrip() for line in flow_graph_code.split("\n")) + flow_graph_code = "\n".join(line.rstrip() + for line in flow_graph_code.split("\n")) output.append((self.file_path, flow_graph_code)) return output @@ -142,7 +148,8 @@ def _imports(self): seen = set() output = [] - need_path_hack = any(imp.endswith("# grc-generated hier_block") for imp in imports) + need_path_hack = any(imp.endswith( + "# grc-generated hier_block") for imp in imports) if need_path_hack: output.insert(0, textwrap.dedent("""\ import os @@ -184,7 +191,8 @@ def _blocks(self): def _get_block_sort_text(block): code = block.templates.render('make').replace(block.name, ' ') try: - code += block.params['gui_hint'].get_value() # Newer gui markup w/ qtgui + # Newer gui markup w/ qtgui + code += block.params['gui_hint'].get_value() except KeyError: # No gui hint pass @@ -195,7 +203,8 @@ def _get_block_sort_text(block): if b.enabled and not (b.get_bypassed() or b.is_import or b.is_snippet or b in parameters or b.key == 'options') ] - blocks = expr_utils.sort_objects(blocks, operator.attrgetter('name'), _get_block_sort_text) + blocks = expr_utils.sort_objects( + blocks, operator.attrgetter('name'), _get_block_sort_text) blocks_make = [] for block in blocks: make = block.templates.render('make') @@ -217,16 +226,19 @@ def _callbacks(self): callbacks_all = [] for block in fg.iter_enabled_blocks(): - callbacks_all.extend(expr_utils.expr_replace(cb, replace_dict) for cb in block.get_callbacks()) + callbacks_all.extend(expr_utils.expr_replace( + cb, replace_dict) for cb in block.get_callbacks()) # Map var id to callbacks def uses_var_id(callback): used = expr_utils.get_variable_dependencies(callback, [var_id]) - return used and (('self.' + var_id in callback) or ('this->' + var_id in callback)) # callback might contain var_id itself + # callback might contain var_id itself + return used and (('self.' + var_id in callback) or ('this->' + var_id in callback)) callbacks = {} for var_id in var_ids: - callbacks[var_id] = [callback for callback in callbacks_all if uses_var_id(callback)] + callbacks[var_id] = [ + callback for callback in callbacks_all if uses_var_id(callback)] return callbacks @@ -253,14 +265,17 @@ def make_port_sig(port): # Get the virtual blocks and resolve their connections connection_factory = fg.parent_platform.Connection - virtual_source_connections = [c for c in connections if isinstance(c.source_block, blocks.VirtualSource)] + virtual_source_connections = [c for c in connections if isinstance( + c.source_block, blocks.VirtualSource)] for connection in virtual_source_connections: sink = connection.sink_port for source in connection.source_port.resolve_virtual_source(): - resolved = connection_factory(fg.orignal_flowgraph, source, sink) + resolved = connection_factory( + fg.orignal_flowgraph, source, sink) connections.append(resolved) - virtual_connections = [c for c in connections if (isinstance(c.source_block, blocks.VirtualSource) or isinstance(c.sink_block, blocks.VirtualSink))] + virtual_connections = [c for c in connections if (isinstance( + c.source_block, blocks.VirtualSource) or isinstance(c.sink_block, blocks.VirtualSink))] for connection in virtual_connections: # Remove the virtual connection connections.remove(connection) @@ -274,7 +289,8 @@ def make_port_sig(port): for block in bypassed_blocks: # Get the upstream connection (off of the sink ports) # Use *connections* not get_connections() - source_connection = [c for c in connections if c.sink_port == block.sinks[0]] + source_connection = [ + c for c in connections if c.sink_port == block.sinks[0]] # The source connection should never have more than one element. assert (len(source_connection) == 1) @@ -286,7 +302,8 @@ def make_port_sig(port): if not sink.enabled: # Ignore disabled connections continue - connection = connection_factory(fg.orignal_flowgraph, source_port, sink.sink_port) + connection = connection_factory( + fg.orignal_flowgraph, source_port, sink.sink_port) connections.append(connection) # Remove this sink connection connections.remove(sink) @@ -301,7 +318,8 @@ def by_domain_and_blocks(c): for con in sorted(connections, key=by_domain_and_blocks): template = templates[con.type] if con.source_port.dtype != 'bus': - code = template.render(make_port_sig=make_port_sig, source=con.source_port, sink=con.sink_port) + code = template.render( + make_port_sig=make_port_sig, source=con.source_port, sink=con.sink_port) rendered.append(code) else: # Bus ports need to iterate over the underlying connections and then render @@ -318,10 +336,8 @@ def by_domain_and_blocks(c): hidden_portb = portb.parent.sinks[port_num_b] connection = fg.parent_platform.Connection( parent=self, source=hidden_porta, sink=hidden_portb) - code = template.render(make_port_sig=make_port_sig, source=hidden_porta, sink=hidden_portb) + code = template.render( + make_port_sig=make_port_sig, source=hidden_porta, sink=hidden_portb) rendered.append(code) - - - return rendered diff --git a/grc/core/io/yaml.py b/grc/core/io/yaml.py index d653dc5f773..3e10af55d1e 100644 --- a/grc/core/io/yaml.py +++ b/grc/core/io/yaml.py @@ -11,6 +11,7 @@ from ..params.param import attributed_str + class GRCDumper(yaml.SafeDumper): @classmethod def add(cls, data_type): @@ -21,7 +22,8 @@ def decorator(func): def represent_ordered_mapping(self, data): value = [] - node = yaml.MappingNode(u'tag:yaml.org,2002:map', value, flow_style=False) + node = yaml.MappingNode(u'tag:yaml.org,2002:map', + value, flow_style=False) if self.alias_key is not None: self.represented_objects[self.alias_key] = node @@ -62,7 +64,8 @@ class MultiLineString(str): GRCDumper.add_representer(OrderedDict, GRCDumper.represent_ordered_mapping) -GRCDumper.add_representer(OrderedDictFlowing, GRCDumper.represent_ordered_mapping_flowing) +GRCDumper.add_representer( + OrderedDictFlowing, GRCDumper.represent_ordered_mapping_flowing) GRCDumper.add_representer(ListFlowing, GRCDumper.represent_list_flowing) GRCDumper.add_representer(tuple, GRCDumper.represent_list) GRCDumper.add_representer(MultiLineString, GRCDumper.represent_ml_string) @@ -71,7 +74,8 @@ class MultiLineString(str): def dump(data, stream=None, **kwargs): - config = dict(stream=stream, default_flow_style=False, indent=4, Dumper=GRCDumper) + config = dict(stream=stream, default_flow_style=False, + indent=4, Dumper=GRCDumper) config.update(kwargs) return yaml.dump_all([data], **config) diff --git a/grc/core/params/dtypes.py b/grc/core/params/dtypes.py index 1c851c4d2c5..a582bcae855 100644 --- a/grc/core/params/dtypes.py +++ b/grc/core/params/dtypes.py @@ -16,7 +16,8 @@ ID_BLACKLIST = ['self', 'default'] + dir(builtins) try: from gnuradio import gr - ID_BLACKLIST.extend(attr for attr in dir(gr.top_block()) if not attr.startswith('_')) + ID_BLACKLIST.extend(attr for attr in dir( + gr.top_block()) if not attr.startswith('_')) except (ImportError, AttributeError): pass @@ -32,12 +33,13 @@ def decorator(func): return func return decorator + class ValidateError(Exception): """Raised by validate functions""" @validates('id') -def validate_block_id(param,black_listed_ids): +def validate_block_id(param, black_listed_ids): value = param.value # Can python use this as a variable? @@ -45,10 +47,11 @@ def validate_block_id(param,black_listed_ids): raise ValidateError('ID "{}" must begin with a letter and may contain letters, numbers, ' 'and underscores.'.format(value)) if value in (black_listed_ids + ID_BLACKLIST) and \ - not getattr(param.parent_block, 'exempt_from_id_validation', False): + not getattr(param.parent_block, 'exempt_from_id_validation', False): # Grant blacklist exemption to epy blocks and modules raise ValidateError('ID "{}" is blacklisted.'.format(value)) - block_names = [block.name for block in param.parent_flowgraph.iter_enabled_blocks()] + block_names = [ + block.name for block in param.parent_flowgraph.iter_enabled_blocks()] # Id should only appear once, or zero times if block is disabled if param.key == 'id' and block_names.count(value) > 1: raise ValidateError('ID "{}" is not unique.'.format(value)) @@ -58,7 +61,7 @@ def validate_block_id(param,black_listed_ids): @validates('name') -def validate_name(param,black_listed_ids): +def validate_name(param, black_listed_ids): # Name of a function or other block that will be generated literally not as a string value = param.value @@ -71,7 +74,7 @@ def validate_name(param,black_listed_ids): @validates('stream_id') -def validate_stream_id(param,black_listed_ids): +def validate_stream_id(param, black_listed_ids): value = param.value stream_ids = [ block.params['stream_id'].value @@ -88,7 +91,7 @@ def validate_stream_id(param,black_listed_ids): @validates('complex', 'real', 'float', 'int') -def validate_scalar(param,black_listed_ids): +def validate_scalar(param, black_listed_ids): valid_types = Constants.PARAM_TYPE_MAP[param.dtype] if not isinstance(param.get_evaluated(), valid_types): raise ValidateError('Expression {!r} is invalid for type {!r}.'.format( @@ -96,19 +99,21 @@ def validate_scalar(param,black_listed_ids): @validates('complex_vector', 'real_vector', 'float_vector', 'int_vector') -def validate_vector(param,black_listed_ids): +def validate_vector(param, black_listed_ids): # todo: check vector types if param.get_evaluated() is None: - raise ValidateError('Expression {!r} is invalid for type{!r}.'.format(param.get_evaluated(), param.dtype)) + raise ValidateError('Expression {!r} is invalid for type{!r}.'.format( + param.get_evaluated(), param.dtype)) valid_types = Constants.PARAM_TYPE_MAP[param.dtype.split('_', 1)[0]] if not all(isinstance(item, valid_types) for item in param.get_evaluated()): raise ValidateError('Expression {!r} is invalid for type {!r}.'.format( param.get_evaluated(), param.dtype)) + @validates('gui_hint') -def validate_gui_hint(param,black_listed_ids): +def validate_gui_hint(param, black_listed_ids): try: param.parse_gui_hint(param.value) except Exception as e: diff --git a/grc/core/params/param.py b/grc/core/params/param.py index 122480dfa24..2cde1facdb2 100644 --- a/grc/core/params/param.py +++ b/grc/core/params/param.py @@ -18,6 +18,7 @@ attributed_str = type('attributed_str', (str,), {}) + @setup_names class Param(Element): @@ -73,12 +74,14 @@ def _init_options(self, values, labels, attributes): options.attributes = collections.defaultdict(dict) padding = [''] * max(len(values), len(labels)) - attributes = {key: value + padding for key, value in attributes.items()} + attributes = {key: value + padding for key, + value in attributes.items()} for i, option in enumerate(values): # Test against repeated keys if option in options: - raise KeyError('Value "{}" already exists in options'.format(option)) + raise KeyError( + 'Value "{}" already exists in options'.format(option)) # get label try: label = str(labels[i]) @@ -86,7 +89,8 @@ def _init_options(self, values, labels, attributes): label = str(option) # Store the option options[option] = label - options.attributes[option] = {attrib: values[i] for attrib, values in attributes.items()} + options.attributes[option] = {attrib: values[i] + for attrib, values in attributes.items()} default = next(iter(options)) if options else '' if not self.value: @@ -151,12 +155,13 @@ def validate(self): """ Element.validate(self) if self.dtype not in Constants.PARAM_TYPE_NAMES: - self.add_error_message('Type "{}" is not a possible type.'.format(self.dtype)) + self.add_error_message( + 'Type "{}" is not a possible type.'.format(self.dtype)) validator = dtypes.validators.get(self.dtype, None) if self._init and validator: try: - validator(self,self.parent_flowgraph.get_imported_names()) + validator(self, self.parent_flowgraph.get_imported_names()) except dtypes.ValidateError as e: self.add_error_message(str(e)) @@ -207,12 +212,14 @@ def evaluate(self): if expr: try: if isinstance(expr, str) and self.is_float(expr[:-1]): - scale_factor = expr[-1:] - if scale_factor in self.scale: - expr = str(float(expr[:-1])*self.scale[scale_factor]) + scale_factor = expr[-1:] + if scale_factor in self.scale: + expr = str(float(expr[:-1]) * + self.scale[scale_factor]) value = self.parent_flowgraph.evaluate(expr) except Exception as e: - raise Exception('Value "{}" cannot be evaluated:\n{}'.format(expr, e)) + raise Exception( + 'Value "{}" cannot be evaluated:\n{}'.format(expr, e)) else: value = None # No parameter value provided if dtype == 'hex': @@ -230,7 +237,8 @@ def evaluate(self): try: value = self.parent.parent.evaluate(expr) except Exception as value: - raise Exception('Value "{}" cannot be evaluated:\n{}'.format(expr, value)) + raise Exception( + 'Value "{}" cannot be evaluated:\n{}'.format(expr, value)) if not isinstance(value, Constants.VECTOR_TYPES): self._lisitify_flag = True value = [value] @@ -339,7 +347,8 @@ def parse_pos(): e = self.parent_flowgraph.evaluate(pos) if not isinstance(e, (list, tuple)) or len(e) not in (2, 4) or not all(isinstance(ei, int) for ei in e): - raise Exception('Invalid GUI Hint entered: {e!r} (Must be a list of {{2,4}} non-negative integers).'.format(e=e)) + raise Exception( + 'Invalid GUI Hint entered: {e!r} (Must be a list of {{2,4}} non-negative integers).'.format(e=e)) if len(e) == 2: row, col = e @@ -348,10 +357,12 @@ def parse_pos(): row, col, row_span, col_span = e if (row < 0) or (col < 0): - raise Exception('Invalid GUI Hint entered: {e!r} (non-negative integers only).'.format(e=e)) + raise Exception( + 'Invalid GUI Hint entered: {e!r} (non-negative integers only).'.format(e=e)) if (row_span < 1) or (col_span < 1): - raise Exception('Invalid GUI Hint entered: {e!r} (positive row/column span required).'.format(e=e)) + raise Exception( + 'Invalid GUI Hint entered: {e!r} (positive row/column span required).'.format(e=e)) return row, col, row_span, col_span @@ -360,7 +371,8 @@ def validate_tab(): if block.key == 'qtgui_tab_widget' and block.name == tab) tab_block = next(iter(tabs), None) if not tab_block: - raise Exception('Invalid tab name entered: {tab} (Tab name not found).'.format(tab=tab)) + raise Exception( + 'Invalid tab name entered: {tab} (Tab name not found).'.format(tab=tab)) tab_index_size = int(tab_block.params['num_tabs'].value) if index >= tab_index_size: @@ -369,7 +381,8 @@ def validate_tab(): # Collision Detection def collision_detection(row, col, row_span, col_span): - my_parent = '{tab}@{index}'.format(tab=tab, index=index) if tab else 'main' + my_parent = '{tab}@{index}'.format(tab=tab, + index=index) if tab else 'main' # Calculate hostage cells for r in range(row, row + row_span): for c in range(col, col + col_span): @@ -378,7 +391,8 @@ def collision_detection(row, col, row_span, col_span): for other in self.get_all_params('gui_hint'): if other is self: continue - collision = next(iter(self.hostage_cells & other.hostage_cells), None) + collision = next( + iter(self.hostage_cells & other.hostage_cells), None) if collision: raise Exception('Block {block!r} is also using parent {parent!r}, cell {cell!r}.'.format( block=other.parent_block.name, parent=collision[0], cell=collision[1] @@ -390,7 +404,8 @@ def collision_detection(row, col, row_span, col_span): if not pos: layout = '{tab}_layout_{index}'.format(tab=tab, index=index) else: - layout = '{tab}_grid_layout_{index}'.format(tab=tab, index=index) + layout = '{tab}_grid_layout_{index}'.format( + tab=tab, index=index) else: if not pos: layout = 'top_layout' @@ -412,8 +427,8 @@ def collision_detection(row, col, row_span, col_span): self.{layout}.setColumnStretch(c, 1) """.strip('\n')).format( layout=layout, widget=widget, - row=row, row_span=row_span, row_end=row+row_span, - col=col, col_span=col_span, col_end=col+col_span, + row=row, row_span=row_span, row_end=row + row_span, + col=col, col_span=col_span, col_end=col + col_span, ) elif self.parent_flowgraph.get_option('output_language') == 'cpp': widget_str = textwrap.dedent(""" @@ -424,17 +439,19 @@ def collision_detection(row, col, row_span, col_span): {layout}->setColumnStretch(c, 1); """.strip('\n')).format( layout=layout, widget=widget, - row=row, row_span=row_span, row_end=row+row_span, - col=col, col_span=col_span, col_end=col+col_span, + row=row, row_span=row_span, row_end=row + row_span, + col=col, col_span=col_span, col_end=col + col_span, ) else: widget_str = '' else: if self.parent_flowgraph.get_option('output_language') == 'python': - widget_str = 'self.{layout}.addWidget({widget})'.format(layout=layout, widget=widget) + widget_str = 'self.{layout}.addWidget({widget})'.format( + layout=layout, widget=widget) elif self.parent_flowgraph.get_option('output_language') == 'cpp': - widget_str = '{layout}->addWidget({widget});'.format(layout=layout, widget=widget) + widget_str = '{layout}->addWidget({widget});'.format( + layout=layout, widget=widget) else: widget_str = '' diff --git a/grc/core/params/template_arg.py b/grc/core/params/template_arg.py index 7250a71827b..53adb740d42 100644 --- a/grc/core/params/template_arg.py +++ b/grc/core/params/template_arg.py @@ -5,7 +5,6 @@ # - class TemplateArg(str): """ A cheetah template argument created from a param. diff --git a/grc/core/platform.py b/grc/core/platform.py index cc825ec953c..7eeb192ece8 100644 --- a/grc/core/platform.py +++ b/grc/core/platform.py @@ -36,7 +36,8 @@ def __init__(self, *args, **kwargs): self.config = self.Config(*args, **kwargs) self.block_docstrings = {} - self.block_docstrings_loaded_callback = lambda: None # dummy to be replaced by BlockTreeWindow + # dummy to be replaced by BlockTreeWindow + self.block_docstrings_loaded_callback = lambda: None self._docstring_extractor = utils.extract_docs.SubprocessLoader( callback_query_result=self._save_docstring_extraction_result, @@ -108,7 +109,8 @@ def load_and_generate_flow_graph(self, file_path, out_dir=None, hier_only=False) Messages.send('>>> Generating: {}\n'.format(generator.file_path)) generator.write() except Exception as e: - Messages.send('>>> Generate Error: {}: {}\n'.format(file_path, str(e))) + Messages.send( + '>>> Generate Error: {}: {}\n'.format(file_path, str(e))) return None, None return flow_graph, generator.file_path @@ -126,8 +128,8 @@ def build_library(self, path=None): self.connection_templates.clear() self.cpp_connection_templates.clear() self._block_categories.clear() - - with Cache(Constants.CACHE_FILE, version = self.config.version) as cache: + + with Cache(Constants.CACHE_FILE, version=self.config.version) as cache: for file_path in self._iter_files_in_block_path(path): if file_path.endswith('.block.yml'): @@ -147,9 +149,11 @@ def build_library(self, path=None): data = cache.get_or_load(file_path) passed = checker.run(data) for msg in checker.messages: - logger.warning('{:<40s} {}'.format(os.path.basename(file_path), msg)) + logger.warning('{:<40s} {}'.format( + os.path.basename(file_path), msg)) if not passed: - logger.info('YAML schema check failed for: ' + file_path) + logger.info( + 'YAML schema check failed for: ' + file_path) loader(data, file_path) except Exception as error: @@ -184,8 +188,8 @@ def build_library(self, path=None): raise RuntimeError(errstr) else: # might have some cleanup to do on the options block in particular - utils.hide_bokeh_gui_options_if_not_installed(self.blocks['options']) - + utils.hide_bokeh_gui_options_if_not_installed( + self.blocks['options']) def _iter_files_in_block_path(self, path=None, ext='yml'): """Iterator for block descriptions and category trees""" @@ -220,13 +224,15 @@ def load_block_description(self, data, file_path): # don't load future block format versions file_format = data['file_format'] if file_format < 1 or file_format > Constants.BLOCK_DESCRIPTION_FILE_FORMAT_VERSION: - log.error('Unknown format version %d in %s', file_format, file_path) + log.error('Unknown format version %d in %s', + file_format, file_path) return block_id = data['id'] = data['id'].rstrip('_') if block_id in self.block_classes_build_in: - log.warning('Not overwriting build-in block %s with %s', block_id, file_path) + log.warning('Not overwriting build-in block %s with %s', + block_id, file_path) return if block_id in self.blocks: log.warning('Block with id "%s" loaded from\n %s\noverwritten by\n %s', @@ -256,7 +262,8 @@ def load_domain_description(self, data, file_path): try: tuple(int(color[o:o + 2], 16) / 255.0 for o in range(1, 6, 2)) except ValueError: - log.warning('Cannot parse color code "%s" in %s', color, file_path) + log.warning('Cannot parse color code "%s" in %s', + color, file_path) return self.domains[domain_id] = self.Domain( @@ -272,8 +279,10 @@ def load_domain_description(self, data, file_path): log.warn('Invalid connection template.') continue connection_id = str(source_id), str(sink_id) - self.connection_templates[connection_id] = connection.get('connect', '') - self.cpp_connection_templates[connection_id] = connection.get('cpp_connect', '') + self.connection_templates[connection_id] = connection.get( + 'connect', '') + self.cpp_connection_templates[connection_id] = connection.get( + 'cpp_connect', '') def load_category_tree_description(self, data, file_path): """Parse category tree file and add it to list""" @@ -326,7 +335,8 @@ def parse_flow_graph(self, filename): # todo: try if not is_xml: data = yaml.safe_load(fp) - validator = schema_checker.Validator(schema_checker.FLOW_GRAPH_SCHEME) + validator = schema_checker.Validator( + schema_checker.FLOW_GRAPH_SCHEME) validator.run(data) if is_xml: @@ -340,13 +350,15 @@ def save_flow_graph(self, filename, flow_graph): data = flow_graph.export_data() try: - data['connections'] = [yaml.ListFlowing(i) for i in data['connections']] + data['connections'] = [yaml.ListFlowing( + i) for i in data['connections']] except KeyError: pass try: for d in chain([data['options']], data['blocks']): - d['states']['coordinate'] = yaml.ListFlowing(d['states']['coordinate']) + d['states']['coordinate'] = yaml.ListFlowing( + d['states']['coordinate']) except KeyError: pass @@ -393,7 +405,8 @@ def get_output_language(self): Connection = Connection block_classes_build_in = blocks.build_ins - block_classes = utils.backports.ChainMap({}, block_classes_build_in) # separates build-in from loaded blocks) + # separates build-in from loaded blocks) + block_classes = utils.backports.ChainMap({}, block_classes_build_in) port_classes = { None: ports.Port, # default diff --git a/grc/core/ports/_virtual_connections.py b/grc/core/ports/_virtual_connections.py index a0e7b05a810..a328531b1ac 100644 --- a/grc/core/ports/_virtual_connections.py +++ b/grc/core/ports/_virtual_connections.py @@ -2,7 +2,7 @@ # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-2.0-or-later -# +# from itertools import chain @@ -28,10 +28,12 @@ def _sources_from_virtual_sink_port(sink_port, _traversed=None): """ source_ports_per_virtual_connection = ( # there can be multiple ports per virtual connection - _sources_from_virtual_source_port(c.source_port, _traversed) # type: list + _sources_from_virtual_source_port( + c.source_port, _traversed) # type: list for c in sink_port.connections(enabled=True) ) - return list(chain(*source_ports_per_virtual_connection)) # concatenate generated lists of ports + # concatenate generated lists of ports + return list(chain(*source_ports_per_virtual_connection)) def _sources_from_virtual_source_port(source_port, _traversed=None): @@ -62,7 +64,8 @@ def _sources_from_virtual_source_port(source_port, _traversed=None): _sources_from_virtual_sink_port(b.sinks[0], _traversed) # type: list for b in connected_virtual_sink_blocks ) - return list(chain(*source_ports_per_virtual_connection)) # concatenate generated lists of ports + # concatenate generated lists of ports + return list(chain(*source_ports_per_virtual_connection)) def downstream_ports(port): @@ -82,7 +85,8 @@ def _sinks_from_virtual_source_port(source_port, _traversed=None): _sinks_from_virtual_sink_port(c.sink_port, _traversed) # type: list for c in source_port.connections(enabled=True) ) - return list(chain(*sink_ports_per_virtual_connection)) # concatenate generated lists of ports + # concatenate generated lists of ports + return list(chain(*sink_ports_per_virtual_connection)) def _sinks_from_virtual_sink_port(sink_port, _traversed=None): @@ -111,4 +115,5 @@ def _sinks_from_virtual_sink_port(sink_port, _traversed=None): _sinks_from_virtual_source_port(b.sources[0], _traversed) # type: list for b in connected_virtual_source_blocks ) - return list(chain(*sink_ports_per_virtual_connection)) # concatenate generated lists of ports + # concatenate generated lists of ports + return list(chain(*sink_ports_per_virtual_connection)) diff --git a/grc/core/ports/port.py b/grc/core/ports/port.py index ade961e296a..534f2138e65 100644 --- a/grc/core/ports/port.py +++ b/grc/core/ports/port.py @@ -34,17 +34,21 @@ def __init__(self, parent, direction, id, label='', domain=Constants.DEFAULT_DOM self._dir = direction self.key = id if not label: - label = id if not id.isdigit() else {'sink': 'in', 'source': 'out'}[direction] + label = id if not id.isdigit() else {'sink': 'in', 'source': 'out'}[ + direction] if dtype == 'bus': # Look for existing busses to give proper index - busses = [p for p in self.parent.ports() if p._dir == self._dir and p.dtype == 'bus'] + busses = [p for p in self.parent.ports() if p._dir == + self._dir and p.dtype == 'bus'] bus_structure = self.parent.current_bus_structure[self._dir] bus_index = len(busses) if len(bus_structure) > bus_index: - number = str(len(busses)) + '#' + str(len(bus_structure[bus_index])) + number = str(len(busses)) + '#' + \ + str(len(bus_structure[bus_index])) label = dtype + number else: - raise ValueError('Could not initialize bus port due to incompatible bus structure') + raise ValueError( + 'Could not initialize bus port due to incompatible bus structure') self.name = self._base_name = label @@ -102,7 +106,8 @@ def validate(self): self.add_error_message('Port is not connected.') if self.dtype not in Constants.TYPE_TO_SIZEOF.keys(): - self.add_error_message('Type "{}" is not a possible type.'.format(self.dtype)) + self.add_error_message( + 'Type "{}" is not a possible type.'.format(self.dtype)) try: domain = platform.domains[self.domain] @@ -113,7 +118,8 @@ def validate(self): self.add_error_message('Domain "{}" can have only one downstream block' ''.format(self.domain)) except KeyError: - self.add_error_message('Domain key "{}" is not registered.'.format(self.domain)) + self.add_error_message( + 'Domain key "{}" is not registered.'.format(self.domain)) def rewrite(self): del self.vlen @@ -150,9 +156,11 @@ def find_port(finder): try: port = find_port(_virtual_connections.upstream_ports) or \ - find_port(_virtual_connections.downstream_ports) - self.set_evaluated('dtype', port.dtype) # we don't want to override the template - self.set_evaluated('vlen', port.vlen) # we don't want to override the template + find_port(_virtual_connections.downstream_ports) + # we don't want to override the template + self.set_evaluated('dtype', port.dtype) + # we don't want to override the template + self.set_evaluated('vlen', port.vlen) self.domain = port.domain except AttributeError: self.domain = Constants.DEFAULT_DOMAIN @@ -206,7 +214,7 @@ def connections(self, enabled=None): enabled: None for all, True for enabled only, False for disabled only """ for con in self.parent_flowgraph.connections: - #TODO clean this up - but how to get past this validation + # TODO clean this up - but how to get past this validation # things don't compare simply with an x in y because # bus ports are created differently. port_in_con = False @@ -242,5 +250,6 @@ def get_associated_ports(self): if bus_structure: busses = [i for i in get_ports if i.dtype == 'bus'] bus_index = busses.index(self) - ports = filter(lambda a: ports.index(a) in bus_structure[bus_index], ports) + ports = filter(lambda a: ports.index( + a) in bus_structure[bus_index], ports) return ports diff --git a/grc/core/schema_checker/block.py b/grc/core/schema_checker/block.py index f336fc4fdb1..801c68b9062 100644 --- a/grc/core/schema_checker/block.py +++ b/grc/core/schema_checker/block.py @@ -12,7 +12,8 @@ options=list, option_labels=list, - option_attributes=Spec(types=dict, required=False, item_scheme=(str, list)), + option_attributes=Spec(types=dict, required=False, + item_scheme=(str, list)), hide=str, ) @@ -59,7 +60,8 @@ value=str, templates=Spec(types=dict, required=False, item_scheme=TEMPLATES_SCHEME), - cpp_templates=Spec(types=dict, required=False, item_scheme=CPP_TEMPLATES_SCHEME), + cpp_templates=Spec(types=dict, required=False, + item_scheme=CPP_TEMPLATES_SCHEME), documentation=str, grc_source=str, diff --git a/grc/core/utils/backports/chainmap.py b/grc/core/utils/backports/chainmap.py index 1f4f4a96fbf..a89c42cddd6 100644 --- a/grc/core/utils/backports/chainmap.py +++ b/grc/core/utils/backports/chainmap.py @@ -30,16 +30,19 @@ def __missing__(self, key): def __getitem__(self, key): for mapping in self.maps: try: - return mapping[key] # can't use 'key in mapping' with defaultdict + # can't use 'key in mapping' with defaultdict + return mapping[key] except KeyError: pass - return self.__missing__(key) # support subclasses that define __missing__ + # support subclasses that define __missing__ + return self.__missing__(key) def get(self, key, default=None): return self[key] if key in self else default def __len__(self): - return len(set().union(*self.maps)) # reuses stored hash values if possible + # reuses stored hash values if possible + return len(set().union(*self.maps)) def __iter__(self): return iter(set().union(*self.maps)) @@ -85,7 +88,8 @@ def __delitem__(self, key): try: del self.maps[0][key] except KeyError: - raise KeyError('Key not found in the first mapping: {!r}'.format(key)) + raise KeyError( + 'Key not found in the first mapping: {!r}'.format(key)) def popitem(self): """Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.""" @@ -99,7 +103,8 @@ def pop(self, key, *args): try: return self.maps[0].pop(key, *args) except KeyError: - raise KeyError('Key not found in the first mapping: {!r}'.format(key)) + raise KeyError( + 'Key not found in the first mapping: {!r}'.format(key)) def clear(self): """Clear maps[0], leaving maps[1:] intact.""" diff --git a/grc/core/utils/descriptors/_lazy.py b/grc/core/utils/descriptors/_lazy.py index 280b128365c..7d5c2c49c03 100644 --- a/grc/core/utils/descriptors/_lazy.py +++ b/grc/core/utils/descriptors/_lazy.py @@ -23,6 +23,7 @@ def __get__(self, instance, owner): def nop_write(prop): """Make this a property with a nop setter""" + def nop(self, value): pass return prop.setter(nop) diff --git a/grc/core/utils/descriptors/evaluated.py b/grc/core/utils/descriptors/evaluated.py index a9735fb8613..e22ff5fc5bd 100644 --- a/grc/core/utils/descriptors/evaluated.py +++ b/grc/core/utils/descriptors/evaluated.py @@ -23,7 +23,8 @@ def default_eval_func(self, instance): value = instance.parent_block.evaluate(raw) except Exception as error: if raw: - instance.add_error_message("Failed to eval '{}': {}".format(raw, error)) + instance.add_error_message( + "Failed to eval '{}': {}".format(raw, error)) return self.default if not isinstance(value, self.expected_type): @@ -68,13 +69,15 @@ def __init__(self, allowed_values, default=None, name=None): if isinstance(allowed_values, str): allowed_values = set(allowed_values.split()) self.allowed_values = allowed_values - default = default if default is not None else next(iter(self.allowed_values)) + default = default if default is not None else next( + iter(self.allowed_values)) super(EvaluatedEnum, self).__init__(str, default, name) def default_eval_func(self, instance): value = super(EvaluatedEnum, self).default_eval_func(instance) if value not in self.allowed_values: - instance.add_error_message("Value '{}' not in allowed values".format(value)) + instance.add_error_message( + "Value '{}' not in allowed values".format(value)) return self.default return value diff --git a/grc/core/utils/epy_block_io.py b/grc/core/utils/epy_block_io.py index 58becc4f2b8..9947fa4831f 100644 --- a/grc/core/utils/epy_block_io.py +++ b/grc/core/utils/epy_block_io.py @@ -12,7 +12,8 @@ 'int8': 'byte', 'uint8': 'byte', } -BlockIO = collections.namedtuple('BlockIO', 'name cls params sinks sources doc callbacks') +BlockIO = collections.namedtuple( + 'BlockIO', 'name cls params sinks sources doc callbacks') def _ports(sigs, msgs): @@ -72,11 +73,13 @@ def extract(cls): def settable(attr): try: - return callable(getattr(cls, attr).fset) # check for a property with setter + # check for a property with setter + return callable(getattr(cls, attr).fset) except AttributeError: return attr in instance.__dict__ # not dir() - only the instance attribs - callbacks = [attr for attr in dir(instance) if attr in init_args and settable(attr)] + callbacks = [attr for attr in dir( + instance) if attr in init_args and settable(attr)] sinks = _ports(instance.in_sig(), pmt.to_python(instance.message_ports_in())) diff --git a/grc/core/utils/expr_utils.py b/grc/core/utils/expr_utils.py index bc669cc7c82..cfb1274049c 100644 --- a/grc/core/utils/expr_utils.py +++ b/grc/core/utils/expr_utils.py @@ -7,6 +7,7 @@ """ +import ast import string @@ -64,12 +65,10 @@ def sort_objects(objects, get_id, get_expr): return [id2obj[id] for id in sorted_ids] -import ast - - def dependencies(expr, names=None): node = ast.parse(expr, mode='eval') - used_ids = frozenset([n.id for n in ast.walk(node) if isinstance(n, ast.Name)]) + used_ids = frozenset( + [n.id for n in ast.walk(node) if isinstance(n, ast.Name)]) return used_ids & names if names else used_ids @@ -93,8 +92,6 @@ def dependent_ids(obj): return objects - - VAR_CHARS = string.ascii_letters + string.digits + '_' @@ -205,7 +202,8 @@ def _sort_variables(exprs): # Determine dependency order while var_graph.get_nodes(): # Get a list of nodes with no edges - indep_vars = [var for var in var_graph.get_nodes() if not var_graph.get_edges(var)] + indep_vars = [var for var in var_graph.get_nodes() + if not var_graph.get_edges(var)] if not indep_vars: raise Exception('circular dependency caught in sort_variables') # Add the indep vars to the end of the list diff --git a/grc/core/utils/extract_docs.py b/grc/core/utils/extract_docs.py index 09bcaeb7c75..a92ce1777e9 100644 --- a/grc/core/utils/extract_docs.py +++ b/grc/core/utils/extract_docs.py @@ -55,7 +55,8 @@ def docstring_guess_from_key(key): else: return doc_strings - pattern = re.compile('^' + init_name.replace('_', '_*').replace('x', r'\w') + r'\w*$') + pattern = re.compile( + '^' + init_name.replace('_', '_*').replace('x', r'\w') + r'\w*$') for match in filter(pattern.match, dir(module)): try: doc_strings[match] = getattr(module, match).__doc__ @@ -135,7 +136,8 @@ def run_worker(self): break try: self._worker = subprocess.Popen( - args=(sys.executable, '-uc', self.BOOTSTRAP.format(__file__)), + args=(sys.executable, '-uc', + self.BOOTSTRAP.format(__file__)), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) @@ -286,7 +288,8 @@ def callback(key, docs): # r.query('uhd_source') r.query('expr_utils_graph') r.query('blocks_add_cc') - r.query('blocks_add_cc', ['import gnuradio.blocks'], 'gnuradio.blocks.add_cc(') + r.query('blocks_add_cc', ['import gnuradio.blocks'], + 'gnuradio.blocks.add_cc(') # r.query('analog_feedforward_agc_cc') # r.query('uhd_source') # r.query('uhd_source') diff --git a/grc/core/utils/flow_graph_complexity.py b/grc/core/utils/flow_graph_complexity.py index e8962b0ae3b..5731769a19b 100644 --- a/grc/core/utils/flow_graph_complexity.py +++ b/grc/core/utils/flow_graph_complexity.py @@ -37,17 +37,20 @@ def calculate(flowgraph): # Disabled multiplier if enabled > 0: - disabled_multi = 1 / (max(1 - ((blocks - enabled) / max(blocks, 1)), 0.05)) + disabled_multi = 1 / \ + (max(1 - ((blocks - enabled) / max(blocks, 1)), 0.05)) else: disabled_multi = 1 # Connection multiplier (How many connections ) if (connections - disabled_connections) > 0: - conn_multi = 1 / (max(1 - (disabled_connections / max(connections, 1)), 0.05)) + conn_multi = 1 / \ + (max(1 - (disabled_connections / max(connections, 1)), 0.05)) else: conn_multi = 1 - final = round(max((dbal - 1) * disabled_multi * conn_multi * connections, 0.0) / 1000000, 6) + final = round(max((dbal - 1) * disabled_multi * + conn_multi * connections, 0.0) / 1000000, 6) return final except Exception: diff --git a/grc/gui/Actions.py b/grc/gui/Actions.py index 1d815cc5333..3c312f65058 100644 --- a/grc/gui/Actions.py +++ b/grc/gui/Actions.py @@ -85,10 +85,10 @@ def register(self, key = "{}.{}".format(prefix, name) if prefix == "app": pass - #self.app.add_action(action) + # self.app.add_action(action) elif prefix == "win": pass - #self.win.add_action(action) + # self.win.add_action(action) #log.debug("Registering action as '{}'".format(key)) self._actions[key] = action @@ -132,7 +132,7 @@ def __str__(self): class Action(Gio.SimpleAction): # Change these to normal python properties. - #prefs_name + # prefs_name def __init__(self, name, @@ -295,7 +295,7 @@ def connect(action, handler=None): "app.flowgraph.duplicate", label='_Duplicate', tooltip='Create a duplicate of current flow graph', - #stock_id=Gtk.STOCK_COPY, + # stock_id=Gtk.STOCK_COPY, keypresses=["d"], ) FLOW_GRAPH_CLOSE = actions.register( @@ -433,26 +433,27 @@ def connect(action, handler=None): keypresses=["b"], ) ZOOM_IN = actions.register("win.zoom_in", - label='Zoom In', - tooltip='Increase the canvas zoom level', - keypresses=["plus","equal","KP_Add"], -) + label='Zoom In', + tooltip='Increase the canvas zoom level', + keypresses=["plus", + "equal", "KP_Add"], + ) ZOOM_OUT = actions.register("win.zoom_out", - label='Zoom Out', - tooltip='Decrease the canvas zoom level', - keypresses=["minus","KP_Subtract"], -) + label='Zoom Out', + tooltip='Decrease the canvas zoom level', + keypresses=["minus", "KP_Subtract"], + ) ZOOM_RESET = actions.register("win.zoom_reset", - label='Reset Zoom', - tooltip='Reset the canvas zoom level', - keypresses=["0","KP_0"], -) + label='Reset Zoom', + tooltip='Reset the canvas zoom level', + keypresses=["0", "KP_0"], + ) TOGGLE_SNAP_TO_GRID = actions.register("win.snap_to_grid", - label='_Snap to grid', - tooltip='Snap blocks to a grid for an easier connection alignment', - preference_name='snap_to_grid', - default=True, -) + label='_Snap to grid', + tooltip='Snap blocks to a grid for an easier connection alignment', + preference_name='snap_to_grid', + default=True, + ) TOGGLE_HIDE_DISABLED_BLOCKS = actions.register( "win.hide_disabled", label='Hide _Disabled Blocks', @@ -493,8 +494,7 @@ def connect(action, handler=None): TOGGLE_FLOW_GRAPH_VAR_EDITOR = actions.register( "win.toggle_variable_editor", label='Show _Variable Editor', - tooltip= - 'Show the variable editor. Modify variables and imports in this flow graph', + tooltip='Show the variable editor. Modify variables and imports in this flow graph', icon_name='accessories-text-editor', default=True, keypresses=["e"], diff --git a/grc/gui/Application.py b/grc/gui/Application.py index 1996d66c1e2..87c5cf0ed81 100644 --- a/grc/gui/Application.py +++ b/grc/gui/Application.py @@ -7,7 +7,6 @@ """ - import logging import os import subprocess @@ -65,7 +64,8 @@ def __init__(self, file_paths, platform): self.set_accels_for_action(x, keypress) # Initialize - self.init_file_paths = [os.path.abspath(file_path) for file_path in file_paths] + self.init_file_paths = [os.path.abspath( + file_path) for file_path in file_paths] self.init = False def do_startup(self): @@ -80,7 +80,7 @@ def do_activate(self): self.main_window.connect('delete-event', self._quit) self.get_focus_flag = self.main_window.get_focus_flag - #setup the messages + # setup the messages Messages.register_messenger(self.main_window.add_console_line) Messages.send_init(self.platform) @@ -117,7 +117,8 @@ def flow_graph_update(fg=flow_graph): file_path_to_show = self.config.file_open() for file_path in (self.init_file_paths or self.config.get_open_files()): if os.path.exists(file_path): - main.new_page(file_path, show=file_path_to_show == file_path) + main.new_page( + file_path, show=file_path_to_show == file_path) if not main.current_page: main.new_page() # ensure that at least a blank page exists @@ -190,9 +191,12 @@ def flow_graph_update(fg=flow_graph): action.load_from_preferences() # Hide the panels *IF* it's saved in preferences - main.update_panel_visibility(main.BLOCKS, Actions.TOGGLE_BLOCKS_WINDOW.get_active()) - main.update_panel_visibility(main.CONSOLE, Actions.TOGGLE_CONSOLE_WINDOW.get_active()) - main.update_panel_visibility(main.VARIABLES, Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR.get_active()) + main.update_panel_visibility( + main.BLOCKS, Actions.TOGGLE_BLOCKS_WINDOW.get_active()) + main.update_panel_visibility( + main.CONSOLE, Actions.TOGGLE_CONSOLE_WINDOW.get_active()) + main.update_panel_visibility( + main.VARIABLES, Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR.get_active()) # Force an update on the current page to match loaded preferences. # In the future, change the __init__ order to load preferences first @@ -210,7 +214,7 @@ def flow_graph_update(fg=flow_graph): # Selections ################################################## elif action == Actions.ELEMENT_SELECT: - pass #do nothing, update routines below + pass # do nothing, update routines below elif action == Actions.NOTHING_SELECT: flow_graph.unselect() elif action == Actions.SELECT_ALL: @@ -271,7 +275,6 @@ def flow_graph_update(fg=flow_graph): x_min = min(block.coordinate[0] for block in selected_blocks) y_min = min(block.coordinate[1] for block in selected_blocks) - for connection in flow_graph.connections: # Get id of connected blocks @@ -283,7 +286,8 @@ def flow_graph_update(fg=flow_graph): pads.append({ 'key': connection.sink_port.key, 'coord': source.coordinate, - 'block_index': selected_blocks.index(sink) + 1, # Ignore the options block + # Ignore the options block + 'block_index': selected_blocks.index(sink) + 1, 'direction': 'source' }) @@ -292,7 +296,8 @@ def flow_graph_update(fg=flow_graph): pads.append({ 'key': connection.source_port.key, 'coord': sink.coordinate, - 'block_index': selected_blocks.index(source) + 1, # Ignore the options block + # Ignore the options block + 'block_index': selected_blocks.index(source) + 1, 'direction': 'sink' }) @@ -335,7 +340,8 @@ def flow_graph_update(fg=flow_graph): pad_block = flow_graph.get_block(pad_id) pad_sink = pad_block.sinks[0] - source_block = flow_graph.get_block(flow_graph.blocks[pad['block_index']].name) + source_block = flow_graph.get_block( + flow_graph.blocks[pad['block_index']].name) source = source_block.get_source(pad['key']) # ensure the port types match @@ -350,13 +356,15 @@ def flow_graph_update(fg=flow_graph): new_connection = flow_graph.connect(source, pad_sink) elif pad['direction'] == 'source': - pad_id = flow_graph.add_new_block('pad_source', pad['coord']) + pad_id = flow_graph.add_new_block( + 'pad_source', pad['coord']) # setup the references to the sink and source pad_block = flow_graph.get_block(pad_id) pad_source = pad_block.sources[0] - sink_block = flow_graph.get_block(flow_graph.blocks[pad['block_index']].name) + sink_block = flow_graph.get_block( + flow_graph.blocks[pad['block_index']].name) sink = sink_block.get_sink(pad['key']) # ensure the port types match @@ -496,7 +504,8 @@ def flow_graph_update(fg=flow_graph): # to be visible. varedit = Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR if active: - log.debug("Variables are hidden. Forcing the variable panel to be visible.") + log.debug( + "Variables are hidden. Forcing the variable panel to be visible.") varedit.disable() else: varedit.enable() @@ -548,8 +557,9 @@ def flow_graph_update(fg=flow_graph): while response == Gtk.ResponseType.APPLY: # rerun the dialog if Apply was hit response = self.dialog.run() if response in (Gtk.ResponseType.APPLY, Gtk.ResponseType.ACCEPT): - page.state_cache.save_new_state(flow_graph.export_data()) - ### Following line forces a complete update of io ports + page.state_cache.save_new_state( + flow_graph.export_data()) + # Following line forces a complete update of io ports flow_graph_update() page.saved = False if response in (Gtk.ResponseType.REJECT, Gtk.ResponseType.ACCEPT): @@ -600,18 +610,21 @@ def flow_graph_update(fg=flow_graph): main.new_page() args = (GLib.Variant('s', 'qt_gui'),) flow_graph = main.current_page.flow_graph - flow_graph.options_block.params['generate_options'].set_value(str(args[0])[1:-1]) + flow_graph.options_block.params['generate_options'].set_value(str(args[0])[ + 1:-1]) flow_graph.options_block.params['author'].set_value(getuser()) flow_graph_update(flow_graph) elif action == Actions.FLOW_GRAPH_NEW_TYPE: main.new_page() if args: flow_graph = main.current_page.flow_graph - flow_graph.options_block.params['generate_options'].set_value(str(args[0])[1:-1]) + flow_graph.options_block.params['generate_options'].set_value(str(args[0])[ + 1:-1]) flow_graph_update(flow_graph) elif action == Actions.FLOW_GRAPH_OPEN: - file_paths = args[0] if args[0] else FileDialogs.OpenFlowGraph(main, page.file_path).run() - if file_paths: # Open a new page for each file, show only the first + file_paths = args[0] if args[0] else FileDialogs.OpenFlowGraph( + main, page.file_path).run() + if file_paths: # Open a new page for each file, show only the first for i, file_path in enumerate(file_paths): main.new_page(file_path, show=(i == 0)) self.config.add_recent_file(file_path) @@ -631,10 +644,10 @@ def flow_graph_update(fg=flow_graph): main.tool_bar.refresh_submenus() main.menu.refresh_submenus() elif action == Actions.FLOW_GRAPH_SAVE: - #read-only or undefined file path, do save-as + # read-only or undefined file path, do save-as if page.get_read_only() or not page.file_path: Actions.FLOW_GRAPH_SAVE_AS() - #otherwise try to save + # otherwise try to save else: try: self.platform.save_flow_graph(page.file_path, flow_graph) @@ -670,18 +683,25 @@ def flow_graph_update(fg=flow_graph): Actions.FLOW_GRAPH_SAVE_AS() else: dup_file_path = page.file_path - dup_file_name = '.'.join(dup_file_path.split('.')[:-1]) + "_copy" # Assuming .grc extension at the end of file_path + # Assuming .grc extension at the end of file_path + dup_file_name = '.'.join( + dup_file_path.split('.')[:-1]) + "_copy" dup_file_path_temp = dup_file_name + Constants.FILE_EXTENSION count = 1 while os.path.exists(dup_file_path_temp): - dup_file_path_temp = '{}({}){}'.format(dup_file_name, count, Constants.FILE_EXTENSION) + dup_file_path_temp = '{}({}){}'.format( + dup_file_name, count, Constants.FILE_EXTENSION) count += 1 - dup_file_path_user = FileDialogs.SaveFlowGraph(main, dup_file_path_temp).run() + dup_file_path_user = FileDialogs.SaveFlowGraph( + main, dup_file_path_temp).run() if dup_file_path_user is not None: - self.platform.save_flow_graph(dup_file_path_user, flow_graph) - Messages.send('Saved Copy to: "' + dup_file_path_user + '"\n') + self.platform.save_flow_graph( + dup_file_path_user, flow_graph) + Messages.send('Saved Copy to: "' + + dup_file_path_user + '"\n') except IOError: - Messages.send_fail_save("Can not create a copy of the flowgraph\n") + Messages.send_fail_save( + "Can not create a copy of the flowgraph\n") elif action == Actions.FLOW_GRAPH_DUPLICATE: previous = flow_graph # Create a new page @@ -694,10 +714,12 @@ def flow_graph_update(fg=flow_graph): page.state_cache.save_new_state(new_flow_graph.export_data()) page.saved = False elif action == Actions.FLOW_GRAPH_SCREEN_CAPTURE: - file_path, background_transparent = FileDialogs.SaveScreenShot(main, page.file_path).run() + file_path, background_transparent = FileDialogs.SaveScreenShot( + main, page.file_path).run() if file_path is not None: try: - Utils.make_screenshot(flow_graph, file_path, background_transparent) + Utils.make_screenshot( + flow_graph, file_path, background_transparent) except ValueError: Messages.send('Failed to generate screen shot\n') ################################################## @@ -717,7 +739,6 @@ def flow_graph_update(fg=flow_graph): except Exception as e: Messages.send_fail_gen(e) - elif action == Actions.FLOW_GRAPH_EXEC: if not page.process: Actions.FLOW_GRAPH_GEN() @@ -734,7 +755,7 @@ def flow_graph_update(fg=flow_graph): flow_graph_page=page, xterm_executable=xterm, callback=self.update_exec_stop - ) + ) elif action == Actions.FLOW_GRAPH_KILL: if page.process: try: @@ -748,7 +769,7 @@ def flow_graph_update(fg=flow_graph): self.platform.build_library() main.btwin.repopulate() - #todo: implement parser error dialog for YAML + # todo: implement parser error dialog for YAML # Force a redraw of the graph, by getting the current state and re-importing it main.update_pages() @@ -791,21 +812,21 @@ def flow_graph_update(fg=flow_graph): selected_blocks = list(flow_graph.selected_blocks()) selected_block = selected_blocks[0] if selected_blocks else None - #update general buttons + # update general buttons Actions.ERRORS_WINDOW_DISPLAY.set_enabled(not flow_graph.is_valid()) Actions.ELEMENT_DELETE.set_enabled(bool(flow_graph.selected_elements)) Actions.BLOCK_PARAM_MODIFY.set_enabled(bool(selected_block)) Actions.BLOCK_ROTATE_CCW.set_enabled(bool(selected_blocks)) Actions.BLOCK_ROTATE_CW.set_enabled(bool(selected_blocks)) - #update alignment options + # update alignment options for act in Actions.BLOCK_ALIGNMENTS: if act: act.set_enabled(len(selected_blocks) > 1) - #update cut/copy/paste + # update cut/copy/paste Actions.BLOCK_CUT.set_enabled(bool(selected_blocks)) Actions.BLOCK_COPY.set_enabled(bool(selected_blocks)) Actions.BLOCK_PASTE.set_enabled(bool(self.clipboard)) - #update enable/disable/bypass + # update enable/disable/bypass can_enable = any(block.state != 'enabled' for block in selected_blocks) can_disable = any(block.state != 'disabled' diff --git a/grc/gui/Bars.py b/grc/gui/Bars.py index 86eb3a57166..84867a8b4c0 100644 --- a/grc/gui/Bars.py +++ b/grc/gui/Bars.py @@ -42,11 +42,14 @@ (Actions.FLOW_GRAPH_OPEN, 'flow_graph_recent'), Actions.FLOW_GRAPH_SAVE, Actions.FLOW_GRAPH_CLOSE], [Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR, Actions.FLOW_GRAPH_SCREEN_CAPTURE], - [Actions.BLOCK_CUT, Actions.BLOCK_COPY, Actions.BLOCK_PASTE, Actions.ELEMENT_DELETE], + [Actions.BLOCK_CUT, Actions.BLOCK_COPY, + Actions.BLOCK_PASTE, Actions.ELEMENT_DELETE], [Actions.FLOW_GRAPH_UNDO, Actions.FLOW_GRAPH_REDO], - [Actions.ERRORS_WINDOW_DISPLAY, Actions.FLOW_GRAPH_GEN, Actions.FLOW_GRAPH_EXEC, Actions.FLOW_GRAPH_KILL], + [Actions.ERRORS_WINDOW_DISPLAY, Actions.FLOW_GRAPH_GEN, + Actions.FLOW_GRAPH_EXEC, Actions.FLOW_GRAPH_KILL], [Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW], - [Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, Actions.BLOCK_BYPASS, Actions.TOGGLE_HIDE_DISABLED_BLOCKS], + [Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, + Actions.BLOCK_BYPASS, Actions.TOGGLE_HIDE_DISABLED_BLOCKS], [Actions.FIND_BLOCKS, Actions.RELOAD_BLOCKS, Actions.OPEN_HIER] ] @@ -56,23 +59,28 @@ ('_File', [ [(Actions.FLOW_GRAPH_NEW, 'flow_graph_new_type'), Actions.FLOW_GRAPH_DUPLICATE, Actions.FLOW_GRAPH_OPEN, (Actions.FLOW_GRAPH_OPEN_RECENT, 'flow_graph_recent')], - [Actions.FLOW_GRAPH_SAVE, Actions.FLOW_GRAPH_SAVE_AS, Actions.FLOW_GRAPH_SAVE_COPY], + [Actions.FLOW_GRAPH_SAVE, Actions.FLOW_GRAPH_SAVE_AS, + Actions.FLOW_GRAPH_SAVE_COPY], [Actions.FLOW_GRAPH_SCREEN_CAPTURE], [Actions.FLOW_GRAPH_CLOSE, Actions.APPLICATION_QUIT] ]), ('_Edit', [ [Actions.FLOW_GRAPH_UNDO, Actions.FLOW_GRAPH_REDO], - [Actions.BLOCK_CUT, Actions.BLOCK_COPY, Actions.BLOCK_PASTE, Actions.ELEMENT_DELETE, Actions.SELECT_ALL], - [Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW, ('_Align', Actions.BLOCK_ALIGNMENTS)], + [Actions.BLOCK_CUT, Actions.BLOCK_COPY, Actions.BLOCK_PASTE, + Actions.ELEMENT_DELETE, Actions.SELECT_ALL], + [Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW, + ('_Align', Actions.BLOCK_ALIGNMENTS)], [Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, Actions.BLOCK_BYPASS], [Actions.BLOCK_PARAM_MODIFY] ]), ('_View', [ [Actions.TOGGLE_BLOCKS_WINDOW], - [Actions.TOGGLE_CONSOLE_WINDOW, Actions.TOGGLE_SCROLL_LOCK, Actions.SAVE_CONSOLE, Actions.CLEAR_CONSOLE], + [Actions.TOGGLE_CONSOLE_WINDOW, Actions.TOGGLE_SCROLL_LOCK, + Actions.SAVE_CONSOLE, Actions.CLEAR_CONSOLE], [Actions.TOGGLE_HIDE_VARIABLES, Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR, Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR_SIDEBAR, Actions.TOGGLE_SHOW_PARAMETER_EXPRESSION, Actions.TOGGLE_SHOW_PARAMETER_EVALUATION], - [Actions.TOGGLE_HIDE_DISABLED_BLOCKS, Actions.TOGGLE_AUTO_HIDE_PORT_LABELS, Actions.TOGGLE_SNAP_TO_GRID, Actions.TOGGLE_SHOW_BLOCK_COMMENTS, Actions.TOGGLE_SHOW_BLOCK_IDS,], + [Actions.TOGGLE_HIDE_DISABLED_BLOCKS, Actions.TOGGLE_AUTO_HIDE_PORT_LABELS, + Actions.TOGGLE_SNAP_TO_GRID, Actions.TOGGLE_SHOW_BLOCK_COMMENTS, Actions.TOGGLE_SHOW_BLOCK_IDS, ], [Actions.TOGGLE_SHOW_CODE_PREVIEW_TAB], [Actions.ZOOM_IN], [Actions.ZOOM_OUT], @@ -87,15 +95,18 @@ [Actions.TOGGLE_SHOW_FLOWGRAPH_COMPLEXITY] ]), ('_Help', [ - [Actions.HELP_WINDOW_DISPLAY, Actions.TYPES_WINDOW_DISPLAY, Actions.KEYBOARD_SHORTCUTS_WINDOW_DISPLAY, Actions.XML_PARSER_ERRORS_DISPLAY], + [Actions.HELP_WINDOW_DISPLAY, Actions.TYPES_WINDOW_DISPLAY, + Actions.KEYBOARD_SHORTCUTS_WINDOW_DISPLAY, Actions.XML_PARSER_ERRORS_DISPLAY], [Actions.GET_INVOLVED_WINDOW_DISPLAY, Actions.ABOUT_WINDOW_DISPLAY] ])] # The list of actions for the context menu. CONTEXT_MENU_LIST = [ - [Actions.BLOCK_CUT, Actions.BLOCK_COPY, Actions.BLOCK_PASTE, Actions.ELEMENT_DELETE], - [Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW, Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, Actions.BLOCK_BYPASS], + [Actions.BLOCK_CUT, Actions.BLOCK_COPY, + Actions.BLOCK_PASTE, Actions.ELEMENT_DELETE], + [Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW, + Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, Actions.BLOCK_BYPASS], [("_More", [ [Actions.BLOCK_CREATE_HIER, Actions.OPEN_HIER], [Actions.BUSSIFY_SOURCES, Actions.BUSSIFY_SINKS] @@ -181,7 +192,8 @@ def build_menu(self, actions, menu): target = "{}.{}".format(parent.prefix, parent.name) menuitem = Gio.MenuItem.new(label, None) if hasattr(parent, "icon_name"): - menuitem.set_icon(Gio.Icon.new_for_string(parent.icon_name)) + menuitem.set_icon( + Gio.Icon.new_for_string(parent.icon_name)) # Create the new submenu if isinstance(child, list): @@ -216,6 +228,7 @@ def refresh_submenus(self): parent_obj.remove(obj_idx) parent_obj.insert_item(obj_idx, obj) + class ToolbarHelper(SubMenuHelper): """ Builds a toolbar from a given list of actions. @@ -275,6 +288,7 @@ def refresh_submenus(self): create_func, parent_obj, _, obj, set_func = self.submenus[name] set_func(obj, create_func()) + class Menu(Gio.Menu, MenuHelper): """ Main Menu """ @@ -309,7 +323,7 @@ def __init__(self): ToolbarHelper.__init__(self) self.set_style(Gtk.ToolbarStyle.ICONS) - #self.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) + # self.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) - #SubMenuCreator.__init__(self) + # SubMenuCreator.__init__(self) self.build_toolbar(TOOLBAR_LIST, self) diff --git a/grc/gui/BlockTreeWindow.py b/grc/gui/BlockTreeWindow.py index 2f359f8c431..05341ec52b7 100644 --- a/grc/gui/BlockTreeWindow.py +++ b/grc/gui/BlockTreeWindow.py @@ -34,7 +34,8 @@ def _format_doc(doc): def _format_cat_tooltip(category): - tooltip = '{}: {}'.format('Category' if len(category) > 1 else 'Module', category[-1]) + tooltip = '{}: {}'.format('Category' if len( + category) > 1 else 'Module', category[-1]) if category == ('Core',): tooltip += '\n\nThis subtree is meant for blocks included with GNU Radio (in-tree).' @@ -68,26 +69,33 @@ def __init__(self, platform): # search entry self.search_entry = Gtk.Entry() try: - self.search_entry.set_icon_from_icon_name(Gtk.EntryIconPosition.PRIMARY, 'edit-find') - self.search_entry.set_icon_activatable(Gtk.EntryIconPosition.PRIMARY, False) - self.search_entry.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, 'window-close') + self.search_entry.set_icon_from_icon_name( + Gtk.EntryIconPosition.PRIMARY, 'edit-find') + self.search_entry.set_icon_activatable( + Gtk.EntryIconPosition.PRIMARY, False) + self.search_entry.set_icon_from_icon_name( + Gtk.EntryIconPosition.SECONDARY, 'window-close') self.search_entry.connect('icon-release', self._handle_icon_event) except AttributeError: pass # no icon for old pygtk self.search_entry.connect('changed', self._update_search_tree) - self.search_entry.connect('key-press-event', self._handle_search_key_press) + self.search_entry.connect( + 'key-press-event', self._handle_search_key_press) self.pack_start(self.search_entry, False, False, 0) # make the tree model for holding blocks and a temporary one for search results - self.treestore = Gtk.TreeStore(GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) - self.treestore_search = Gtk.TreeStore(GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) + self.treestore = Gtk.TreeStore( + GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) + self.treestore_search = Gtk.TreeStore( + GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) self.treeview = Gtk.TreeView(model=self.treestore) self.treeview.set_enable_search(False) # disable pop up search box self.treeview.set_search_column(-1) # really disable search self.treeview.set_headers_visible(False) self.treeview.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) - self.treeview.connect('button-press-event', self._handle_mouse_button_press) + self.treeview.connect('button-press-event', + self._handle_mouse_button_press) self.treeview.connect('key-press-event', self._handle_search_key_press) self.treeview.get_selection().set_mode(Gtk.SelectionMode.SINGLE) @@ -99,13 +107,16 @@ def __init__(self, platform): column.set_sort_column_id(0) self.treestore.set_sort_column_id(0, Gtk.SortType.ASCENDING) # setup drag and drop - self.treeview.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, Constants.DND_TARGETS, Gdk.DragAction.COPY) + self.treeview.enable_model_drag_source( + Gdk.ModifierType.BUTTON1_MASK, Constants.DND_TARGETS, Gdk.DragAction.COPY) self.treeview.connect('drag-data-get', self._handle_drag_get_data) # make the scrolled window to hold the tree view scrolled_window = Gtk.ScrolledWindow() - scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + scrolled_window.set_policy( + Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) scrolled_window.add(self.treeview) - scrolled_window.set_size_request(Constants.DEFAULT_BLOCKS_WINDOW_WIDTH, -1) + scrolled_window.set_size_request( + Constants.DEFAULT_BLOCKS_WINDOW_WIDTH, -1) self.pack_start(scrolled_window, True, True, 0) # map categories to iters, automatic mapping for root self._categories = {tuple(): None} @@ -128,10 +139,11 @@ def expand_module_in_tree(self, module_name='Core'): self.treeview.collapse_all() core_module_iter = self._categories.get((module_name,)) if core_module_iter: - self.treeview.expand_row(self.treestore.get_path(core_module_iter), False) + self.treeview.expand_row( + self.treestore.get_path(core_module_iter), False) ############################################################ - ## Block Tree Methods + # Block Tree Methods ############################################################ def add_block(self, block, treestore=None, categories=None): """ @@ -144,16 +156,19 @@ def add_block(self, block, treestore=None, categories=None): treestore = treestore or self.treestore categories = categories or self._categories - category = tuple(filter(str, block.category)) # tuple is hashable, remove empty cats + # tuple is hashable, remove empty cats + category = tuple(filter(str, block.category)) # add category and all sub categories for level, parent_cat_name in enumerate(category, 1): parent_category = category[:level] if parent_category not in categories: - iter_ = treestore.insert_before(categories[parent_category[:-1]], None) + iter_ = treestore.insert_before( + categories[parent_category[:-1]], None) treestore.set_value(iter_, NAME_INDEX, parent_cat_name) treestore.set_value(iter_, KEY_INDEX, '') - treestore.set_value(iter_, DOC_INDEX, _format_cat_tooltip(parent_category)) + treestore.set_value( + iter_, DOC_INDEX, _format_cat_tooltip(parent_category)) categories[parent_category] = iter_ # add block iter_ = treestore.insert_before(categories[category], None) @@ -175,7 +190,7 @@ def update_doc(model, _, iter_): self.treestore_search.foreach(update_doc) ############################################################ - ## Helper Methods + # Helper Methods ############################################################ def _get_selected_block_key(self): """ @@ -195,7 +210,7 @@ def _expand_category(self): self.treeview.expand_to_path(path) ############################################################ - ## Event Handlers + # Event Handlers ############################################################ def _handle_icon_event(self, widget, icon, event): if icon == Gtk.EntryIconPosition.PRIMARY: @@ -216,7 +231,8 @@ def _update_search_tree(self, widget): self.treestore_search.clear() self._categories_search = {tuple(): None} for block in matching_blocks: - self.add_block(block, self.treestore_search, self._categories_search) + self.add_block(block, self.treestore_search, + self._categories_search) self.treeview.set_model(self.treestore_search) self.treeview.expand_all() @@ -232,7 +248,8 @@ def _handle_search_key_press(self, widget, event): selected = self.treestore_search.iter_children(selected) if selected is not None: key = self.treestore_search.get_value(selected, KEY_INDEX) - if key: self.emit('create_new_block', key) + if key: + self.emit('create_new_block', key) elif widget == self.treeview: key = self._get_selected_block_key() if key: @@ -248,7 +265,7 @@ def _handle_search_key_press(self, widget, event): self.search_entry.hide() elif (event.get_state() & Gdk.ModifierType.CONTROL_MASK and event.keyval == Gdk.KEY_f) \ - or event.keyval == Gdk.KEY_slash: + or event.keyval == Gdk.KEY_slash: # propagation doesn't work although treeview search is disabled =( # manually trigger action... Actions.FIND_BLOCKS.activate() @@ -258,7 +275,7 @@ def _handle_search_key_press(self, widget, event): Actions.TOGGLE_BLOCKS_WINDOW.activate() else: - return False # propagate event + return False # propagate event return True diff --git a/grc/gui/Config.py b/grc/gui/Config.py index ee354ba54de..35d2eefcca6 100644 --- a/grc/gui/Config.py +++ b/grc/gui/Config.py @@ -142,7 +142,8 @@ def set_open_files(self, files): def get_recent_files(self): """ Gets recent files, removes any that do not exist and re-saves it """ - files = list(filter(os.path.exists, self.get_file_list('files_recent'))) + files = list( + filter(os.path.exists, self.get_file_list('files_recent'))) self.set_recent_files(files) return files @@ -168,9 +169,9 @@ def variable_editor_position(self, pos=None, sidebar=False): # Figure out default if sidebar: _, h = self.main_window_size() - return self.entry('variable_editor_sidebar_position', pos, default=int(h*0.7)) + return self.entry('variable_editor_sidebar_position', pos, default=int(h * 0.7)) else: - return self.entry('variable_editor_position', pos, default=int(self.blocks_window_position()*0.5)) + return self.entry('variable_editor_position', pos, default=int(self.blocks_window_position() * 0.5)) def variable_editor_sidebar(self, pos=None): return self.entry('variable_editor_sidebar', pos, default=False) diff --git a/grc/gui/Console.py b/grc/gui/Console.py index 40345b96999..f88191cd881 100644 --- a/grc/gui/Console.py +++ b/grc/gui/Console.py @@ -7,17 +7,15 @@ """ +from ..core import Messages +from .Dialogs import TextDisplay, MessageDialogWrapper +from .Constants import DEFAULT_CONSOLE_WINDOW_WIDTH +from gi.repository import Gtk, Gdk, GObject import os import logging import gi gi.require_version('Gtk', '3.0') -from gi.repository import Gtk, Gdk, GObject - -from .Constants import DEFAULT_CONSOLE_WINDOW_WIDTH -from .Dialogs import TextDisplay, MessageDialogWrapper - -from ..core import Messages log = logging.getLogger(__name__) diff --git a/grc/gui/Constants.py b/grc/gui/Constants.py index 2effc8c98cc..dd744974683 100644 --- a/grc/gui/Constants.py +++ b/grc/gui/Constants.py @@ -91,7 +91,8 @@ # _SCREEN = Gdk.Screen.get_default() # _SCREEN_RESOLUTION = _SCREEN.get_resolution() if _SCREEN else -1 # DPI_SCALING = _SCREEN_RESOLUTION / 96.0 if _SCREEN_RESOLUTION > 0 else 1.0 -DPI_SCALING = 1.0 # todo: figure out the GTK3 way (maybe cairo does this for us +# todo: figure out the GTK3 way (maybe cairo does this for us +DPI_SCALING = 1.0 # Gtk-themes classified as dark GTK_DARK_THEMES = [ @@ -113,7 +114,10 @@ def update_font_size(font_size): PORT_FONT = BLOCK_FONT PARAM_FONT = "%s %f" % (FONT_FAMILY, font_size - 0.5) - PORT_SEPARATION = PORT_SPACING + 2 * PORT_LABEL_PADDING + int(1.5 * font_size) - PORT_SEPARATION += -PORT_SEPARATION % (2 * CANVAS_GRID_SIZE) # even multiple + PORT_SEPARATION = PORT_SPACING + 2 * \ + PORT_LABEL_PADDING + int(1.5 * font_size) + PORT_SEPARATION += - \ + PORT_SEPARATION % (2 * CANVAS_GRID_SIZE) # even multiple + update_font_size(DEFAULT_FONT_SIZE) diff --git a/grc/gui/Dialogs.py b/grc/gui/Dialogs.py index a51b1c44e7b..7bdfb2aecbf 100644 --- a/grc/gui/Dialogs.py +++ b/grc/gui/Dialogs.py @@ -237,7 +237,8 @@ def update(self, flowgraph): aspect = "Connection to '{}'".format(element.sink_block.name) elif element.is_port: src = element.parent_block.name - aspect = "{} '{}'".format('Sink' if element.is_sink else 'Source', element.name) + aspect = "{} '{}'".format( + 'Sink' if element.is_sink else 'Source', element.name) elif element.is_param: src = element.parent_block.name aspect = "Param '{}'".format(element.name) @@ -279,7 +280,7 @@ def show_about(parent, config): except GLib.Error: Messages.send("Failed to set window logo\n") - #ad.set_comments("") + # ad.set_comments("") ad.set_copyright(config.license.splitlines()[0]) ad.set_website(config.website) @@ -311,6 +312,7 @@ def show_help(parent): parent, Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE, title='Help', markup=markup ).run_and_destroy() + def show_keyboard_shortcuts(parent): """ Display keyboard shortcut-keys. """ markup = textwrap.dedent("""\ @@ -371,7 +373,8 @@ def show_get_involved(parent): def show_types(parent): """ Display information about standard data types. """ - colors = [(name, color) for name, key, sizeof, color in Constants.CORE_TYPES] + colors = [(name, color) + for name, key, sizeof, color in Constants.CORE_TYPES] max_len = 10 + max(len(name) for name, code in colors) message = '\n'.join( @@ -424,7 +427,8 @@ def choose_editor(parent, config): file_dialog = Gtk.FileChooserDialog( 'Select an Editor...', None, Gtk.FileChooserAction.OPEN, - ('gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-open', Gtk.ResponseType.OK), + ('gtk-cancel', Gtk.ResponseType.CANCEL, + 'gtk-open', Gtk.ResponseType.OK), transient_for=parent ) file_dialog.set_select_multiple(False) @@ -449,7 +453,8 @@ def choose_editor(parent, config): # Save editor = config.editor = process except Exception: - Messages.send('>>> Unable to load the default editor. Please choose an editor.\n') + Messages.send( + '>>> Unable to load the default editor. Please choose an editor.\n') if editor == '': Messages.send('>>> No editor selected.\n') diff --git a/grc/gui/DrawingArea.py b/grc/gui/DrawingArea.py index 5295caedbb4..d94a890272c 100644 --- a/grc/gui/DrawingArea.py +++ b/grc/gui/DrawingArea.py @@ -79,10 +79,10 @@ def _handle_notify_event(widget, event, focus_flag): self.set_can_focus(True) self.connect('focus-out-event', self._handle_focus_lost_event) - ########################################################################## # Handlers ########################################################################## + def _handle_drag_data_received(self, widget, drag_context, x, y, selection_data, info, time): """ Handle a drag and drop by adding a block at the given coordinate. @@ -96,7 +96,7 @@ def zoom_in(self): self._set_zoom_factor(zoom_factor) def zoom_out(self): - change = 1/1.2 + change = 1 / 1.2 zoom_factor = max(self.zoom_factor * change, 0.1) self._set_zoom_factor(zoom_factor) diff --git a/grc/gui/Executor.py b/grc/gui/Executor.py index 4505ef0b374..78f91d93e2b 100644 --- a/grc/gui/Executor.py +++ b/grc/gui/Executor.py @@ -80,7 +80,8 @@ def _cpp_popen(self): Execute this C++ flow graph after generating and compiling it. """ generator = self.page.get_generator() - run_command = generator.file_path + '/build/' + self.flow_graph.get_option('id') + run_command = generator.file_path + \ + '/build/' + self.flow_graph.get_option('id') dirname = generator.file_path builddir = os.path.join(dirname, 'build') diff --git a/grc/gui/FileDialogs.py b/grc/gui/FileDialogs.py index acb2ed86102..ceca9195310 100644 --- a/grc/gui/FileDialogs.py +++ b/grc/gui/FileDialogs.py @@ -41,7 +41,8 @@ def __init__(self, parent, current_file_path): Gtk.FileChooserDialog.__init__(self, title=self.title, action=self.action, transient_for=parent) - self.add_buttons('gtk-cancel', Gtk.ResponseType.CANCEL, ok_stock, Gtk.ResponseType.OK) + self.add_buttons('gtk-cancel', Gtk.ResponseType.CANCEL, + ok_stock, Gtk.ResponseType.OK) self.set_select_multiple(False) self.set_local_only(True) @@ -49,12 +50,14 @@ def __init__(self, parent, current_file_path): self.current_file_path = current_file_path or path.join( Constants.DEFAULT_FILE_PATH, Constants.NEW_FLOGRAPH_TITLE + Constants.FILE_EXTENSION) - self.set_current_folder(path.dirname(current_file_path)) # current directory + self.set_current_folder(path.dirname( + current_file_path)) # current directory self.setup_filters() def setup_filters(self, filters=None): set_default = True - filters = filters or ([(self.filter_label, self.filter_ext)] if self.filter_label else []) + filters = filters or ( + [(self.filter_label, self.filter_ext)] if self.filter_label else []) filters.append(('All Files', '')) for label, ext in filters: if not label: @@ -81,7 +84,8 @@ class SaveFileDialog(FileDialogHelper): def __init__(self, parent, current_file_path): super(SaveFileDialog, self).__init__(parent, current_file_path) - self.set_current_name(path.splitext(path.basename(self.current_file_path))[0] + self.filter_ext) + self.set_current_name(path.splitext(path.basename( + self.current_file_path))[0] + self.filter_ext) self.set_create_folders(True) self.set_do_overwrite_confirmation(True) @@ -94,7 +98,8 @@ def show_missing_message(self, filename): Dialogs.MessageDialogWrapper( self.parent, Gtk.MessageType.WARNING, Gtk.ButtonsType.CLOSE, 'Cannot Open!', - 'File {filename} Does not Exist!'.format(filename=Utils.encode(filename)), + 'File {filename} Does not Exist!'.format( + filename=Utils.encode(filename)), ).run_and_destroy() def get_filename(self): @@ -145,7 +150,8 @@ class SaveConsole(SaveFileDialog): class SaveScreenShot(SaveFileDialog): title = 'Save a Flow Graph Screen Shot...' - filters = [('PDF Files', '.pdf'), ('PNG Files', '.png'), ('SVG Files', '.svg')] + filters = [('PDF Files', '.pdf'), ('PNG Files', '.png'), + ('SVG Files', '.svg')] filter_ext = '.pdf' # the default def __init__(self, parent, current_file_path=''): @@ -154,7 +160,8 @@ def __init__(self, parent, current_file_path=''): self.config = Gtk.Application.get_default().config self._button = button = Gtk.CheckButton(label='Background transparent') - self._button.set_active(self.config.screen_shot_background_transparent()) + self._button.set_active( + self.config.screen_shot_background_transparent()) self.set_extra_widget(button) def setup_filters(self, filters=None): @@ -164,7 +171,8 @@ def show_missing_message(self, filename): Dialogs.MessageDialogWrapper( self.parent, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, 'Can not Save!', - 'File Extension of {filename} not supported!'.format(filename=Utils.encode(filename)), + 'File Extension of {filename} not supported!'.format( + filename=Utils.encode(filename)), ).run_and_destroy() def run(self): diff --git a/grc/gui/MainWindow.py b/grc/gui/MainWindow.py index 7e8462b3ef5..5561c264195 100644 --- a/grc/gui/MainWindow.py +++ b/grc/gui/MainWindow.py @@ -43,7 +43,8 @@ def __init__(self, app, platform): MainWindow constructor Setup the menu, toolbar, flow graph editor notebook, block selection window... """ - Gtk.ApplicationWindow.__init__(self, title="GNU Radio Companion", application=app) + Gtk.ApplicationWindow.__init__( + self, title="GNU Radio Companion", application=app) log.debug("__init__()") self._platform = platform @@ -63,7 +64,8 @@ def __init__(self, app, platform): icon = icon_theme.lookup_icon("gnuradio-grc", 48, 0) if not icon: # Set default window icon - self.set_icon_from_file(os.path.dirname(os.path.abspath(__file__)) + "/icon.png") + self.set_icon_from_file(os.path.dirname( + os.path.abspath(__file__)) + "/icon.png") else: # Use gnuradio icon self.set_icon(icon.load_icon()) @@ -85,7 +87,7 @@ def __init__(self, app, platform): vbox.pack_start(self.tool_bar, False, False, 0) # Main parent container for the different panels - self.main = Gtk.HPaned() #(orientation=Gtk.Orientation.HORIZONTAL) + self.main = Gtk.HPaned() # (orientation=Gtk.Orientation.HORIZONTAL) vbox.pack_start(self.main, True, True, 0) # Create the notebook @@ -99,15 +101,19 @@ def __init__(self, app, platform): # Create the block tree and variable panels self.btwin = BlockTreeWindow(platform) - self.btwin.connect('create_new_block', self._add_block_to_current_flow_graph) + self.btwin.connect('create_new_block', + self._add_block_to_current_flow_graph) self.vars = VariableEditor() - self.vars.connect('create_new_block', self._add_block_to_current_flow_graph) - self.vars.connect('remove_block', self._remove_block_from_current_flow_graph) + self.vars.connect('create_new_block', + self._add_block_to_current_flow_graph) + self.vars.connect( + 'remove_block', self._remove_block_from_current_flow_graph) # Figure out which place to put the variable editor - self.left = Gtk.VPaned() #orientation=Gtk.Orientation.VERTICAL) - self.right = Gtk.VPaned() #orientation=Gtk.Orientation.VERTICAL) - self.left_subpanel = Gtk.HPaned() #orientation=Gtk.Orientation.HORIZONTAL) + self.left = Gtk.VPaned() # orientation=Gtk.Orientation.VERTICAL) + self.right = Gtk.VPaned() # orientation=Gtk.Orientation.VERTICAL) + # orientation=Gtk.Orientation.HORIZONTAL) + self.left_subpanel = Gtk.HPaned() self.variable_panel_sidebar = self.config.variable_editor_sidebar() if self.variable_panel_sidebar: @@ -133,9 +139,11 @@ def __init__(self, app, platform): self.main.set_position(self.config.blocks_window_position()) self.left.set_position(self.config.console_window_position()) if self.variable_panel_sidebar: - self.right.set_position(self.config.variable_editor_position(sidebar=True)) + self.right.set_position( + self.config.variable_editor_position(sidebar=True)) else: - self.left_subpanel.set_position(self.config.variable_editor_position()) + self.left_subpanel.set_position( + self.config.variable_editor_position()) self.show_all() log.debug("Main window ready") @@ -238,16 +246,18 @@ def new_page(self, file_path='', show=False): file_path: optional file to load into the flow graph show: true if the page should be shown after loading """ - #if the file is already open, show the open page and return - if file_path and file_path in self._get_files(): #already open - page = self.notebook.get_nth_page(self._get_files().index(file_path)) + # if the file is already open, show the open page and return + if file_path and file_path in self._get_files(): # already open + page = self.notebook.get_nth_page( + self._get_files().index(file_path)) self._set_page(page) return - try: #try to load from file - if file_path: Messages.send_start_load(file_path) + try: # try to load from file + if file_path: + Messages.send_start_load(file_path) flow_graph = self._platform.make_flow_graph() flow_graph.grc_file_path = file_path - #print flow_graph + # print flow_graph page = Page( self, flow_graph=flow_graph, @@ -260,18 +270,20 @@ def new_page(self, file_path='', show=False): str(Messages.flowgraph_error) ) ) - if file_path: Messages.send_end_load() - except Exception as e: #return on failure + if file_path: + Messages.send_end_load() + except Exception as e: # return on failure Messages.send_fail_load(e) if isinstance(e, KeyError) and str(e) == "'options'": # This error is unrecoverable, so crash gracefully exit(-1) return - #add this page to the notebook + # add this page to the notebook self.notebook.append_page(page, page.tab) self.notebook.set_tab_reorderable(page, True) - #only show if blank or manual - if not file_path or show: self._set_page(page) + # only show if blank or manual + if not file_path or show: + self._set_page(page) def close_pages(self): """ @@ -280,25 +292,29 @@ def close_pages(self): Returns: true if all closed """ - open_files = [file for file in self._get_files() if file] #filter blank files + open_files = [file for file in self._get_files() + if file] # filter blank files open_file = self.current_page.file_path - #close each page + # close each page for page in sorted(self.get_pages(), key=lambda p: p.saved): self.page_to_be_closed = page closed = self.close_page(False) if not closed: break - if self.notebook.get_n_pages(): return False - #save state before closing + if self.notebook.get_n_pages(): + return False + # save state before closing self.config.set_open_files(open_files) self.config.file_open(open_file) self.config.main_window_size(self.get_size()) self.config.console_window_position(self.left.get_position()) self.config.blocks_window_position(self.main.get_position()) if self.variable_panel_sidebar: - self.config.variable_editor_position(self.right.get_position(), sidebar=True) + self.config.variable_editor_position( + self.right.get_position(), sidebar=True) else: - self.config.variable_editor_position(self.left_subpanel.get_position()) + self.config.variable_editor_position( + self.left_subpanel.get_position()) self.config.save() return True @@ -311,29 +327,31 @@ def close_page(self, ensure=True): Args: ensure: boolean """ - if not self.page_to_be_closed: self.page_to_be_closed = self.current_page - #show the page if it has an executing flow graph or is unsaved + if not self.page_to_be_closed: + self.page_to_be_closed = self.current_page + # show the page if it has an executing flow graph or is unsaved if self.page_to_be_closed.process or not self.page_to_be_closed.saved: self._set_page(self.page_to_be_closed) - #unsaved? ask the user + # unsaved? ask the user if not self.page_to_be_closed.saved: - response = self._save_changes() # return value is either OK, CLOSE, or CANCEL + response = self._save_changes() # return value is either OK, CLOSE, or CANCEL if response == Gtk.ResponseType.OK: - Actions.FLOW_GRAPH_SAVE() #try to save - if not self.page_to_be_closed.saved: #still unsaved? - self.page_to_be_closed = None #set the page to be closed back to None + Actions.FLOW_GRAPH_SAVE() # try to save + if not self.page_to_be_closed.saved: # still unsaved? + self.page_to_be_closed = None # set the page to be closed back to None return False elif response == Gtk.ResponseType.CANCEL: self.page_to_be_closed = None return False - #stop the flow graph if executing + # stop the flow graph if executing if self.page_to_be_closed.process: Actions.FLOW_GRAPH_KILL() - #remove the page - self.notebook.remove_page(self.notebook.page_num(self.page_to_be_closed)) + # remove the page + self.notebook.remove_page( + self.notebook.page_num(self.page_to_be_closed)) if ensure and self.notebook.get_n_pages() == 0: - self.new_page() #no pages, make a new one - self.page_to_be_closed = None #set the page to be closed back to None + self.new_page() # no pages, make a new one + self.page_to_be_closed = None # set the page to be closed back to None return True ############################################################ @@ -405,7 +423,8 @@ def _set_page(self, page): page: the page widget """ self.current_page = page - self.notebook.set_current_page(self.notebook.page_num(self.current_page)) + self.notebook.set_current_page( + self.notebook.page_num(self.current_page)) def _save_changes(self): """ diff --git a/grc/gui/Notebook.py b/grc/gui/Notebook.py index 02f27dc3168..457e115d3f1 100644 --- a/grc/gui/Notebook.py +++ b/grc/gui/Notebook.py @@ -118,9 +118,12 @@ def __init__(self, main_window, flow_graph, file_path=''): self.viewport.add(self.drawing_area) self.scrolled_window = Gtk.ScrolledWindow() - self.scrolled_window.set_size_request(MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT) - self.scrolled_window.set_policy(Gtk.PolicyType.ALWAYS, Gtk.PolicyType.ALWAYS) - self.scrolled_window.connect('key-press-event', self._handle_scroll_window_key_press) + self.scrolled_window.set_size_request( + MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT) + self.scrolled_window.set_policy( + Gtk.PolicyType.ALWAYS, Gtk.PolicyType.ALWAYS) + self.scrolled_window.connect( + 'key-press-event', self._handle_scroll_window_key_press) self.scrolled_window.add(self.viewport) self.pack_start(self.scrolled_window, True, True, 0) diff --git a/grc/gui/ParamWidgets.py b/grc/gui/ParamWidgets.py index 1cdfc34989f..acb95b106f7 100644 --- a/grc/gui/ParamWidgets.py +++ b/grc/gui/ParamWidgets.py @@ -42,6 +42,7 @@ def is_dark_theme(theme_name): return False return is_dark_theme(theme) + def add_style_provider(): """ Load GTK styles @@ -55,6 +56,8 @@ def add_style_provider(): style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION ) + + add_style_provider() @@ -93,7 +96,8 @@ def _update_gui(self, *args): """ Set the markup, color, tooltip, show/hide. """ - self.label.set_markup(self.param.format_label_markup(self._have_pending_changes)) + self.label.set_markup( + self.param.format_label_markup(self._have_pending_changes)) self.set_color('dtype_' + self.param.dtype) self.set_tooltip_text(self.param.format_tooltip_text()) @@ -117,14 +121,14 @@ def _apply_change(self, *args): Handle a gui change by setting the new param value, calling the callback (if applicable), and updating. """ - #set the new value + # set the new value self.param.set_value(self.get_text()) - #call the callback + # call the callback if self._changed_callback: self._changed_callback(self, None) else: self.param.validate() - #gui update + # gui update self._have_pending_changes = False self._update_gui() @@ -205,7 +209,8 @@ def __init__(self, *args, **kwargs): self.pack_start(button, True, True, True) def open_editor(self, widget=None): - self.param.parent_flowgraph.install_external_editor(self.param, parent=self._transient_for) + self.param.parent_flowgraph.install_external_editor( + self.param, parent=self._transient_for) def get_text(self): pass # we never update the value from here @@ -297,13 +302,15 @@ def _handle_clicked(self, widget=None): """ # get the paths file_path = self.param.is_valid() and self.param.get_evaluated() or '' - (dirname, basename) = os.path.isfile(file_path) and os.path.split(file_path) or (file_path, '') + (dirname, basename) = os.path.isfile( + file_path) and os.path.split(file_path) or (file_path, '') # check for qss theme default directory if self.param.key == 'qt_qss_theme': dirname = os.path.dirname(dirname) # trim filename if not os.path.exists(dirname): - config = self.param.parent_platform.config - dirname = os.path.join(config.install_prefix, '/share/gnuradio/themes') + config = self.param.parent_platform.config + dirname = os.path.join( + config.install_prefix, '/share/gnuradio/themes') if not os.path.exists(dirname): dirname = os.getcwd() # fix bad paths @@ -313,17 +320,20 @@ def _handle_clicked(self, widget=None): title='Open a Data File...', action=Gtk.FileChooserAction.OPEN, transient_for=self._transient_for, ) - file_dialog.add_buttons('gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-open', Gtk.ResponseType.OK) + file_dialog.add_buttons( + 'gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-open', Gtk.ResponseType.OK) elif self.param.dtype == 'file_save': file_dialog = Gtk.FileChooserDialog( title='Save a Data File...', action=Gtk.FileChooserAction.SAVE, transient_for=self._transient_for, ) - file_dialog.add_buttons('gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-save', Gtk.ResponseType.OK) + file_dialog.add_buttons( + 'gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-save', Gtk.ResponseType.OK) file_dialog.set_do_overwrite_confirmation(True) file_dialog.set_current_name(basename) # show the current filename else: - raise ValueError("Can't open file chooser dialog for type " + repr(self.param.dtype)) + raise ValueError( + "Can't open file chooser dialog for type " + repr(self.param.dtype)) file_dialog.set_current_folder(dirname) # current directory file_dialog.set_select_multiple(False) file_dialog.set_local_only(True) @@ -334,6 +344,7 @@ def _handle_clicked(self, widget=None): self._apply_change() file_dialog.destroy() # destroy the dialog + class DirectoryParam(FileParam): """Provide an entry box for a directory and a button to browse for it.""" @@ -344,23 +355,26 @@ def _handle_clicked(self, widget=None): """ dirname = self.param.get_evaluated() if self.param.is_valid() else '' - if not os.path.isdir(dirname): # Check if directory exists, if not fall back to workdir + # Check if directory exists, if not fall back to workdir + if not os.path.isdir(dirname): dirname = os.getcwd() - if self.param.dtype == "dir_select": # Setup directory selection dialog, and fail for unexpected dtype + if self.param.dtype == "dir_select": # Setup directory selection dialog, and fail for unexpected dtype dir_dialog = Gtk.FileChooserDialog( title='Select a Directory...', action=Gtk.FileChooserAction.SELECT_FOLDER, transient_for=self._transient_for ) else: - raise ValueError("Can't open directory chooser dialog for type " + repr(self.param.dtype)) + raise ValueError( + "Can't open directory chooser dialog for type " + repr(self.param.dtype)) # Set dialog properties - dir_dialog.add_buttons('gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-open', Gtk.ResponseType.OK) + dir_dialog.add_buttons( + 'gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-open', Gtk.ResponseType.OK) dir_dialog.set_current_folder(dirname) dir_dialog.set_local_only(True) dir_dialog.set_select_multiple(False) - + # Show dialog and update parameter on success if Gtk.ResponseType.OK == dir_dialog.run(): path = dir_dialog.get_filename() diff --git a/grc/gui/ParserErrorsDialog.py b/grc/gui/ParserErrorsDialog.py index 12f6f4c7a7e..745dc47f0ab 100644 --- a/grc/gui/ParserErrorsDialog.py +++ b/grc/gui/ParserErrorsDialog.py @@ -24,7 +24,8 @@ def __init__(self, error_logs): Args: block: a block instance """ - GObject.GObject.__init__(self, title='Parser Errors', buttons=(Gtk.STOCK_CLOSE, Gtk.ResponseType.ACCEPT)) + GObject.GObject.__init__(self, title='Parser Errors', buttons=( + Gtk.STOCK_CLOSE, Gtk.ResponseType.ACCEPT)) self._error_logs = None self.tree_store = Gtk.TreeStore(str) @@ -48,11 +49,12 @@ def __init__(self, error_logs): tree_view.expand_row(row.path, False) scrolled_window = Gtk.ScrolledWindow() - scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + scrolled_window.set_policy( + Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) scrolled_window.add(tree_view) self.vbox.pack_start(scrolled_window, True) - self.set_size_request(2*MIN_DIALOG_WIDTH, MIN_DIALOG_HEIGHT) + self.set_size_request(2 * MIN_DIALOG_WIDTH, MIN_DIALOG_HEIGHT) self.show_all() def update_tree_store(self, error_logs): @@ -68,7 +70,8 @@ def update_tree_store(self, error_logs): code = None for error in errors: # http://lxml.de/api/lxml.etree._LogEntry-class.html - em = self.tree_store.append(parent, ["Line {e.line}: {e.message}".format(e=error)]) + em = self.tree_store.append( + parent, ["Line {e.line}: {e.message}".format(e=error)]) if code: self.tree_store.append(em, ["\n".join( "{} {}{}".format(line, code[line - 1].replace("\t", " ").strip("\n"), diff --git a/grc/gui/PropsDialog.py b/grc/gui/PropsDialog.py index e7dd72edcf8..570e6a45763 100644 --- a/grc/gui/PropsDialog.py +++ b/grc/gui/PropsDialog.py @@ -64,7 +64,8 @@ def __init__(self, parent, block): self._docs_text_display = doc_view = SimpleTextDisplay() doc_view.get_buffer().create_tag('b', weight=Pango.Weight.BOLD) self._docs_box = Gtk.ScrolledWindow() - self._docs_box.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + self._docs_box.set_policy( + Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self._docs_vbox = Gtk.VBox(homogeneous=False, spacing=0) self._docs_box.add(self._docs_vbox) self._docs_link = Gtk.Label(use_markup=True) @@ -81,7 +82,8 @@ def __init__(self, parent, block): # todo: set font size in non-deprecated way # code_view.override_font(Pango.FontDescription('monospace %d' % Constants.FONT_SIZE)) code_box = Gtk.ScrolledWindow() - code_box.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + code_box.set_policy(Gtk.PolicyType.AUTOMATIC, + Gtk.PolicyType.AUTOMATIC) code_box.add(self._code_text_display) notebook.append_page(code_box, Gtk.Label(label="Generated Code")) else: @@ -90,7 +92,8 @@ def __init__(self, parent, block): # Error Messages for the block self._error_messages_text_display = SimpleTextDisplay() self._error_box = Gtk.ScrolledWindow() - self._error_box.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + self._error_box.set_policy( + Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self._error_box.add(self._error_messages_text_display) vpaned.pack2(self._error_box) vpaned.set_position(int(0.65 * Constants.MIN_DIALOG_HEIGHT)) @@ -117,7 +120,8 @@ def unique_categories(): label = Gtk.Label() vbox = Gtk.VBox() scroll_box = Gtk.ScrolledWindow() - scroll_box.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + scroll_box.set_policy(Gtk.PolicyType.AUTOMATIC, + Gtk.PolicyType.AUTOMATIC) scroll_box.add(vbox) self.notebook.append_page(scroll_box, label) self._params_boxes.append((category, label, vbox)) @@ -232,7 +236,8 @@ def _update_docs_page(self): buf.insert(pos, '\n') # if given the current parameters an exact match can be made - block_constructor = self._block.templates.render('make').rsplit('.', 2)[-1] + block_constructor = self._block.templates.render( + 'make').rsplit('.', 2)[-1] block_class = block_constructor.partition('(')[0].strip() if block_class in docstrings: docstrings = {block_class: docstrings[block_class]} diff --git a/grc/gui/StateCache.py b/grc/gui/StateCache.py index b3eb4e92325..fff261a29ef 100644 --- a/grc/gui/StateCache.py +++ b/grc/gui/StateCache.py @@ -9,6 +9,7 @@ from . import Actions from .Constants import STATE_CACHE_SIZE + class StateCache(object): """ The state cache is an interface to a list to record data/states and to revert to previous states. @@ -23,7 +24,7 @@ def __init__(self, initial_state): Args: initial_state: the initial state (nested data) """ - self.states = [None] * STATE_CACHE_SIZE #fill states + self.states = [None] * STATE_CACHE_SIZE # fill states self.current_state_index = 0 self.num_prev_states = 0 self.num_next_states = 0 @@ -38,10 +39,12 @@ def save_new_state(self, state): Args: state: the new state """ - self.current_state_index = (self.current_state_index + 1)%STATE_CACHE_SIZE + self.current_state_index = ( + self.current_state_index + 1) % STATE_CACHE_SIZE self.states[self.current_state_index] = state self.num_prev_states = self.num_prev_states + 1 - if self.num_prev_states == STATE_CACHE_SIZE: self.num_prev_states = STATE_CACHE_SIZE - 1 + if self.num_prev_states == STATE_CACHE_SIZE: + self.num_prev_states = STATE_CACHE_SIZE - 1 self.num_next_states = 0 self.update_actions() @@ -63,7 +66,8 @@ def get_prev_state(self): the previous state or None """ if self.num_prev_states > 0: - self.current_state_index = (self.current_state_index + STATE_CACHE_SIZE -1)%STATE_CACHE_SIZE + self.current_state_index = ( + self.current_state_index + STATE_CACHE_SIZE - 1) % STATE_CACHE_SIZE self.num_next_states = self.num_next_states + 1 self.num_prev_states = self.num_prev_states - 1 return self.get_current_state() @@ -77,7 +81,8 @@ def get_next_state(self): the next state or None """ if self.num_next_states > 0: - self.current_state_index = (self.current_state_index + 1)%STATE_CACHE_SIZE + self.current_state_index = ( + self.current_state_index + 1) % STATE_CACHE_SIZE self.num_next_states = self.num_next_states - 1 self.num_prev_states = self.num_prev_states + 1 return self.get_current_state() diff --git a/grc/gui/Utils.py b/grc/gui/Utils.py index 165537c383f..5c643c95964 100644 --- a/grc/gui/Utils.py +++ b/grc/gui/Utils.py @@ -32,7 +32,7 @@ def get_rotated_coordinate(coor, rotation): # handles negative angles rotation = (rotation + 360) % 360 if rotation not in Constants.POSSIBLE_ROTATIONS: - raise ValueError('unusable rotation angle "%s"'%str(rotation)) + raise ValueError('unusable rotation angle "%s"' % str(rotation)) # determine the number of degrees to rotate cos_r, sin_r = { 0: (1, 0), 90: (0, 1), 180: (-1, 0), 270: (0, -1), @@ -76,7 +76,7 @@ def eng_notation(value, fmt='g'): """Convert a number to a string in engineering notation. E.g., 5e-9 -> 5n""" template = '{:' + fmt + '}{}' magnitude = abs(value) - for exp, symbol in zip(range(9, -15-1, -3), 'GMk munpf'): + for exp, symbol in zip(range(9, -15 - 1, -3), 'GMk munpf'): factor = 10 ** exp if magnitude >= factor: return template.format(value / factor, symbol.strip()) @@ -87,7 +87,8 @@ def eng_notation(value, fmt='g'): if num == 0: return '0' output = eng_notation(num.real) if num.real else '' - output += eng_notation(num.imag, '+g' if output else 'g') + 'j' if num.imag else '' + output += eng_notation(num.imag, '+g' if output else 'g') + \ + 'j' if num.imag else '' return output else: return str(num) @@ -144,6 +145,7 @@ def scale_scalar(coor, reverse=False): factor = Constants.DPI_SCALING if not reverse else 1 / Constants.DPI_SCALING return int(coor * factor) + def get_modifier_key(angle_brackets=False): """ Get the modifier key based on platform. @@ -167,9 +169,11 @@ def get_modifier_key(angle_brackets=False): _nproc = None + + def get_cmake_nproc(): """ Get number of cmake processes for C++ flowgraphs """ - global _nproc # Cached result + global _nproc # Cached result if _nproc: return _nproc try: @@ -180,5 +184,5 @@ def get_cmake_nproc(): if not _nproc: _nproc = 1 - _nproc = max(_nproc//2 - 1, 1) + _nproc = max(_nproc // 2 - 1, 1) return _nproc diff --git a/grc/gui/VariableEditor.py b/grc/gui/VariableEditor.py index c5090ba8990..4cda5b2c6df 100644 --- a/grc/gui/VariableEditor.py +++ b/grc/gui/VariableEditor.py @@ -22,29 +22,35 @@ def __init__(self, var_edit): Gtk.Menu.__init__(self) self.imports = Gtk.MenuItem(label="Add _Import") - self.imports.connect('activate', var_edit.handle_action, var_edit.ADD_IMPORT) + self.imports.connect( + 'activate', var_edit.handle_action, var_edit.ADD_IMPORT) self.add(self.imports) self.variables = Gtk.MenuItem(label="Add _Variable") - self.variables.connect('activate', var_edit.handle_action, var_edit.ADD_VARIABLE) + self.variables.connect( + 'activate', var_edit.handle_action, var_edit.ADD_VARIABLE) self.add(self.variables) self.add(Gtk.SeparatorMenuItem()) self.enable = Gtk.MenuItem(label="_Enable") - self.enable.connect('activate', var_edit.handle_action, var_edit.ENABLE_BLOCK) + self.enable.connect( + 'activate', var_edit.handle_action, var_edit.ENABLE_BLOCK) self.disable = Gtk.MenuItem(label="_Disable") - self.disable.connect('activate', var_edit.handle_action, var_edit.DISABLE_BLOCK) + self.disable.connect( + 'activate', var_edit.handle_action, var_edit.DISABLE_BLOCK) self.add(self.enable) self.add(self.disable) self.add(Gtk.SeparatorMenuItem()) self.delete = Gtk.MenuItem(label="_Delete") - self.delete.connect('activate', var_edit.handle_action, var_edit.DELETE_BLOCK) + self.delete.connect( + 'activate', var_edit.handle_action, var_edit.DELETE_BLOCK) self.add(self.delete) self.add(Gtk.SeparatorMenuItem()) self.properties = Gtk.MenuItem(label="_Properties...") - self.properties.connect('activate', var_edit.handle_action, var_edit.OPEN_PROPERTIES) + self.properties.connect( + 'activate', var_edit.handle_action, var_edit.OPEN_PROPERTIES) self.add(self.properties) self.show_all() @@ -87,13 +93,16 @@ def __init__(self): self.treeview = Gtk.TreeView(model=self.treestore) self.treeview.set_enable_search(False) self.treeview.set_search_column(-1) - #self.treeview.set_enable_search(True) - #self.treeview.set_search_column(ID_INDEX) + # self.treeview.set_enable_search(True) + # self.treeview.set_search_column(ID_INDEX) self.treeview.get_selection().set_mode(Gtk.SelectionMode.SINGLE) self.treeview.set_headers_visible(True) - self.treeview.connect('button-press-event', self._handle_mouse_button_press) - self.treeview.connect('button-release-event', self._handle_mouse_button_release) - self.treeview.connect('motion-notify-event', self._handle_motion_notify) + self.treeview.connect('button-press-event', + self._handle_mouse_button_press) + self.treeview.connect('button-release-event', + self._handle_mouse_button_release) + self.treeview.connect('motion-notify-event', + self._handle_motion_notify) self.treeview.connect('key-press-event', self._handle_key_button_press) # Block Name or Category @@ -133,9 +142,11 @@ def __init__(self): # Make the scrolled window to hold the tree view scrolled_window = Gtk.ScrolledWindow() - scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + scrolled_window.set_policy( + Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) scrolled_window.add(self.treeview) - scrolled_window.set_size_request(Constants.DEFAULT_BLOCKS_WINDOW_WIDTH, -1) + scrolled_window.set_size_request( + Constants.DEFAULT_BLOCKS_WINDOW_WIDTH, -1) self.pack_start(scrolled_window, True, True, 0) # Context menus @@ -215,9 +226,11 @@ def _rebuild(self, *args): imports = self.treestore.append(None, [None, 'Imports']) variables = self.treestore.append(None, [None, 'Variables']) for block in self._imports: - self.treestore.append(imports, [block, block.params['id'].get_value()]) + self.treestore.append( + imports, [block, block.params['id'].get_value()]) for block in sorted(self._variables, key=lambda v: v.name): - self.treestore.append(variables, [block, block.params['id'].get_value()]) + self.treestore.append( + variables, [block, block.params['id'].get_value()]) def _handle_name_edited_cb(self, cell, path, new_text): block = self.treestore[path][BLOCK_INDEX] @@ -243,7 +256,7 @@ def handle_action(self, item, key, event=None): self.emit('create_new_block', 'variable') elif key == self.OPEN_PROPERTIES: # TODO: This probably isn't working because the action doesn't expect a parameter - #Actions.BLOCK_PARAM_MODIFY() + # Actions.BLOCK_PARAM_MODIFY() pass elif key == self.DELETE_BLOCK: self.emit('remove_block', self._block.name) @@ -251,12 +264,15 @@ def handle_action(self, item, key, event=None): if self._confirm_delete: # Create a context menu to confirm the delete operation confirmation_menu = Gtk.Menu() - block_id = self._block.params['id'].get_value().replace("_", "__") + block_id = self._block.params['id'].get_value().replace( + "_", "__") confirm = Gtk.MenuItem(label="Delete {}".format(block_id)) - confirm.connect('activate', self.handle_action, self.DELETE_BLOCK) + confirm.connect('activate', self.handle_action, + self.DELETE_BLOCK) confirmation_menu.add(confirm) confirmation_menu.show_all() - confirmation_menu.popup(None, None, None, None, event.button, event.time) + confirmation_menu.popup( + None, None, None, None, event.button, event.time) else: self.handle_action(None, self.DELETE_BLOCK, None) elif key == self.ENABLE_BLOCK: @@ -287,7 +303,8 @@ def _handle_mouse_button_press(self, widget, event): if self._block and event.type == Gdk.EventType._2BUTTON_PRESS: # Open the advanced dialog if it is a gui variable if self._block.key not in ("variable", "import"): - self.handle_action(None, self.OPEN_PROPERTIES, event=event) + self.handle_action( + None, self.OPEN_PROPERTIES, event=event) return True if event.type == Gdk.EventType.BUTTON_PRESS: # User is adding/removing blocks @@ -295,19 +312,24 @@ def _handle_mouse_button_press(self, widget, event): if path[2] > col.cell_get_position(self.action_cell)[0]: if row[1] == "Imports": # Add a new import block. - self.handle_action(None, self.ADD_IMPORT, event=event) + self.handle_action( + None, self.ADD_IMPORT, event=event) elif row[1] == "Variables": # Add a new variable block - self.handle_action(None, self.ADD_VARIABLE, event=event) + self.handle_action( + None, self.ADD_VARIABLE, event=event) else: - self.handle_action(None, self.DELETE_CONFIRM, event=event) + self.handle_action( + None, self.DELETE_CONFIRM, event=event) return True elif event.button == 3 and event.type == Gdk.EventType.BUTTON_PRESS: if self._block: - self._context_menu.update_sensitive(True, enabled=self._block.enabled) + self._context_menu.update_sensitive( + True, enabled=self._block.enabled) else: self._context_menu.update_sensitive(False) - self._context_menu.popup(None, None, None, None, event.button, event.time) + self._context_menu.popup( + None, None, None, None, event.button, event.time) # Null handler. Stops the treeview from handling double click events. if event.type == Gdk.EventType._2BUTTON_PRESS: diff --git a/grc/gui/__init__.py b/grc/gui/__init__.py index 8b137891791..e69de29bb2d 100644 --- a/grc/gui/__init__.py +++ b/grc/gui/__init__.py @@ -1 +0,0 @@ - diff --git a/grc/gui/canvas/block.py b/grc/gui/canvas/block.py index a2964bd7e74..c80e2b8771c 100644 --- a/grc/gui/canvas/block.py +++ b/grc/gui/canvas/block.py @@ -64,7 +64,8 @@ def coordinate(self, coor): """ coor = Utils.scale(coor, reverse=True) if Actions.TOGGLE_SNAP_TO_GRID.get_active(): - offset_x, offset_y = (0, self.height / 2) if self.is_horizontal() else (self.height / 2, 0) + offset_x, offset_y = ( + 0, self.height / 2) if self.is_horizontal() else (self.height / 2, 0) coor = ( Utils.align_to_grid(coor[0] + offset_x) - offset_x, Utils.align_to_grid(coor[1] + offset_y) - offset_y @@ -137,8 +138,10 @@ def create_shapes(self): for ports, has_busses in zip((self.active_sources, self.active_sinks), bussified): if not ports: continue - port_separation = Constants.PORT_SEPARATION if not has_busses else ports[0].height + Constants.PORT_SPACING - offset = (self.height - (len(ports) - 1) * port_separation - ports[0].height) / 2 + port_separation = Constants.PORT_SEPARATION if not has_busses else ports[ + 0].height + Constants.PORT_SPACING + offset = (self.height - (len(ports) - 1) * + port_separation - ports[0].height) / 2 for port in ports: port.create_shapes() port.coordinate = { @@ -148,7 +151,8 @@ def create_shapes(self): 270: (offset, +self.width), }[port.connector_direction] - offset += Constants.PORT_SEPARATION if not has_busses else port.height + Constants.PORT_SPACING + offset += Constants.PORT_SEPARATION if not has_busses else port.height + \ + Constants.PORT_SPACING def create_labels(self, cr=None): """Create the labels for the signal block.""" @@ -178,7 +182,8 @@ def create_labels(self, cr=None): markups = [param.format_block_surface_markup() for param in self.params.values() if (param.hide not in ('all', 'part') or (param.dtype == 'id' and force_show_id))] else: - markups = ['key: {key}'.format(font=Constants.PARAM_FONT, key=self.key)] + markups = ['key: {key}'.format( + font=Constants.PARAM_FONT, key=self.key)] params_layout.set_spacing(Constants.LABEL_SEPARATION * Pango.SCALE) params_layout.set_markup('\n'.join(markups)) @@ -197,12 +202,13 @@ def create_labels(self, cr=None): self.create_port_labels() def get_min_height_for_ports(ports): - min_height = 2 * Constants.PORT_BORDER_SEPARATION + len(ports) * Constants.PORT_SEPARATION + min_height = 2 * Constants.PORT_BORDER_SEPARATION + \ + len(ports) * Constants.PORT_SEPARATION # If any of the ports are bus ports - make the min height larger if any([p.dtype == 'bus' for p in ports]): min_height = 2 * Constants.PORT_BORDER_SEPARATION + sum( port.height + Constants.PORT_SPACING for port in ports if port.dtype == 'bus' - ) - Constants.PORT_SPACING + ) - Constants.PORT_SPACING else: if ports: @@ -213,11 +219,13 @@ def get_min_height_for_ports(ports): get_min_height_for_ports(self.active_sinks), get_min_height_for_ports(self.active_sources)) - self.width, self.height = width, height = Utils.align_to_grid((width, height)) + self.width, self.height = width, height = Utils.align_to_grid( + (width, height)) self._surface_layouts_offsets = [ (0, (height - label_height) / 2.0), - (0, (height - label_height) / 2.0 + Constants.LABEL_SEPARATION + title_height / Pango.SCALE) + (0, (height - label_height) / 2.0 + + Constants.LABEL_SEPARATION + title_height / Pango.SCALE) ] title_layout.set_width(width * Pango.SCALE) @@ -243,7 +251,8 @@ def create_comment_layout(self): complexity = utils.flow_graph_complexity.calculate(self.parent) markups.append( '' - 'Complexity: {num}bal'.format(num=Utils.num_to_str(complexity), font=Constants.BLOCK_FONT) + 'Complexity: {num}bal'.format( + num=Utils.num_to_str(complexity), font=Constants.BLOCK_FONT) ) comment = self.comment # Returns None if there are no comments if comment: @@ -303,7 +312,8 @@ def what_is_selected(self, coor, coor_m=None): for port in self.active_ports(): port_selected = port.what_is_selected( coor=[a - b for a, b in zip(coor, self.coordinate)], - coor_m=[a - b for a, b in zip(coor, self.coordinate)] if coor_m is not None else None + coor_m=[ + a - b for a, b in zip(coor, self.coordinate)] if coor_m is not None else None ) if port_selected: return port_selected @@ -359,7 +369,8 @@ def type_controller_modify(self, direction): true for change """ type_templates = ' '.join(p.dtype for p in self.params.values()) + ' ' - type_templates += ' '.join(p.get_raw('dtype') for p in (self.sinks + self.sources)) + type_templates += ' '.join(p.get_raw('dtype') + for p in (self.sinks + self.sources)) type_param = None for key, param in self.params.items(): if not param.is_enum(): @@ -396,7 +407,8 @@ def port_controller_modify(self, direction): """ changed = False # Concat the nports string from the private nports settings of all ports - nports_str = ' '.join(str(port.get_raw('multiplicity')) for port in self.ports()) + nports_str = ' '.join(str(port.get_raw('multiplicity')) + for port in self.ports()) # Modify all params whose keys appear in the nports string for key, param in self.params.items(): if param.is_enum() or param.key not in nports_str: diff --git a/grc/gui/canvas/colors.py b/grc/gui/canvas/colors.py index 2ab49337619..89f5025d0e2 100644 --- a/grc/gui/canvas/colors.py +++ b/grc/gui/canvas/colors.py @@ -25,6 +25,7 @@ def get_color(color_code): # fg colors ################################################################################# + HIGHLIGHT_COLOR = get_color('#00FFFF') BORDER_COLOR = get_color('#616161') BORDER_COLOR_DISABLED = get_color('#888888') @@ -62,8 +63,10 @@ def get_color(color_code): # port colors ################################################################################# -PORT_TYPE_TO_COLOR = {key: get_color(color) for name, key, sizeof, color in Constants.CORE_TYPES} -PORT_TYPE_TO_COLOR.update((key, get_color(color)) for key, (_, color) in Constants.ALIAS_TYPES.items()) +PORT_TYPE_TO_COLOR = {key: get_color( + color) for name, key, sizeof, color in Constants.CORE_TYPES} +PORT_TYPE_TO_COLOR.update((key, get_color(color)) + for key, (_, color) in Constants.ALIAS_TYPES.items()) ################################################################################# @@ -109,4 +112,3 @@ def get_color(color_code): #enum_custom { background-color: #EEEEEE; } """ - diff --git a/grc/gui/canvas/connection.py b/grc/gui/canvas/connection.py index 316ecbdd097..be5db73b659 100644 --- a/grc/gui/canvas/connection.py +++ b/grc/gui/canvas/connection.py @@ -73,11 +73,13 @@ def create_shapes(self): # first two components relative to source connector, rest relative to sink connector self._rel_points = [ - rotate((15, 0), source.rotation), # line from 0,0 to here, bezier curve start + # line from 0,0 to here, bezier curve start + rotate((15, 0), source.rotation), rotate((50, 0), source.rotation), # bezier curve control point 1 rotate((-50, 0), sink.rotation), # bezier curve control point 2 rotate((-15, 0), sink.rotation), # bezier curve end - rotate((-CONNECTOR_ARROW_HEIGHT, 0), sink.rotation), # line to arrow head + rotate((-CONNECTOR_ARROW_HEIGHT, 0), + sink.rotation), # line to arrow head ] self._current_coordinates = None # triggers _make_path() @@ -110,7 +112,8 @@ def _make_path(self, cr=None): # make rel_point all relative to source connector p0 = 0, 0 # x_start - x_pos, y_start - y_pos - p1, p2, (dx_e1, dy_e1), (dx_e2, dy_e2), (dx_e3, dy_e3) = self._rel_points + p1, p2, (dx_e1, dy_e1), (dx_e2, dy_e2), (dx_e3, + dy_e3) = self._rel_points p3 = x_e + dx_e1, y_e + dy_e1 p4 = x_e + dx_e2, y_e + dy_e2 p5 = x_e + dx_e3, y_e + dy_e3 @@ -137,7 +140,8 @@ def draw(self, cr): self.create_shapes() # triggers _make_path() call below self._current_port_rotations = port_rotations - new_coordinates = (source.parent_block.coordinate, sink.parent_block.coordinate) + new_coordinates = (source.parent_block.coordinate, + sink.parent_block.coordinate) if self._current_coordinates != new_coordinates: self._make_path(cr) self._current_coordinates = new_coordinates @@ -175,7 +179,7 @@ def draw(self, cr): cr.set_source_rgba(*color2) cr.rotate(self._arrow_rotation) cr.rel_move_to(CONNECTOR_ARROW_HEIGHT, 0) - cr.rel_line_to(-CONNECTOR_ARROW_HEIGHT, -CONNECTOR_ARROW_BASE/2) + cr.rel_line_to(-CONNECTOR_ARROW_HEIGHT, -CONNECTOR_ARROW_BASE / 2) cr.rel_line_to(0, CONNECTOR_ARROW_BASE) cr.close_path() cr.fill() @@ -238,4 +242,5 @@ def update(self, coordinate=None, rotation=None, sink_port=None): def has_real_sink(self): return self.sink_port is not self._dummy_port + DummyConnection = Connection.make_cls_with_base(DummyCoreConnection) diff --git a/grc/gui/canvas/flowgraph.py b/grc/gui/canvas/flowgraph.py index cb63f578acd..7c086f36411 100644 --- a/grc/gui/canvas/flowgraph.py +++ b/grc/gui/canvas/flowgraph.py @@ -125,7 +125,8 @@ def install_external_editor(self, param, parent=None): editor.open_editor() except Exception as e: # Problem launching the editor. Need to select a new editor. - Messages.send('>>> Error opening an external editor. Please select a different editor.\n') + Messages.send( + '>>> Error opening an external editor. Please select a different editor.\n') # Reset the editor to force the user to select a new one. self.parent_platform.config.editor = '' @@ -153,10 +154,13 @@ def add_new_block(self, key, coor=None): # calculate the position coordinate h_adj = scroll_pane.get_hadjustment() v_adj = scroll_pane.get_vadjustment() - if coor is None: coor = ( - int(random.uniform(.25, .75)*h_adj.get_page_size() + h_adj.get_value()), - int(random.uniform(.25, .75)*v_adj.get_page_size() + v_adj.get_value()), - ) + if coor is None: + coor = ( + int(random.uniform(.25, .75) * + h_adj.get_page_size() + h_adj.get_value()), + int(random.uniform(.25, .75) * + v_adj.get_page_size() + v_adj.get_value()), + ) # get the new block block = self.new_block(key) block.coordinate = coor @@ -218,17 +222,17 @@ def copy_to_clipboard(self): Returns: the clipboard """ - #get selected blocks + # get selected blocks blocks = list(self.selected_blocks()) if not blocks: return None - #calc x and y min + # calc x and y min x_min, y_min = blocks[0].coordinate for block in blocks: x, y = block.coordinate x_min = min(x, x_min) y_min = min(y, y_min) - #get connections between selected blocks + # get connections between selected blocks connections = list(filter( lambda c: c.source_block in blocks and c.sink_block in blocks, self.connections, @@ -281,7 +285,8 @@ def paste_from_clipboard(self, clipboard): block.move((x_off, y_off)) while any(Utils.align_to_grid(block.coordinate) == Utils.align_to_grid(other.coordinate) for other in self.blocks if other is not block): - block.move((Constants.CANVAS_GRID_SIZE, Constants.CANVAS_GRID_SIZE)) + block.move((Constants.CANVAS_GRID_SIZE, + Constants.CANVAS_GRID_SIZE)) # shift all following blocks x_off += Constants.CANVAS_GRID_SIZE y_off += Constants.CANVAS_GRID_SIZE @@ -353,15 +358,16 @@ def move_selected(self, delta_coordinate): if not blocks: return - min_x, min_y = self.selected_block.coordinate + min_x, min_y = self.selected_block.coordinate for selected_block in blocks: x, y = selected_block.coordinate min_x, min_y = min(min_x, x), min(min_y, y) # Sanitize delta_coordinate so that blocks don't move to negative coordinate - delta_coordinate = max(delta_coordinate[0],-min_x), max(delta_coordinate[1], -min_y) + delta_coordinate = max( + delta_coordinate[0], -min_x), max(delta_coordinate[1], -min_y) - # Move selected blocks + # Move selected blocks for selected_block in blocks: selected_block.move(delta_coordinate) self.element_moved = True @@ -388,15 +394,15 @@ def align_selected(self, calling_action=None): x += selected_block.width y += selected_block.height max_x, max_y = max(max_x, x), max(max_y, y) - ctr_x, ctr_y = (max_x + min_x)/2, (max_y + min_y)/2 + ctr_x, ctr_y = (max_x + min_x) / 2, (max_y + min_y) / 2 # align the blocks as requested transform = { Actions.BLOCK_VALIGN_TOP: lambda x, y, w, h: (x, min_y), - Actions.BLOCK_VALIGN_MIDDLE: lambda x, y, w, h: (x, ctr_y - h/2), + Actions.BLOCK_VALIGN_MIDDLE: lambda x, y, w, h: (x, ctr_y - h / 2), Actions.BLOCK_VALIGN_BOTTOM: lambda x, y, w, h: (x, max_y - h), Actions.BLOCK_HALIGN_LEFT: lambda x, y, w, h: (min_x, y), - Actions.BLOCK_HALIGN_CENTER: lambda x, y, w, h: (ctr_x-w/2, y), + Actions.BLOCK_HALIGN_CENTER: lambda x, y, w, h: (ctr_x - w / 2, y), Actions.BLOCK_HALIGN_RIGHT: lambda x, y, w, h: (max_x - w, y), }.get(calling_action, lambda *args: args) @@ -419,21 +425,22 @@ def rotate_selected(self, rotation): """ if not any(self.selected_blocks()): return False - #initialize min and max coordinates + # initialize min and max coordinates min_x, min_y = max_x, max_y = self.selected_block.coordinate # rotate each selected block, and find min/max coordinate for selected_block in self.selected_blocks(): selected_block.rotate(rotation) - #update the min/max coordinate + # update the min/max coordinate x, y = selected_block.coordinate min_x, min_y = min(min_x, x), min(min_y, y) max_x, max_y = max(max_x, x), max(max_y, y) - #calculate center point of selected blocks - ctr_x, ctr_y = (max_x + min_x)/2, (max_y + min_y)/2 - #rotate the blocks around the center point + # calculate center point of selected blocks + ctr_x, ctr_y = (max_x + min_x) / 2, (max_y + min_y) / 2 + # rotate the blocks around the center point for selected_block in self.selected_blocks(): x, y = selected_block.coordinate - x, y = Utils.get_rotated_coordinate((x - ctr_x, y - ctr_y), rotation) + x, y = Utils.get_rotated_coordinate( + (x - ctr_x, y - ctr_y), rotation) selected_block.coordinate = (x + ctr_x, y + ctr_y) return True @@ -496,7 +503,7 @@ def create_labels(self, cr=None): element.create_labels(cr) def create_shapes(self): - #TODO - this is a workaround for bus ports not having a proper coordinate + # TODO - this is a workaround for bus ports not having a proper coordinate # until the shape is drawn. The workaround is to draw blocks before connections for element in filter(lambda x: x.is_block, self._elements_to_draw): @@ -582,7 +589,8 @@ def update_selected_elements(self): else: # called from a mouse release if not self.element_moved and (not self.selected_elements or self.drawing_area.ctrl_mask) and not self._new_connection: - selected_elements = self.what_is_selected(self.coordinate, self.press_coor) + selected_elements = self.what_is_selected( + self.coordinate, self.press_coor) # this selection and the last were ports, try to connect them if self.make_connection(): @@ -635,7 +643,8 @@ def what_is_selected(self, coor, coor_m=None): if selected_port and selected_port.is_source: selected.remove(selected_port.parent_block) - self._new_connection = DummyConnection(selected_port, coordinate=coor) + self._new_connection = DummyConnection( + selected_port, coordinate=coor) self.drawing_area.queue_draw() # update selected ports if selected_port is not self._new_selected_port: @@ -806,19 +815,21 @@ def _handle_mouse_motion_drag(self, coordinate): dX, dY = x - X, y - Y if Actions.TOGGLE_SNAP_TO_GRID.get_active() or self.drawing_area.mod1_mask: - dX, dY = int(round(dX / Constants.CANVAS_GRID_SIZE)), int(round(dY / Constants.CANVAS_GRID_SIZE)) + dX, dY = int(round(dX / Constants.CANVAS_GRID_SIZE) + ), int(round(dY / Constants.CANVAS_GRID_SIZE)) dX, dY = dX * Constants.CANVAS_GRID_SIZE, dY * Constants.CANVAS_GRID_SIZE else: dX, dY = int(round(dX)), int(round(dY)) if dX != 0 or dY != 0: self.move_selected((dX, dY)) - self.coordinate = (X+dX, Y+dY) + self.coordinate = (X + dX, Y + dY) redraw = True return redraw def get_extents(self): show_comments = Actions.TOGGLE_SHOW_BLOCK_COMMENTS.get_active() + def sub_extents(): for element in self._elements_to_draw: yield element.get_extents() @@ -828,5 +839,6 @@ def sub_extents(): extent = 10000000, 10000000, 0, 0 cmps = (min, min, max, max) for sub_extent in sub_extents(): - extent = [cmp(xy, e_xy) for cmp, xy, e_xy in zip(cmps, extent, sub_extent)] + extent = [cmp(xy, e_xy) + for cmp, xy, e_xy in zip(cmps, extent, sub_extent)] return tuple(extent) diff --git a/grc/gui/canvas/param.py b/grc/gui/canvas/param.py index 6b33ef223ca..488ca7a5c3c 100644 --- a/grc/gui/canvas/param.py +++ b/grc/gui/canvas/param.py @@ -86,20 +86,20 @@ def format_tooltip_text(self): tooltip_lines.extend(' * ' + msg for msg in errors) return '\n'.join(tooltip_lines) - - ################################################## # Truncate helper method ################################################## + def truncate(self, string, style=0): max_len = max(27 - len(self.name), 3) if len(string) > max_len: if style < 0: # Front truncate - string = '...' + string[3-max_len:] + string = '...' + string[3 - max_len:] elif style == 0: # Center truncate - string = string[:max_len//2 - 3] + '...' + string[-max_len//2:] + string = string[:max_len // 2 - 3] + \ + '...' + string[-max_len // 2:] elif style > 0: # Rear truncate - string = string[:max_len-3] + '...' + string = string[:max_len - 3] + '...' return string def pretty_print(self): @@ -183,5 +183,5 @@ def format_block_surface_markup(self): display_value = expr_string return '{label}: {value}'.format( - foreground='foreground="red"' if not self.is_valid() else '', font=Constants.PARAM_FONT, + foreground='foreground="red"' if not self.is_valid() else '', font=Constants.PARAM_FONT, label=Utils.encode(self.name), value=display_value) diff --git a/grc/gui/canvas/port.py b/grc/gui/canvas/port.py index d963964cdcb..f78fd621793 100644 --- a/grc/gui/canvas/port.py +++ b/grc/gui/canvas/port.py @@ -68,9 +68,11 @@ def _update_colors(self): color = colors.PORT_TYPE_TO_COLOR.get('message') else: self._font_color[-1] = 1.0 - color = colors.PORT_TYPE_TO_COLOR.get(self.dtype) or colors.PORT_TYPE_TO_COLOR.get('') + color = colors.PORT_TYPE_TO_COLOR.get( + self.dtype) or colors.PORT_TYPE_TO_COLOR.get('') if self.vlen > 1: - dark = (0, 0, 30 / 255.0, 50 / 255.0, 70 / 255.0)[min(4, self.vlen)] + dark = (0, 0, 30 / 255.0, 50 / 255.0, + 70 / 255.0)[min(4, self.vlen)] color = tuple(max(c - dark, 0) for c in color) self._bg_color = color self._border_color = tuple(max(c - 0.3, 0) for c in color) @@ -84,8 +86,8 @@ def create_shapes(self): self.bounds_from_area(self._area) self._connector_coordinate = { - 0: (self.width, self.height / 2), - 90: (self.height / 2, 0), + 0: (self.width, self.height / 2), + 90: (self.height / 2, 0), 180: (0, self.height / 2), 270: (self.height / 2, self.width) }[self.connector_direction] @@ -112,7 +114,8 @@ def create_labels(self, cr=None): label_width, label_height = self.label_layout.get_size() self.width = 2 * Constants.PORT_LABEL_PADDING + label_width / Pango.SCALE - self.height = (2 * Constants.PORT_LABEL_PADDING + label_height*(3 if self.dtype == 'bus' else 1)) / Pango.SCALE + self.height = (2 * Constants.PORT_LABEL_PADDING + label_height * + (3 if self.dtype == 'bus' else 1)) / Pango.SCALE self._label_layout_offsets = [0, Constants.PORT_LABEL_PADDING] self.height += self.height % 2 # uneven height diff --git a/grc/main.py b/grc/main.py index 06097ed58de..5362618840f 100755 --- a/grc/main.py +++ b/grc/main.py @@ -4,12 +4,14 @@ # SPDX-License-Identifier: GPL-2.0-or-later # -import argparse, logging, sys +from gi.repository import Gtk +import argparse +import logging +import sys import gi gi.require_version('Gtk', '3.0') gi.require_version('PangoCairo', '1.0') -from gi.repository import Gtk VERSION_AND_DISCLAIMER_TEMPLATE = """\ @@ -34,7 +36,8 @@ def main(): parser = argparse.ArgumentParser( description=VERSION_AND_DISCLAIMER_TEMPLATE % gr.version()) parser.add_argument('flow_graphs', nargs='*') - parser.add_argument('--log', choices=['debug', 'info', 'warning', 'error', 'critical'], default='warning') + parser.add_argument( + '--log', choices=['debug', 'info', 'warning', 'error', 'critical'], default='warning') args = parser.parse_args() # Enable logging @@ -73,7 +76,8 @@ def main(): log.debug("Loading platform") platform = Platform( version=gr.version(), - version_parts=(gr.major_version(), gr.api_version(), gr.minor_version()), + version_parts=(gr.major_version(), gr.api_version(), + gr.minor_version()), prefs=gr.prefs(), install_prefix=gr.prefix() ) diff --git a/grc/scripts/gnuradio-companion b/grc/scripts/gnuradio-companion index 2f299744717..38a421f5156 100755 --- a/grc/scripts/gnuradio-companion +++ b/grc/scripts/gnuradio-companion @@ -47,6 +47,7 @@ def die(error, message): print("The original error message follows.", file=sys.stderr) sys.exit(type(error).__name__ + '\n\n' + msg) + def check_gtk(): try: import gi diff --git a/grc/tests/test_block_templates.py b/grc/tests/test_block_templates.py index df9ab37550c..bd3dd492eba 100644 --- a/grc/tests/test_block_templates.py +++ b/grc/tests/test_block_templates.py @@ -37,9 +37,11 @@ def test_list(): def test_parse_error(): with pytest.raises(TemplateError): - MakoTemplates(_bind_to=Block(num='123'), test='abc${num NOT CLOSING').render('test') + MakoTemplates(_bind_to=Block(num='123'), + test='abc${num NOT CLOSING').render('test') def test_parse_error2(): with pytest.raises(TemplateError): - MakoTemplates(_bind_to=Block(num='123'), test='abc${ WRONG_VAR }').render('test') + MakoTemplates(_bind_to=Block(num='123'), + test='abc${ WRONG_VAR }').render('test') diff --git a/grc/tests/test_cheetah_converter.py b/grc/tests/test_cheetah_converter.py index acb0ac402c9..02944a31eea 100644 --- a/grc/tests/test_cheetah_converter.py +++ b/grc/tests/test_cheetah_converter.py @@ -39,7 +39,8 @@ def test_conditional(): def test_simple_format_string(): - convert = functools.partial(parser.Converter(names={'abc'}).convert_simple, spec=parser.FormatString) + convert = functools.partial(parser.Converter( + names={'abc'}).convert_simple, spec=parser.FormatString) assert '{abc}' == convert('$abc') assert '{abc:eval}' == convert('$abc()') assert '{abc}' == convert('$(abc)') @@ -50,7 +51,8 @@ def test_simple_format_string(): def test_hard_format_string(): names = {'abc': {'ff'}, 'param1': {}, 'param2': {}} - convert = functools.partial(parser.Converter(names).convert_hard, spec=parser.FormatString) + convert = functools.partial(parser.Converter( + names).convert_hard, spec=parser.FormatString) assert 'make_a_cool_block_{abc.ff}({param1}, {param2})' == \ convert('make_a_cool_block_${abc.ff}($param1, $param2)') @@ -66,7 +68,8 @@ def test_opts(): def test_nested(): - assert 'abc(abc) abc + abc abc[abc]' == c2p('$abc($abc) $(abc + $abc) ${abc[$abc]}') + assert 'abc(abc) abc + abc abc[abc]' == c2p( + '$abc($abc) $(abc + $abc) ${abc[$abc]}') assert '(abc_abc_)' == c2p('(abc_$(abc)_)') diff --git a/grc/tests/test_compiler.py b/grc/tests/test_compiler.py index fbdffd3e0f8..4e0e2628093 100644 --- a/grc/tests/test_compiler.py +++ b/grc/tests/test_compiler.py @@ -13,11 +13,13 @@ from grc.compiler import main + def test_compiler(capsys): args = Namespace( output=tempfile.gettempdir(), user_lib_dir=False, - grc_files=[path.join(path.dirname(__file__), 'resources', 'test_compiler.grc')], + grc_files=[path.join(path.dirname(__file__), + 'resources', 'test_compiler.grc')], run=True ) diff --git a/grc/tests/test_cpp.py b/grc/tests/test_cpp.py index 52d977a31a9..6f585a575ff 100644 --- a/grc/tests/test_cpp.py +++ b/grc/tests/test_cpp.py @@ -13,11 +13,13 @@ from grc.compiler import main + def test_cpp(capsys): args = Namespace( output=tempfile.gettempdir(), user_lib_dir=False, - grc_files=[path.join(path.dirname(__file__), 'resources', 'test_cpp.grc')], + grc_files=[path.join(path.dirname(__file__), + 'resources', 'test_cpp.grc')], run=True ) diff --git a/grc/tests/test_examples.py b/grc/tests/test_examples.py index 2b590a4a943..ecc37f0c988 100644 --- a/grc/tests/test_examples.py +++ b/grc/tests/test_examples.py @@ -14,12 +14,14 @@ # Gather blocks BLOCK_PATHS = [] ROOT = path.join(path.dirname(__file__), '../..') -BLOCK_PATHS = [path.join(path.dirname(__file__), '../../grc/blocks'), '../../build/gr-uhd/grc'] +BLOCK_PATHS = [path.join(path.dirname( + __file__), '../../grc/blocks'), '../../build/gr-uhd/grc'] for file_dir in os.scandir(ROOT): # If it is a module if path.isdir(file_dir) and file_dir.name.startswith("gr-"): BLOCK_PATHS.append(path.join(file_dir, "grc")) + def gather_examples(): global ROOT example_paths = [] @@ -39,11 +41,13 @@ def gather_examples(): continue return example_paths + def print_proper(element): if element.is_block: return element.name return f"{element.parent.name} - {element}" + @pytest.mark.examples @pytest.mark.parametrize("example", gather_examples()) def test_all_examples(example): @@ -62,7 +66,9 @@ def test_all_examples(example): flow_graph.rewrite() flow_graph.validate() - assert flow_graph.is_valid(), (example.name, [f"{print_proper(elem)}: {msg}" for elem, msg in flow_graph.iter_error_messages()]) + assert flow_graph.is_valid(), (example.name, [ + f"{print_proper(elem)}: {msg}" for elem, msg in flow_graph.iter_error_messages()]) - generator = platform.Generator(flow_graph, path.join(path.dirname(__file__), 'resources/tests')) + generator = platform.Generator(flow_graph, path.join( + path.dirname(__file__), 'resources/tests')) generator.write() diff --git a/grc/tests/test_generator.py b/grc/tests/test_generator.py index c6ae5b1109a..931d3e9af31 100644 --- a/grc/tests/test_generator.py +++ b/grc/tests/test_generator.py @@ -15,7 +15,8 @@ def test_generator(): # c&p form compiler code. - grc_file = path.join(path.dirname(__file__), 'resources', 'test_compiler.grc') + grc_file = path.join(path.dirname(__file__), + 'resources', 'test_compiler.grc') out_dir = tempfile.gettempdir() block_paths = [ path.join(path.dirname(__file__), '../../grc/blocks'), @@ -35,5 +36,6 @@ def test_generator(): assert flow_graph.is_valid() - generator = platform.Generator(flow_graph, path.join(path.dirname(__file__), 'resources')) + generator = platform.Generator( + flow_graph, path.join(path.dirname(__file__), 'resources')) generator.write() diff --git a/grc/tests/test_xml_parser.py b/grc/tests/test_xml_parser.py index 0fd5a94b3de..28ec770cf6f 100644 --- a/grc/tests/test_xml_parser.py +++ b/grc/tests/test_xml_parser.py @@ -11,7 +11,8 @@ def test_flow_graph_converter(): - filename = path.join(path.dirname(__file__), 'resources', 'test_compiler.grc') + filename = path.join(path.dirname(__file__), + 'resources', 'test_compiler.grc') data = flow_graph.from_xml(filename) @@ -19,7 +20,8 @@ def test_flow_graph_converter(): def test_flow_graph_converter_with_fp(): - filename = path.join(path.dirname(__file__), 'resources', 'test_compiler.grc') + filename = path.join(path.dirname(__file__), + 'resources', 'test_compiler.grc') with open(filename, 'rb') as fp: data = flow_graph.from_xml(fp) diff --git a/grc/tests/test_yaml_checker.py b/grc/tests/test_yaml_checker.py index 0b658a10871..87f8e5ffe78 100644 --- a/grc/tests/test_yaml_checker.py +++ b/grc/tests/test_yaml_checker.py @@ -58,7 +58,8 @@ def test_min(): def test_extra_keys(): checker = Validator(BLOCK_SCHEME) assert checker.run({'id': 'test', 'abcdefg': 'nonsense', 'file_format': 1}) - assert checker.messages == [('block', 'warn', "Ignoring extra key 'abcdefg'")] + assert checker.messages == [ + ('block', 'warn', "Ignoring extra key 'abcdefg'")] def test_checker(): diff --git a/tools/autoformat_python.sh b/tools/autoformat_python.sh new file mode 100644 index 00000000000..385f16567c4 --- /dev/null +++ b/tools/autoformat_python.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +############################################################################# +# Perform python formatting on the GNU Radio source tree +# Requires: +# - autopep8 +# - pycodestyle +# +# Usage: +# sh autoformat_python.sh /path/to/module/ +# Example +# sh check_pep8.sh ./gr-digital +# sh check_pep8.sh . # to check the entire source tree +# +# WARNING: +# autopep8 can be a bit aggressive - it particularly messes with __init__.py +# files because of some of the import ordering +############################################################################# + +if [ $# -lt 1 ]; then + echo The number of arguments provided is incorrect. Please provide the path \ + to the module to be formatted. + exit 1 +fi + +echo "WARNING: this script calls autopep8 which can cause issues in __init__py especially" + +TARGET=$1 + +autopep8 -r -i ./$TARGET --select E101,E11,E121,E122,E123,E124,E125,E126,E127,\ +E128,E129,E131,E133,E20,E211,E22,E224,E225,E226,E227,E228,E231,E241,E242,E251,\ +E252,E26,E265,E266,E27,E301,E302,E303,E304,E305,E306,E401,E402,E501,E502,E701,\ +E70,E711,E712,E713,E714,E721,E722,E731,W291,W292,W293,W391,W503,W601,W602,W603,\ +W604,W690 + +find ./$TARGET -iname *.py | xargs pycodestyle --max-line-length=120 --ignore \ +E265,E266,E402,E501,E704,E712,E713,E714,E711,E722,E741,W504,W605 \ No newline at end of file diff --git a/tools/check_pep8.sh b/tools/check_pep8.sh new file mode 100644 index 00000000000..8515f345917 --- /dev/null +++ b/tools/check_pep8.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +############################################################################# +# Check python formatting on the GNU Radio source tree +# Requires: +# - pycodestyle +# +# Usage: +# sh autoformat_python.sh /path/to/module/ +# Example +# sh check_pep8.sh ./gr-digital +# sh check_pep8.sh . # to check the entire source tree +############################################################################# + +if [ $# -lt 1 ]; then + echo The number of arguments provided is incorrect. Please provide the path \ + to the module to be formatted. + exit 1 +fi + +TARGET=$1 + +find ./$TARGET -iname *.py | xargs pycodestyle --max-line-length=120 --ignore \ +E265,E266,E402,E501,E704,E712,E713,E714,E711,E722,E741,W504,W605 \ No newline at end of file diff --git a/tools/clang_format.py b/tools/clang_format.py index adf3fe45867..4653aa231a4 100755 --- a/tools/clang_format.py +++ b/tools/clang_format.py @@ -126,8 +126,8 @@ def __init__(self, path): if self.path is None or not os.path.isfile( self.path) or not self._validate_version(): print( - "ERROR:clang-format not found in $PATH, please install clang-format " - + CLANG_FORMAT_VERSION) + "ERROR:clang-format not found in $PATH, please install clang-format " + + CLANG_FORMAT_VERSION) raise NameError("No suitable clang-format found") self.print_lock = threading.Lock() @@ -140,8 +140,8 @@ def _validate_version(self): return True print( - "WARNING: clang-format found in path, but incorrect version found at " - + self.path + " with version: " + cf_version) + "WARNING: clang-format found in path, but incorrect version found at " + + self.path + " with version: " + cf_version) return False @@ -636,9 +636,9 @@ def _reformat_branch(clang_format, commit_prior_to_reformat, if not repo.is_ancestor(commit_prior_to_reformat, commit_after_reformat): raise ValueError(( - "Commit Prior to Reformat '%s' is not a valid ancestor of Commit After" - + " Reformat '%s' in this repo") % (commit_prior_to_reformat, - commit_after_reformat)) + "Commit Prior to Reformat '%s' is not a valid ancestor of Commit After" + + " Reformat '%s' in this repo") % (commit_prior_to_reformat, + commit_after_reformat)) # Validate the user is on a local branch that has the right merge base if repo.is_detached(): @@ -791,7 +791,8 @@ def parse_args(): "--clang-format", default="clang-format", help="clang-format binary") - subparsers = parser.add_subparsers(help="clang-format action", dest="action") + subparsers = parser.add_subparsers( + help="clang-format action", dest="action") subparsers.required = True lint_parser = subparsers.add_parser( "lint", help="Lint-only (no modifications)") diff --git a/tools/template_convert.py b/tools/template_convert.py index 439d76e922c..8f99f1a83de 100755 --- a/tools/template_convert.py +++ b/tools/template_convert.py @@ -12,7 +12,8 @@ r"(?P\w+)\s+(?P\w+_XX?X?)(_impl)?\s+(?P[\w\s]+)" + r"\)$") cpp_keywords = ["abs", "add", "and", "max", "min" "not" "xor"] -types = {"s": "std::int16_t", "i": "std::int32_t", "b": "std::uint8_t", "c": "gr_complex", "f": "float"} +types = {"s": "std::int16_t", "i": "std::int32_t", + "b": "std::uint8_t", "c": "gr_complex", "f": "float"} def get_real_name(block_definition):