Example #1
0
def audiolazy_namer(name):
    """
  Process a name to get Sphinx reStructuredText internal references like
  ``:obj:`name <audiolazy.lazy_something.name>``` for a given name string,
  specific for AudioLazy.

  """
    sp_name = name.split(".")
    try:

        # Find the audiolazy module name
        data = getattr(audiolazy, sp_name[0])
        if isinstance(data, audiolazy.StrategyDict):
            module_name = data.default.__module__
        else:
            module_name = data.__module__
            if not module_name.startswith("audiolazy"):  # Decorated math, cmath, ...
                del module_name
                for mname in audiolazy.__modules__:
                    if sp_name[0] in getattr(audiolazy, mname).__all__:
                        module_name = "audiolazy." + mname
                        break

        # Now gets the referenced item
        location = ".".join([module_name] + sp_name)
        for sub_name in sp_name[1:]:
            data = getattr(data, sub_name)

        # Finds the role to be used for referencing
        type_dict = OrderedDict(
            [
                (audiolazy.StrategyDict, "obj"),
                (Exception, "exc"),
                (types.MethodType, "meth"),
                (types.FunctionType, "func"),
                (types.ModuleType, "mod"),
                (property, "attr"),
                (type, "class"),
            ]
        )
        role = [v for k, v in iteritems(type_dict) if isinstance(data, k)][0]

    # Not found
    except AttributeError:
        return ":obj:`{0}`".format(name)

    # Found!
    else:
        return ":{0}:`{1} <{2}>`".format(role, name, location)
Example #2
0
def audiolazy_namer(name):
  """
  Process a name to get Sphinx reStructuredText internal references like
  ``:obj:`name <audiolazy.lazy_something.name>``` for a given name string,
  specific for AudioLazy.

  """
  sp_name = name.split(".")
  try:

    # Find the audiolazy module name
    data = getattr(audiolazy, sp_name[0])
    if isinstance(data, audiolazy.StrategyDict):
      module_name = data.default.__module__
    else:
      module_name = data.__module__
      if not module_name.startswith("audiolazy"): # Decorated math, cmath, ...
        del module_name
        for mname in audiolazy.__modules__:
          if sp_name[0] in getattr(audiolazy, mname).__all__:
            module_name = "audiolazy." + mname
            break

    # Now gets the referenced item
    location = ".".join([module_name] + sp_name)
    for sub_name in sp_name[1:]:
      data = getattr(data, sub_name)

    # Finds the role to be used for referencing
    type_dict = OrderedDict([
      (audiolazy.StrategyDict, "obj"),
      (Exception, "exc"),
      (types.MethodType, "meth"),
      (types.FunctionType, "func"),
      (types.ModuleType, "mod"),
      (property, "attr"),
      (type, "class"),
    ])
    role = [v for k, v in iteritems(type_dict) if isinstance(data, k)][0]

  # Not found
  except AttributeError:
    return ":obj:`{0}`".format(name)

  # Found!
  else:
    return ":{0}:`{1} <{2}>`".format(role, name, location)
