def parse_chunk(value, elements, chunks): log.debug("Parse_chunk %s", value) chunk = [] parts = utils.split_ignoring_parentheses(value, ",") log.debug(parts) for part in parts: if "symmetry" in part: continue if "inv" in part: # Reverse a sequence of elements. When doing this, swap # the entrance and exit angles for any dipoles. chunk_to_invert = re.match("inv\\((.*)\\)", part).groups()[0] inverted_chunk = [] for el in reversed(chunks[chunk_to_invert]): if el.__class__ == Dipole: inverted_dipole = el.copy() inverted_dipole.EntranceAngle = el.ExitAngle inverted_dipole.ExitAngle = el.EntranceAngle inverted_chunk.append(inverted_dipole) else: inverted_chunk.append(el) chunk.extend(inverted_chunk) elif "*" in part: num, contents = part.split("*") if contents.startswith("("): assert contents[-1] == ")" contents = contents[1:-1] chunk.extend(int(num) * parse_chunk(contents, elements, chunks)) elif part in elements: chunk.append(elements[part]) elif part in chunks: chunk.extend(chunks[part]) else: raise Exception("part {} not understood".format(part)) return chunk
def tracy_element_from_string(name, element_string, variables): log.debug("Parsing tracy element {}".format(element_string)) parts = utils.split_ignoring_parentheses(element_string, ",") params = {} element_type = parts[0] for part in parts[1:]: try: key, value = utils.split_ignoring_parentheses(part, "=") except ValueError: key, value = part, None if value in variables: value = variables[value] if key == "hom": assert value[0] == "(" assert value[-1] == ")" polynom_a, polynom_b = parse_hom(value[1:-1], variables) params["PolynomA"] = polynom_a params["PolynomB"] = polynom_b else: params[key] = value return ELEMENT_MAP[element_type](name, params, variables)
def test_split_ignoring_parentheses(string, delimiter, target): assert split_ignoring_parentheses(string, delimiter) == target