utilities package

Submodules

utilities.createGUI module

utilities.createGUI.createGUI(obj)[source]

A function to simplify creating GUIs from classes with appropriate argparse-related functions.

utilities.TransformationMatrix module

utilities.TransformationMatrix.Identity(size)[source]

Create an identity matrix.

Parameters:size (int) – The size of the identity matrix to construct [2, 4].
Returns:A new identity matrix.
Return type:Matrix
utilities.TransformationMatrix.Mag(vec)[source]

return the magnitude (rho in spherical coordinate system)

utilities.TransformationMatrix.Mag2(vec)[source]

return the magnitude squared (faster than Mag for comparisons)

utilities.TransformationMatrix.Rotation(angle_rad, size, axis=None)[source]

Create a matrix representing a rotation.

Parameters:
  • angle_rad (float) – The angle of rotation desired, in radians.
  • size (int) – The size of the rotation matrix to construct [2, 4].
  • axis (string or Vector) – a string in [‘X’, ‘Y’, ‘Z’] or a 3D Vector Object (optional when size is 2).
Return:

A new rotation matrix.

Return type:

Matrix

utilities.TransformationMatrix.Scale(factor, size, axis=None)[source]

Create a matrix representing a scaling.

Parameters:
  • factor (float) – The factor of scaling to apply.
  • size (int) – The size of the scale matrix to construct [2, 4].
  • axis (Vector) – Direction to influence scale. (optional).
Returns:

A new scale matrix.

Return type:

Matrix

utilities.TransformationMatrix.Translation(vector)[source]

Create a matrix representing a translation.

Parameters:vector (Vector) – The translation vector.
Returns:An identity matrix with a translation.
Return type:Matrix
utilities.TransformationMatrix.Unit(vec)[source]

return unit vector parallel to vec.

utilities.TransformationMatrix.applyTransformation(M, voxel)[source]

Applies 4x4 transformation matrix M to list, array or matrix voxel of size 3 or 4.

  • If voxel is of size 4, the 4th element will not be affected (Useful for power)!
  • If voxel is of size 3, a 4th element of value -1 is added.
Returns:a voxel with the transformed location and same power (or -1 if no previous power given)
utilities.TransformationMatrix.rotationMatrix(axis_point, axis_direction, angle_degrees)[source]

return a rotation matrix for a rotation around an arbitrary axis

utilities.brisFDTD_ID_info module

