Esempio n. 1
0
    def test_SaveAndLoad(self):
        H, n = Hamiltonians.longrange(7)

        # test saving and loading by both file name
        # and file object
        f = 'save_test.msc'

        with self.subTest(m='save'):
            H.save(f)

        with self.subTest(m='load_str'):
            Hf = do.Load(f)
            self.assertEqual(H, Hf)

            # also make sure that the generated PETSc matrix
            # works
            r, msg = check_dnm_np(Hf, n)
            self.assertTrue(r, msg=msg)

        with self.subTest(m='load_file'):

            with open(f, 'rb') as fd:
                Hf = do.Load(fd)
                self.assertEqual(H, Hf)

                # also make sure that the generated PETSc matrix
                # works
                r, msg = check_dnm_np(Hf, n)
                self.assertTrue(r, msg=msg)

        COMM_WORLD.barrier()
        if COMM_WORLD.rank == 0:
            remove(f)
Esempio n. 2
0
    def save(self, fout):
        """
        Save the MSC representation of the operator to disk.
        Can be loaded again through :class:`Load`.

        Parameters
        ----------
        fout : str
            The path to the file to save the operator in.
        """

        # only process 0 should save
        if COMM_WORLD.rank == 0:

            # The file format is:
            # L,nterms,masks,signs,coefficients
            # where each is just a binary blob, one after the other.

            # do this first so that we haven't already created the file if
            # it fails for some reason
            msc = self.get_MSC()

            with open(fout, mode='wb') as f:

                # write the chain length to the file. This is the only parameter
                # that we save other than the MSC representation.
                L = self.L
                if L is None:
                    raise ValueError('L must be set before saving to disk.')

                # cast it to the type that C will be looking for
                int_t = msc.dtype[0].type
                L = int_t(L)

                f.write(L.tobytes())

                # write out the length of the MSC representation
                size = int_t(msc.size)
                f.write(size.tobytes())

                f.write(msc['masks'].tobytes())
                f.write(msc['signs'].tobytes())
                f.write(msc['coeffs'].tobytes())

        COMM_WORLD.barrier()