Пример #1
0
def read_MeshFormat(file: TextIOWrapper, data: dict):
    """
    Read version of .msh file

    :param file: opened .msh file
    :param data: dictionary with data describing mesh
    """

    mesh_format = file.readline()
    mesh_format = mesh_format.split(' ')

    data['version'] = 'MSH ' + mesh_format[0] + ' ASCII'

    check_ending('$EndMeshFormat\n', file.readline())
Пример #2
0
def read_Elements(file: TextIOWrapper, data: dict):
    """
    Read Elements section from .msh file

    :param file: opened .msh file
    :param data: dictionary with data describing mesh
    """
    n_entities = entity_block_info(file)[0]

    data['element_lists'] = []
    data['id_list'] = []

    for i in range(n_entities):
        n_elements, elements_str_list, el_type, tag, dim = parse_entity(file)
        if dim != 0:
            data['id_list'].append(data['entities'][dim][tag])
            element_list = gmshTypes[el_type](n_elements)
            for j in range(n_elements):
                el = elements_str_list[j]
                connectivity = [(int(i) - 1) for i in el.split(' ')]
                element_list[j] = connectivity[1:]

            data['element_lists'].append(element_list)

    check_ending('$EndElements\n', file.readline())
Пример #3
0
    def tokenize_file(self, file: _io.TextIOWrapper):
        """
        :param file:
        :return:
        """
        line = file.readline()
        line_num = 1
        in_doc = False
        doc = ""
        while line:
            tup = (line_num, self.file_name)
            last_index = len(self.tokens)
            in_doc, doc = self.proceed_line(line, tup, in_doc, doc)
            self.find_include(last_index, len(self.tokens))
            line = file.readline()
            line_num += 1

        self.tokens.append(stl.Token((stl.EOF, None)))
Пример #4
0
def skip_section(file: TextIOWrapper, data: dict):
    """
    Skip section in .msh file

    :param file: opened .msh file
    :param data: dictionary with data describing mesh
    """

    while file.readline()[0:4] != '$End':
        pass
Пример #5
0
def read_PhysicalNames(file: TextIOWrapper, data: dict):
    """
    Read information about physical names of each entity

    :param file: opened .msh file
    :param data: dictionary with data describing mesh
    """
    n = int(file.readline()[:-1])
    data['phys_names'] = {}
    data['phys_names'][0] = {}
    data['phys_names'][1] = {}
    data['phys_names'][2] = {}
    data['phys_names'][3] = {}
    for i in range(n):
        entity_phys_info = file.readline()[:-1].split(' ')

        data['phys_names'][int(entity_phys_info[0])][int(
            entity_phys_info[1])] = entity_phys_info[2][1:-1]

    check_ending('$EndPhysicalNames\n', file.readline())
Пример #6
0
def parse_entity(file: TextIOWrapper) -> (int, list, int, int, int):
    """
    Parse one entity block in .msh format

    :param file: opened .msh file
    :return: number of objects, objects, objects type, entity tag, entity dimension
    """
    info = file.readline()
    info = [int(i) for i in info[:-1].split(' ')]

    objects = []
    entity_dimension = info[0]
    entity_tag = info[1]
    obj_type = info[2]
    n_object = info[3]

    # read objects as strings
    for i in range(n_object):
        objects.append(file.readline()[:-2])  # append but delete <\n>

    return n_object, objects, obj_type, entity_tag, entity_dimension
Пример #7
0
def entity_block_info(file: TextIOWrapper) -> (int, int):
    """
    Read information about current entity block

    :param file: opened .msh file
    :return: number of entity blocks, number of objects
    """
    block = file.readline()
    block = [int(i) for i in block[:-1].split(' ')]

    # number of entity blocks and number of objects in such block
    return block[0], block[1]
