Module Breakdown¶
mango.mango module¶
Call Flow Diagram¶
Main processing
Parallel processing
Mango.
A program to simulate magnetic nanoparticles in a non magnetic fluid. Developed by James Cook 2015-2019 with supervison by Lorenzo Stella.
mango.arguments module¶
- 
class 
mango.arguments.SmartFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]¶ Bases:
argparse.HelpFormatterSmart help formatter.
Allows for splitting the help over multiple lines by starting help with ‘R|’
- 
mango.arguments.column_manip(column_var, files)[source]¶ Create a list of plots to be made.
TODO cleanup
- Parameters
 column_var (list) – list parsed from user input eg. [“time kinetic[5,:,3] + avtrans_pot / - avmag_pot[:100]”, “time kinetic”]
files (dict) – files to create
- Returns
 plot_store (dict) – plots to create
files (dict) – files to create
- 
mango.arguments.filenaming(var, flg, run=1)[source]¶ File naming.
Avoid overwriting files etc.
- Parameters
 flg (var,) – class variable and flag instances
- 
mango.arguments.list_add_arguments(self, k)[source]¶ Parse arguments from dictionary.
- Parameters
 k (OrderedDict) – Dictionary of keywords and defaults
- 
mango.arguments.parse(argparse, opts={})[source]¶ Parse user input.
- Parameters
 argparse (bool) – Is argparse used?
opts (dict) – dict of arguments if argparse isn’t used
- Returns
 parsing – instance of variables
- Return type
 instance
- 
mango.arguments.parse_in(k={'keywords'})[source]¶ Argparse function.
- Parameters
 k (Ordereddict) – dictionary of available commands
- Returns
 parser – argparse parser instance
- Return type
 instance
- 
mango.arguments.restart_in(parsing)[source]¶ Get data from run to be restarted.
- Parameters
 parsing (instance) – argparse parsing instance
- Returns
 variables – class instance of all variables to be used
- Return type
 instance
- 
mango.arguments.setdefaults(parsing, default_val)[source]¶ Set default values for variables that weren’t in input.
- Parameters
 parsing (instance) – ArgumentParser instance
default_val (dict) – Default Values
- Returns
 parsing – ArgumentParser instance
- Return type
 instance
mango.boundaries module¶
- 
class 
mango.boundaries.periodic[source]¶ Bases:
objectPeriodic Boundary Conditions.
The positions are only wrapped at the end of a single step because the values are not used until they are saved to file. The distances are always wrapped because they are used during a single step.
- 
DBG¶ 
- 
boxsize¶ 
- 
dist¶ 
- 
distance(pos)[source]¶ Provide a distance matrix for both periodic and non periodic conditions.
- Returns
 dist (array) – All pairs distances n(n+1)/2 by 3
dist_mat (array) – distance matrix n by n only ever used as its inverse so calculated as inverse
- 
getdist¶ 
- 
pbc¶ 
- 
posones¶ 
- 
setup(boxsize, pbc, pos, sigma, tri)[source]¶ Set up periodic conditions.
Not using __init__ for this allows more decorator flexibility
- 
sigma¶ 
- 
sigma_err¶ 
- 
tri¶ 
- 
wrap¶ 
- 
 
mango.constants module¶
- 
mango.constants.CPU()[source]¶ Get number of cores available.
- Returns
 processors – number of processors
- Return type
 int
- 
mango.constants.EMPI()[source]¶ Test whether MPI entry point os used.
- Returns
 MPI.COMM_WORLD (comm) – All processors communicator
MPI (module) – MPI module from mpi4py or class
- 
mango.constants.GT()[source]¶ Get terminal information.
- Returns
 Terminal (instance) – Blessings terminal class instance
Terminal info (dict) – Terminal info
- 
mango.constants.INTTERM()[source]¶ Check for interactive terminal.
- Returns
 interactive – Is environment interactive?
- Return type
 bool
- 
mango.constants.LCT()[source]¶ Construct Levi-Civita Tensor.
- Returns
 eijk – Levi-Civita tensor
- Return type
 array
- 
mango.constants.MPL()[source]¶ Test matplotlib is functioning.
- Returns
 mpl – Can we use matplotlib?
- Return type
 bool
