1.7. py_pol.utils module

Common functions to classes

py_pol.utils.prepare_variables(vars, expand=[False], length=1, obj=None, give_shape=False)[source]

Function that forces all variables of creation methods to be arrays, checks if all variables are a number or arrays of the same size, and expands the required variables if neccessary. If an object is introduced, it also checks that the length of the variables corresponds to the required lengtth for the object.

Parameters:
  • vars (list) – List of variables.

  • expand (bool or list) – List of bools indicating which variables must be expanded.

  • length (int) – If some variables must be expanded but all of them have length 1, this will be the length of the new variables.

  • obj (Py_pol object) – Optical element object.

Returns:

List of prepared variables. obj (Py_pol object): Optical element object (only if an obj was given to the function). shape (tuple): Shape of the variable with higher dimensionality.

Return type:

vars (list)

py_pol.utils.expand_objects(lista, length=1, copy=False)[source]

Expand a list of objects.

Parameters:
  • lista (list) – List of py_pol objects.

  • length (int) – If some variables must be expanded but all of them have length 1, this will be the length of the new variables. Default: 1.

  • copy (bool) – If True, the object are copied. Default: False.

Returns:

List of expanded objects.

Return type:

new_list (list)

py_pol.utils.reshape(vars, shape_like=None, shape_fun=None, shape=None, obj=None)[source]

Reshapes an array of parameters to have the desired shape.

Parameters:
  • vars (list) – List of variables.

  • shape_like (numpy.ndarray or py_pol object) – Use the shape of this object to reshape the variables.

  • shape_fun (tuple, list or string) – User-defined shape. If it is a string (like ‘array’) no manipulation is performed.

  • shape (tuple or list) – Default shape.

  • obj (py_pol object) – Py_pol object to take the shape from. Its preference is less than shape_like.

Returns:

Reshaped list of variables.

Return type:

vars (list)

py_pol.utils.select_shape(obj=None, shape_var=None, shape_fun=None, shape_like=None)[source]

Selects which shape to save.

Parameters:
  • obj (py_pol object) – Object to be applied the shape. It is given here to check if the new shape is correct.

  • shape_var (tuple or list) – Shape of variables.

  • shape_fun (tuple or list) – Shape introduced manually by the user.

  • shape_like (numpy.ndarray or py_pol object) – Object to take the shape from.

Returns:

Selected shape. ndim (int): Number of dimensions.

Return type:

shape (tuple or list)

py_pol.utils.multitake(arr, indices, axes)[source]

Function that implements the numpy.take function in multiple axes.

Parameters:
  • arr (numpy.ndarray) – Original array.

  • indices (tuple or list) – List with the indices values. In this function, only one value per axis is allowed.

  • axes (tuple or list) – List of axes.

Returns:

Taken array.

Return type:

arr (numpy.ndarray)

py_pol.utils.merge_indices(ind1, ind2, axis)[source]

Merges two sets of indices with poritions given by axis.

py_pol.utils.combine_indices(list_ind)[source]

Combines the information given by np.unravel_index.

py_pol.utils.PrintParam(param, verbose=True, draw=True, statistics=True, shape=None, kind='jones', title='', heading='')[source]

Function to print the information during the calculation of some parameters.

Parameters:
  • param (np.array, list or tuple) – List of variables to be represented.

  • verbose (bool) – If True, print the numeric values. Default: True.

  • draw (bool) – If True, plot 1D and 2D parameters. Default: True.

  • statistics (bool) – If True, a basic statistical analysis will be performed. Default: True.

  • shape (list or tuple) – Shape of the elements.

  • kind (string) – Type of jones matrix representation. If ‘jones’ represents real and imaginary part. If ‘amplitude_phase’ represents the amplitude and phase of the Jones matrix. Default: ‘jones’.

  • title (string or list) – Title or list of titles (1-D and 2-D elements).

py_pol.utils.take_shape(objs)[source]

Calculates the shape with higher dimensionality.

