Takes a Lattice object and transforms it.
        :param lattice: Lattice
        :return:
499278
def transform_lattice(self, lattice):
        # type: (Lattice) -> Lattice
        
        return Lattice(np.matmul(lattice.matrix, self.P))
318968
def transform(self, X):
        

        for i, col in enumerate(X.columns):
            X.loc[:, col] = self._transform_col(X[col], i)

        return X
943532
def transform_array(rot_mtx,vec_array):

    '''

    '''

    return map( lambda x,m=rot_mtx:transform(m,x), vec_array )
391209
def apply_transformation(self, structure, return_ranked_list=False):
        

        if not structure.is_ordered:
            raise ValueError("Create an ordered approximation of "
                             "your  input structure first.")

        # retrieve order parameters
        order_parameters = [MagOrderParameterConstraint.from_dict(op_dict)
                            for op_dict in self.order_parameter]
        # add dummy species on which to perform enumeration
        structure = self._add_dummy_species(structure, order_parameters)

        # trivial case
        if structure.is_ordered:
            structure = self._remove_dummy_species(structure)
            return [structure] if return_ranked_list > 1 else structure

        enum_kwargs = self.enum_kwargs.copy()

        enum_kwargs["min_cell_size"] = max(
            int(self.determine_min_cell(structure)),
            enum_kwargs.get("min_cell_size", 1)
        )

        if enum_kwargs.get("max_cell_size", None):
            if enum_kwargs["min_cell_size"] > enum_kwargs["max_cell_size"]:
                warnings.warn("Specified max cell size ({}) is smaller "
                              "than the minimum enumerable cell size ({}), "
                              "changing max cell size to {}".format(enum_kwargs["max_cell_size"],
                                                                    enum_kwargs["min_cell_size"],
                                                                    enum_kwargs["min_cell_size"]))
                enum_kwargs["max_cell_size"] = enum_kwargs["min_cell_size"]
        else:
            enum_kwargs["max_cell_size"] = enum_kwargs["min_cell_size"]

        t = EnumerateStructureTransformation(**enum_kwargs)

        alls = t.apply_transformation(structure,
                                      return_ranked_list=return_ranked_list)

        # handle the fact that EnumerateStructureTransformation can either
        # return a single Structure or a list
        if isinstance(alls, Structure):
            # remove dummy species and replace Spin.up or Spin.down
            # with spin magnitudes given in mag_species_spin arg
            alls = self._remove_dummy_species(alls)
            alls = self._add_spin_magnitudes(alls)
        else:
            for idx, _ in enumerate(alls):
                alls[idx]["structure"] = self._remove_dummy_species(alls[idx]["structure"])
                alls[idx]["structure"] = self._add_spin_magnitudes(alls[idx]["structure"])

        try:
            num_to_return = int(return_ranked_list)
        except ValueError:
            num_to_return = 1

        if num_to_return == 1 or not return_ranked_list:
            return alls[0]["structure"] if num_to_return else alls

        # remove duplicate structures and group according to energy model
        m = StructureMatcher(comparator=SpinComparator())
        key = lambda x: SpacegroupAnalyzer(x, 0.1).get_space_group_number()
        out = []
        for _, g in groupby(sorted([d["structure"] for d in alls],
                                   key=key), key):
            g = list(g)
            grouped = m.group_structures(g)
            out.extend([{"structure": g[0],
                         "energy": self.energy_model.get_energy(g[0])}
                        for g in grouped])

        self._all_structures = sorted(out, key=lambda d: d["energy"])

        return self._all_structures[0:num_to_return]
375119
def transform_df(self, df):
        
        if (len(df) == 0) or (len(self) == 0):
            return df

        # Each scale transforms the columns it understands
        for sc in self:
            df = sc.transform_df(df)
        return df
656337
def _convert_template_option(template):
    '''
    '''

    option = {}
    extraction_method = template.get('extraction_method')
    if extraction_method == 'guess':
        option['guess'] = True
    elif extraction_method == 'lattice':
        option['lattice'] = True
    elif extraction_method == 'stream':
        option['stream'] = True

    option['pages'] = template.get('page')
    option['area'] = [round(template['y1'], 3), round(template['x1'], 3), round(template['y2'], 3), round(template['x2'], 3)]

    return option
1268003
def _transform(self, *transforms):
        
        sequence = None
        for transform in transforms:
            if sequence:
                sequence = Sequence(sequence, transform=transform)
            else:
                sequence = Sequence(self, transform=transform)
        return sequence
