Coder Social home page Coder Social logo

ubermag / ubermagtable Goto Github PK

View Code? Open in Web Editor NEW
6.0 6.0 2.0 1.97 MB

Python package for manipulating tabular data.

Home Page: https://ubermag.github.io

License: BSD 3-Clause "New" or "Revised" License

Python 100.00%
oommf mumax3 binder ubermag manipulating-tabular-data python pandas micromagnetics windows linux

ubermagtable's Introduction

ubermag

Marijan Beg1,2, Martin Lang2, Samuel Holt2,3, Swapneel Amit Pathak2,4, Ryan A. Pepper5, Thomas Kluyver6, Jeroen Mulkers7, Jonathan Leliaert7, and Hans Fangohr2,4,8

1 Department of Earth Science and Engineering, Imperial College London, London SW7 2AZ, UK
2 Faculty of Engineering and Physical Sciences, University of Southampton, Southampton SO17 1BJ, UK
3 Department of Physics, University of Warwick, Coventry CV4 7AL, UK
4 Max Planck Institute for the Structure and Dynamics of Matter, Luruper Chaussee 149, 22761 Hamburg, Germany
5 Research Software Group, University of Birmingham, Birmingham B15 2TT, UK
6 European XFEL GmbH, Holzkoppel 4, 22869 Schenefeld, Germany
7 Faculty of Sciences, Ghent University, Krijgslaan 281, S12, 9000 Ghent, Belgium
8 Center for Free-Electron Laser Science, Luruper Chaussee 149, 22761 Hamburg, Germany

Description Badge
Tests Build status
conda
Linting pre-commit.ci status
Code style: black
Releases PyPI version
Anaconda-Server Badge
Coverage codecov
Documentation Documentation
YouTube YouTube
Binder Binder
Platforms Platforms
Downloads Downloads
License License
DOI DOI

About

ubermag is a Python package, integrated with Jupyter, providing:

  • Meta package for Ubermag project,

  • Logging control in Ubermag packages.

It is available on Windows, MacOS, and Linux. It requires Python 3.8+.

Documentation

APIs and tutorials are available in the documentation. To access the documentation, use the badge in the table above.

Installation, testing, and upgrade

We recommend installation using conda package manager. Instructions can be found in the documentation.

Binder

This package can be used in the cloud via Binder. To access Binder, use the badge in the table above.

YouTube

YouTube video tutorials are available on the Ubermag channel.

Support

If you require support, have questions, want to report a bug, or want to suggest an improvement, please raise an issue in ubermag/help repository.

Contributions

All contributions are welcome, however small they are. If you would like to contribute, please fork the repository and create a pull request. If you are not sure how to contribute, please contact us by raising an issue in ubermag/help repository, and we are going to help you get started and assist you on the way.

Contributors:

License

Licensed under the BSD 3-Clause "New" or "Revised" License. For details, please refer to the LICENSE file.

How to cite

  1. M. Beg, M. Lang, and H. Fangohr. Ubermag: Towards more effective micromagnetic workflows. IEEE Transactions on Magnetics 58, 7300205 (2022).

  2. M. Beg, R. A. Pepper, and H. Fangohr. User interfaces for computational science: A domain specific language for OOMMF embedded in Python. AIP Advances 7, 56025 (2017).

  3. Marijan Beg, Martin Lang, Samuel Holt, Swapneel Amit Pathak, Ryan A. Pepper, Thomas Kluyver, Jeroen Mulkers, Jonathan Leliaert, and Hans Fangohr. ubermag: Meta package for Ubermag project. DOI: 10.5281/zenodo.3539495 (2022).

Acknowledgements

  • OpenDreamKit โ€“ Horizon 2020 European Research Infrastructure project (676541)

  • EPSRC Programme Grant on Skyrmionics (EP/N032128/1)

ubermagtable's People

Contributors

dependabot[bot] avatar fangohr avatar lang-m avatar marijanbeg avatar pre-commit-ci[bot] avatar rpep avatar samjrholt avatar sergii-mamedov avatar stibus avatar swapneelap avatar takluyver avatar ubermag-bot avatar vanessanehruji avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ubermagtable's Issues

Power spectral density (PSD)