py_pol.utils.kron_axis(a, b, axis=None)[source]

Function that implements the kronecker product along a given axis.

Parameters:
  • a (numpy.ndarray) – Arrays to perform the operation.

  • b (numpy.ndarray) – Arrays to perform the operation.

  • axis (int) – Axis to perform the operation. a and b sizes in the rest of dimensions must be the same. If None, default np.kron is used.

Result:

(numpy.ndarray): Result.

py_pol.utils.prepare_variables_blocks(M00=None, Dv=None, Pv=None, m=None, extend=[False, False, False, False], multiply_by_M00=False, length=1, obj=None, other_shape=None, give_shape=False)[source]

Function that forces Mueller matrix block variables to be arrays of the desired size, checks they are compatible between them, and expands the required variables. If an object is introduced, it also checks that the length of the variables corresponds to the required lengtth for the object.

Parameters:
  • M00 (numpy.ndarray or float) – Mean transmission coefficient.

  • Dv (numpy.ndarray) – Diattenuation vector. At least one of its dimensions must be of size 3.

  • Pv (numpy.ndarray) – Polarizance vector. At least one of its dimensions must be of size 3.

  • m (numpy.ndarray) – Small matrix m. At least two of its dimensions must be of size 3.

  • extend (tuple or list with 4 bools) – For each value, stretch the corresponding variable to match max size. Default: [False] * 4.

  • multiply_by_M00 (bool) – If True, multiplies Dv, Pv and m by M00.

  • length (int) – If some variables must be expanded but all of them have length 1, this will be the length of the new variables.

  • obj (Py_pol object) – Optical element object.

  • give_shape (bool) – If True, the output includes the shape variable.

  • other_shape (int, tuple or list) – Other suggested shape given by prepare_variables function.

Returns:

1xN array. Dv (numpy.ndarray): 3xN array. Pv (numpy.ndarray): 3xN array. m (numpy.ndarray): 3x3xN array. obj (Py_pol object): Optical element object (only if an obj was given to the function). shape (tuple): Shape of the variable with higher dimensionality.

Return type:

M00 (numpy.ndarray or float)

py_pol.utils.NumberOfSubplots(n)[source]

Auxiliar function to calculate the number of desired subplots.

py_pol.utils.PrintMatrices(list, Nspaces=3)[source]

Creates the print string of a list of matrices to be printed in a line.

Parameters:
  • list (list) – list of matrices.

  • Nspaces (int) – Number of spaces between matrices.

Returns:

String to be printed.

Return type:

str (string)

py_pol.utils.rotation_matrix_Jones(angle, length=1)[source]

Creates an array of Jones 2x2 rotation matrices.

Parameters:
  • angle (np.array) – array of angle of rotation, in radians.

  • length (int) – If some variables must be expanded but all of them have length 1, this will be the length of the new variables.

Returns:

2x2xN matrix

Return type:

numpy.array

py_pol.utils.rotation_matrix_Mueller(angle=0)[source]

Mueller 4x4 matrix for rotation

References

Gil, Ossikovski (4.30) - p. 131 Handbook of Optics vol 2. 22.16 (eq.8) is with changed sign in sin

Parameters:

angle (float) – angle of rotation with respect to 0 deg.

Returns:

4x4xN rotation matrix.

Return type:

(numpy.array)

py_pol.utils.azimuth_elipt_2_charac_angles(azimuth, ellipticity, out_number=True)[source]

Function that converts azimuth and elipticity to characteristic angles in Jones space.

\[cos(2 \alpha) = cos(2 \phi) * cos(2 \chi)\]
\[tan(\delta) = \frac{tan(2 \chi)}{sin(2 \phi)}\]

TODO: Improve the 2D way of calculating

References

J.J. Gil, R. Ossikovsky “Polarized light and the Mueller Matrix approach”, CRC Press (2016), pp 137 and 1543.

Parameters:
  • azimuth (float or numpy.ndarray) – Azimuth (angle of rotation).

  • ellipticity (float or numpy.ndarray) – Elipticity angle.

  • out_number (bool) – if True and the result is a 1x1 array, return a number instead. Default: True.

