Needful things

A collection of helpers, which have no place elsewhere.

Nested loop iterator

class PyAstronomy.pyaC.NestedLoop(limits, lowerLimits=None)

Implements an iteration over a nested loop.

Iterates over nested loops. First, increases the first counter, then increments the second and so on.

Parameters
limitslist of int

The upper limits for the loops.

lowerLimitslist of int, optional

The lower limits of the loops. The default is zero.

Example

from __future__ import print_function
from PyAstronomy import pyaC

nl = pyaC.NestedLoop([4,2,5], lowerLimits=[0,0,-5])

for indices in nl:
  print(indices)

Invert index selection

PyAstronomy.pyaC.invertIndexSelection(a, indi)

Invert index selection in one-dimensional array.

Say, e.g., a numpy.where operation produced an array of indices (indi), which you needed for one reason, but now, for another reason, you need all elements of the array, which were not selected by the operation. This is the situation handled by this function.

Parameters
aint or array

Either the length of the array to which indi refers to or the array (one-dimensional) itself.

indiarray

An array of indices selected from a.

Returns
Inverse selectionarray

An array containing the indices of all array elements not referenced by indi.

Example

from __future__ import print_function
import numpy as np
from PyAstronomy import pyaC as pc

# Create "data" values and select some
x = np.exp(np.arange(20.0)/20.0)
indi = np.where(np.logical_and(x > 1.4, x < 1.7))

print("Selected indices and values:")
print("  indices: ", indi)
print("  values : ", x[indi])

indiInv = pc.invertIndexSelection(x, indi)

print()
print("Inverted selection:")
print("  indices: ", indiInv)
print("  values : ", x[indiInv])

# Check that the same result is obtained by simply
# passing the length of the array `x`

indiInvLen = pc.invertIndexSelection(len(x), indi)

print()
print("Are indiInv and indiInvLen are the same? ")
print("  ", np.all(indiInvLen == indiInv))

Fuzzy word matching

PyAstronomy.pyaC.fuzzyMatch(inkey, wordList, caseSensitive=True, n=3, cutoff=0.6, raises=False)

Find exact and approximate matches for input in word list.

Uses get_close_matches from Python’s difflib to search for the best matches between the input keyword and a list of words.

Parameters
inkeystring

The input keyword.

wordListlist of strings

List of words with possible matches for inkey.

caseSensitiveboolean, optional

If True (default), the search will be case sensitive.

nint, optional

Number of potential matches returned by get_close_matches.

cutofffloat, optional

Number between 0 and 1 indicating the degree of similarity between inkey and the entries from wordList. The lower the number, the more dissimilar the potential matches may be. (cutoff parameter from get_close_matches).

raisesboolean, optional

If True, a PyAValError giving a summary of the failure will be raised if no exact match is found. The default is false.

Returns
Matchesdictionary

If found, contains the exact match (key “em”) found in the list (in lower case if caseSensitive is True) and a list of close matches (key “cm”), which the user may have meant to specify. If an exact match is found, also its index in wordList is provided.

Example

from __future__ import print_function
from PyAstronomy import pyaC

wordList = ["one", "two", "three", "four", "o-ne"]

r = pyaC.fuzzyMatch("One", wordList)
print("Exact match: {em:}, close match(es): {cm:}".format(**r))

r = pyaC.fuzzyMatch("One", wordList, cutoff=0.4)
print("Exact match: {em:}, close match(es): {cm:}".format(**r))

r = pyaC.fuzzyMatch("One", wordList, caseSensitive=False)
print("Exact match: {em:}, close match(es): {cm:}".format(**r))

Matrix (2d) output

PyAstronomy.pyaC.matrix2doutput(m, oformat='% 6.2e', colsep=' | ', rowNames=None, colNames=None, transpose=False, toScreen=True)

Format a matrix in readable form and write it to screen.

The column is specified by the second index, e.g., the first entry in the second column is given by m[0,1]. The first entry in the third row is, consequently, given by m[2,0].

Parameters
m2-dimensional array

The data to be formatted.

oformatstring or list of strings, optional

The output format. If string, the same format string will be used for all columns. If a list of strings is given, the associated specifier will be used for each individual column.

colsepstring, optional

The separator used between columns.

rowNameslist of strings, optional

The names of the rows.

colNameslist of strings optional

The names of the columns.

transposeboolean, optional

If True, the input matrix will be transposed. In effect, this exchanges the roles of columns and rows. Note, however, that the role of colNames and rowNames remains unaltered. The default is False.

toScreenboolean, optional

If True (default), the result will be written to screen.

Returns
Formatted matrixlist of strings

The formatted output is a list of strings, which might be written to screen.

Example

from __future__ import print_function
from PyAstronomy import pyaC as PC
import numpy as np

m = np.zeros((4, 3))
colNames = ["first", "second", "third"]
rowNames = ["1", "2", "3", "4"]

for j in range(4):
    for i in range(3):
        m[j, i] = (i+1) * 10**(j+1) * np.sin(i*j)

PC.matrix2doutput(m, colNames=colNames, rowNames=rowNames)
print()
PC.matrix2doutput(m, rowNames=rowNames)
print()
PC.matrix2doutput(m, colsep=" ")
print()
PC.matrix2doutput(m, oformat="% 12.5f", colNames=colNames, rowNames=rowNames)
print()
PC.matrix2doutput(m, oformat=["% 12.5f", "% 6.3f", "% e"], colNames=colNames)

Simple Input-Output file

class PyAstronomy.pyaC.SimIOF(origin, *args, **kwargs)

Simple Input/Output file.

If a file is opened for writing, the origin and date will be added at the top of the file. If it is opened for reading, the properties will be read, converted into float of possible, and stored in the args attribute. If the float-conversion fails, the value is kept as a string.

Parameters
originstr

Identifies the script/program writing the file.

argstuple

Passed to the constructor of a file object.

kwargsdictionary

Passed to the constructor of a file object.

Methods

addColInfo(cns[, oneLine])

Add enumerated column names to file.

addProp(name, value[, fmt])

Add a property to the file.

close()

Close file.

write(*args, **kwargs)

Write to file object

addColInfo(cns, oneLine=True)

Add enumerated column names to file.

Parameters
cnslist of strings

List of names

oneLineboolean, optional

If True, all definitions will be written into a single line. Otherwise each definition is written on its own line.

addProp(name, value, fmt=None)

Add a property to the file.

Parameters
namestring or list of strings

Name of the property

valueany, or list of any type

Value of that property

fmtstring, list, optional

The format-string used to represent the property. If a single string is given, it is applied to all properties. Otherwise, one format string for every property should be given.

close()

Close file.

write(*args, **kwargs)

Write to file object

from __future__ import print_function
from PyAstronomy import pyaC as PC
import numpy as np

f = PC.SimIOF("origin", "test.tmp", 'w')

a = 5.6
b = 8.7
c = 5

f.addProp("a", a, fmt="% 4.4e")
f.addProp(["b", "c"], [b, c])

for x in range(10):
    f.write(str(x) + "\n")

f.close()

g = PC.SimIOF("origin", "test.tmp", 'r')

# See the properties assigned
print(g.args)
# Use loadtxt to load the data
print(np.loadtxt(g))