Example #3
0
def pre_processor(app, what, name, obj, options, lines,
                  namer=lambda name: ":obj:`{0}`".format(name)):
  """
  Callback preprocessor function for docstrings.
  Converts data from Spyder pattern to Sphinx, using a ``namer`` function
  that defaults to ``lambda name: ":obj:`{0}`".format(name)`` (specific for
  ``.. seealso::``).

  """
  # Duplication removal
  if what == "module": # For some reason, summary appears twice
    idxs = [idx for idx, el in enumerate(lines) if el.startswith("Summary")]
    if len(idxs) >= 2:
      del lines[idxs.pop():] # Remove the last summary
    if len(idxs) >= 1:
      lines.insert(idxs[-1] + 1, "")
      if obj is audiolazy.lazy_math:
        lines.insert(idxs[-1] + 1, ".. tabularcolumns:: cl")
      else:
        lines.insert(idxs[-1] + 1, ".. tabularcolumns:: CJ")
      lines.insert(idxs[-1] + 1, "")

  # Real docstring format pre-processing
  result = []
  for name, blk in iteritems(splitter(lines)):
    nlower =  name.lower()

    if nlower == "parameters":
      starters = audiolazy.Stream(idx for idx, el in enumerate(blk)
                                      if len(el) > 0
                                      and not el.startswith(" ")
                                 ).append([len(blk)])
      for idx1, idx2 in starters.blocks(size=2, hop=1):
        param_data = " ".join(b.strip() for b in blk[idx1:idx2])
        param, expl = param_data.split(":", 1)
        if "," in param:
          param = param.strip()
          if not param[0] in ("(", "[", "<", "{"):
            param = "[{0}]".format(param)
        while "," in param:
          fparam, param = param.split(",", 1)
          result.append(":param {0}: {1}".format(fparam.strip(), "\.\.\."))
        result.append(":param {0}: {1}".format(param.strip(), expl.strip()))

    elif nlower == "returns":
      result.append(":returns: " + " ".join(blk))

    elif nlower in ("note", "warning", "hint"):
      result.append(".. {0}::".format(nlower))
      result.extend("  " + el for el in blk)

    elif nlower == "examples":
      result.append("**Examples**:")
      result.extend("  " + el for el in blk)

    elif nlower == "see also":
      result.append(".. seealso::")
      for el in blk:
        if el.endswith(":"):
          result.append("") # Skip a line
           # Sphinx may need help here to find some object locations
          refs = [namer(f.strip()) for f in el[:-1].split(",")]
          result.append("  " + ", ".join(refs))
        else:
          result.append("  " + el)

    else: # Unkown block name, perhaps the starting one (empty)
      result.extend(blk)

    # Skip a line after each block
    result.append("")

  # Replace lines with the processed data while keeping the actual lines id
  del lines[:]
  lines.extend(result)
Example #4
0
)]


# Texinfo output configuration
texinfo_documents = [(
  master_doc,
  project, # Target
  title,
  author,
  project, # Dir menu entry
  description, # From README.rst
  "Miscellanous", # Category
)]


# Epub output configuration
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright


#
# Item in sys.modules for StrategyDict instances (needed for automodule)
#
for name, sdict in iteritems(audiolazy.__dict__):
  if isinstance(sdict, audiolazy.StrategyDict):
    fname = ".".join([sdict.default.__module__, name])
    sdict.__all__ = tuple(x[0] for x in sdict.keys())
    sys.modules[fname] = sdict
Example #5
0
def save_to_rst(prefix, data):
    """
  Saves a RST file with the given prefix into the script file location.

  """
    with open(find_full_name(prefix), "w") as rst_file:
        rst_file.write(full_gpl_for_rst)
        rst_file.write(data)


#
# First chapter! Splits README.rst data into the gen_blocks iterable
#
readme_data = splitter(readme_file_contents)
rfc_copyright = readme_data.popitem()[1]  # Last block is a small license msg
gen_blocks = iteritems(readme_data)

# Process GPL license comment at the beginning to put it in all RST files
gpl_to_add = "  File auto-generated by the rst_creator.py script."
full_gpl_for_rst = next(gen_blocks)[1]  # It's before the first readable block
full_gpl_for_rst = "\n".join(full_gpl_for_rst[:-1] + [gpl_to_add] +
                             full_gpl_for_rst[-1:] + ["\n\n"])
gpl_for_rst = "\n  ".join(
    full_gpl_for_rst.strip().strip(".").splitlines()[:-2])

# Process the first readable block (project name and small description)
rfc_name, rfc_description = next(gen_blocks)  # Second block
rfc_name = " ".join([rfc_name, "|version|"])  # Puts version in title ...
rfc_name = [rfc_name, "=" * len(rfc_name)]  # ... and the syntax of a title

# Process last block to have a nice looking, and insert license file link
    ("hsll", "Highest Side Lobe Level (dB)"),
    ("slfo", "Side Lobe Fall Off (dB/oct)"),
    ("cg", "Coherent gain"),
    ("enbw", "Equivalent Noise Bandwidth (bins)"),
    ("bw3", "50% power bandwidth (bins)"),
    ("scallop", "Scallop loss (dB)"),  #
    ("wcpl", "Worst case process loss (dB)"),  #
    ("bw6", "25% power bandwidth (bins)"),  #
    ("ol75", "75% overlap correlation (percent)"),  #
    ("ol50", "50% overlap correlation (percent)"),  #
])