Hello,
How can i calculate PSD analogous to this paper "Dynamics of skyrmionic states in confined helimagnetic nanostructures" (DOI: 10.1103/PhysRevB.95.014433)?
Thanks,

Possible bug(s) introduced in 0.8.3

Hi

There seem to be some problems with oommfodt 0.8.3. I have tested under Windows 10 Pro (native), docker, and a dual boot Ubuntu 18.10 using both python 3.7 and 3.6.
Running python -c "import oommfc; oommfc.test()" results in
============ 3 failed, 140 passed, 3 skipped, 5 deselected, 35 warnings in 249.23 seconds ============
For all combinations I tested, the errors were the same, and seem to arise from oommfodt. So today I downgraded to oommfodt 0.8.2 and everything is fine again.
============ 143 passed, 3 skipped, 5 deselected in 348.30 seconds ============

Regards,
Peter.

Details:
The first test in test_energy:

>       dt = oommfodt.read(odt_file, replace_columns=False)
E       TypeError: read() got an unexpected keyword argument 'replace_columns'

For Standard Problem 3, the error appears to be when calling the total energy
e.g:
querying "system":

System object 'stdprob3':
	hamiltonian: Exchange(A=1.5625e-10, name="exchange") + UniaxialAnisotropy(K1=100000.0, K2=0, u=(0, 0, 1), name="uniaxialanisotropy") + Demag(name="demag")
	dynamics   : 
	m          : <Field(mesh=Mesh(p1=(0, 0, 0), p2=(1e-07, 1e-07, 1e-07), cell=(6.25e-09, 6.25e-09, 6.25e-09), pbc=set(), name="mesh"), dim=3, name="field")>

but system.total_energy() returns

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-19-de510c4400e2> in <module>
----> 1 system.total_energy()

~\Anaconda3\lib\site-packages\oommfc\system.py in total_energy(self)
     24 
     25     def total_energy(self):
---> 26         return self.dt.tail(1)["E"][0]

~\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    765         key = com._apply_if_callable(key, self)
    766         try:
--> 767             result = self.index.get_value(self, key)
    768 
    769             if not is_scalar(result):

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   3116         try:
   3117             return self._engine.get_value(s, k,
-> 3118                                           tz=getattr(series.dtype, 'tz', None))
   3119         except KeyError as e1:
   3120             if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

the same for vortex.total_energy(), or flower.total_energy()

Failures output from oommfc.test() are:

================================== FAILURES ===================================
___________________________ TestDerive.test_energy ____________________________

self = <oommfc.tests.test_derive.TestDerive object at 0x00000230F62B21D0>

    def test_energy(self):
        hamiltonian = self.system.hamiltonian
>       assert isinstance(hamiltonian.exchange.energy, float)

Anaconda3\lib\site-packages\oommfc\tests\test_derive.py:26:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Anaconda3\lib\site-packages\micromagneticmodel\hamiltonian\energyproperties.py:16: in energy
    return self._data.energy
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <oommfc.data.Data object at 0x00000230F62B20F0>

    @property
    def energy(self):
        _dict = {"Demag": "Demag::Energy",
                 "Exchange": "UniformExchange::Energy",
                 "UniaxialAnisotropy": "UniaxialAnisotropy::Energy",
                 "Zeeman": "FixedZeeman::Energy",
                 "Hamiltonian": "RungeKuttaEvolve:evolver:Totalenergy"}
        td = oc.TimeDriver()
        td.drive(self.system, derive="energy")

        dirname = os.path.join(self.system.name, "")
        odt_file = max(glob.iglob("{}*.odt".format(dirname)),
                       key=os.path.getctime)

>       dt = oommfodt.read(odt_file, replace_columns=False)
E       TypeError: read() got an unexpected keyword argument 'replace_columns'

Anaconda3\lib\site-packages\oommfc\data.py:41: TypeError
---------------------------- Captured stdout call -----------------------------
2019/01/14 11:54: Running OOMMF (derive_tests\derive_tests.mif) ... Start: "C:/Users/pdunn/derive_tests/derive_tests.mif"
Options: -exitondone 1 -threads 2
Boxsi version 2.0a0
Running on: 
OS/machine: Windows NT/amd64
User: pdunn     PID: 6096
Number of threads: 2
Mesh geometry: 4 x 4 x 2 = 32 cells
Checkpoint file: C:/Users/pdunn/derive_tests/derive_tests.restart
Boxsi run end.
 <1> mmarchive killed
 <2> mmarchive killed
 <3> mmarchive killed