- 
mango.constants.PROF()[source]¶ Test for code profiling.
- Returns
 profile – Is profile in argv?
- Return type
 bool
- 
mango.constants.UCODE(t)[source]¶ Set up unicode strings.
- Returns
 ustr (class) – Unicode chars store
uc (bool) – Is environment unicode?
- 
mango.constants.UIP()[source]¶ Test for Jupyter Notebooks.
- Returns
 using_IP – Are we using Jupyter notebooks?
- Return type
 bool
- 
mango.constants.asciistring(length)[source]¶ Get a list of characters of desired length.
Current max is 26 characters
- Parameters
 length (int) – number of characters to return
- Returns
 - Return type
 str of length specified
- 
class 
mango.constants.bin_count(**argd)[source]¶ Bases:
objectFast ufunc.at.
bincount OR ufunc.at but ufunc.at is slower: https://github.com/numpy/numpy/issues/5922 Much faster even with the manipulation needed for bincount
pass flattened arrays in eg arr.ravel()
- 
leng¶ 
- 
shape¶ 
- 
 
- 
mango.constants.boolconvert(boolean)[source]¶ Convert strings to bool correctly.
- Parameters
 boolean (str) –
- Returns
 - Return type
 bool
- 
class 
mango.constants.const[source]¶ Bases:
objectConstants and version number.Internal UnitsMaintime: 1e-12 [s]
length: 1e-6 [cm]
mass: 1e-18 [g]
Derivedenergy unit: 1e-6 [erg]
temperature unit: 1e0 [K]
magnetic induction: 1e6 [gauss]
magnetisation: 1e-12 [emu]
force: 1 [g/cm.s^2]
- 
mango.constants.nestedDict()[source]¶ Nested Dictionaries.
In principle this creates an infinitely deep nested dictionary
eg. dict_name[“key”][“key”][“key”]= value
each key can have sub keys and because defaultdict creates the key if it doesn’t exist this is all that is needed
mango.debug module¶
- 
class 
mango.debug.debug(aspects=None)[source]¶ Bases:
objectDebugging helper.
Aspects are provided as list of arguments which are decorators of the function to debug.
eg.
set(['io','core'])the flag TT will print out the run time for each function only
Inspiration from https://wiki.python.org/moin/PythonDecoratorLibrary#Controllable_DIY_debug
- 
mango.debug.set_debug()[source]¶ Allow for setting debugging from the command line.
eg.
--debug [ io core ]
mango.errors module¶
- 
exception 
mango.errors.ExitQuiet[source]¶ Bases:
mango.errors.QuietExit Program Quietly Exception.
- 
class 
mango.errors.Reprinter[source]¶ Bases:
objectRewrite terminal output using ANSI escape sequences.
- 
class 
mango.errors.error(op=<built-in function open>)[source]¶ Bases:
mango.errors._stringsError class.
Handles error printing to the terminal
All errors are written to stderr
mango.hdf5io module¶
- 
mango.hdf5io.backup(location, name)[source]¶ Backup useful variables.
- Parameters
 location (node) –
name (str) –
- 
mango.hdf5io.load(filename, location=None, chunk=None, keylist=False)[source]¶ Load hdf5 datasets in (hopefully) the same format.
- Parameters
 filename (string) – file to load
location – location of data within file eg: “data/movement/position”
- 
mango.hdf5io.save(filename, data, compression=None, datalength=None, append={}, name='data')[source]¶ Allow incremental saving of data to hdf5 files.
Wrapping all information to be stored in a dictionary gives much more customisation of storage names and avoids overwiting data
- Parameters
 filename (string) – filename for hdf5 file