1111425
def transform(self, col):
        
        out = pd.DataFrame()
        out[self.col_name] = self.safe_datetime_cast(col)
        out[self.col_name] = self.to_timestamp(out)

        return out
382194
def inverse(self):
        
        inv_rotation = self.rotation.T
        inv_translation = np.dot(-self.rotation.T, self.translation)
        return RigidTransform(inv_rotation, inv_translation,
                              from_frame=self._to_frame,
                              to_frame=self._from_frame)
14581
def from_dict(cls, d, fmt=None):
        
        if fmt == "abivars":
            from pymatgen.io.abinit.abiobjects import structure_from_abivars
            return structure_from_abivars(cls=cls, **d)

        lattice = Lattice.from_dict(d["lattice"])
        sites = [PeriodicSite.from_dict(sd, lattice) for sd in d["sites"]]
        charge = d.get("charge", None)
        return cls.from_sites(sites, charge=charge)
1301097
def lattice_array_to_unit_cell(lattice_array):
    """"""
    cell_lengths = np.sqrt(np.sum(lattice_array**2, axis=0))
    gamma_r = np.arccos(lattice_array[0][1] / cell_lengths[1])
    beta_r = np.arccos(lattice_array[0][2] / cell_lengths[2])
    alpha_r = np.arccos(
        lattice_array[1][2] * np.sin(gamma_r) / cell_lengths[2]
        + np.cos(beta_r) * np.cos(gamma_r)
        )
    cell_angles = [
        np.rad2deg(alpha_r), np.rad2deg(beta_r), np.rad2deg(gamma_r)
        ]
    return np.append(cell_lengths, cell_angles)
917422
def _set_lattice(self):
        

        unit = self._values[0]
        if unit == 'alat':
            if not self._tags['celldm(1)']:
                print("celldm(1) has to be specified when using alat.")
                sys.exit(1)
            else:
                factor = self._tags['celldm(1)']  # in Bohr
        elif unit == 'angstrom':
            factor = 1.0 / Bohr
        else:
            factor = 1.0

        if len(self._values[1:]) < 9:
            print("CELL_PARAMETERS is wrongly set.")
            sys.exit(1)

        lattice = np.reshape([float(x) for x in self._values[1:10]], (3, 3))
        self._tags['cell_parameters'] = lattice * factor
1135048
def move_to_device(obj, cuda_device: int):
    
    if cuda_device < 0 or not has_tensor(obj):
        return obj
    elif isinstance(obj, torch.Tensor):
        return obj.cuda(cuda_device)
    elif isinstance(obj, dict):
        return {key: move_to_device(value, cuda_device) for key, value in obj.items()}
    elif isinstance(obj, list):
        return [move_to_device(item, cuda_device) for item in obj]
    elif isinstance(obj, tuple):
        return tuple([move_to_device(item, cuda_device) for item in obj])
    else:
        return obj
677195
def to_nibabel(image):
    
    if image.dimension != 3:
        raise ValueError('Only 3D images currently supported')

    import nibabel as nib
    array_data = image.numpy()
    affine = np.hstack([image.direction*np.diag(image.spacing),np.array(image.origin).reshape(3,1)])
    affine = np.vstack([affine, np.array([0,0,0,1.])])
    affine[:2,:] *= -1
    new_img = nib.Nifti1Image(array_data, affine)
    return new_img
199037
def _get_lattice_parameters(lattice):
    

    return np.array(np.sqrt(np.dot(lattice.T, lattice).diagonal()),
                    dtype='double')
715181
def _independent_lattice(self, shape, lattice=None):
        
        I, J = shape

        if lattice is not None:
            end_I = min(I, max(lattice[..., 3])) - 1
            end_J = min(J, max(lattice[..., 4])) - 1
            unvisited_nodes = deque([(i, j, s)
                                     for i in range(end_I)
                                     for j in range(end_J)
                                     for s in self._start_states])
            lattice = lattice.tolist()
        else:
            lattice = []
            unvisited_nodes = deque([(0, 0, s) for s in self._start_states])
        lattice += _grow_independent_lattice(self._transitions, 
                                             self.n_states, (I, J), 
                                             unvisited_nodes)
        lattice = np.array(sorted(lattice), dtype='int64')
        return lattice
175437
def from_pb(cls, pb):
        
        obj = cls._from_pb(pb)
        obj._pb = pb
        return obj