Module Breakdown

mango.mango module

Call Flow Diagram

Main processing

_images/mprof.svg

Parallel processing

_images/wprof.svg

Mango.

A program to simulate magnetic nanoparticles in a non magnetic fluid. Developed by James Cook 2015-2019 with supervison by Lorenzo Stella.

mango.mango.main(argparse, opts)[source]

Main.

the input is parsed variables are stored calculations are started Any plotting is completed as required

mango.mango.setup(argparse, opts)[source]

mango.arguments module

class mango.arguments.SmartFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]

Bases: argparse.HelpFormatter

Smart help formatter.

Allows for splitting the help over multiple lines by starting help with ‘R|’

mango.arguments.array_vars(parsing, variables)[source]

Set up arrays for variables.

mango.arguments.calcsigmalim(radius, np)[source]

Calculate sigma and cutoff limit.

mango.arguments.col_check(check)[source]

Check columns are available.

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.fixparam(p)[source]

Modify parameters for units and types.

mango.arguments.gethelp(opts, parser)[source]

Help output selector.

mango.arguments.interactive_help(k={'keywords'})[source]

Print commandline help.

mango.arguments.list_add_arguments(self, k)[source]

Parse arguments from dictionary.

Parameters

k (OrderedDict) – Dictionary of keywords and defaults

mango.arguments.notebook_help(k={'keywords'})[source]

Print Help in Jupyter Notebook.

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.sanity(p)[source]

Sanity checks.

mango.arguments.set_const(no_molecules)[source]
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.arguments.splitvars(p)[source]

Split parameters into variables and flags.

Parameters

p (instance) – argparse instance

Returns

var, flg – variable and flag instances

Return type

instance

mango.arguments.verbosity(var, flg)[source]

Verbosity Changing.

Parameters

flg (var,) – class variable and flag instances

mango.boundaries module

class mango.boundaries.periodic[source]

Bases: object

Periodic 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

distance_full(pos)[source]

See distance.

For the full trajectory

getdist
pbc
posones
reset_wrap()[source]

Start false.

setup(boxsize, pbc, pos, sigma, tri)[source]

Set up periodic conditions.

Not using __init__ for this allows more decorator flexibility

setup_full(pos)[source]

See setup.

For the full trajectory.

sigma
sigma_err
tri
wrap
wrapping(pos)[source]

Simplistic wrapping of coordinates.

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.MTrnd(seed=12345)[source]

Random number generator.

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: object

Fast 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()

addat(to, at, fro)[source]

Add at.

leng
reshape(to)[source]

Reshape to given shape.

shape
subtractat(to, at, fro)[source]

Subtract at.

mango.constants.boolconvert(boolean)[source]

Convert strings to bool correctly.

Parameters

boolean (str) –

Returns

Return type

bool

class mango.constants.const[source]

Bases: object

Constants and version number.
Internal Units

Main

  • time: 1e-12 [s]

  • length: 1e-6 [cm]

  • mass: 1e-18 [g]

Derived

  • energy unit: 1e-6 [erg]

  • temperature unit: 1e0 [K]

  • magnetic induction: 1e6 [gauss]

  • magnetisation: 1e-12 [emu]

  • force: 1 [g/cm.s^2]


Error(msg)[source]

Simple error printer.

Use managers.serverwrapper(‘Error’) decorator for fully fledged error management

Prog(msg)[source]

Blank function, replaced on the fly with progressbar if required.

clear()[source]

Clear screen and move cursor.

echo(msg, x, y)[source]

Print at specified cursor location.

header(constants, debug_pr)[source]

Output file header.

jump(jumps)[source]
reseed(seed=12345)[source]
set_accuracy(EPS_val=None)[source]
class mango.constants.getkeywords[source]

Bases: object

Get keywords and organise them.

flgorvar()[source]

Sort arguments into list of flags or variables.

Returns

  • var_list (list) – list of vars

  • flg_list (list) – list of flags

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.constants.rmemptyfile(filename)[source]

Remove files of Zero size.

Parameters

filename (str) – Full filename

mango.constants.switch(switch_name)[source]

Decorate to switch off a function.

Improvements- TODO

  • Still return expected return values but with no changes to variables or new variables set to 0 or none

  • only call if switched off

mango.debug module

class mango.debug.debug(aspects=None)[source]

Bases: object

Debugging 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

dcall(f)[source]

Wrap function to print debugging info.

Generically gives all wrapped class methods the DBG variable Can be used to carry out debugging methods (eg. if hasattr(self, “DBG”): …)