data (nearly anything) – data to be stored currently works for most types, standard numpy arrays, tuples, lists and dictionaries.
compression (tuple or list) – Compression is set by name, such as blosc and compression level eg. (blosc,9) see the manual for your version of pytables for the full list.
datalength (int) – The length of the array being stored (or a rough guess) specfiy to improve file I/O speeds especially for appending
append (set) – For anything to be saved incrementally a set of variable names needs to be provided. The append list works for any entry and all sub entries eg. append=set([“energy”]) would apply to both ./energy and ./energy/*. Attributes such as single number values not in arrays will always be overwritten
name (string) – This is not used for dictionaries. Otherwise the default name is data.
mango.io module¶
- 
class 
mango.io.Data[source]¶ Bases:
object- 
append= {'forces', 'iter_time', 'magnetic_field', 'magnetisation', 'momentum', 'neel_relaxation', 'position'}¶ 
- 
 
- 
mango.io.file_write(data_array, f, timescale, directory, run, flg, mmag, boxsize)[source]¶ Write a file of energy changes or momenta changes.
- Parameters
 data_array (np.array) – shape of (x, y, 15) for momenta or (x, y, 4) for energy
f (string) – Magnetisation “M” or Energy “E”
run (int) – run number
- 
mango.io.getvar()[source]¶ Get variables from existing run.
Run with
mango_vars -f [Files…] -v [VARS….]
- 
mango.io.inputregen(file=None, outfile=None, explanation=False)[source]¶ Generate an input file based of an existing results file.
- Parameters
 (or argv[1]) (file) – Data file location
(or argv[2]) (outfile) – Input file name (optional, defaults to ‘Input’)
- 
class 
mango.io.read_data(fname, rtype=None, xyzpp=False)[source]¶ Bases:
mango.io.DataReads data in for post processing.
Improvements * Only read in data required rather than all data - Works for hdf5 files
- 
lengthcheck()[source]¶ Check which row number is the last iteration.
Redundency check to make sure the last used row is the last row
- 
read(obj=None, fname=None, restart=False, lengthcheck=False, keylist=False, chunk=None, xyzpp=False)[source]¶ Read in pickle and hdf5 outputs.
- Parameters
 obj (string) – object to be read in
fname (string) – file to be read in
restart (bool) – Is read in to restart run
lengthcheck (bool) – Get lenth of position data and last iteration
- 
txtread(obj, *args)[source]¶ Read in text file output.
Not restartable
- Parameters
 obj (string) – type of data to be read in, Variables “vars”, Data “data”
- 
xyzppread(obj=None, *args)[source]¶ Post process from xyz file.
Requires associated <filename>.var file with variables needed for post processing also needs to include the variable columns with the xyz column variable names.
e.g. mass 1.111 radius 1.23e-4 columns position,velocity,force
Only internal variable names currently supported
- 
 
- 
mango.io.restart_gen(file=None, reps=None, outfile=None)[source]¶ Restart generator.
Run with
mango_restartregen [file] [reps] [outfile <optional>]
- 
mango.io.txt_data(moldata_dict, no_mol)[source]¶ Write output as textfile.
Specify “txt”
- Parameters
 moldata_dict (dict) – dictionary of data to be written
no_mol (int) – Number of Moelcules
- 
class 
mango.io.write_data(var, flg)[source]¶ Bases:
mango.io.DataWriting all calculated data to file.
- 
mango.io.xyz_write(xyz_mol_data, timescale, directory, run, flg, mmag, boxsize)[source]¶ Write an extended xyz file.
[n, number of atoms] [timestep] [current time] [flags...] mol[0] [position x y z] [momentum x y z] [magnetisation x y z] [forces x y z] . . mol[n -1]...
- Parameters
 xyz_mol_data (np.array) – array of data in the form [pos(xyz) mom(xyz) mag(xyz) force(xyz)] for each molecule
timescale (np.array) – timescale list
directory (string) – save directory
run (int) – run number
flg (class) – class of flags flags used - pbc, mag_sw, align
mmag (float) – Magnetic saturation * volume
boxsize (float) – periodic boxsize
mango.initpositions module¶
- 
mango.initpositions.initpos(lj_num, sigma, location=None, boxsize=0, xyz=False)[source]¶ Get the positions of particles.
Also can collect magnetisations and momentums
Can be user specified with location or downloaded using urllj
Downloaded positions from standard LJ stable structures
An (extended) xyz file can be specified the last frame in the file will be used
- Parameters
 lj_num (int) – Number of molecules
sigma (float) – distance between particle centres
location (string) – location of file to load
boxsize (float) – periodic boxsize (only required for 2 particle periodic systems)
- 
mango.initpositions.posfile(location, sigma, xyz=False, com=0)[source]¶ Open position file.
Reads first two lines to check if xyz open xyz otherwise read as unscaled coordinates
- 
mango.initpositions.twoparticlesinabox(boxsize, sigma)[source]¶ Set location of 2 particles.
put two particles next to each other
- 
mango.initpositions.urllj(lj_num, url='http://doye.chem.ox.ac.uk/jon/structures/LJ/points/{}')[source]¶ Download lj configuration.
Default url is http://doye.chem.ox.ac.uk/jon/structures/LJ/
- Parameters
 lj_num (int) – Number of molecules
url (str) – url with formatting {} for lj_num
mango.imports module¶
- 
mango.imports.fftw()[source]¶ Import the fastest version of fftw installed.
- Returns
 output – Fastest fft implementations available
- Return type
 fft, ffts, ifft
- 
mango.imports.getpotentials(name)[source]¶ Load pluggable potentials.
- Parameters
 name (string) – Filename of potentials module to import
- Returns
 output – Loaded module
- Return type
 module
- 
mango.imports.inquirer()[source]¶ Import inquirer if required.
- Returns
 bool – Is inquirere available?
tuple – inquirer functions
- 
class 
mango.imports.matplotlib(backend=None)[source]¶ Bases:
objectImporting matplotlib when necessary, allows for changing the backend before import.
mango.magnetic_motion module¶
Magnetic motion setup.
Set up environment and start calculation loop
- 
mango.magnetic_motion.calc_wrap(calc, stat)[source]¶ Wrap calculate to allow decoration in multiprocessing.
Could be used in future for any function
- 
class 
mango.magnetic_motion.calculate(**argd)[source]¶ Bases:
object1st parallel section.
This function does the boilerplate around the brunt of the calculation it is run once for each statistic
All the data is then saved in one of three user specified forms
hdf5
pickle
plain text
- 
mango.magnetic_motion.dictionary_creation(var, flg, extra=False)[source]¶ Creation of initial dictionary.
all data is the same at this point
Uses nested dictionaries for ease of storage
- 
mango.magnetic_motion.field(time, H0=167.0, nu=267000.0)[source]¶ Calculate the phase of the external magnetic field.
- 
mango.magnetic_motion.integrate(var={}, flg={})[source]¶ Set up of Calculation.
Setting up of initial positions magnetisations and momentums as well as neel relaxations for each molecule
This is all passed to the parallelisation of the statistical separations
- 
mango.magnetic_motion.num_iters(iters, skip)[source]¶ Get number of iterations including first and last iterations.
- 
class 
mango.magnetic_motion.save_m(neel, wd)[source]¶ Bases:
objectStoring function.
Stores data in memory until asked to save to file where it calls the writer
- Parameters
 neel (bool) – Is neel relaxation required?
wd (instance) – instance of writing class
- 
file(data_dict, SCFcount=0)[source]¶ Save current data block to file.
- Parameters
 data_dict (dict) – Storage dictionary
- 
memory(data_dict, data, time)[source]¶ Save to memory current iteration data.
- Parameters
 data_dict (dict) – Storage dictionary
data (dict) – data to be stored
time (instance) – timestep instance
- Returns
 data_dict – Storage dictionary
- Return type
 dict
mango.managers module¶
mango.multiproc module¶
- 
mango.multiproc.getlocalprocs(commworld, stats, perprocessor=1, Error=None)[source]¶ Split processors into groups.
- Parameters
 commworld (class) – MPI_COMM_WORLD communicator
stats (int) – number of statistics to calculate
perprocessor (int) – number of cores per group
- Returns
 communicators (tuple) – node communicator, group communicator
realNodeRank (int) – rank
run (int) – number of statistics to run
- 
mango.multiproc.mp_handle()[source]¶ Check if we are running in MPI or normal mode.
- Returns
 Runner – function for running the calculation
- Return type
 func
- 
mango.multiproc.mp_handler(mp_worker, data, stats, para=True)[source]¶ Multiprocessing handler.
Uses pythons builtin OpenMP like multiprocessing to separate parallel commands into different processes
- Parameters
 mp_worker (object) – Object to run
data (dictionary) – data to be passed to the object
stats (int) – number of repetitions to complete
para (bool) – multiprocess or not
- 
mango.multiproc.splitnode(perprocessor, stats, commworld, nodecomm, adname)[source]¶ Split cores into groups.
Avoids splitting cores across nodes
- Parameters
 perprocessor (int) – number of cores per group
stats (int) – number of statistics to calculate
commworld (class) – MPI_COMM_WORLD communicator
nodecomm (class) – local node communicator
adname (str) – current adler string
- Returns
 run (int or None) – number of statistics for group (only for rank 0) otherwise None
groupcomm – local group communicator
mango.position module¶
The Main engine.
Iteration loop module for updating properties of particles.
- 
class 
mango.position.Communal(epsilon, sigma, tri, comb, limit)[source]¶ Bases:
objectReused variables and methods for propogation.
- 
class 
mango.position.countneel(var, dt)[source]¶ Bases:
objectCounting and storing neel relaxations.
initialise with timestep(dt) and Neel relaxation time (tauN)
run with each magnetisation step
- 
class 
mango.position.energy(communal, singleframe=True)[source]¶ Bases:
mango.position.CommunalEnergy potentials.
- 
energy_vars(dm)¶ Set reused energy variables.
- 
 
- 
class 
mango.position.force(communal, nm)[source]¶ Bases:
mango.position.Communal,mango.constants.bin_countForce potentials.
- 
comb¶ 
- 
dmag¶ 
- 
epsilon¶ 
- 
epsilon24¶ 
- 
ff_trans()[source]¶ Create variables for all forces.
forces are updated twice without positional changes, therefore no change in translational force
- 
fmag¶ 
- 
fmag_temp¶ 
- 
force_trans¶ 
- 
force_transR¶ 
- 
force_vars(d, dm)¶ Set reused force variables.
- 
fstr1¶ 
- 
fstr2¶ 
- 
fstr3¶ 
- 
fstr4¶ 
- 
fstr5¶ 
- 
fstr6ia¶ 
- 
ftrans¶ 
- 
hfia¶ 
- 
hfia_temp¶ 
- 
hfja¶ 
- 
hfja_temp¶ 
- 
hind¶ 
- 
ja¶ 
- 
limit¶ 
- 
lind¶ 
- 
lj¶ 
- 
lj6¶ 
- 
long_ia¶ 
- 
long_ja¶ 
- 
magi¶ 
- 
magj¶ 
- 
rij¶ 
- 
rij3¶ 
- 
rij4¶ 
- 
rijz¶ 
- 
sigma¶ 
- 
triag_ind¶ 
- 
unitv¶ 
- 
zeros¶ 
- 
 
- 
class 
mango.position.position(**argd)[source]¶ Bases:
mango.position.CommunalMain calculation class.
Calling propogate will calculate 1 iteration
- 
boundary= <mango.boundaries.periodic object>¶ 
- 
initialconditions()[source]¶ Set initial conditions of particles and boundary conditions.
If MPI is used reinitialise potentials.
- 
 
mango.potentials module¶
Lennard jones 6 -12 translational potential.
Potentials to test against current magliq version.
mango.pp.main module¶
- 
mango.pp.main.collectdata(reader, name, flg, var, eq=0.1)[source]¶ Collect data from files as required.
- Parameters
 reader (instance) – file reader
name (str) – file name
flg (instance) – flg storage instance requires - files kinetic lengthcheck save_type ufile suscep align prog
var (instance) – requires - dt, no_mol, stats, skip, skip_iters, epsilon, sigma, limit, mass
eq (float) – equilibration fraction
- Returns
 timescale
datalen
xyz_data
energy_data
momenta_data
sus_data
stats
- 
mango.pp.main.kinetic_temperature(align, basename, mass, mom, equi=0)[source]¶ Kinetic Temperature.
Calculate the kinetic temperature of the system and write to file.
- Parameters
 TODO –
- 
mango.pp.main.lengthcheck(flg, run, directory, pos, block)[source]¶ Length of chain check.
Assumes the particles furthest away from each other are particle 0 and N
Improvements: generalise for systems with multiple chains generalise for systems without chains eg furthest distance between particles in a cluster
- 
mango.pp.main.readin(fname, run, directory, block, flg, fig_event=None)[source]¶ Manipulate Data.
This function reads in data from file and then produces visualisation or files as required
Possible options from input flags:
Extended XYZ file (Positions, Magnetisations, Forces)
Suceptibility (Data needs to be collected specifically for the purpose)
Data comparison plots, plot set(s) of data against time etc.
Kinetic Temperature
Chain length check
- Parameters
 fname (string) – filename (no extension)
run (int) – run number
directory (string) – file directory
flg (class) – Required flags: save_type, column, suscep, files, kinetic, lengthcheck, align, showg, saveg, save_type, ufile,
mango.pp.acf module¶
- 
class 
mango.pp.acf.Autocorr(flg, sus_data, dt, skip, mmag)[source]¶ Bases:
objectCalculates the ACF and MDOS of provided data.
- 
mango.pp.acf.get_suscep(flg, skip, dt, sus_data, blocks, stats, mass, vol, ms)[source]¶ Calculate the ACF of data for different properties.
- Returns
 atc_data – A dictionary of all the calculated ACF
- Return type
 dict
- 
mango.pp.acf.save_suscep(flg, directory, run, no_mol, cblock, xaxis, yaxis, stddev_y, autocorr_labels, scale, line_d={}, **kwargs)[source]¶ Save the susceptibility calculation.
Saves autocorrelation data in raw text, The columns are shown below with yaxis and std_y will always be 3 columns:
xaxis yaxis… std_y…
- Parameters
 directory (str) – save location
run (int) – run number
no_mol (int) – number of particles
cblock (int) – current block length
xaxis (ndarray) – x data
yaxis (ndarray) – y data
stddev_y (ndarray) – y error data
autocorr_labels (dict) – dictionary of x and y labels
scale (float) – scale value for data
mango.pp.util module¶
- 
class 
mango.pp.util.Dataarrays(flg, reader, var, name, eq=0.1)[source]¶ Bases:
objectData array collection.
- 
mango.pp.util.dictfind(key, dictionary)[source]¶ Find key in nested dictionary, Returns as soon as found.
- Parameters
 key (str) – key to find
dictionary (dict) – 2 level dictionary of all data
- Returns
 d (ndarray) – data array
u (str) – units
std_var (ndarray/bool) – standard deviation array, False if data not averaged
- 
mango.pp.util.getlocation(keys, dictionary, stats, kd={})[source]¶ Apply any basic arithmetic to keys with newly found location.
Arrays can be split eg array[:,1] etc
- 
mango.pp.util.interactive_getfiles(flg, check_name, files)[source]¶ Get postprocessing jobs if none selected, Check file exists.
- Parameters
 Error (func) –
flg (instance) – instance of required flags
check_name (str) – name of file to read in
files (list) – list of files in selected directory
- 
class 
mango.pp.util.loader(flg, run, directory)[source]¶ Bases:
objectLoad postprocessed data files.
- 
class 
mango.pp.util.onevent(mpl)[source]¶ Bases:
object- 
connect(fig, leg=None, line=None)[source]¶ Connect figures to events.
- Parameters
 fig (figure) –
leg (legend) –
line (line) –
- 
 
mango.progress module¶
mango.time module¶
mango.tools.visualiser module¶
Mango particle visualiser.
Controls:
0 - reset cameras
- 1 - toggle camera between regular 3D (turntable), first person (fly),
 arcball and Pan Zoom
2 - toggle between real particles and vector spheres
+/- - speed up/slow down simulation
! - start/stop simulation
. - reset simulation speed
I - save image of current frame
With fly camera:
WASD or arrow keys - move around
SPACE - brake
FC - move up-down
IJKL or mouse - look around
TODO:
Change arrow size based on strength
speed up read in
- 
mango.tools.visualiser.read(filename, speed)[source]¶ Read in extended xyz file and names columns in recorded arrays.
Future:
Error checking
crash gracefully when memory gets too full
mango.tools.string_generation module¶
- 
mango.tools.string_generation.strings()[source]¶ Mango Strings XYZ file generation.
commandline parameters [radius]%[tolerance] [number of particles] [postion Phi] [position Theta] [magnetisation Phi] [magnetisation Theta]
Phi and Theta are the azimuthal angle and the polar angle for position and magnetisation, they are optional and default to aligning along the z axis. -h help -v verbose