예제 #1
0
파일: body.py 프로젝트: rorni/mckit
    def simplify(self,
                 box=GLOBAL_BOX,
                 split_disjoint=False,
                 min_volume=MIN_BOX_VOLUME,
                 trim_size=1):
        """Simplifies this cell by removing unnecessary surfaces.

        The simplification procedure goes in the following way.
        # TODO: insert brief description!

        Parameters
        ----------
        box : Box
            Box where geometry should be simplified.
        split_disjoint : bool
            Whether to split disjoint geometries into separate geometries.
        min_volume : float
            The smallest value of box's volume when the process of box splitting
            must be stopped.
        trim_size : int
            Max size of set to return. It is used to prevent unlimited growth
            of the variant set.

        Returns
        -------
        simple_cell : Cell
            Simplified version of this cell.
        """
        # print('Collect stage...')
        self._shape.collect_statistics(box, min_volume)
        # print('finding optimal solution...')
        variants = self._shape.get_simplest(trim_size)
        # print(len(variants))
        options = filter_dict(self.options, 'original')
        return Body(variants[0], **options)
예제 #2
0
 def cell(self, p):
     reference_body = self.cells[p[2]]
     options = filter_dict(reference_body.options, "original", "comment",
                           "comment_above")
     options.update(p.attributes)
     options["name"] = p[0]
     new_body = Body(reference_body, **options)
     return self.build_cell(new_body, options)
예제 #3
0
파일: universe.py 프로젝트: MC-kit/mckit
    def rename(
        self,
        start_cell: int = None,
        start_surf: int = None,
        start_mat: int = None,
        start_tr: int = None,
        name: int = None,
    ) -> None:
        """Renames all entities contained in the universe.

        All new names are sequential starting from the specified name. If name
        is None, than names of entities are leaved untouched.

        Parameters
        ----------
        start_cell :
            Starting name for cells. Default: None.
        start_surf :
            Starting name for surfaces. Default: None.
        start_mat :
            Starting name for materials. Default: None.
        start_tr :
            Starting name for transformations. Default: None.
        name :
            Name for the universe. Default: None.
        """
        # TODO dvp: implement transformations renaming
        assert start_tr is None, "Transformation renaming is not implemented yet"
        if name:
            self._name = name
            for c in self:
                c.options = filter_dict(c.options, "original")
        if start_cell:
            for c in self:
                c.rename(start_cell)
                start_cell += 1
        if start_surf:
            surfs = self.get_surfaces()
            for s in sorted(surfs, key=Card.name):
                s.rename(start_surf)
                start_surf += 1
        if start_mat:
            mats = self.get_compositions()
            for m in sorted(mats, key=Card.name):
                if m not in self._common_materials:
                    m.rename(start_mat)
                    start_mat += 1
예제 #4
0
파일: body.py 프로젝트: rorni/mckit
    def union(self, other):
        """Gets an union if this cell with the other.

        The resulting cell inherits all options of this one (the caller).

        Parameters
        ----------
        other : Cell
            Other cell.

        Returns
        -------
        cell : Cell
            The result.
        """
        geometry = self._shape.union(other)
        options = filter_dict(self.options, 'original')
        return Body(geometry, **options)
예제 #5
0
파일: body.py 프로젝트: rorni/mckit
    def transform(self, tr):
        """Applies transformation to this cell.

        Parameters
        ----------
        tr : Transform
            Transformation to be applied.

        Returns
        -------
        cell : Cell
            The result of this cell transformation.
        """
        geometry = self._shape.transform(tr)
        options = filter_dict(self.options, 'original')
        cell = Body(geometry, **options)
        fill = cell.options.get('FILL', None)
        if fill:
            tr_in = fill.get('transform', Transformation())
            new_tr = tr.apply2transform(tr_in)
            fill['transform'] = new_tr
        return cell
예제 #6
0
파일: test_utils.py 프로젝트: MC-kit/mckit
def test_deep_copy_dict(dictionary, drop_items, expected):
    actual = filter_dict(dictionary, drop_items)
    assert actual == expected
