Пример #1
0
    def simulation_sample(self, sample_tag, sample_id, start_time=0):
        """
        Evaluate model using generated or set input data sample.
        :param sample_tag: A unique ID used as work directory of the single simulation run.
        :return: tuple (sample tag, sample directory path)
        TODO:
        - different mesh and yaml files for individual levels/fine/coarse
        - reuse fine mesh from previous level as coarse mesh

        1. create work dir
        2. write input sample there
        3. call flow through PBS or a script that mark the folder when done
        """
        out_subdir = os.path.join("samples", str(sample_tag))
        sample_dir = os.path.join(self.work_dir, out_subdir)

        force_mkdir(sample_dir, True)
        fields_file = os.path.join(sample_dir, self.FIELDS_FILE)

        gmsh_io.GmshIO().write_fields(fields_file, self.ele_ids,
                                      self._input_sample)
        prepare_time = (t.time() - start_time)
        package_dir = self.run_sim_sample(out_subdir)

        return sample.Sample(directory=sample_dir,
                             sample_id=sample_id,
                             job_id=package_dir,
                             prepare_time=prepare_time)
Пример #2
0
def test_check_flat_quad_degen():
    h = 0.005
    nodes = np.array([[0, 0, 0], [0.501, 0.501, 0], [0, 1, h], [1, 0, h]], dtype=float)
    mesh_io = gmsh_io.GmshIO()
    for inn, n in enumerate(nodes):
        mesh_io.nodes[inn] = n
    mesh_io.elements[0] = (4, (1,2,3), [0,1,2,3])

    hm = heal_mesh.HealMesh(mesh_io)
    hm._check_flat_tetra(0, 0.01)
Пример #3
0
def prepare_th_input(config_dict):
    """
    Prepare FieldFE input file for the TH simulation.
    :param config_dict: Parsed config.yaml. see key comments there.
    """
    # pass
    # we have to read region names from the input mesh
    # input_mesh = gmsh_io.GmshIO(config_dict['hm_params']['mesh'])
    #
    # is_bc_region = {}
    # for name, (id, _) in input_mesh.physical.items():
    #     unquoted_name = name.strip("\"'")
    #     is_bc_region[id] = (unquoted_name[0] == '.')

    # read mesh and mechanichal output data
    mechanics_output = os.path.join(config_dict['hm_params']["output_dir"],
                                    'mechanics.msh')
    mesh = gmsh_io.GmshIO(mechanics_output)

    n_bulk = len(mesh.elements)
    ele_ids = np.array(list(mesh.elements.keys()), dtype=float)

    init_fr_cs = float(config_dict['hm_params']['fr_cross_section'])
    init_fr_K = float(config_dict['hm_params']['fr_conductivity'])
    init_bulk_K = float(config_dict['hm_params']['bulk_conductivity'])
    min_fr_cross_section = float(
        config_dict['th_params']['min_fr_cross_section'])

    time_idx = 1
    time, field_cs = mesh.element_data['cross_section_updated'][time_idx]

    cs = np.maximum(np.array([v[0] for v in field_cs.values()]),
                    min_fr_cross_section)

    K = np.where(
        cs == 1.0,  # condition
        init_bulk_K,  # true array
        init_fr_K * (cs / init_fr_cs)**2)

    # mesh.write_fields('output_hm/th_input.msh', ele_ids, {'conductivity': K})
    th_input_file = 'th_input.msh'
    with open(th_input_file, "w") as fout:
        mesh.write_ascii(fout)
        mesh.write_element_data(fout, ele_ids, 'conductivity', K[:, None])
        mesh.write_element_data(fout, ele_ids, 'cross_section_updated',
                                cs[:, None])