(6.0 s)
________________________________ test_stdprob3 ________________________________

    @pytest.mark.oommf
    def test_stdprob3():
        name = "stdprob3"

        # Remove any previous simulation directories.
        if os.path.exists(name):
            shutil.rmtree(name)

        # Function for initiaising the flower state.
        def m_init_flower(pos):
            x, y, z = pos[0]/1e-9, pos[1]/1e-9, pos[2]/1e-9
            mx = 0
            my = 2*z - 1
            mz = -2*y + 1
            norm_squared = mx**2 + my**2 + mz**2
            if norm_squared <= 0.05:
                return (1, 0, 0)
            else:
                return (mx, my, mz)

        # Function for initialising the vortex state.
        def m_init_vortex(pos):
            x, y, z = pos[0]/1e-9, pos[1]/1e-9, pos[2]/1e-9
            mx = 0
            my = np.sin(np.pi/2 * (x-0.5))
            mz = np.cos(np.pi/2 * (x-0.5))

            return (mx, my, mz)

        def minimise_system_energy(L, m_init):
            N = 16  # discretisation in one dimension
            cubesize = 100e-9  # cube edge length (m)
            cellsize = cubesize/N  # discretisation in all three dimensions.
            lex = cubesize/L  # exchange length.

            Km = 1e6  # magnetostatic energy density (J/m**3)
            Ms = np.sqrt(2*Km/oc.mu0)  # magnetisation saturation (A/m)
            A = 0.5 * oc.mu0 * Ms**2 * lex**2  # exchange energy constant
            K = 0.1*Km  # Uniaxial anisotropy constant
            u = (0, 0, 1)  # Uniaxial anisotropy easy-axis

            p1 = (0, 0, 0)  # Minimum sample coordinate.
            p2 = (cubesize, cubesize, cubesize)  # Maximum sample coordinate.
            cell = (cellsize, cellsize, cellsize)  # Discretisation.
            mesh = oc.Mesh(p1=(0, 0, 0), p2=(cubesize, cubesize, cubesize),
                           cell=(cellsize, cellsize, cellsize))

            system = oc.System(name=name)
            system.hamiltonian = oc.Exchange(A) + oc.UniaxialAnisotropy(K, u) + \
                oc.Demag()
            system.m = df.Field(mesh, value=m_init, norm=Ms)

            md = oc.MinDriver()
            md.drive(system)

            return system

        def energy_difference(L):
            vortex = minimise_system_energy(L, m_init_vortex)
            flower = minimise_system_energy(L, m_init_flower)

            return vortex.total_energy() - flower.total_energy()

>       cross_section = bisect(energy_difference, 8, 9, xtol=0.1)

..\test_stdprob3.py:74:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\..\..\scipy\optimize\zeros.py:287: in bisect
    r = _zeros._bisect(f,a,b,xtol,rtol,maxiter,args,full_output,disp)
..\test_stdprob3.py:72: in energy_difference
    return vortex.total_energy() - flower.total_energy()
..\..\system.py:26: in total_energy
    return self.dt.tail(1)["E"][0]
..\..\..\pandas\core\series.py:767: in __getitem__
    result = self.index.get_value(self, key)
..\..\..\pandas\core\indexes\base.py:3118: in get_value
    tz=getattr(series.dtype, 'tz', None))
pandas\_libs\index.pyx:106: in pandas._libs.index.IndexEngine.get_value
    ???
pandas\_libs\index.pyx:114: in pandas._libs.index.IndexEngine.get_value
    ???
pandas\_libs\index.pyx:162: in pandas._libs.index.IndexEngine.get_loc
    ???
pandas\_libs\hashtable_class_helper.pxi:958: in pandas._libs.hashtable.Int64HashTable.get_item
    ???
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

>   ???
E   KeyError: 0