Converts between the numeric IDs numID (01, 02, 67, etc) and alphabetic IDs alphaID (01, A1, df, jk, {l, etc) used by Bristol FDTD for its data files.

Note

Since BFDTD 2008, “ba” comes after “az” instead of “a{“.

Make sure you specify “pre_2008_BFDTD_version = True” if you are working with data generated by BFDTD versions < 2008!!!

Please stop using the old BFDTD 2003 for any new simulations.

Note

If there is a mix of time snapshots, epsilon snapshots and/or mode filtered probes, they will be numbered together!!!

i.e. 1 esnap + 1 tsnap will lead to x1…+x2… according to their respective order of appearance in the .inp file.

Note

snap_time_number starts at 0 for ModeFilteredProbes and at 1 for time and epsilon snapshots.

Maximum amount of output files BFDTD can generate: 2549 time/epsilon snapshots for BFDTD 2014, but this might lead to bad filenames. (This might actually be a system-specific limit on the maximum number of simultaneously open files.)

class utilities.brisFDTD_ID_info.Test_brisFDTD_ID_info_Functions(methodName='runTest')[source]

Bases: unittest.case.TestCase

FrequencySnapshotID_List(pre_2008_BFDTD_version)[source]
FrequencySnapshotID_ViceVersa(pre_2008_BFDTD_version)[source]
test_FrequencySnapshotID_List_post_2008_BFDTD_version()[source]
test_FrequencySnapshotID_List_pre_2008_BFDTD_version()[source]
test_FrequencySnapshotID_ViceVersa_post_2008_BFDTD_version()[source]
test_FrequencySnapshotID_ViceVersa_pre_2008_BFDTD_version()[source]
test_ModeFilteredProbeID_List()[source]
test_ModeFilteredProbeID_ViceVersa()[source]
test_ProbeID_List()[source]
test_ProbeID_ViceVersa()[source]
test_TimeSnapshotID_List()[source]
test_TimeSnapshotID_ViceVersa()[source]
utilities.brisFDTD_ID_info.alphaID_to_numID(alphaID_or_filename, expected_object_type=None, probe_ident=None, pre_2008_BFDTD_version=False)[source]

Converts alpha IDs used by Bristol FDTD to numeric IDs.

Returns:(numID, snap_plane, probe_ident, snap_time_number, fixed_filename, object_type)

Examples:

  • z -> 26
  • a{ -> 26+27
  • 99 -> 99
  • :0 -> 100
utilities.brisFDTD_ID_info.numID_to_alphaID_FrequencySnapshot(numID, snap_plane='x', probe_ident='_id_', snap_time_number=0, pre_2008_BFDTD_version=False)[source]

Converts numeric IDs to alpha IDs used by Bristol FDTD for frequency snapshots.

Parameters:
  • update_limits (bool) – If true, updateLimits() will be called.
  • numID (int) – numeric ID
  • snap_plane (str) – snapshot plane letter, i.e. ‘x’, ‘y’ or ‘z’. Default: ‘x’
  • probe_ident (str) – ID string used in data output. Default: ‘_id_’
  • snap_time_number (int) – “snapshot time number”, i.e. the index at the end of data filenames. Default: 0
  • pre_2008_BFDTD_version (bool) – If True, the pre-2008 BFDTD indexing will be used. Default: False
Returns:

(filename, alphaID, pair)

Examples:

  • 26 -> z
  • 26 + 26 -> az
  • 26 + 27 -> ba for BFDTD version >= 2008
  • 26 + 27 -> a{ for BFDTD version < 2008

Maximum values:

  • MAXIMUM NUMBER OF SNAPSHOTS: 32767 (=(2^8)*(2^8)/2 -1)
  • MAXIMUM NUMBER OF SNAPSHOTS BEFORE RETURN to aa: 6938 = 26+256*27
  • MAXIMUM NUMBER OF SNAPSHOTS BEFORE DUPLICATE IDs: 4508 = 26+(6-(ord(‘a’)-1)+256)*27+1 (6=character before non-printable bell character)
  • MAXIMUM NUMBER OF SNAPSHOTS BEFORE ENTERING DANGER AREA (non-printable characters):
    • 806 = 26 + (126-(ord(‘a’)-1))*26 (first digit: a-~, second digit: a-z) for BFDTD version >= 2008
    • 836 = 26 + (126-(ord(‘a’)-1))*27 (first digit: a-~, second digit: a-{) for BFDTD version < 2008
utilities.brisFDTD_ID_info.numID_to_alphaID_ModeFilteredProbe(numID, probe_ident='_id_', snap_time_number=1)[source]

Converts numeric IDs to alpha IDs used by Bristol FDTD for mode filtered probes.

Returns:(filename, alphaID, pair)

Examples:

  • 9 -> 9
  • 10 -> :
utilities.brisFDTD_ID_info.numID_to_alphaID_Probe(numID, probe_ident='_id_')[source]

Converts numeric IDs to alpha IDs used by Bristol FDTD for probes.

Returns:(filename, alphaID, pair)

Examples: * 99 -> 99 * 100 -> :0

utilities.brisFDTD_ID_info.numID_to_alphaID_TimeSnapshot(numID, snap_plane='x', probe_ident='_id_', snap_time_number=1)[source]

Converts numeric IDs to alpha IDs used by Bristol FDTD for time snapshots.

Note

This function can also be used for epsilon snapshots, since they are just a subclass of time snapshots.

Returns:(filename, alphaID, pair)

Examples:

  • 99 -> 99
  • 100 -> :0

utilities.common module

utilities.common.Angle(p, q)[source]

return the angle w.r.t. another 3-vector

utilities.common.LimitsToThickness(limits)[source]
utilities.common.Orthogonal(u)[source]

get vector v orthogonal to u ex: v = Orthogonal(u)

utilities.common.addDoubleQuotesIfMissing(orig)[source]
utilities.common.addExtension(filename, default_extension)[source]

add default_extension if the file does not end in .geo or .inp

utilities.common.checkSnapshotNumber(filename, verbose=False)[source]

Returns the number of snapshots and frequency snapshots in the file filename.

Returns:(N_time_snaps, N_freq_snaps)
utilities.common.check_call_and_log(cmd, log_file_object)[source]

Custom extension of the check_call function from the python subprocess module. It redirects stderr to stdout and prints both out to the screen, while also writing them to the file object log_file_object.

utilities.common.difft(start, end)[source]

returns the difference in seconds between two datetime.time objects

utilities.common.difft_string(start, end)[source]

prints the difference between two datetime.time objects in a nice format

utilities.common.eng_string(x, format='%s', si=False)[source]

Returns float/int value <x> formatted in a simplified engineering format - using an exponent that is a multiple of 3.

format: printf-style string used to format the value before the exponent.

si: if true, use SI suffix for exponent, e.g. k instead of e3, n instead of e-9 etc.

E.g. with format=’%.2f’:

  1.23e-08 => 12.30e-9
       123 => 123.00
    1230.0 => 1.23e3
-1230000.0 => -1.23e6

and with si=True:

    1230.0 => 1.23k
-1230000.0 => -1.23M

References/sources:

utilities.common.findNearest(a, a0)[source]

Element in nd array a closest to the scalar value a0 returns (idx, a.flat[idx]) = (index of closest value, closest value)

utilities.common.findNearestInSortedArray(a, a0, direction)[source]

Find value in a closest to a0. Returns its index and the value.

  • direction = -1: if a0 is not in a, choose closest, but smaller value
  • direction = 0: just choose closest
  • direction = +1: if a0 is not in a, choose closest, but larger value
NOTES:
  • Only for ordered/sorted arrays.
  • Supports arrays with duplicate values.
utilities.common.fixLowerUpper(L, U)[source]
utilities.common.float_array(A)[source]

convert string array to float array

utilities.common.getExtension(filename)[source]

returns extension of filename .. todo:: get rid of this and replace it with os.path.splitext wherever used

utilities.common.getProbeColumnFromExcitation(excitation)[source]
utilities.common.getVecAlphaDirectionFromVar(var)[source]

Returns ([1,0,0],’x’),etc corresponding to var(alpha or vector)

utilities.common.int_array(A)[source]

convert string array to int array

utilities.common.is_number(s)[source]

returns true if s can be converted to a float, otherwise false

utilities.common.matlab_range(start, step, stop)[source]

Returns a list of values going from start to stop with a step step, but so that all values are less than OR EQUAL TO stop. i.e. it works like the matlab slice notation start:step:stop or like numpy.arange(start, stop, step) but with values on the closed interval [start, stop].

utilities.common.planeNumberName(var)[source]

Returns numindex(1,2,3) and char(‘X’,’Y’,’Z’) corresponding to var(num or alpha index)

utilities.common.rotation_matrix3(axis, theta)[source]

Returns a rotation matrix of size 3 to rotate something around vector v by angle theta.

Usage:

v = numpy.array([3,5,0])
axis = numpy.array([4,4,1])
theta = 1.2 
print(numpy.dot(rotation_matrix3(axis,theta),v))

source: http://stackoverflow.com/questions/6802577/python-rotation-of-3d-vector

TODO: Replace with some existing complete geometry module???

utilities.common.rotation_matrix4(axis, theta)[source]

Returns a rotation matrix of size 4 to rotate something around vector v by angle theta.

Usage:

v = numpy.array([3,5,0])
axis = numpy.array([4,4,1])
theta = 1.2 
print(numpy.dot(rotation_matrix(axis,theta),v))

source: http://stackoverflow.com/questions/6802577/python-rotation-of-3d-vector

utilities.common.runCommandAndStoreOutput(cmd, outfilename, verbosity=0)[source]
utilities.common.runSimulation(exe, inFileName, outfilename=None, verbosity=0)[source]

Just a simple convenience function to run a simulation in the directory of the input file and then going back to the original working directory. The output is saved in a file of the form basename(inFileName)+'.out' by default.

Parameters:
  • exe (str) – The executable to use.
  • inFileName (str) – The input file to use.
  • outfilename (str) – The output file to use (i.e. logfile). If None, a filename will be built by replacing the extension of inFileName with “.out”. Default: None
  • verbosity (int) – If verbosity>=1, the final command used will be printed out. If verbosity>=2, the commands output will also be printed to screen. Default: 0
utilities.common.str2list(instr, numeric=True, array=True)[source]

Converts strings of the form ‘[1,2,3],[4,5,6],[7,8,9]’ into a list of lists of the form [[‘1’, ‘2’, ‘3’], [‘4’, ‘5’, ‘6’], [‘7’, ‘8’, ‘9’]]

  • If numeric is set to True, converts all elements to float, otherwise leaves them as strings.
  • If array is set to True, converts the lists to numpy arrays.
  • If instr is not of type string, it raises a TypeError.

Note

Seems to only be used in the weijeiWoodpile.py script at the moment to deal with input from ConfigParser.

Note

This could be done with an eval-like function… I guess this is safer in the end?

utilities.common.substituteExtension(s, oldext, newext)[source]

For easier to read code?

utilities.common.symmetrifyAndSubtractOdd(vec, max)[source]

[1, 2, 3]->[1, 2, 3, 8, 9] for max = 10 [0, 1, 2, 3]->[0, 1, 2, 3, 4, 5, 6] for max = 6

utilities.common.symmetrifyEven(vec)[source]

[1, 2, 3]->[1, 2, 3, 3, 2, 1]

utilities.common.symmetrifyOdd(vec)[source]

[1, 2, 3]->[1, 2, 3, 2, 1]

utilities.common.timestodelta(starttime, endtime)[source]

returns the difference in seconds between two datetime.time objects

utilities.common.todatetime(time)[source]

converts a datetime.time object to a datetime.datetime object using the current date

utilities.common.unitVector(vec)[source]

utilities.dumpObj module

utilities.dumpObj.delchars(str, chars)[source]

Returns a string for which all occurrences of characters in chars have been removed.

utilities.dumpObj.dumpObj(obj, maxlen=77, lindent=24, maxspew=600)[source]

Print a nicely formatted overview of an object.

The output lines will be wrapped at maxlen, with lindent of space for names of attributes. A maximum of maxspew characters will be printed for each attribute value.

You can hand dumpObj any data type – a module, class, instance, new class.

Note that in reformatting for compactness the routine trashes any formatting in the docstrings it prints.

Example:
>>> class Foo(object):
        a = 30
        def bar(self, b):
            "A silly method"
            return a*b
... ... ... ... 
>>> foo = Foo()
>>> dumpObj(foo)
Instance of class 'Foo' as defined in module __main__ with id 136863308
Documentation string:   None
Built-in Methods:       __delattr__, __getattribute__, __hash__, __init__
                        __new__, __reduce__, __repr__, __setattr__,       
                        __str__
Methods:
  bar                   "A silly method"
Attributes:
  __dict__              {}
  __weakref__           None
  a                     30
utilities.dumpObj.nukenewlines(string)[source]

Strip newlines and any trailing/following whitespace; rejoin with a single space where the newlines were.

Bug: This routine will completely butcher any whitespace-formatted text.

utilities.dumpObj.prettyPrint(string, maxlen=75, split=' ')[source]

Pretty prints the given string to break at an occurrence of split where necessary to avoid lines longer than maxlen.

This will overflow the line if no convenient occurrence of split is found

utilities.dumpObj.prettyPrintCols(strings, widths, split=' ')[source]

Pretty prints text in colums, with each string breaking at split according to prettyPrint. margins gives the corresponding right breaking point.

utilities.dumpObj.printDict(di, format='%-25s %s')[source]

utilities.getuserdir module

utilities.getuserdir.getuserdir()[source]

Returns the platform’s “user directory”.

utilities.plotDatFile module

Currently broken. automodule:: utilities.plotDatFile :members: :undoc-members: :show-inheritance:

utilities.prnutils module

for future ref: functions of interest in python/matlab/octave are eval, exec and genvarname

csv options to consider for general reader/writer/printing functions:
  • delimiter
  • field names
  • printing format
current main csv files:
  • probe output
  • epsilon snapshots
  • time snapshots
  • frequency snapshots
  • harminv output
  • harminv selection output (from plotProbe)

Links:

utilities.prnutils.genvarname()[source]

should act like genvarname from Matlab/Octave

utilities.prnutils.getDimensions(data, header=None)[source]
utilities.prnutils.printHarminvOutput(harminv_output)[source]
utilities.prnutils.printHarminvOutputDirect(harminv_output)[source]
utilities.prnutils.printHarminvOutputSelection(harminv_output)[source]
utilities.prnutils.prnToVariables(prn_file)[source]

A function reading in a .prn file and putting the data directly into usable variables named after the column headers. It then drops you into an interactive python session.

utilities.prnutils.readHarminvOutput(filename)[source]
utilities.prnutils.readHarminvOutputDirect(filename)[source]
utilities.prnutils.readHarminvOutputSelection(filename)[source]
utilities.prnutils.readPrnFile(fname)[source]
utilities.prnutils.readPrnFile_old(filename, max_lines=None, max_cols=None, delimiter='\t')[source]
utilities.prnutils.readProbeFile(fname)[source]
utilities.prnutils.reshapeData(data, Nrows=None, Ncols=None, header=None)[source]
utilities.prnutils.writePrnFile(fname, X)[source]

Module contents