Пример #4
0
    def _extract_mesh(self, mesh_file):
        """
        Extract mesh from file
        :param mesh_file: Mesh file path
        :return: None
        """

        mesh = gmsh_io.GmshIO(mesh_file)
        is_bc_region = {}
        self.region_map = {}
        for name, (id, _) in mesh.physical.items():
            unquoted_name = name.strip("\"'")
            is_bc_region[id] = (unquoted_name[0] == '.')
            self.region_map[unquoted_name] = id

        bulk_elements = []
        for id, el in mesh.elements.items():
            _, tags, i_nodes = el
            region_id = tags[0]
            if not is_bc_region[region_id]:
                bulk_elements.append(id)

        n_bulk = len(bulk_elements)
        centers = np.empty((n_bulk, 3))
        self.ele_ids = np.zeros(n_bulk, dtype=int)
        self.point_region_ids = np.zeros(n_bulk, dtype=int)

        for i, id_bulk in enumerate(bulk_elements):
            _, tags, i_nodes = mesh.elements[id_bulk]
            region_id = tags[0]
            centers[i] = np.average(np.array(
                [mesh.nodes[i_node] for i_node in i_nodes]),
                                    axis=0)
            self.point_region_ids[i] = region_id
            self.ele_ids[i] = id_bulk

        min_pt = np.min(centers, axis=0)
        max_pt = np.max(centers, axis=0)
        diff = max_pt - min_pt
        min_axis = np.argmin(diff)
        non_zero_axes = [0, 1, 2]
        # TODO: be able to use this mesh_dimension in fields
        if diff[min_axis] < 1e-10:
            non_zero_axes.pop(min_axis)
        self.points = centers[:, non_zero_axes]
Пример #5
0
def prepare_th_input(sample_dir):
    """
    Prepare FieldFE input file for the TH simulation.
    """

    # #we have to read region names from the input mesh
    # input_mesh = gmsh_io.GmshIO(config_dict['hm_params']['mesh'])
    #
    # is_bc_region = {}
    # for name, (id, _) in input_mesh.physical.items():
    #     unquoted_name = name.strip("\"'")
    #     is_bc_region[id] = (unquoted_name[0] == '.')

    config_dict = load_config_dict()

    # read mesh and mechanical output data
    mesh = gmsh_io.GmshIO(os.path.join(sample_dir, 'output_hm/mechanics.msh'))

    n_bulk = len(mesh.elements)
    ele_ids = np.zeros(n_bulk, dtype=int)
    for i, id_bulk in zip(range(n_bulk), mesh.elements.items()):
        ele_ids[i] = id_bulk[0]

    init_fr_cs = float(config_dict['hm_params']['fr_cross_section'])
    init_fr_K = float(config_dict['hm_params']['fr_conductivity'])
    init_bulk_K = float(config_dict['hm_params']['bulk_conductivity'])

    field_cs = mesh.element_data['cross_section_updated'][1]

    K = np.zeros((n_bulk, 1), dtype=float)
    cs = np.zeros((n_bulk, 1), dtype=float)
    for i, valcs in zip(range(n_bulk), field_cs[1].values()):
        cs_el = valcs[0]
        cs[i, 0] = cs_el
        if cs_el != 1.0:  # if cross_section == 1, i.e. 3d bulk
            K[i, 0] = init_fr_K * (cs_el * cs_el) / (init_fr_cs * init_fr_cs)
        else:
            K[i, 0] = init_bulk_K

    # mesh.write_fields('output_hm/th_input.msh', ele_ids, {'conductivity': K})
    th_input_file = os.path.join(sample_dir, 'output_hm/th_input.msh')
    with open(th_input_file, "w") as fout:
        mesh.write_ascii(fout)
        mesh.write_element_data(fout, ele_ids, 'conductivity', K)
        mesh.write_element_data(fout, ele_ids, 'cross_section_updated', cs)
Пример #6
0
 def read_mesh(mesh_file, node_tol=0.0001):
     import gmsh_io
     return HealMesh(gmsh_io.GmshIO(mesh_file), mesh_file, node_tol)
Пример #7
0
options, args = parser.parse_known_args()

def default_ctor(loader, tag_suffix, node):
    ctor = yaml.constructor.BaseConstructor()
    dict = ctor.construct_mapping(node)
    #assert isinstance(node, yaml.MappingNode)
    return dict