pandas\_libs\hashtable_class_helper.pxi:964: KeyError
---------------------------- Captured stdout call -----------------------------
2019/01/14 11:57: Running OOMMF (stdprob3\stdprob3.mif) ... Start: "C:/Users/pdunn/Anaconda3/Lib/site-packages/oommfc/tests/test_files/stdprob3/stdprob3.mif"
Options: -exitondone 1 -threads 2
Boxsi version 2.0a0
Running on: 
OS/machine: Windows NT/amd64
User: pdunn     PID: 16168
Number of threads: 2
Mesh geometry: 16 x 16 x 16 = 4 096 cells
Checkpoint file: C:/Users/pdunn/Anaconda3/Lib/site-packages/oommfc/tests/test_files/stdprob3/stdprob3.restart
Boxsi run end.
 <1> mmarchive killed
 <2> mmarchive killed
(8.6 s)
2019/01/14 11:57: Running OOMMF (stdprob3\stdprob3.mif) ... Start: "C:/Users/pdunn/Anaconda3/Lib/site-packages/oommfc/tests/test_files/stdprob3/stdprob3.mif"
Options: -exitondone 1 -threads 2
Boxsi version 2.0a0
Running on: 
OS/machine: Windows NT/amd64
User: pdunn     PID: 13308
Number of threads: 2
Mesh geometry: 16 x 16 x 16 = 4 096 cells
Checkpoint file: C:/Users/pdunn/Anaconda3/Lib/site-packages/oommfc/tests/test_files/stdprob3/stdprob3.restart
Boxsi run end.
 <1> mmarchive killed
 <2> mmarchive killed
(6.3 s)
________________________________ test_stdprob5 ________________________________

    @pytest.mark.oommf
    def test_stdprob5():
        name = "stdprob5"

        # Remove any previous simulation directories.
        if os.path.exists(name):
            shutil.rmtree(name)

        # Geometry
        lx = 100e-9  # x dimension of the sample(m)
        ly = 100e-9  # y dimension of the sample (m)
        lz = 10e-9  # sample thickness (m)

        # Material (permalloy) parameters
        Ms = 8e5  # saturation magnetisation (A/m)
        A = 1.3e-11  # exchange energy constant (J/m)

        # Dynamics (LLG + STT equation) parameters
        gamma = 2.211e5  # gyromagnetic ratio (m/As)
        alpha = 0.1  # Gilbert damping
        ux = -72.35  # velocity in x direction
        beta = 0.05  # non-adiabatic STT parameter

        system = oc.System(name=name)
        mesh = oc.Mesh(p1=(0, 0, 0), p2=(100e-9, 100e-9, 10e-9),
                       cell=(5e-9, 5e-9, 5e-9))
        system.hamiltonian = oc.Exchange(A) + oc.Demag()

        def m_vortex(pos):
            x, y, z = pos[0]/1e-9-50, pos[1]/1e-9-50, pos[2]/1e-9
            return (-y, x, 10)

        system.m = df.Field(mesh, value=m_vortex, norm=Ms)

        md = oc.MinDriver()
        md.drive(system)

        system.dynamics += oc.Precession(gamma) + oc.Damping(alpha) + \
            oc.STT(u=(ux, 0, 0), beta=beta)

        td = oc.TimeDriver()
        td.drive(system, t=8e-9, n=100)

        mx = system.dt["mx"].values

>       assert -0.03 < mx.max() < 0
E       assert 1.397303195124719e-12 < 0
E        +  where 1.397303195124719e-12 = <built-in method max of numpy.ndarray object at 0x00000230FA44E990>()
E        +    where <built-in method max of numpy.ndarray object at 0x00000230FA44E990> = array([3.60159902e-17, 4.56456993e-13, 1.06732815e-12, 1.28478808e-12,\n       1.39730320e-12, 5.30105142e-13, 5.275923...631e-13, 4.60973702e-13,\n       4.63244432e-13, 4.58266329e-13, 4.50678307e-13, 4.49944833e-13,\n       4.53052926e-13]).max