예제 #7
0
파일: compose.py 프로젝트: MC-kit/mckit
def compose(output, fill_descriptor_path, source, override):
    logger.info("Loading model from {s}", s=source)
    parse_result: ParseResult = from_file(source)
    envelopes = parse_result.universe
    source = Path(source)
    universes_dir = source.absolute().parent
    assert universes_dir.is_dir()
    logger.info("Loading fill-descriptor from {f}", f=fill_descriptor_path)
    with fill_descriptor_path.open() as fid:
        fill_descriptor = tk.parse(fid.read())

    universes = load_universes(fill_descriptor, universes_dir)
    named_transformations = load_named_transformations(fill_descriptor)

    comps = {}

    for k, v in universes.items():
        u, _ = v
        cps = u.get_compositions()
        comps[k] = {c for c in cps}

    common = reduce(set.union, comps.values())
    envelopes.set_common_materials(common)
    cells_index = dict((cell.name(), cell) for cell in envelopes)

    for i, spec in universes.items():
        universe, transformation = spec
        universe.set_common_materials(common)
        cell = cells_index[i]
        cell.options = filter_dict(cell.options, "original")
        cell.options["FILL"] = {"universe": universe}
        if transformation is not None:
            if isinstance(transformation, tk_items.Array):
                transformation1 = np.fromiter(map(float, iter(transformation)),
                                              dtype=np.double)
                try:
                    translation = transformation1[:3]
                    if len(transformation1) > 3:
                        rotation = transformation1[3:]
                    else:
                        rotation = None
                    transformation2 = mk.Transformation(
                        translation=translation,
                        rotation=rotation,
                        indegrees=
                        True,  # Assuming that on decompose we store a transformation in degrees as well
                    )
                except ValueError as ex:
                    raise ValueError(
                        f"Failed to process FILL transformation in cell #{cell.name()} of universe #{universe.name()}"
                    ) from ex
                cell.options["FILL"]["transform"] = transformation2
            elif isinstance(transformation, tk_items.Integer):
                assert (
                    named_transformations is not None
                ), "There are no named transformations in the fill descriptor file"
                transformation1 = named_transformations[int(transformation)]
                cell.options["FILL"]["transform"] = transformation1
            else:
                raise NotImplementedError(
                    f"Unexpected type of transformation parameter {type(transformation)}"
                )
    save_mcnp(envelopes, output, override)
예제 #8
0
파일: compose.py 프로젝트: rorni/mckit
def compose(output, fill_descriptor_path, source, override):
    parse_result: ParseResult = from_file(source)
    envelopes = parse_result.universe
    source = Path(source)
    universes_dir = source.absolute().parent
    assert universes_dir.is_dir()

    with fill_descriptor_path.open() as fid:
        fill_descriptor = tk.parse(fid.read())

    universes = {}

    for k, v in fill_descriptor.items():
        if isinstance(v, dict) and 'universe' in v:
            cell_name = int(k)
            universe_name = int(v['universe'])
            transformation = v.get('transform', None)
            universe_path = Path(v['file'])
            if not universe_path.exists():
                universe_path = universes_dir / universe_path
                if not universe_path.exists():
                    raise FileNotFoundError(universe_path)
            parse_result: ParseResult = from_file(universe_path)
            universe: mk.Universe = parse_result.universe
            universe.rename(name=universe_name)
            universes[cell_name] = (universe, transformation)

    comps = {}

    for k, v in universes.items():
        u, _ = v
        cps = u.get_compositions()
        comps[k] = {c for c in cps}

    common = reduce(set.union, comps.values())
    envelopes.set_common_materials(common)
    cells_index = dict((cell.name(), cell) for cell in envelopes)

    for i, spec in universes.items():
        universe, transformation = spec
        universe.set_common_materials(common)
        cell = cells_index[i]
        cell.options = filter_dict(cell.options, "original")
        cell.options["FILL"] = {"universe": universe}
        if transformation is not None:
            if isinstance(transformation, tk.array):
                transformation = np.fromiter(map(float, iter(transformation)),
                                             dtype=np.double)
                transformation = mk.Transformation(
                    translation=transformation[:3],
                    rotation=transformation[3:],
                    indegrees=True,
                )
                cell.options["FILL"]["transform"] = transformation
            else:
                # TODO dvp: use parse results to implement this: there's an index of transformations
                raise NotImplementedError("""\
                    Specification of fill with a universe with a named transformation "fill=<...> ( number )" occurs. \
                    Only anonymous transformations are implemented.\
                    """)
    save_mcnp(envelopes, output, override)