Giter Club home page Giter Club logo

magpylib's Introduction

Warning

Version 5 introduces critical breaking changes with, among others, the move to SI units. We recommended to pin your dependencies to magpylib>=4.5<5 until you are ready to migrate to the latest version! (see details)


Magpylib is a Python package for calculating 3D static magnetic fields of magnets, line currents and other sources. The computation is based on explicit expressions and is therefore extremely fast. A user friendly API enables convenient positioning of sources and observers.

Installation

Install from PyPI using pip

pip install magpylib

Install from conda forge using conda

conda install -c conda-forge magpylib

Magpylib supports Python3.8+ and relies on common scientific computation libraries Numpy, Scipy, Matplotlib and Plotly. Optionally, Pyvista is recommended as graphical backend.

Resources

Quickstart

Here is an example on how to use Magpylib.

import magpylib as magpy

# Create a Cuboid magnet with sides 1,2 and 3 cm respectively, and a polarization
# of 1000 mT pointing in x-direction.
cube = magpy.magnet.Cuboid(
    polarization=(1, 0, 0),  # in SI Units (T)
    dimension=(0.01, 0.02, 0.03),  # in SI Units (m)
)

# By default, the magnet position is (0,0,0) and its orientation is the unit
# rotation (given by a scipy rotation object), which corresponds to magnet sided
# parallel to global coordinate axes.
print(cube.position)  # --> [0. 0. 0.]
print(cube.orientation.as_rotvec())  # --> [0. 0. 0.]

# Manipulate object position and orientation through the respective attributes,
# or by using the powerful `move` and `rotate` methods.
cube.move((0, 0, -0.02))# in SI Units (m)
cube.rotate_from_angax(angle=45, axis="z")
print(cube.position)  # --> [0. 0. -0.02]
print(cube.orientation.as_rotvec(degrees=True))  # --> [0. 0. 45.]

# Compute the magnetic B-field in units of T at a set of observer positions. Magpylib
# makes use of vectorized computation. Hand over all field computation instances,
# e.g. different observer positions, at one function call. Avoid Python loops !!!
observers = [(0, 0, 0), (0.01, 0, 0), (0.02, 0, 0)]  # in SI Units (m)
B = magpy.getB(cube, observers)
print(B.round(2))  # --> [[-0.09 -0.09  0.  ]
#                         [ 0.   -0.04  0.08]
#                         [ 0.02 -0.01  0.03]]  # in SI Units (T)

# Sensors are observer objects that can have their own position and orientation.
# Compute the H-field in units of A/m.
sensor = magpy.Sensor(position=(0, 0, 0))
sensor.rotate_from_angax(angle=45, axis=(1, 1, 1))
H = magpy.getH(cube, sensor)
print(H.round())  # --> [-94537. -35642. -14085.]  # in SI Units (A/m)

# Position and orientation attributes of Magpylib objects can be vectors of
# multiple positions/orientations referred to as "paths". When computing the
# magnetic field of an object with a path, it is computed at every path index.
cube.position = [(0, 0, -.02), (1, 0, -.02), (2, 0, -.02)]  # in SI Units (m)
B = cube.getB(sensor)
print(B.round(2))  # --> [[-0.12 -0.04 -0.02]
#                         [ 0.   -0.    0.  ]
#                         [ 0.   -0.    0.  ]] # in SI Units (T)

# When several objects are involved and things are getting complex, make use of
# the `show` function to view your system through Matplotlib, Plotly or Pyvista backends.
magpy.show(cube, sensor, backend="pyvista")

More details and other important features are described in detail in the Documentation. Key features are:

  • Collections: Group multiple objects for common manipulation
  • Complex shapes: Create magnets with arbitrary shapes
  • Graphics: Styling options, graphic backends, animations, and 3D models
  • CustomSource: Integrate your own field implementation
  • Direct interface: Bypass the object oriented interface (max speed)

How can I cite this library ?

We would be happy if you give us credit for our efforts. A valid bibtex entry for the 2020 open-access paper would be

@article{ortner2020magpylib,
  title={Magpylib: A free Python package for magnetic field computation},
  author={Ortner, Michael and Bandeira, Lucas Gabriel Coliado},
  journal={SoftwareX},
  volume={11},
  pages={100466},
  year={2020},
  publisher={Elsevier}
}