yaml.add_multi_constructor('', default_ctor)
with open(options.yaml_file, "r") as f:

    input_content = yaml.load(f)

mesh_file = input_content['problem']['mesh']['mesh_file']
mesh = gmsh_io.GmshIO()
with open(mesh_file, "r") as f:
    mesh.read(f)

input_fields = input_content['problem']['flow_equation']['input_fields']
for in_field in input_fields:
    if 'conductivity' in in_field:
        conductivity_file = in_field['conductivity']['gmsh_file']
        conductivity_name = in_field['conductivity']['field_name']

conductivity_file = conductivity_file.replace("${INPUT}", options.input_dir)
field_mesh = gmsh_io.GmshIO()
with open(conductivity_file, "r") as f:
    field_mesh.read(f)

time_idx = 0
Пример #8
0
def prepare_th_input(config_dict):
    """
    Prepare FieldFE input file for the TH simulation.
    :param config_dict: Parsed config.yaml. see key comments there.
    """
    # pass
    # we have to read region names from the input mesh
    # input_mesh = gmsh_io.GmshIO(config_dict['hm_params']['mesh'])
    #
    # is_bc_region = {}
    # for name, (id, _) in input_mesh.physical.items():
    #     unquoted_name = name.strip("\"'")
    #     is_bc_region[id] = (unquoted_name[0] == '.')

    # read mesh and mechanichal output data
    mechanics_output = os.path.join(config_dict['hm_params']["output_dir"],
                                    'mechanics.msh')
    mesh = gmsh_io.GmshIO(mechanics_output)

    n_bulk = len(mesh.elements)
    ele_ids = np.array(list(mesh.elements.keys()), dtype=float)

    init_fr_cs = float(config_dict['hm_params']['fr_cross_section'])
    init_fr_K = float(config_dict['hm_params']['fr_conductivity'])
    init_bulk_K = float(config_dict['hm_params']['bulk_conductivity'])
    min_fr_cross_section = float(
        config_dict['th_params']['min_fr_cross_section'])
    max_fr_cross_section = float(
        config_dict['th_params']['max_fr_cross_section'])

    time_idx = 1
    time, field_cs = mesh.element_data['cross_section_updated'][time_idx]

    # cut small and large values of cross-section
    cs = np.maximum(np.array([v[0] for v in field_cs.values()]),
                    min_fr_cross_section)
    cs = np.minimum(cs, max_fr_cross_section)

    K = np.where(
        cs == 1.0,  # condition
        init_bulk_K,  # true array
        init_fr_K * (cs / init_fr_cs)**2)

    # get cs and K on fracture elements only
    fr_indices = np.array(
        [int(key) for key, val in field_cs.items() if val[0] != 1])
    cs_fr = np.array([cs[i] for i in fr_indices])
    k_fr = np.array([K[i] for i in fr_indices])

    # compute cs and K statistics and write it to a file
    fr_param = {}
    avg = float(np.average(cs_fr))
    median = float(np.median(cs_fr))
    interquantile = float(
        1.5 * (np.quantile(cs_fr, 0.75) - np.quantile(cs_fr, 0.25)))
    fr_param["fr_cross_section"] = {
        "avg": avg,
        "median": median,
        "interquantile": interquantile
    }

    avg = float(np.average(k_fr))
    median = float(np.median(k_fr))
    interquantile = float(1.5 *
                          (np.quantile(k_fr, 0.75) - np.quantile(k_fr, 0.25)))
    fr_param["fr_conductivity"] = {
        "avg": avg,
        "median": median,
        "interquantile": interquantile
    }

    with open('fr_param_output.yaml', 'w') as outfile:
        yaml.dump(fr_param, outfile, default_flow_style=False)

    # mesh.write_fields('output_hm/th_input.msh', ele_ids, {'conductivity': K})
    th_input_file = 'th_input.msh'
    with open(th_input_file, "w") as fout:
        mesh.write_ascii(fout)
        mesh.write_element_data(fout, ele_ids, 'conductivity', K[:, None])
        mesh.write_element_data(fout, ele_ids, 'cross_section_updated',
                                cs[:, None])