..\test_stdprob5.py:56: AssertionError
---------------------------- Captured stdout call -----------------------------
2019/01/14 11:58: Running OOMMF (stdprob5\stdprob5.mif) ... Start: "C:/Users/pdunn/Anaconda3/Lib/site-packages/oommfc/tests/test_files/stdprob5/stdprob5.mif"
Options: -exitondone 1 -threads 2
Boxsi version 2.0a0
Running on: 
OS/machine: Windows NT/amd64
User: pdunn     PID: 12524
Number of threads: 2
Mesh geometry: 20 x 20 x 2 = 800 cells
Checkpoint file: C:/Users/pdunn/Anaconda3/Lib/site-packages/oommfc/tests/test_files/stdprob5/stdprob5.restart
Boxsi run end.
 <1> mmarchive killed
 <2> mmarchive killed
(6.1 s)
2019/01/14 11:58: Running OOMMF (stdprob5\stdprob5.mif) ... Start: "C:/Users/pdunn/Anaconda3/Lib/site-packages/oommfc/tests/test_files/stdprob5/stdprob5.mif"
Options: -exitondone 1 -threads 2
Boxsi version 2.0a0
Running on: 
OS/machine: Windows NT/amd64
User: pdunn     PID: 7160
Number of threads: 2
Mesh geometry: 20 x 20 x 2 = 800 cells
Checkpoint file: C:/Users/pdunn/Anaconda3/Lib/site-packages/oommfc/tests/test_files/stdprob5/stdprob5.restart
Boxsi run end.
 <1> mmarchive killed
 <2> mmarchive killed
 <3> mmarchive killed
(22.1 s)

Add units to the pandas DataFrame

At the moment there is no nice way of associating units to the pandas DataFrame columns. Before, we had an OOMMFodt class which stored units.

Abandon OOMMFodt class

This package should contain only a function which takes odt file and returns a Pandas dataframe.

ODT files are not read correctly when using magnetoelasticity extension

When adding the magnetoelastic term to my simulation, reading the generated ODT file would fail because the number of columns returned by ubermagtable.util.columns() would not match the number of columns in the data. Inspecting the code I figured that the YY_ prefix was not considered when splitting the column labels. This patch fixes the issue for me:

diff --git a/ubermagtable/table.py b/ubermagtable/table.py
index 8c4ffbc..6ab6113 100644
--- a/ubermagtable/table.py
+++ b/ubermagtable/table.py
@@ -272,11 +272,7 @@ class Table:
         >>> table = ut.Table.fromfile(odtfile, x='t')
 
         """
-        # MagnetoElastic OOMMF extension adds energy twice to data. The
-        # following lines are just a way to fix that in the data.
         cols = uu.columns(filename, rename=rename)
-        if 'MEL_E' in cols:
-            cols.insert(cols.index('E'), 'E')
 
         return cls(data=pd.DataFrame(uu.data(filename), columns=cols),
                    units=uu.units(filename, rename=rename), x=x)
diff --git a/ubermagtable/util/util.py b/ubermagtable/util/util.py
index f87ad86..b2765fb 100644
--- a/ubermagtable/util/util.py
+++ b/ubermagtable/util/util.py
@@ -43,8 +43,8 @@ oommf_dict = {'RungeKuttaEvolve:evolver:Total energy': 'E',
               'CGEvolve::Cycle count': 'cycle_count',
               'CGEvolve::Cycle sub count': 'cycle_sub_count',
               'CGEvolve::Energy calc count': 'energy_calc_count',
-              'CGEvolve:evolver:Energy calc count YY_FixedMEL::Energy':
-              'MEL_E',
+              'FixedMEL::Energy': 'MEL_E',
+              'FixedMEL:magnetoelastic:Energy': 'MEL_E',
               'SpinTEvolve:evolver:Total energy': 'E',
               'SpinTEvolve:evolver:Energy calc count': 'E_calc_count',
               'SpinTEvolve:evolver:Max dm/dt': 'max_dmdt',
@@ -183,7 +183,7 @@ def columns(filename, rename=True):
 
     if lines[0].startswith('# ODT'):  # OOMMF odt file
         cline = list(filter(lambda l: l.startswith('# Columns:'), lines))[0]
-        cline = re.split(r'Oxs_|Anv_|Southampton_|My_|UHH_', cline)[1:]
+        cline = re.split(r'Oxs_|Anv_|Southampton_|My_|YY_|UHH_', cline)[1:]
         cline = list(map(lambda col: re.sub(r'[{}]', '', col), cline))
         cols = list(map(lambda s: s.strip(), cline))
         cols_dict = oommf_dict

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.