Returns:

tan(alpha) is the ratio between the maximum amplitudes of the polarization elipse in X-Y coordinates. delta (float) [0, 2*pi]: phase difference between both components of the eigenstates in Jones formalism.

Return type:

alpha (float) [0,np.pi]

py_pol.utils.charac_angles_2_azimuth_elipt(alpha, delta)[source]

Function that converts azimuth and elipticity to characteristic angles in Jones space.

\[cos(2 \alpha) = cos(2 \phi) * cos(2 \chi)\]
\[tan(\delta) = \frac{tan(2 \chi)}{sin(2 \phi)}\]

References

    1. Gil, “Polarized light and the Mueller Matrix approach”, pp 137 and 154.

Parameters:
  • alpha (float) – tan(alpha) is the ratio between the maximum

  • coordinates. (amplitudes of the polarization elipse in X-Y) –

  • delta (float) – phase difference between both components of the eigenstates in Jones formalism.

Returns:

Azimuth (angle of rotation). ellipticity (float) [-pi/4,np.pi/4]: Elipticity angle.

Return type:

azimuth (float) [0,np.pi]

py_pol.utils.extract_azimuth_elipt(vector, use_nan=True)[source]

Function that extracts azimuth and ellipticity from a diattenuation, polarizance or retardance vector. All of them are of the form of: TODO.

\[cos(2 \alpha) = cos(2 \phi) * cos(2 \chi)\]
\[tan(\delay) = \tan(2 \chi) / sin(2 \phi)\]

References

    1. Gil, “Polarized light and the Mueller Matrix approach”, pp 128 and 142.

Parameters:

vector (np.array 1x3 or 3x1) – vector to be measured

Returns:

Azimuth (angle of rotation). ellipticity (float) [-pi/4,np.pi/4]: Elipticity angle.

Return type:

azimuth (float) [0,np.pi]

py_pol.utils.extract_charac_angles(vector, use_nan=True, type='diattenuator')[source]

Function that extracts azimuth and ellipticity from a diattenuation, polarizance or retardance vector. All of them are of the form of: TODO.

\[cos(2 \alpha) = cos(2 \phi) * cos(2 \chi)\]
\[tan(\delay) = \frac{tan(2 \chi)}{sin(2 \phi)}\]

References

    1. Gil, “Polarized light and the Mueller Matrix approach”, pp 128 and 142.

Parameters:

vector (np.array 1x3 or 3x1) – vector to be measured

Returns:

tan(alpha) is the ratio between the maximum amplitudes of the polarization elipse in X-Y coordinates. delay (float) [0, 2*pi]: phase difference between both components of the eigenstates in Jones formalism.

Return type:

alpha (float) [0,np.pi]

py_pol.utils.which_quad(angle, octant=True)[source]

Auxiliary function to calculate which quadrant or octant angle belongs to. Half angles means that it is exactly between two quarants.

Parameters:

(float) – Angle to determine the quadrant.

Returns:

Quadrant

Return type:

(float)

py_pol.utils.put_in_limits(x, typev, out_number=True)[source]

When dealing with polarization elipse coordinates, make sure that they are in the valid limits, which are set in the declaration of this class.

Parameters:
  • x (1xN array) – Value

  • typev (string) – Which type of variable is: alpha, delta, azimuth or ellipticity.

  • out_number (bool) – if True and the result is a 1x1 array, return a number instead. Default: True.

Returns:

Corresponding angle inside the valid limits.

Return type:

y (1xN array)

py_pol.utils.execute_multiprocessing(__function_process__, dict_parameters, num_processors, verbose=False)[source]

Executes multiprocessing reading a dictionary.

Parameters:
  • __function_process__ (func) – function to process, it only accepts a dictionary

  • dict_parameters (dict) – dictionary / array with parameters

  • num_processors (int) – Number of processors. if 1 no multiprocessing is used

  • verbose (bool) – Prints processing time.