If specifically selected with aspects, prints timing and/or arguments

start_timer(fname)[source]

Start timer.

mango.debug.profile(*args, file=None)[source]

Profile code.

mango.debug.set_debug()[source]

Allow for setting debugging from the command line.

eg. --debug [ io core ]

mango.debug.timing(name, f_dict, f_result=None)[source]

Time functions.

Get total run time of functions

class mango.debug.v_print(verbose)[source]

Bases: object

Debug printing.

mango.errors module

exception mango.errors.ExitQuiet[source]

Bases: mango.errors.Quiet

Exit Program Quietly Exception.

exception mango.errors.Quiet[source]

Bases: Exception

Base Exception for no traceback.

class mango.errors.Reprinter[source]

Bases: object

Rewrite terminal output using ANSI escape sequences.

reprint(text)[source]

Reprinter.

Parameters

text (string) – text to be overwritable

mango.errors.ecol(m)[source]

Colour crash errors.

class mango.errors.error(op=<built-in function open>)[source]

Bases: mango.errors._strings

Error class.

Handles error printing to the terminal

  • All errors are written to stderr

addpid(pid)[source]

PID collection.

count(etype, msg)[source]

“>” infront of error message will remove call count.

Parameters
  • etype (string) – Error type W, F, G, B, M, ME (Warning, Fatal, Oops, Keyboard, Message, Message exit)

  • msg (string) – message for error

endproc()[source]

Write errors to file at end of run.

print()[source]

Print errors to screen.

setup(w_message, directory, run, pp=0)[source]

Set up for the error system.

Parameters
  • w_message (bool) – Turns (most) errors on or off, defaults to on

  • directory (string) – Error save directory

  • run (int) – run number

mango.errors.notraceback(kind, message, traceback)[source]

Exceptionhook only print errors if not Quiet.

mango.hdf5io module

mango.hdf5io.annihilate(filename, location)[source]
mango.hdf5io.backup(location, name)[source]

Backup useful variables.

Parameters
  • location (node) –

  • name (str) –

mango.hdf5io.backupcheck(location, name)[source]

Backup variables.

mango.hdf5io.chunkindex(loc_s1, cs_ind1, c1)[source]

Return positive array index for numpy array.

mango.hdf5io.get_allattr(file, location)[source]
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.get_restartdata(restart_data, filenames)[source]

Collect all restart data from all files.

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.Data

Reads data in for post processing.

Improvements * Only read in data required rather than all data - Works for hdf5 files

getrestart(position, last_iter)[source]

Get restart data.

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

xyzread(*args)[source]

Read all data from (extended) xyz file.

mango.io.read_inputfile(filename, restart=None, kwds={'keywords'})[source]

Input File Reading.

mango.io.restart_gen(file=None, reps=None, outfile=None)[source]

Restart generator.

Run with

mango_restartregen [file] [reps] [outfile <optional>]

mango.io.restartfile_read(r_file)[source]

Read restart file.

mango.io.separater(response)[source]
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.Data

Writing all calculated data to file.

addtorestart(fname)[source]
restart()[source]
setup(name)[source]
write(*args, **kw)[source]
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: object

Importing matplotlib when necessary, allows for changing the backend before import.

static close()[source]
col()[source]
static errorbarpicker()[source]
htuple()[source]

single legend entry for multiple connected graphs with one legend. see mango.tools.plotting

prettyplot()[source]
static showg()[source]
suscep()[source]
mango.imports.read(save_type)[source]

Import modules based on options for reading data files.

Parameters

save_type (str) – file type extension desired

Returns

  • load (func) – loading files function

  • save_type (str) – save type based on available

mango.imports.write(save_type)[source]

Import modules based on options for writing data files.

Parameters

save_type (str) – file type extension desired

Returns

  • dump (func) – save files function

  • save_type (str) – save type based on available

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: object

1st 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

  1. hdf5

  2. pickle

  3. plain text

dictionarys()[source]

Create dictionaries for data storage.

disksaveloop()[source]

Save to disk loop.

finaliteration()[source]

Last iteration loop.

Setup for last step saving useful things for restart

finishdata(SCFcount, count)[source]
firststep()[source]

Set up initial conditions and calculate first step.

iterationadjust()[source]

Adjust iterations for writing and storing.

memorysaveloop(loop)[source]

Save to memory loop.

Parameters

loop (int) – loop size

prerange()[source]

Preallocate ranges.

progress_report()[source]

Progress reporter.

randomnumbers()[source]

Set up random number starting point.

run(stat)[source]

Run calculation.

Parameters