A valid software citation could be

@software{magpylib,
    author = {{Michael-Ortner et al.}},
    title = {magpylib},
    url = {https://magpylib.readthedocs.io/en/latest/},
    version = {5.0.1},
    date = {2023-06-25},
}

magpylib's People

Contributors

alexboiboi avatar eposs74 avatar feldnerd avatar fslanovc avatar fspacheco avatar jcafhe avatar laikh avatar lgtm-com[bot] avatar lucasgcb avatar luizenger avatar ortnermichael avatar pre-commit-ci[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

magpylib's Issues

Final Library Structure - and tool tips

Is there a better way for initialization of modules to achieve tool tips as desired?
This should work nicely for Spyder, Jupyter and Pycharm

Current structure:
.
├── current
│   └── __init__.py
├── __init__.py
├── _lib
│   ├── classes
│   │   ├── base.py
│   │   ├── collection.py
│   │   ├── currents.py
│   │   └── magnets.py
│   ├── fields
│   │   ├── Current_CircularLoop.py
│   │   ├── Current_Line.py
│   │   ├── Moment_Dipole.py
│   │   ├── PM_Cube.py
│   │   ├── PM_Cylinder.py
│   │   └── PM_Sphere.py
│   ├── mathLibPrivate.py
│   └── mathLibPublic.py
├── magnet
│   └── __init__.py
├── math
│   └── __init__.py
├── README.md
└── RotateExample.py

Documentation Webpage

  • Update once V1.0 is ready

  • maybe include graphics in docstrings on webpage

Michael: this can be part of the documentation pdf
Lucas: It may be possible on the webpage Doku


DOKUMENTATION - HTML - PDF

  • Docstrings -> HTML

  • Possible autodoc tools for Docstrig integration and more:

  • Possible Hosting sites for autodocs (update automatically):

  • documentation on webpage

  • Maybe combine auto-generated HTML with additional features like graphics

  • detailed pdf documentation

    • 1. Programming Class descriptions
    • 2. Mathematical package doku how is it structured (Coordinate Systems, Translations + Rotations, ...)
    • 3. Phys doku: how are fields calculated, collect the papers where formulas can be found and upload or generate a document with all calcuations
    • 4. Physics Plausibility checks:
      • a. compare to FEM
      • b. check precision/convergence of diametral cylinder class
      • c. characterize demagnetization

Windows requires extra work for multiprocessing

https://docs.python.org/3/library/multiprocessing.html#examples

As per given, Windows handles creating of different processes differently.

When users make code they want to use with multiprocessing, if they are on Linux:
Linux code is valid:

import time
from magpylib import source

def getPos():
        return [2,2,2]

a = source.magnet.Box(mag=(2,3,5),dim=(2,2,2))
start = time.time()
listOfPos=[getPos() for a in range(5000)] # 5000 positions
result = a.getBsweep(listOfPos,multiprocessing=True)
end = time.time()
print(end - start)
print(result)

If they are on Windows however, the following guard is necessary to avoid lock up:

import time
from magpylib import source

def getPos():
        return [2,2,2]
def main():
        a = source.magnet.Box(mag=(2,3,5),dim=(2,2,2))
        start = time.time()
        listOfPos=[getPos() for a in range(5000)] # 5000 positions
        result = a.getBsweep(listOfPos,multiprocessing=True)
        end = time.time()
        print(end - start)
        print(result)

from multiprocessing import freeze_support # windows support
if __name__ == '__main__':  #################### These two define 
    freeze_support() ########################### the Windows OS
    main()

Cube vs Box class

  • Change name of Cube to Box
  • Fix all dependencies e.g. docstrings etc

CUBE CORNER PROBLEM !!!!

Add fundamental tests for the lines:

pm = magpy.source.magnet.Box(mag=[0,0,1000],dim=[0.5,0.1,1],pos=[.25,.55,-1111])
print(pm.getB([.5,.5,5]))

this returns NAN NAN NAN!!!!!

MULTICORE GETB

  • Multi getB restructure ( #69 )
  • At first make this a new method, then later integrate with getB functions as option
  • input vector of positions
  • introduce use of parallel computing to calculate points in parallel
  • return vector of fields

Check Input Type - "debug Mode"

  • Proper checking of inputs and input formats

Make sure invalid inputs will be notified
Make toolbox foolproof


  • Check performance reduction of input type checking - input type checking should not decrease performance

  • Consider feasibility of Debug mode with asserts
    • proper error handling, braking of program and return msg
    • should negate performance impact as it disables checks outside of debug mode

fix PUBLIC PAGES

  • webpage
    • check git hub pages possibility
    • wordpress as alternative
    • NO ADVERTISEMENT
  • Git hub readme
  • Read the docs - use Markdown
    • check out alternatives.

Introduce SENSOR class

The idea is to introduce a new class type that mimics a sensor with position and orientation that can determine the field from existing source objects.
This has the advantage that sensor positions and especially rotations must not be implemented b the user.

Problems that we cant fix

  • 3d plot z-order problems in display system, specifically when bounding boxes are overlapping

  • in current version of Spyder tool tips sometimes do not display.

    • start in project mode
    • wait till Spyder has caught up

rename CoR kwarg as "anchor"

rename "CoR" as "anchor"

  • replace name in all methods and classes
  • replace name in all doc strings
  • any other issues?

Guideline for adding new sources

  • REVIEW GUIDELINE

what has to be done when a completely new source class is added
point out all positions in the code where one must do something :)

DOCSTRING

  • docstrings format to numpy native

  • Fix outdated examples in docstrings

  • Check alternatives for placement of docstrings (i.e. keep them in an external file)

Lucas: not a good practice as far as guidelines go,
while feasible in external .txt file + making a tool for release


  • getB - how to avoid multiple times the same docstring (in each case there is only one line different)

Lucas: solution depends entirely on tool being used to analyze docstring placement,
ctrl+c ctrl+v seems to be the universal solution so far.
Could still explore more of class inheritance and overriding for this, though it
would take major refactoring of existing code.

Installation of magpylib for users

  • REVIEW INSTALLATION TIPS

How to best distribute the library?

  • download from GITHUB or webpage and use as separate "folder" in each program
    • no so practical
    • no problems with backwards compatibility
  • integration in pip
    • backwards compatibility problems?
  • integration with Python package index (PyPI)
    • easy for all users
    • keeping it running over the years?
  • add to conda cloud

improve displaySystem()

  • Give an option to display a motion.

    • Is it worth the effort?
  • Display current direction and magnetization direction

    • arrows on current lines
    • put thin axes "through" magnets that indicate the magnetization vector
  • Introduce Markers of positions

    • e.g. to indicate anchor points
    • by default introduce marker at center ?
  • fix plt.cm package use

    • is this just some outdated code?

review displaySystem()

  • dipole sizes may vary (relative definition to SYSSIZE)
    • If dipoles get initialized at expanding coordinates, their size will vary.
  • Coose better color function and color assignement

Testing sources with different getB positions

  1. Test all 8 quadrants for each source (INSIDE AND OUTSIDE of magnet)
  2. UNDERSTAND WHAT WE WANT TO TEST: SPECIAL CASES (LINES, CORNERS, SURFACES, ...)

pm = magpy.source.magnet.Box(mag=[0,0,1000],dim=[0.5,0.1,1],pos=[.25,.55,-1111])
print(pm.getB([.5,.5,5]))
this returns NAN NAN NAN!!!!!

After testing structure for all the getBs are set up, just define the quadrants to reinforce robustness.

image

LICENCE

figure out the license structure

  • Contributor's License details
  • Repository License

Implement Functional IO Testing Harness

  • Automated unit tests within test suites for development
    • Very brief "Black/White Box" (check if input -> output always) testing scripts for each function
    • Will allow us to make code modification experiments freely (while after performance, etc) as it notifies inconsistencies in behavior
      • Could also be useful in implementing new functions since we know what we want
      • Counts as documentation! Usually only have to write once, add more when needed
    • Automated Tools for open projects run the tests, hold onto clearly broken updates + let us know

Webpage

simple static webpage only with links to GitHub and Doku

NO COMMERCIALS !!!!

class and method arguments - args VS kwargs

At class init all args are kwargs for class methods they are not.

Does it make sense to make all args kwargs?

  • better for understanding
  • worse for shortening and simplifying codes

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.