Returns:

results of multiprocessing (float): processing time

Return type:

data

Example:

def __function_process__(xd):
    x = xd['x']
    y = xd['y']
    # grt = copy.deepcopy(grating)
    suma = x + y
    return dict(sumas=suma, ij=xd['ij'])

def creation_dictionary_multiprocessing():
    # create parameters for multiprocessing
    t1 = time.time()
    X = sp.linspace(1, 2, 10)
    Y = sp.linspace(1, 2, 1000)
    dict_parameters = []
    ij = 0
    for i, x in enumerate(X):
        for j, y in enumerate(Y):
            dict_parameters.append(dict(x=x, y=y, ij=[ij]))
            ij += 1
    t2 = time.time()
    print "time creation dictionary = {}".format(t2 - t1)
    return dict_parameters
py_pol.utils.divide_in_blocks(M)[source]

Function that creates a mueller matrix from their block components.

References: J.J. Gil, R. Ossikovsky “Polarized light and the Mueller Matrix approach”, CRC Press (2016)

Parameters:

M (4x4 matrix) – Mueller matrix of the diattenuator.

Returns:

Diattenuation vector. Pv (1x3 or 3x1 float): Diattenuation vector. m (3x3 matrix): Small m matrix. m00 (float, default 1): [0, 1] Parameter of average intensity.

Return type:

Dv (1x3 or 3x1 float)

py_pol.utils.list_of_objects_depercated(size, type_object)[source]

Creates a list of objects.

py_pol.utils.inv_pypol(M)[source]

Calculates the inverse matrix of the matrix of a py_pol object.

Parameters:

M (numpy.ndarray) – Array to calculate the inverse. Its shape must be (NxNxM). The result will have the same shape.

Returns:

Result.

Return type:

(numpy.ndarray)

py_pol.utils.obj_error(sol, test, shape=None, shape_like=None, out_number=None)[source]

Calculates the difference between two abjects and calculates the error as the norm.

py_pol.utils.matmul_pypol(M1, M2)[source]

Calculates the multiplication of two matrices from pypol objects.

Parameters:

M1 (numpy.ndarray) – Left array to multiply. Its shape must be (NxNxM).

:param : Left array to multiply. Its shape must be (NxNxM). :type : numpy.ndarray :param M1: Right array to multiply. Its shape must be (NxNxM) or (NxM). The result will have the same shape. :type M1: numpy.ndarray :param : Right array to multiply. Its shape must be (NxNxM) or (NxM). The result will have the same shape. :type : numpy.ndarray

Returns:

Result.

Return type:

(numpy.ndarray)

py_pol.utils.list_of_objects(size, type_object)[source]

Creates a list of objects.

py_pol.utils.iscolumn(v)[source]

Checks if the array v is a column array or not.

Parameters:

v (array) – Array to be tested.

Returns:

True if v is a column array.

Return type:

cond (bool)

py_pol.utils.isrow(v)[source]

Checks if the array v is a row array or not.

Parameters:

v (array) – Array to be tested.

Returns:

True if v is a row array.

Return type:

cond (bool)

py_pol.utils.delta_kron(a, b)[source]

Computes the Kronecker delta.

Parameters:
  • a (int) – Numbers.

  • b (int) – Numbers.

Returns:

Result.

Return type:

d (int)

py_pol.utils.order_eig(val, vect, kind='normal')[source]

Function that orders the eigenvalues from max to min, and then orders the eigenvectors following the same order.

Parameters:
  • val (numpy.ndarray) – Array of eigenvalues.

  • vect (numpy.ndarray) – Matrix with the eigenvectors as columns.

  • kind (string) – Choses if the sort order is normal (min to max) or reverse (max to min).

Returns:

Array of ordered eigenvalues. m (numpy.ndarray): Matrix with the eigenvectors ordered as columns.

Return type:

q (numpy.ndarray)

py_pol.utils.check_eig(q, m, M)[source]

Function that checks the eigenvalues and eigenvectors.