Пример #8
0
 def parse_map(self, server_messages: TextIOWrapper) -> StateInit:
     """Parse the initial server message into a map."""
     # a level has a header with color specifications followed by the map
     # the map starts after the line "#initial"
     line = server_messages.readline().rstrip()
     initial = False  # mark start of level map
     goal = False  # mark start of level map
     map = []
     goal_state = []
     col_count = 0
     while line:
         if goal:
             if line.find("#end") != -1:
                 len_line = max(len(l) for l in map)
                 for i in range(len(map)):
                     map[i] += "+" * (len_line - len(map[i]))
                     goal_state[i] += "+" * (len_line - len(goal_state[i]))
                 println("\n".join(["".join(line) for line in map]))
                 return self.build_map(map, goal_state)
             goal_state.append(list(self._formatl(line)))
         elif initial:
             if line.find("#goal") != -1:
                 goal = True
             else:
                 map.append(list(self._formatl(line)))
         else:
             if line.find("#initial") != -1:
                 initial = True
             else:
                 color_matched = self.colors_re.search(line)
                 if color_matched:
                     col_count += 1
                     color = color_matched[1]
                     self.colors[color_matched[2]] = color
                     for obj in line[len(color) + 5:].split(", "):
                         self.colors[obj] = color
         line = server_messages.readline().replace("\r",
                                                   "")[:-1]  # chop last
Пример #9
0
def parse_nodes(file: TextIOWrapper, ref_node_tags: list) -> list:
    """
    Parse one $Nodes entity block in .msh format

    :param file: opened .msh file
    :param ref_node_tags: mutable node tags list
    :return: nodal coordinates as string
    """
    info = file.readline()
    info = [int(i) for i in info[:-1].split(' ')]

    nodes = []

    n_nodes = info[3]

    # read node tags in order to check if eny nodes have been skiped
    for i in range(n_nodes):
        ref_node_tags.append(int(file.readline()[:-1]))

    # read nodal coordinates as strings
    for i in range(n_nodes):
        nodes.append(file.readline()[:-1])  # append but delete <\n>

    return nodes
Пример #10
0
def read_Entities(file: TextIOWrapper, data: dict):
    """
    Read information about entities

    :param file: opened .msh file
    :param data: dictionary with data describing mesh
    """

    entities = file.readline()
    entities = [int(i) for i in entities[:-1].split(' ')]
    data['#points'] = entities[0]
    data['#curves'] = entities[1]
    data['#surfaces'] = entities[2]
    data['#volumes'] = entities[3]

    data['entities'] = {}

    data['entities'][0] = {}

    if 'phys_names' in data:
        named = True
    else:
        named = False

    for i in range(data['#points']):
        file.readline()

    data['entities'][1] = {}
    for i in range(data['#curves']):
        curve = [int(float(i)) for i in file.readline()[:-2].split(' ')]
        if named and curve[8] in data['phys_names'][1]:
            data['entities'][1][i + 1] = data['phys_names'][1][curve[8]]
        else:
            data['entities'][1][i + 1] = curve[8]

    data['entities'][2] = {}
    for i in range(data['#surfaces']):
        surface = [int(float(i)) for i in file.readline()[:-2].split(' ')]
        if named and surface[8] in data['phys_names'][2]:
            data['entities'][2][i + 1] = data['phys_names'][2][surface[8]]
        else:
            data['entities'][2][i + 1] = surface[8]

    data['entities'][3] = {}
    for i in range(data['#volumes']):
        volume = [int(float(i)) for i in file.readline()[:-2].split(' ')]
        data['entities'][3][i + 1] = volume[8]

    check_ending('$EndEntities\n', file.readline())
Пример #11
0
def read_Nodes(file: TextIOWrapper, data: dict):
    """
    Read Nodes section from .msh file

    :param file: opened .msh file
    :param data: dictionary with data describing mesh
    """
    n_entities, n_nodes = entity_block_info(file)
    node_list = np.empty((3, n_nodes))
    node_tags = []
    j = 0
    for i in range(n_entities):

        nodes = parse_nodes(file, node_tags)

        for node in nodes:
            node = node.split(' ')
            node_list[:, j] = [float(node[0]), float(node[1]), float(node[2])]
            j += 1

    check_ending('$EndNodes\n', file.readline())

    data['nodes'] = node_list
    data['node_tags'] = node_tags