size = 50  # Must be even!
full_size = 20 * size
table = []
for name, wnd_func in iteritems(table_wnds):
    if name in has_separator_before:
        table.append([".."] + [""] * (len(schema) - 1))

    wnd = wnd_func(size)
    spectrum = dB20(rfft(wnd, full_size))

    wnd_full = wnd_func(full_size)
    wnd_data = {
        "name": name,
        "hsll": hsll(wnd_full),
        "slfo": slfo(wnd_full),
        "cg": coherent_gain(wnd_full),
        "enbw": enbw(wnd_full),
        "bw3": 2 * find_xdb_bin(wnd, .5),
        "scallop": scalloping_loss(wnd_full),
Example #7
0
def pre_processor(app, what, name, obj, options, lines, namer=lambda name: ":obj:`{0}`".format(name)):
    """
  Callback preprocessor function for docstrings.
  Converts data from Spyder pattern to Sphinx, using a ``namer`` function
  that defaults to ``lambda name: ":obj:`{0}`".format(name)`` (specific for
  ``.. seealso::``).

  """
    # Duplication removal
    if what == "module":  # For some reason, summary appears twice
        idxs = [idx for idx, el in enumerate(lines) if el.startswith("Summary")]
        if len(idxs) >= 2:
            del lines[idxs.pop() :]  # Remove the last summary
        if len(idxs) >= 1:
            lines.insert(idxs[-1] + 1, "")
            if obj is audiolazy.lazy_math:
                lines.insert(idxs[-1] + 1, ".. tabularcolumns:: cl")
            else:
                lines.insert(idxs[-1] + 1, ".. tabularcolumns:: CJ")
            lines.insert(idxs[-1] + 1, "")

    # Real docstring format pre-processing
    result = []
    for name, blk in iteritems(splitter(lines)):
        nlower = name.lower()

        if nlower == "parameters":
            starters = audiolazy.Stream(
                idx for idx, el in enumerate(blk) if len(el) > 0 and not el.startswith(" ")
            ).append([len(blk)])
            for idx1, idx2 in starters.blocks(size=2, hop=1):
                param_data = " ".join(b.strip() for b in blk[idx1:idx2])
                param, expl = param_data.split(":", 1)
                if "," in param:
                    param = param.strip()
                    if not param[0] in ("(", "[", "<", "{"):
                        param = "[{0}]".format(param)
                while "," in param:
                    fparam, param = param.split(",", 1)
                    result.append(":param {0}: {1}".format(fparam.strip(), "\.\.\."))
                result.append(":param {0}: {1}".format(param.strip(), expl.strip()))

        elif nlower == "returns":
            result.append(":returns: " + " ".join(blk))

        elif nlower in ("note", "warning", "hint"):
            result.append(".. {0}::".format(nlower))
            result.extend("  " + el for el in blk)

        elif nlower == "examples":
            result.append("**Examples**:")
            result.extend("  " + el for el in blk)

        elif nlower == "see also":
            result.append(".. seealso::")
            for el in blk:
                if el.endswith(":"):
                    result.append("")  # Skip a line
                    # Sphinx may need help here to find some object locations
                    refs = [namer(f.strip()) for f in el[:-1].split(",")]
                    result.append("  " + ", ".join(refs))
                else:
                    result.append("  " + el)

        else:  # Unkown block name, perhaps the starting one (empty)
            result.extend(blk)

        # Skip a line after each block
        result.append("")

    # Replace lines with the processed data while keeping the actual lines id
    del lines[:]
    lines.extend(result)
Example #8
0
# Texinfo output configuration
texinfo_documents = [
    (
        master_doc,
        project,  # Target
        title,
        author,
        project,  # Dir menu entry
        description,  # From README.rst
        "Miscellanous",  # Category
    )
]


# Epub output configuration
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright


#
# Item in sys.modules for StrategyDict instances (needed for automodule)
#
for name, sdict in iteritems(audiolazy.__dict__):
    if isinstance(sdict, audiolazy.StrategyDict):
        fname = ".".join([sdict.default.__module__, name])
        sdict.__all__ = tuple(x[0] for x in sdict.keys())
        sys.modules[fname] = sdict
  ("hsll", "Highest Side Lobe Level (dB)"),
  ("slfo", "Side Lobe Fall Off (dB/oct)"),
  ("cg", "Coherent gain"),
  ("enbw", "Equivalent Noise Bandwidth (bins)"),
  ("bw3", "50% power bandwidth (bins)"),
  ("scallop", "Scallop loss (dB)"), #
  ("wcpl", "Worst case process loss (dB)"), #
  ("bw6", "25% power bandwidth (bins)"), #
  ("ol75", "75% overlap correlation (percent)"), #
  ("ol50", "50% overlap correlation (percent)"), #
])