py_pol.utils.distance(x1, x2)[source]

Compute distance between two vectors.

Parameters:
  • x1 (numpy.ndarray) – vector 1

  • x2 (numpy.ndarray) – vector 2

Returns:

distance between vectors.

Return type:

(float)

py_pol.utils.nearest(vector, number)[source]

Computes the nearest element in vector to number.

Parameters:
  • vector (numpy.ndarray) – array with numbers

  • number (float) – number to determine position

Returns:

index - index of vector which is closest to number. (float): value - value of vector[index]. (float): distance - difference between number and chosen element.

Return type:

(int)

py_pol.utils.nearest2(vector, numbers)[source]

Computes the nearest element in vector to numbers.

Parameters:
  • vector (numpy.ndarray) – array with numbers

  • number (numpy.ndarray) – numbers to determine position

Returns:

index - indexes of vector which is closest to number. (numpy.ndarray): value - values of vector[indexes]. (numpy.ndarray): distance - difference between numbers and chosen elements.

Return type:

(numpy.ndarray)

py_pol.utils.repair_name(name_initial)[source]

Repairs name when several angles are included.

Example

M1 @45.00deg @45.00deg @45.00deg @45.00deg @45.00deg @45.00deg @45.00deg

passes to:

M1 @135.00deg

Parameters:

name_initial (str) – String with the name.

Returns:

Repaired name

Return type:

(str)

py_pol.utils.comparison(proposal, solution, maximum_diff=1e-06)[source]

This functions is mainly for testing. It compares compares proposal to solution.

Parameters:
  • proposal (numpy.matrix) – proposal of result.

  • solution (numpy.matrix) – results of the test.

  • maximum_diff (float) – maximum difference allowed.

Returns:

True if comparison is possitive, else False.

Return type:

(bool)

py_pol.utils.params_to_list(J, verbose=False)[source]

Makes a list from data provided at parameters.dict_params

Parameters:
  • J (object) – Object Jones_vector, Jones_matrix, Stokes or Mueller.

  • verbose (bool) – If True prints the parameters

Returns:

List with parameters from dict_params.

Return type:

(list)

py_pol.utils.fit_distribution(param, dist, irrelevant=0)[source]
py_pol.utils.fit_cos(par, x, y)[source]

Function to fit a cos function using the least_squares function from scipy.optimize.

py_pol.utils.fit_sine(t, data, has_draw=True)[source]

fit a sine function

py_pol.utils.obj_2_xyz(S, Ninterp=1, DAinterp=None, in_degrees=False, param=None, interp_to_surf=False, depol=False)[source]

Function to calculate the x, y and z coordinates of the Poincare sphere.

Parameters:
  • S (Jones_vector or Stokes) – 0D or 1D object to be represented.

  • Ninterp (number) – Multiplication factor to interpolate angles if DAinterp is not None. Default: 1.

  • DAinterp (number) – Angle step for interpolation. Default: None.

  • return_azel (bool) – If True, returns interpolated azimuth and ellipticity. Default: False.

  • in_degrees (bool) – If True, azimuth and ellipticity are returned in degrees. Default: False.

  • interp_to_surf (bool) – If True and S is 1D, transform it to 2D. Default: True.

  • depol (bool) – If True, the depolarization is taking into account for scatter and line plots shrinking the radius below 1. Default: False.

Returns:

Calculated coordinates. az, el (np.ndarray): Interpolated azimuth and ellipticity. param (np.ndarray): Calculated and interpolated parameter.

Return type:

x, y, z (np.ndarray)

py_pol.utils.azel_2_xyz(az, el, pol=1)[source]

Transforms azimuth and ellipticity angle to x, y and z coordinates of the Poincare sphere.

Parameters:
  • az (np.ndarray) – Azimuth.

  • el (np.ndarray) – Ellipticity angle.

  • pol (np.ndarray) – Polarization degree.

Returns:

Calculated coordinates.

Return type:

x, y, z (np.ndarray)