stat (int) – statistic number

savechunk()[source]

Adjust savechunk.

setup()[source]

Set up instance for each parallel calculation.

skiploop(loop)[source]

Skip loop, no saving required.

Parameters

loop (int) – loop size

starttime()[source]

Start timestep recording.

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.get_particles(var, flg)[source]
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.new_vars(var)[source]

Calculate New variables from input.

mango.magnetic_motion.num_iters(iters, skip)[source]

Get number of iterations including first and last iterations.

mango.magnetic_motion.sanity_checks(var, pos, mag, xyz)[source]

Sanity check input.

class mango.magnetic_motion.save_m(neel, wd)[source]

Bases: object

Storing 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

cutter(orig, copy, start, end)[source]

Return a section of input dictionary.

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

remove_state(data_dict)[source]

Remove current state.

restart(name, extra_iter, SCFcount, written)[source]

Save extra_iters, SCFcount and current written.

setup(name)[source]

Set up writing class.

state(data_dict, SCFcount)[source]

Save current state.

stop(data_dict, SCFcount=0)[source]

Emergency Stop saving.

Save current data block to file.

Parameters

data_dict (dict) – Storage dictionary

mango.managers module

class mango.managers.Server(q_in, q_out, op=<built-in function open>)[source]

Bases: object

async errorhandler(data)[source]

Send errors to error class.

async handler(reader, writer)[source]
async proghandler(data)[source]

Send progress to progress bar.

class mango.managers.addpid(wraptype)[source]

Bases: object

Decorator to add PID to server list.

class mango.managers.serverwrapper(wraptype)[source]

Bases: object

Decorator to start servers.

mango.managers.start_server(s_type)[source]

Start server for multiprocessing.

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.ismpi(argparse=True, opts={})[source]

Entry point function for MPI running.

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: object

Reused variables and methods for propogation.

set_attr(var_list, val)[source]

Initialise multiple arrays with same shape.

class mango.position.countneel(var, dt)[source]

Bases: object

Counting and storing neel relaxations.

initialise with timestep(dt) and Neel relaxation time (tauN)

run with each magnetisation step

run(dt, mag)[source]

Counter.

class mango.position.energy(communal, singleframe=True)[source]

Bases: mango.position.Communal

Energy potentials.

energy_vars(dm)

Set reused energy variables.

vv_mag(mag, d)[source]

Calculate magnetic potential energy.

vv_trans()[source]

Calculate translation potential energy.

class mango.position.force(communal, nm)[source]

Bases: mango.position.Communal, mango.constants.bin_count

Force potentials.

bin_count_setup()[source]

bin_count setup.

create variables needed for bincount

comb
dmag
epsilon
epsilon24
estrings()[source]
ff_mag(mag)[source]

Calculate Magnetic force.

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
hh_mag(mag)[source]

Calculate Applied field.

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.Communal

Main calculation class.

Calling propogate will calculate 1 iteration

boundary = <mango.boundaries.periodic object>
deltamag(mag, dt, umag, hfield, _Heff)[source]

Update magnetisation.

estrings()[source]
force_step()[source]

Calculate the forces between atoms.

init_pot()[source]

Initialise potentials.

initialconditions()[source]

Set initial conditions of particles and boundary conditions.

If MPI is used reinitialise potentials.

magnetisation_step(dt)[source]

Update magnetisation.

momentum_step(dt)[source]

Calculate the momentum of all the particles.

neel(magstep, dt)[source]

Wrap magnetisation if neel relaxation is used.

optimise(toll=1e-06, iprint=2)[source]

Optimise particle position based on magnetisation.

position_step(dt)[source]

Calculate the new position of the particle.

propagate(Hext, noise_setup)[source]

Calculate propagation loop.

scfloop(mag, dt, umag, hfield, Heff, mag_old, diff, new_norm, count=0)[source]

SCF loop to update magnetisation and check the magnetisation norm isn’t changed.

Most (more than 50%) of the simulation is spent here improvements to the for loop have the largest impact

set_pot()[source]

Set new potentials if required.

stochastic_step(dt, noise_row)[source]

Apply noise to system.

mango.potentials module

Lennard jones 6 -12 translational potential.

mango.potentials.LennardJones6_12.ff_trans(self)[source]

Calculate Translational Force.

mango.potentials.LennardJones6_12.vv_trans(self)[source]

Lennard Jones Potential.

Potentials to test against current magliq version.

