def test_field_basic(): f = Field.create_generic('f', spatial_dimensions=2) assert FieldType.is_generic(f) assert f['E'] == f[1, 0] assert f['N'] == f[0, 1] assert '_' in f.center._latex('dummy') f = Field.create_fixed_size('f', (10, 10), strides=(80, 8), dtype=np.float64) assert f.spatial_strides == (10, 1) assert f.index_strides == () assert f.center_vector == sp.Matrix([f.center]) f = Field.create_fixed_size('f', (8, 8, 2, 2), index_dimensions=2) assert f.center_vector == sp.Matrix([[f(0, 0), f(0, 1)], [f(1, 0), f(1, 1)]]) field_access = f[1, 1] assert field_access.nr_of_coordinates == 2 assert field_access.offset_name == 'NE' neighbor = field_access.neighbor(coord_id=0, offset=-2) assert neighbor.offsets == (-1, 1) assert '_' in neighbor._latex('dummy') f = Field.create_generic('f', spatial_dimensions=5, index_dimensions=2) field_access = f[1, -1, 2, -3, 0](1, 0) assert field_access.offsets == (1, -1, 2, -3, 0) assert field_access.index == (1, 0)
def create_lb_update_rule(collision_rule=None, lbm_config=None, lbm_optimisation=None, config=None, optimization=None, **kwargs): """Creates an update rule (list of Assignments) for a LB method that describe a full sweep""" lbm_config, lbm_optimisation, config = update_with_default_parameters(kwargs, optimization, lbm_config, lbm_optimisation, config) if lbm_config.collision_rule is not None: collision_rule = lbm_config.collision_rule if collision_rule is None: collision_rule = create_lb_collision_rule(lbm_config.lb_method, lbm_config=lbm_config, lbm_optimisation=lbm_optimisation, config=config) lb_method = collision_rule.method field_data_type = config.data_type q = collision_rule.method.stencil.Q if lbm_optimisation.symbolic_field is not None: src_field = lbm_optimisation.symbolic_field elif lbm_optimisation.field_size: field_size = tuple([s + 2 for s in lbm_optimisation.field_size] + [q]) src_field = Field.create_fixed_size(lbm_config.field_name, field_size, index_dimensions=1, layout=lbm_optimisation.field_layout, dtype=field_data_type) else: src_field = Field.create_generic(lbm_config.field_name, spatial_dimensions=collision_rule.method.dim, index_shape=(q,), layout=lbm_optimisation.field_layout, dtype=field_data_type) if lbm_optimisation.symbolic_temporary_field is not None: dst_field = lbm_optimisation.symbolic_temporary_field else: dst_field = src_field.new_field_with_different_name(lbm_config.temporary_field_name) kernel_type = lbm_config.kernel_type if kernel_type == 'stream_pull_only': return create_stream_pull_with_output_kernel(lb_method, src_field, dst_field, lbm_config.output) else: if kernel_type == 'default_stream_collide': if lbm_config.streaming_pattern == 'pull' and any(lbm_optimisation.builtin_periodicity): accessor = PeriodicTwoFieldsAccessor(lbm_optimisation.builtin_periodicity, ghost_layers=1) else: accessor = get_accessor(lbm_config.streaming_pattern, lbm_config.timestep) elif kernel_type == 'collide_only': accessor = CollideOnlyInplaceAccessor elif isinstance(kernel_type, PdfFieldAccessor): accessor = kernel_type else: raise ValueError("Invalid value of parameter 'kernel_type'", lbm_config.kernel_type) return create_lbm_kernel(collision_rule, src_field, dst_field, accessor)
def compile_macroscopic_values_getter(lb_method, output_quantities, pdf_arr=None, ghost_layers=1, iteration_slice=None, field_layout='numpy', target=Target.CPU, streaming_pattern='pull', previous_timestep=Timestep.BOTH): """ Create kernel to compute macroscopic value(s) from a pdf field (e.g. density or velocity) Args: lb_method: instance of :class:`lbmpy.methods.AbstractLbMethod` output_quantities: sequence of quantities to compute e.g. ['density', 'velocity'] pdf_arr: optional numpy array for pdf field - used to get optimal loop structure for kernel ghost_layers: a sequence of pairs for each coordinate with lower and upper nr of ghost layers that should be excluded from the iteration. If None, the number of ghost layers is determined automatically and assumed to be equal for all dimensions. iteration_slice: if not None, iteration is done only over this slice of the field field_layout: layout for output field, also used for pdf field if pdf_arr is not given target: `Target.CPU` or `Target.GPU` previous_step_accessor: The accessor used by the streaming pattern of the previous timestep Returns: a function to compute macroscopic values: - pdf_array - keyword arguments from name of conserved quantity (as in output_quantities) to numpy field """ if not (isinstance(output_quantities, list) or isinstance(output_quantities, tuple)): output_quantities = [output_quantities] cqc = lb_method.conserved_quantity_computation unknown_quantities = [ oq for oq in output_quantities if oq not in cqc.conserved_quantities ] if unknown_quantities: raise ValueError( "No such conserved quantity: %s, conserved quantities are %s" % (str(unknown_quantities), str(cqc.conserved_quantities.keys()))) if pdf_arr is None: pdf_field = Field.create_generic('pdfs', lb_method.dim, index_dimensions=1, layout=field_layout) else: pdf_field = Field.create_from_numpy_array('pdfs', pdf_arr, index_dimensions=1) output_mapping = {} for output_quantity in output_quantities: number_of_elements = cqc.conserved_quantities[output_quantity] assert number_of_elements >= 1 ind_dims = 0 if number_of_elements <= 1 else 1 if pdf_arr is None: output_field = Field.create_generic(output_quantity, lb_method.dim, layout=field_layout, index_dimensions=ind_dims) else: output_field_shape = pdf_arr.shape[:-1] if ind_dims > 0: output_field_shape += (number_of_elements, ) field_layout = get_layout_of_array(pdf_arr) else: field_layout = get_layout_of_array( pdf_arr, index_dimension_ids=[len(pdf_field.shape) - 1]) output_field = Field.create_fixed_size(output_quantity, output_field_shape, ind_dims, pdf_arr.dtype, field_layout) output_mapping[output_quantity] = [ output_field(i) for i in range(number_of_elements) ] if len(output_mapping[output_quantity]) == 1: output_mapping[output_quantity] = output_mapping[output_quantity][ 0] stencil = lb_method.stencil previous_step_accessor = get_accessor(streaming_pattern, previous_timestep) pdf_symbols = previous_step_accessor.write(pdf_field, stencil) eqs = cqc.output_equations_from_pdfs(pdf_symbols, output_mapping).all_assignments if target == Target.CPU: import pystencils.cpu as cpu kernel = cpu.make_python_function( cpu.create_kernel(eqs, ghost_layers=ghost_layers, iteration_slice=iteration_slice)) elif target == Target.GPU: import pystencils.gpucuda as gpu kernel = gpu.make_python_function( gpu.create_cuda_kernel(eqs, ghost_layers=ghost_layers, iteration_slice=iteration_slice)) else: raise ValueError( "Unknown target '%s'. Possible targets are `Target.CPU` and `Target.GPU`" % (target, )) def getter(pdfs, **kwargs): if pdf_arr is not None: assert pdfs.shape == pdf_arr.shape and pdfs.strides == pdf_arr.strides, \ "Pdf array not matching blueprint which was used to compile" + str(pdfs.shape) + str(pdf_arr.shape) if not set(output_quantities).issubset(kwargs.keys()): raise ValueError( "You have to specify the output field for each of the following quantities: %s" % (str(output_quantities), )) kernel(pdfs=pdfs, **kwargs) return getter
def test_error_handling(): struct_dtype = np.dtype([('a', np.int32), ('b', np.float64), ('c', np.uint32)]) Field.create_generic('f', spatial_dimensions=2, index_dimensions=0, dtype=struct_dtype) with pytest.raises(ValueError) as e: Field.create_generic('f', spatial_dimensions=2, index_dimensions=1, dtype=struct_dtype) assert 'index dimension' in str(e.value) arr = np.array([[1, 2.0, 3], [1, 2.0, 3]], dtype=struct_dtype) Field.create_from_numpy_array('f', arr, index_dimensions=0) with pytest.raises(ValueError) as e: Field.create_from_numpy_array('f', arr, index_dimensions=1) assert 'Structured arrays' in str(e.value) arr = np.zeros([3, 3, 3]) Field.create_from_numpy_array('f', arr, index_dimensions=2) with pytest.raises(ValueError) as e: Field.create_from_numpy_array('f', arr, index_dimensions=3) assert 'Too many' in str(e.value) Field.create_fixed_size('f', (3, 2, 4), index_dimensions=0, dtype=struct_dtype, layout='reverse_numpy') with pytest.raises(ValueError) as e: Field.create_fixed_size('f', (3, 2, 4), index_dimensions=1, dtype=struct_dtype, layout='reverse_numpy') assert 'Structured arrays' in str(e.value) f = Field.create_fixed_size('f', (10, 10)) with pytest.raises(ValueError) as e: f[1] assert 'Wrong number of spatial indices' in str(e.value) f = Field.create_generic('f', spatial_dimensions=2, index_shape=(3, )) with pytest.raises(ValueError) as e: f(3) assert 'out of bounds' in str(e.value) f = Field.create_fixed_size('f', (10, 10, 3, 4), index_dimensions=2) with pytest.raises(ValueError) as e: f(3, 0) assert 'out of bounds' in str(e.value) with pytest.raises(ValueError) as e: f(1, 0)(1, 0) assert 'Indexing an already indexed' in str(e.value) with pytest.raises(ValueError) as e: f(1) assert 'Wrong number of indices' in str(e.value) with pytest.raises(ValueError) as e: Field.create_generic('f', spatial_dimensions=2, layout='wrong') assert 'Unknown layout descriptor' in str(e.value) assert layout_string_to_tuple('fzyx', dim=4) == (3, 2, 1, 0) with pytest.raises(ValueError) as e: layout_string_to_tuple('wrong', dim=4) assert 'Unknown layout descriptor' in str(e.value)