Пример #12
0
def deserialization(rf: _io.TextIOWrapper) -> TreeNode:
    pNode = TreeNode(int(rf.readline()))
    pNode.left = deserialization(rf)
    pNode.right = deserialization(rf)
    return pNode
Пример #13
0
def parse_input_file(fh: TextIOWrapper, stop_if: Callable = None) -> Tuple[BertiniConfig, BertiniInput, list]:
    """Given an open file handle, read until stopping criterion is satisfied
    and try to parse an input file from it.

    Parameters
    ----------
    fh : _io.TextIOWrapper
        An open file handle.
    stop_if : function, optional
        Stop when the next line satisfies this function.

    Returns
    -------
    config : BertiniConfig
        Key-value pairs of parameters set in the CONFIG section.
    inputs : BertiniInput
        Values set in the INPUT section.
    """
    if stop_if is None:
        stop_if = lambda l: l == ""

    config = BertiniConfig()
    inputs = BertiniInput()
    misclines = []

    in_config = in_input = False
    vargroup_re = re.compile(r"^variable_group\s+", re.I)
    var_re = re.compile(r"^variable\s+", re.I)
    homvargroup_re = re.compile(r"^hom_variable_group\s+", re.I)
    pathvar_re = re.compile(r"^pathvariable\s+", re.I)
    random_re = re.compile(r"^random\s+", re.I)
    constant_re = re.compile(r"^constant\s+", re.I)
    function_re = re.compile(r"^function\s+", re.I)
    parameter_re = re.compile(r"^parameter\s+", re.I)

    line = fh.readline()
    while line and not stop_if(line):
        line = line.strip()

        if line.lower() == "config":
            in_config = True
        elif line.lower() == "input":
            in_input = True
        elif line.lower().strip(";") == "end":
            in_input = in_config = False
        elif not line.startswith("%") and len(line) > 0:
            if not line.endswith(";"):  # statement spans several lines
                multiline = line
                line = fh.readline()
                while line and not line.endswith(";"):
                    multiline += " " + line.strip()
                    line = fh.readline()

                line = multiline

            line = line.strip(" ;")

            if in_config:
                key, val = map(lambda l: l.strip(), line.split(":"))
                val = val.split("%")[0].strip(" ;")  # remove comment, semicolon, trailing whitespace

                setattr(config, key.lower(), val)

            elif in_input:
                if vargroup_re.match(line):
                    line = vargroup_re.sub("", line)
                    inputs.variable_group.append(re.split(r",\s*", line))
                elif var_re.match(line):
                    line = var_re.sub("", line)
                    inputs.variable.append(re.split(r",\s*", line))
                elif homvargroup_re.match(line):
                    line = homvargroup_re.sub("", line)
                    inputs.hom_variable_group.append(re.split(r",\s*", line))
                elif pathvar_re.match(line):
                    line = pathvar_re.sub("", line)
                    inputs.pathvariable.append(re.split(r",\s*", line))
                elif random_re.match(line):
                    line = random_re.sub("", line)
                    inputs.random.append(re.split(r",\s*", line))
                elif constant_re.match(line):
                    line = constant_re.sub("", line)
                    constants = re.split(r",\s*", line)
                    for c in constants:
                        inputs.constant[c] = None
                elif function_re.match(line):
                    line = function_re.sub("", line)
                    functions = re.split(r",\s*", line)
                    for f in functions:
                        inputs.function[f] = None
                elif parameter_re.match(line):
                    line = parameter_re.sub("", line)
                    params = re.split(r",\s*", line)
                    for p in params:
                        inputs.parameter[p] = None
                else:
                    terms = re.split(r";\s*", line)
                    for term in terms:
                        # remove comments
                        term = term.split("%")[0].strip()
                        # split by =
                        term = re.split(r"\s*=\s*", term)
                        if len(term) != 2:
                            misclines.append("=".join(term))
                        else:
                            term, val = term
                            if term in inputs.constant:
                                inputs.constant[term] = val
                            elif term in inputs.function:
                                inputs.function[term] = val
                            elif term in inputs.parameter:
                                inputs.parameter[term] = val
                            else:
                                inputs.subfunction[term] = val

        line = fh.readline()

    return config, inputs, misclines