mango.potentials.magliq_debug.ff_mag(self, mag)[source]
mango.potentials.magliq_debug.ff_trans(self)[source]
mango.potentials.magliq_debug.hh_mag(self, mag)[source]
mango.potentials.magliq_debug.vv_mag(self, mag, d)[source]
mango.potentials.magliq_debug.vv_trans(self)[source]

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.get_ppflags(reader)[source]

Get post processing flags if stored in save file.

mango.pp.main.get_ppvars(flg, reader, extras=False)[source]

Get post processing variables.

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: object

Calculates the ACF and MDOS of provided data.

analysis(blocks)[source]

Carry out DOS and ACF calculation for provided data and blocks.

Parameters

blocks (int) – number of blocks

conv(no_stats, RMS=True)[source]

Carry out blocking convergence tests.

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.com module

class mango.pp.com.CoM_motion_rm(mass, no_mol)[source]

Bases: object

align(xyz_data, sus_data)[source]
inertia_angular(xyz_data, sus_data)[source]
suscep_align(sus_data)[source]
xyz_align(xyz_data)[source]
mango.pp.com.get_angular(pos, pos_com, mom, mom_com)[source]
mango.pp.com.get_inertia(pos, pos_com, mass)[source]
mango.pp.com.remove_CoMm(pos, mom, mass, no_mol)[source]

mango.pp.util module

class mango.pp.util.Dataarrays(flg, reader, var, name, eq=0.1)[source]

Bases: object

Data array collection.

energy(stat, name, epsilon=None, sigma=None, limit=None, mass=None)[source]

Get total energy data.

length()[source]
momenta(stat, name, epsilon=None, sigma=None, limit=None, mass=None)[source]

Get momenta data.

sus(stat, name)[source]

Get susceptibility data.

xyz(stat, name)[source]

Get xyz data.

mango.pp.util.at_least2d_end(*args)[source]
mango.pp.util.captured_output()[source]
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.get_expon(number)[source]
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.getvars(varib, lst)[source]
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: object

Load postprocessed data files.

lengthcheck(block)[source]

Load numpy length check array.

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) –

static fig_d(fig)[source]

Set picker for yaxis.

Parameters

fig (fig instance) –

static line_d(legh, line)[source]

Set picker for legend.

Parameters
  • legh (legendHandles) –

  • line (line object) –

Returns

a dictionary linking legend entry and line

Return type

dict

onkey(event)[source]

On key events.

onpick(event)[source]

Switch lines visibility.

mango.pp.util.showgraph(mpl, showg=False)[source]

Show graphs onscreen at end of run.

mango.progress module

class mango.progress.prog[source]

Bases: object

Progress Bar

static END()[source]
static Test()[source]
bar(prefix='', it=0, stat='1')[source]

Print loading bar to screen.

Parameters
  • prefix (string) – String to have before loading bar

  • it (float/str) – fraction complete

  • stat (str) – current stage

setup(*data)[source]

Set size of progress bar.

Parameters

data (str) – list of processes and size of bar eg ‘[1, 2, 3] size=40’

mango.time module

class mango.time.end(startinst)[source]

Bases: object

Make sure the program exits within the walltime.

finished()[source]

Return current run time.

gettimegone()[source]
gettimeleft()[source]

Return time left in run.

class mango.time.grace(stats)[source]

Bases: object

class mango.time.start(walltime)[source]

Bases: object

Set walltime of the program for clean exiting.

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.main()[source]
mango.tools.visualiser.move_to(self, trans)[source]
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.visualiser.rotate_to(self, rot)[source]
class mango.tools.visualiser.scene_setup(application, radii, skip=1, freeze=False, true_size=True, fps=False, video=False, sm_box=True, loop=True)[source]

Bases: object

angle(arr1, arr2, string=None)[source]
arrows(a)[source]
camera(fov)[source]
cone_rotation(arr1)[source]
cr_arr2(i, pradius)[source]
cr_bsph(i, pradius, xyz)[source]
get_data(radii, freeze, sm_box, skip=1)[source]
makevideo()[source]
on_key_press(event)[source]
on_mouse_move(event)[source]
on_timer(event)[source]
positions(a, freeze)[source]
rotate_array(angle, rotax, ia, ir)[source]
static rotdp(matrix, angle, axis)[source]
scene(xyz, n, pradius, bsize)[source]
static spinner(arr)[source]
static spinner2(arr)[source]
static translucent(obj)[source]
mango.tools.visualiser.translate_to(self, trans)[source]

mango.tools.string_generation module

mango.tools.string_generation.r_unit(p, t)[source]
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

class mango.tools.string_generation.v_print(verbose)[source]

Bases: object