size = 50 # Must be even!
full_size = 20 * size
table = []
for name, wnd_func in iteritems(table_wnds):
  if name in has_separator_before:
    table.append([".."] + [""] * (len(schema) - 1))

  wnd = wnd_func(size)
  spectrum = dB20(rfft(wnd, full_size))

  wnd_full = wnd_func(full_size)
  wnd_data = {
    "name": name,
    "hsll": hsll(wnd_full),
    "slfo": slfo(wnd_full),
    "cg": coherent_gain(wnd_full),
    "enbw": enbw(wnd_full),
    "bw3": 2 * find_xdb_bin(wnd, .5),
    "scallop": scalloping_loss(wnd_full),
schema = OrderedDict([
  ("name", "Window"), # Window name
  ("cg", "CG"), # Coherent gain
  ("enbw", "ENBW"), # Equivalent Noise Bandwidth (bins)
  ("bw3", "3dB BW"), # 50% power bandwidth (bins)
  ("scallop", "Scallop"), # Scallop loss (dB)
  ("wcpl", "Worst PL"), # Worst case process loss (dB)
  ("bw6", "6dB BW"), # 25% power bandwidth (bins)
  ("ol75", "75% OL"), # 75% overlap correlation (percent)
  ("ol50", "50% OL"), # 50% overlap correlation (percent)
])

size = 50 # Must be even!
full_size = 20 * size
table = []
for name, wnd_func in iteritems(table_wnds):
  wnd = wnd_func(size)
  spectrum = dB20(rfft(wnd, full_size))

  wnd_full = wnd_func(full_size)
  wnd_data = {
    "name": name,
    "cg": coherent_gain(wnd_full),
    "enbw": enbw(wnd_full),
    "bw3": 2 * find_xdb_bin(wnd, .5),
    "scallop": scalloping_loss(wnd_full),
    "wcpl": worst_case_processing_loss(wnd_full),
    "bw6": 2 * find_xdb_bin(wnd, .25),
    "ol75": overlap_correlation(wnd_full, .25 * full_size) * 100,
    "ol50": overlap_correlation(wnd_full, .5 * full_size) * 100,
  }
Example #11
0
def save_to_rst(prefix, data):
  """
  Saves a RST file with the given prefix into the script file location.

  """
  with open(find_full_name(prefix), "w") as rst_file:
    rst_file.write(full_gpl_for_rst)
    rst_file.write(data)


#
# First chapter! Splits README.rst data into the gen_blocks iterable
#
readme_data = splitter(readme_file_contents)
rfc_copyright = readme_data.popitem()[1] # Last block is a small license msg
gen_blocks = iteritems(readme_data)

# Process GPL license comment at the beginning to put it in all RST files
gpl_to_add = "  File auto-generated by the rst_creator.py script."
full_gpl_for_rst = next(gen_blocks)[1] # It's before the first readable block
full_gpl_for_rst = "\n".join(full_gpl_for_rst[:-1] + [gpl_to_add] +
                             full_gpl_for_rst[-1:] + ["\n\n"])
gpl_for_rst = "\n  ".join(full_gpl_for_rst.strip()
                                          .strip(".").splitlines()[:-2])

# Process the first readable block (project name and small description)
rfc_name, rfc_description = next(gen_blocks) # Second block
rfc_name = " ".join([rfc_name, "|version|"]) # Puts version in title ...
rfc_name = [rfc_name, "=" * len(rfc_name)] # ... and the syntax of a title

# Process last block to have a nice looking, and insert license file link