Exemple #1
0
def score_combined(decoder_current,  # h_t
                   decoder_previous,  # h_i
                   reuse_variables=False,
                   dtype=tf.float32):
  """ Applies a score function of the form

              v.(W1.hi + W2.hs)

  where W is a weight matrix, v is a vector of parameters, hi is one
  of each of the decoder hidden states and hs is the current hidden state at
  timestep t.

  The function performs a 1-by-1 convolution to calculate W.hi  and performs
  the W2.hs step using a ``linear'' cell (see cells.linear for the
  documentation)  and broadcasted into the result of W1.hi (encoder_hiddens)
  via multiplication step.  After this step a reduce_sum is performed over
  axis=[2,3] so the correct results are obtained.

  Args:
      decoder_current: not used
      attn_size: the size of the attention vectors
      encoder_hiddens: 3-D Tensor [batch_size, timestep, hidden_dim]. It
          represents the hidden sattes of the decoder up to the current
          timestep.
      current_hidden: Tensor, representing the current hidden state at
          timestep t

  Returns:
      beta: decoder hidden states after applying the content function

  """
  with tf.variable_scope("score_salton_combined") as scope:
    if reuse_variables:
      scope.reuse_variables()

    _, output_size = get_2d_tensor_shapes(decoder_current)

    decoder_current = cells.linear(
      [decoder_current], output_size, bias=False, dtype=dtype)

    #
    decoder_previous, attn_dim = reshape_attention(decoder_previous)

    # we first get the correct weight matrix
    ws = tf.get_variable("AttnDecWs", [1, 1, attn_dim, attn_dim], dtype=dtype)

    # we apply a small convolution to the decoder states - it is more
    # efficient than performing a recurrent matrix * matrix
    hidden_features = convolve(decoder_previous, ws)

    hidden_features = hidden_features + decoder_current

    # we then get the vector v that will be used on the second
    # multiplication op.
    vs = tf.get_variable("AttnDecVs", [attn_dim], dtype=dtype)

    scores = tf.reduce_sum((vs * tf.tanh(hidden_features)), [2, 3])

  return scores
    def global_pooling_branch(self):
        
        global_pool = tf.layers.average_pooling2d(inputs = self.layer,pool_size = self.layer_shape[1],strides = 1)
        conv1_2 = convolve(layer = global_pool, ksize = self.layer_shape[1], in_depth = self.layer_shape[-1], 
                           out_depth = self.layer_shape[-1], padding = 'VALID') 
        upsampled = convolve_T(layer = conv1_2, ksize = self.layer_shape[1], strides = [1,self.layer_shape[1],self.layer_shape[1],1], 
                               in_depth = self.layer_shape[-1], out_depth = self.layer_shape[-1], output_shape = self.layer_shape)
#        
        return upsampled
Exemple #3
0
    def _convolve(self, src_neglogprob, src_branch_neglogprob, inverse_time):
        """
        Compute the convolution of parent (target) and child (source)
        nodes negative log-likelihood distributions.
        Take the source node log-LH distribution, extracts its grid. Based on
        the branch length probability distribution (also neg log-LH), find
        approximate position of the target node. Make the grid for the target
        node, and for each point of this newly generated grid, compute the
        convolution over all possible positions of the source node.

        Args:

        - src_neglogprob (scipy.interpolate.interp1d): neg log-LH
         distribution of the node to be integrated, represented as scipy
         interpolation object

        - src_branch_neglogprob(scipy.interpolate.interp1d): neg log-LH
         distribution of the branch lenghts between the two nodes, represented
         as scipy interpolation object

         - inverse_time (bool): Whether the time should be inversed.
         True if we go from leaves to root (against absolute time scale), and
         the convolution is computed over positions of the child node.
         False if the messages are propagated from root towards leaves (the same
         direction as the absolute time axis), and the convolution is being
         computed over the position of the parent node

        """

        opt_source_pos = utils.min_interp(src_neglogprob)
        opt_branch_len = utils.min_interp(src_branch_neglogprob)
        if inverse_time:
            opt_target_pos = opt_source_pos + opt_branch_len  # abs_t
        else:
            opt_target_pos = opt_source_pos - opt_branch_len

        # T
        target_grid = utils.make_node_grid(opt_target_pos)
        target_grid.sort()  # redundant
        if hasattr(src_neglogprob, 'delta_pos'):  # convolve with delta-fun
            x_axis = target_grid - src_neglogprob.delta_pos
            x_axis[x_axis < ttconf.MIN_T] = ttconf.MIN_T
            x_axis[x_axis > ttconf.MAX_T] = ttconf.MAX_T
            res_y = src_branch_neglogprob(x_axis)
            res = interp1d(target_grid, res_y, kind='linear')
        else:  # convolve two different distributions
            pre_b = np.min(src_branch_neglogprob.y)
            pre_n = np.min(src_neglogprob.y)
            src_branch_neglogprob.y -= pre_b
            src_neglogprob.y -= pre_n
            res = utils.convolve(target_grid, src_neglogprob,
                                 src_branch_neglogprob)
            src_branch_neglogprob.y += pre_b
            src_neglogprob.y += pre_n
            res.y += pre_b
            res.y += pre_n
        return res
Exemple #4
0
    def _convolve(self, src_neglogprob, src_branch_neglogprob, inverse_time):
        """
        Compute the convolution of parent (target) and child (source)
        nodes negative log-likelihood distributions.
        Take the source node log-LH distribution, extracts its grid. Based on
        the branch length probability distribution (also neg log-LH), find
        approximate position of the target node. Make the grid for the target
        node, and for each point of this newly generated grid, compute the
        convolution over all possible positions of the source node.

        Args:

        - src_neglogprob (scipy.interpolate.interp1d): neg log-LH
         distribution of the node to be integrated, represented as scipy
         interpolation object

        - src_branch_neglogprob(scipy.interpolate.interp1d): neg log-LH
         distribution of the branch lenghts between the two nodes, represented
         as scipy interpolation object

         - inverse_time (bool): Whether the time should be inversed.
         True if we go from leaves to root (against absolute time scale), and
         the convolution is computed over positions of the child node.
         False if the messages are propagated from root towards leaves (the same
         direction as the absolute time axis), and the convolution is being
         computed over the position of the parent node

        """

        opt_source_pos = utils.min_interp(src_neglogprob)
        opt_branch_len = utils.min_interp(src_branch_neglogprob)
        if inverse_time:
            opt_target_pos = opt_source_pos + opt_branch_len # abs_t
        else:
            opt_target_pos = opt_source_pos - opt_branch_len

        # T
        target_grid = utils.make_node_grid(opt_target_pos)
        target_grid.sort() # redundant
        if hasattr(src_neglogprob, 'delta_pos'): # convolve with delta-fun
            x_axis = target_grid - src_neglogprob.delta_pos
            x_axis[x_axis < ttconf.MIN_T] = ttconf.MIN_T
            x_axis[x_axis > ttconf.MAX_T] = ttconf.MAX_T
            res_y = src_branch_neglogprob(x_axis)
            res = interp1d(target_grid, res_y, kind='linear')
        else: # convolve two different distributions
            pre_b = np.min(src_branch_neglogprob.y)
            pre_n = np.min(src_neglogprob.y)
            src_branch_neglogprob.y -= pre_b
            src_neglogprob.y -= pre_n
            res = utils.convolve(target_grid, src_neglogprob, src_branch_neglogprob)
            src_branch_neglogprob.y += pre_b
            src_neglogprob.y += pre_n
            res.y += pre_b
            res.y += pre_n
        return res
Exemple #5
0
def score_single(
        unused_arg,  # not used - pylint: disable=W0613
        decoder_previous,  # h_i
        reuse_variables=False,
        dtype=tf.float32):
    """ Applies a score function of the form

              v.(W.hi)

  to the hidden states of the decoder, where W is a weight matrix, v is a
  vector of parameters and hi is one of each of the decoder hidden states.

  The function performs a 1-by-1 convolution to calculate W.hi and the vector
  v is broadcasted with a multiplication step into the result of W.hi. After
  this step a reduce_sum is performed over axis=[2,3] so the correct results
  are obtained.

  Args:
      decoder_current: not used
      attn_size: the size of the attention vectors
      encoder_hiddens: 3-D Tensor [batch_size, timestep, hidden_dim]. It
          represents the hidden sattes of the decoder up to the current
          timestep.
      current_hidden: Tensor, representing the current hidden state at
          timestep t

  Returns:
      beta: decoder hidden states after applying the content function

  """

    with tf.variable_scope("score_salton_single") as scope:
        if reuse_variables:
            scope.reuse_variables()

        #
        decoder_previous, attn_dim = reshape_attention(decoder_previous)

        # we first get the correct weight matrix
        ws = tf.get_variable("AttnDecWs", [1, 1, attn_dim, attn_dim],
                             dtype=dtype)

        # we apply a small convolution to the decoder states - it is more
        # efficient than performing a recurrent matrix * matrix
        hidden_features = convolve(decoder_previous, ws)

        # we then get the vector v that will be used on the second
        # multiplication op.
        vs = tf.get_variable("AttnDecV_%d" % 0, [attn_dim], dtype=dtype)

        scores = tf.reduce_sum((vs * tf.tanh(hidden_features)), [2, 3])

    return scores
def edge_detection(im):
    '''
	Function that convolves im with vertial and horizontal sobel filters
	to find edges in a photo

	Args:
		im: np.array of shape [H, W, 3]
	'''
    image = gausian_blur(im, 5, 1.4)

    image = grayscale_mean(image)

    # Using vertical and horizontal Sobel kernels
    sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    sobel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])

    edge_x = convolve(image, sobel_x)
    edge_y = convolve(image, sobel_y)
    edge = np.round(np.sqrt(np.power(edge_x, 2) + np.power(edge_y, 2)))

    return edge, edge_x, edge_y
Exemple #7
0
def wahabFilter(image, orientations, w=8):
    result = np.empty(image.shape)

    height, width = image.shape
    for y in range(0, height - w, w):
        for x in range(0, width - w, w):
            orientation = orientations[y+w//2, x+w//2]
            kernel = wahabKernel(16, orientation)
            result[y:y+w, x:x+w] = utils.convolve(image, kernel, (y, x), (w, w))
            result[y:y+w, x:x+w] /= np.sum(kernel)

    return result
 def downsample(self):
             
     max_pool_1 = MaxPool2d(layer = self.layer)
     conv7_1 = convolve(layer = max_pool_1, ksize = 7, in_depth = self.layer_shape[-1], 
                        out_depth = self.layer_shape[-1])
     conv7_2 = convolve(layer = conv7_1, ksize = 7, in_depth = self.layer_shape[-1], 
                        out_depth = self.layer_shape[-1])
     
     max_pool_2 = MaxPool2d(layer = conv7_1)
     conv5_1 = convolve(layer = max_pool_2, ksize = 5, in_depth = self.layer_shape[-1], 
                        out_depth = self.layer_shape[-1])
     conv5_2 = convolve(layer = conv5_1, ksize = 5, in_depth = self.layer_shape[-1], 
                        out_depth = self.layer_shape[-1])
     
     max_pool_3 = MaxPool2d(layer = conv5_1)
     conv3_1 = convolve(layer = max_pool_3, ksize = 3, in_depth = self.layer_shape[-1], 
                        out_depth = self.layer_shape[-1])
     conv3_2 = convolve(layer = conv3_1, ksize = 3, in_depth = self.layer_shape[-1], 
                        out_depth = self.layer_shape[-1])
     
     upsampled_8 = convolve_T(layer = conv3_2, ksize = 2, in_depth = self.layer_shape[-1], out_depth = self.layer_shape[-1], 
                              output_shape = conv5_2.get_shape().as_list())
     added_1 = tf.add(upsampled_8, conv5_2)
     upsampled_16 = convolve_T(layer = added_1, ksize = 2, in_depth = self.layer_shape[-1], out_depth = self.layer_shape[-1], 
                              output_shape = conv7_2.get_shape().as_list())
     added_2 = tf.add(upsampled_16, conv7_2)
     upsampled_32 = convolve_T(layer = added_2, ksize = 2, in_depth = self.layer_shape[-1], out_depth = self.layer_shape[-1], 
                              output_shape = self.layer.get_shape().as_list())
     
     return upsampled_32
def gausian_blur(im, kernel_size=5, kernel_sigma=1.0):
    ''' 
	A function that convolves im with kernel.
	
	Args:
		im: np.array of shape [H, W, 3]
		kernel: nparray of shape [S, S]
	
	Returns:
		np.array of shape [H, W, 3]
	'''
    kernel = gausian_kernel(kernel_size, kernel_sigma)
    return convolve(im, kernel)
Exemple #10
0
def q2_3_b():
    impulseH = np.zeros(8000)
    impulseH[1] = 1
    impulseH[4000] = 0.5
    impulseH[7900] = 0.3
    play_sound(ipcleanfilename)
    Fs, sampleX_16bit = read_sound(ipcleanfilename)
    sampleX_float = fnNormalize16BitToFloat(sampleX_16bit)
    y = convolve(sampleX_float, impulseH)
    y_16bit = fnNormalizeFloatTo16Bit(y)
    save_file_name = "t2_16bit.wav"
    save_sound(save_file_name, Fs, y_16bit)
    play_sound(save_file_name)
Exemple #11
0
def score_single(unused_arg,  # not used - pylint: disable=W0613
                 decoder_previous,  # h_i
                 reuse_variables=False,
                 dtype=tf.float32):
  """ Applies a score function of the form

              v.(W.hi)

  to the hidden states of the decoder, where W is a weight matrix, v is a
  vector of parameters and hi is one of each of the decoder hidden states.

  The function performs a 1-by-1 convolution to calculate W.hi and the vector
  v is broadcasted with a multiplication step into the result of W.hi. After
  this step a reduce_sum is performed over axis=[2,3] so the correct results
  are obtained.

  Args:
      decoder_current: not used
      attn_size: the size of the attention vectors
      encoder_hiddens: 3-D Tensor [batch_size, timestep, hidden_dim]. It
          represents the hidden sattes of the decoder up to the current
          timestep.
      current_hidden: Tensor, representing the current hidden state at
          timestep t

  Returns:
      beta: decoder hidden states after applying the content function

  """

  with tf.variable_scope("score_salton_single") as scope:
    if reuse_variables:
      scope.reuse_variables()

    #
    decoder_previous, attn_dim = reshape_attention(decoder_previous)

    # we first get the correct weight matrix
    ws = tf.get_variable("AttnDecWs", [1, 1, attn_dim, attn_dim], dtype=dtype)

    # we apply a small convolution to the decoder states - it is more
    # efficient than performing a recurrent matrix * matrix
    hidden_features = convolve(decoder_previous, ws)

    # we then get the vector v that will be used on the second
    # multiplication op.
    vs = tf.get_variable("AttnDecV_%d" % 0, [attn_dim], dtype=dtype)

    scores = tf.reduce_sum((vs * tf.tanh(hidden_features)), [2, 3])

  return scores
Exemple #12
0
def q2_3_a():
    impulseH = np.zeros(8000)
    impulseH[1] = 1
    impulseH[4000] = 0.5
    impulseH[7900] = 0.3
    plt.stem(impulseH)
    plt.grid()
    plt.show()
    x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
    h = np.array([1, 2, 3, 4, 5, 6])
    y_test = convolve(x, h)
    y = np.convolve(x, h)
    comparison = y == y_test
    assert comparison.all()
Exemple #13
0
def q2_4_b():
    h1 = np.array(
        [0.06523, 0.14936, 0.21529, 0.2402, 0.21529, 0.14936, 0.06523],
        dtype='float')
    h2 = np.array(
        [-0.06523, -0.14936, -0.21529, 0.7598, -0.21529, -0.14936, -0.06523],
        dtype='float')
    n = np.arange(0, 10)
    x = np.zeros(len(n))
    for i in range(len(n)):
        x[i] = delta(n[i]) - 2 * delta(n[i] - 15)
    results_1_1 = convolve(x, h1)
    results_1_2 = np.convolve(x, h1)
    results_1_3 = signal.lfilter(h1, [1], x)
    print(results_1_1)
    print(results_1_2)
    print(results_1_3)
    results_2_1 = convolve(x, h2)
    results_2_2 = np.convolve(x, h2)
    results_2_3 = signal.lfilter(h2, [1], x)
    print(results_2_1)
    print(results_2_2)
    print(results_2_3)
Exemple #14
0
#Transform Function
transform = lambda x: activation_function(
    (np.dot(x, hidden.value) + bias.value)).tolist()

#Load
data = sc.textFile(file_input).map(lambda x: float(x.split(";")[1]))

#Indexing
data = utils.zip_index(data)

#normalization
data_min, data_max, data = utils.normalization(sc, data)

#Convolve Data (Feature Selection)
data = utils.convolve(data, jumlah_fitur)

#Transform data
data = data.map(lambda x: (x[0], x[1], transform(x[2])))

#Split train and test
train, test = utils.train_test_split(data)

#Labelling Points
train = utils.labelled_points(train)
test = utils.labelled_points(test)

#Regression (this is not least square but SGD)
lrm = LinearRegressionWithSGD()
model = lrm.train(train)
Exemple #15
0
end_queue_v = manager.Queue(30)

multiprocessing.Pool(1, worker, (beg_queue_v, 0, 25, valid_paths))
multiprocessing.Pool(1, worker, (mid_queue_v, 26, 125, valid_paths))
multiprocessing.Pool(1, worker, (end_queue_v, 126, 999, valid_paths))

observation_placeholder = tf.placeholder("float32",
                                         [batch_size, dims, dims, 3])
moves_placeholder = tf.placeholder("float32", [batch_size, dims, dims, 5])
mask_placeholder = tf.placeholder("float32", [batch_size, dims, dims])
rewards_placeholder = tf.placeholder("float32", [batch_size, 1])
training_placeholder = tf.placeholder(tf.bool)
learning_rate = tf.Variable(1e-4, trainable=False)

with tf.variable_scope('model'):
    h_conv1 = convolve(observation_placeholder, 3, 256, 'c1')
    h_conv2 = convolve(h_conv1, 256, 128, 'c2', kernel=3)
    h_conv3 = convolve(h_conv2, 128, 128, 'c3', kernel=3)
    h_conv5 = convolve(h_conv3, 128, 128, 'c51', kernel=3)
    h_conv7 = convolve(h_conv5, 128, 128, 'c61', kernel=3)
    h_conv4 = convolve(h_conv7, 128, 256, 'c5', kernel=3)
    h_conv18 = convolve(h_conv4, 256, 5, 'c18', False, kernel=5)

prediction_layer = h_conv18

ce = tf.nn.softmax_cross_entropy_with_logits(
    prediction_layer, moves_placeholder) * mask_placeholder

pre_loss = tf.reduce_sum(
    tf.reshape(ce, [batch_size, -1]) * rewards_placeholder)
def generator(acres):
    for _ in range(1000):
        acres = convolve(acres)
        yield score(acres)
Exemple #17
0
def score_combined(
        decoder_current,  # h_t
        decoder_previous,  # h_i
        reuse_variables=False,
        dtype=tf.float32):
    """ Applies a score function of the form

              v.(W1.hi + W2.hs)

  where W is a weight matrix, v is a vector of parameters, hi is one
  of each of the decoder hidden states and hs is the current hidden state at
  timestep t.

  The function performs a 1-by-1 convolution to calculate W.hi  and performs
  the W2.hs step using a ``linear'' cell (see cells.linear for the
  documentation)  and broadcasted into the result of W1.hi (encoder_hiddens)
  via multiplication step.  After this step a reduce_sum is performed over
  axis=[2,3] so the correct results are obtained.

  Args:
      decoder_current: not used
      attn_size: the size of the attention vectors
      encoder_hiddens: 3-D Tensor [batch_size, timestep, hidden_dim]. It
          represents the hidden sattes of the decoder up to the current
          timestep.
      current_hidden: Tensor, representing the current hidden state at
          timestep t

  Returns:
      beta: decoder hidden states after applying the content function

  """
    with tf.variable_scope("score_salton_combined") as scope:
        if reuse_variables:
            scope.reuse_variables()

        _, output_size = get_2d_tensor_shapes(decoder_current)

        decoder_current = cells.linear([decoder_current],
                                       output_size,
                                       bias=False,
                                       dtype=dtype)

        #
        decoder_previous, attn_dim = reshape_attention(decoder_previous)

        # we first get the correct weight matrix
        ws = tf.get_variable("AttnDecWs", [1, 1, attn_dim, attn_dim],
                             dtype=dtype)

        # we apply a small convolution to the decoder states - it is more
        # efficient than performing a recurrent matrix * matrix
        hidden_features = convolve(decoder_previous, ws)

        hidden_features = hidden_features + decoder_current

        # we then get the vector v that will be used on the second
        # multiplication op.
        vs = tf.get_variable("AttnDecVs", [attn_dim], dtype=dtype)

        scores = tf.reduce_sum((vs * tf.tanh(hidden_features)), [2, 3])

    return scores
Exemple #18
0
#!/usr/bin/env python

from __future__ import print_function

from utils import convolve
from utils import reader
from utils import score

if __name__ == '__main__':
    with open('data.txt', 'r') as f:
        acres = reader(f)

    for _ in range(10):
        acres = convolve(acres)

    print('Answer:', score(acres))
    # 589931
norm_imgs_show = (norm_imgs - np.min(norm_imgs)) / (np.max(norm_imgs) -
                                                    np.min(norm_imgs))
plt.figure(figsize=(10, 10))
plt.imshow(utils.montage(norm_imgs_show, 'normalized.png'))

#creates kernel
ksize = 16
kernel = np.concatenate(
    [utils.gabor(ksize)[:, :, np.newaxis] for i in range(3)], axis=2)
kernel_4d = tf.reshape(kernel, [kernel.shape[0], kernel.shape[1], 3, 1])
plt.figure(figsize=(5, 5))
plt.imshow(kernel_4d[:, :, 0, 0], cmap='gray')
plt.imsave(arr=kernel_4d[:, :, 0, 0], fname='kernel.png', cmap='gray')

#convolutes image
convolved = utils.convolve(imgs, kernel_4d)
convolved_show = (convolved - np.min(convolved)) / (np.max(convolved) -
                                                    np.min(convolved))
print(convolved_show.shape)
plt.figure(figsize=(10, 10))
plt.imshow(utils.montage(convolved_show[..., 0], 'convolved.png'), cmap='gray')

flattened = tf.reshape(convolved, (100, 10000))
# Now calculate some statistics about each of our images
values = tf.reduce_sum(flattened, axis=1)

# Then create another operation which sorts those values
# and then calculate the result:
idxs = tf.nn.top_k(values, k=100)[1]

# Then finally use the sorted indices to sort your images:
Exemple #20
0
	def compute_defocus(self, start, stop, step, letter_size):
		letter_size = 5 * letter_size / 20.
		plotdimension = 60. * self.PARAMS['1'] * (180. * 60. / np.pi) * self.PARAMS['5'] *.001 / self.PARAMS['4']
		letter_size = self.PARAMS['1'] * letter_size * 60. / plotdimension 
		E = utils.make_E(letter_size, self.PARAMS['1'] ) # make an E of designated letter size

		self.c[:5] = 0 # set the correctable terms to zero
		defocus_range = np.arange(start, stop + step, step) # range of defoci in dioptres
		# fig, ax = plt.subplots(1, len(defocus_range), figsize=(6,2)) # intitialize figure

		if not os.path.isdir('static'):
			os.mkdir('static')
		else:
			# for filename in glob.glob(os.path.join('static', '*.png')):
			# 	os.remove(filename)
		
		fig, ax = plt.subplots(1,len(defocus_range))
		for i, defocus in enumerate(defocus_range):
			self.c[3] = utils.calculateDefocus(self.PARAMS['2'], defocus)
			PSF = self.PSF()[1]
			Conv = utils.convolve(E, PSF.T)
			ax[i].imshow(Conv, cmap='gray')
			ax[i].xaxis.set_visible(False)
			ax[i].yaxis.set_visible(False)
			ax[i].set_title(str(defocus) + " D")


		plotfile = os.path.join('static', 'DE_' + str(time.time()) + '.png')
		fig.savefig(plotfile)

		return plotfile




	def defocus_e(self):
		pass

	def defocus_streh_rms(self):
		pass

	def defocus_mtf(self):
		pass

	def PSF(self):
		pupilfunc = self.Zphase_MahajanOSA()

		Hamp = np.fft.fft2(pupilfunc)
		Hint = Hamp * np.conj(Hamp)


		plotdimension = 60 * self.PARAMS['1'] * (180 *60 / np.pi) * self.PARAMS['5'] *.001 / self.PARAMS['4'] # divided by the size of the pupil field.
		PSF = np.real(np.fft.fftshift(Hint)) # reorients the PSF so the origin is at the center of the image
		PSF = PSF / (self.PARAMS['6']**2) # scale the PSF so that peak represents the Strehl ratio

		axisPSF = np.arange(-plotdimension/2, ((plotdimension/2)-(plotdimension/self.PARAMS['1'])) + (plotdimension/self.PARAMS['1']), plotdimension/self.PARAMS['1'])

		# plot psf
		plt.figure(figsize=(8,4))
		plt.imshow(PSF, cmap='gray', extent=[-plotdimension/2, plotdimension/2, -plotdimension/2, plotdimension/2], aspect='auto')
		plt.title('Point Spread Function')
		plt.xlabel('arcsec')
		plt.ylabel('arcsec')
		plt.xlim([-plotdimension/2, plotdimension/2])
		plt.ylim([-plotdimension/2, plotdimension/2])

		# if not os.path.isdir('static'):
		# 	os.mkdir('static')
		# # else:
		# # 	for filename in glob.glob(os.path.join('static', '*.png')):
		# # 		os.remove(filename)
		plotfile = os.path.join('static', 'PSF_' + str(time.time()) + '.png')
		plt.savefig(plotfile)
		#plt.savefig("static/last/psf.png")
		return plotfile, PSF


	def compWaveOSA(self):
		waveabermap = self.Zwave_MahajanOSA()
		
		# waveabermap = waveabermap.T --> transpose for Austin's method
		n = waveabermap.shape

		# Define the axes of the wavefront plot in cyc/degree
		axispupil = np.arange(-self.PARAMS['2']/2, (self.PARAMS['2']/2)-(self.PARAMS['2']/n[0]) + self.PARAMS['2']/n[0], self.PARAMS['2']/n[0])

		# set parameters and display the wavefront aberration as a mesh plot
		v = np.arange(np.floor(np.min(waveabermap)) - 0.25, np.ceil(np.max(waveabermap)) + 0.25, 0.25)

		# plot wave aberration contour plot
		plt.figure(figsize=(8,4))
		plt.contourf(axispupil, axispupil, waveabermap)
		plt.colorbar()
		plt.title('Wavefront Aberration')
		plt.xlabel('mm (right-left)')
		plt.ylabel('mm (superior-inferior)')

		if not os.path.isdir('static'):
			os.mkdir('static')
		else:
			for filename in glob.glob(os.path.join('static', '*.png')):
				os.remove(filename)
		plotfile = os.path.join('static', 'WAM_' + str(time.time()) + '.png')
		plt.savefig(plotfile)
		#plt.savefig("static/last/wavemap.png")
		return plotfile

	def Zwave_MahajanOSA(self):
		newsize = np.ceil(self.PARAMS['7']*self.PARAMS['2']).astype(int)
		waveabermap = np.zeros((newsize, newsize))
		sizeoffield = self.PARAMS['2']

		self.PARAMS['6'] = 0

		#------ Joel's Method -------------------------------------------------------------
		nx = z_adjust(np.arange(1, newsize+1), sizeoffield, newsize)
		ny = z_adjust(np.arange(1, newsize+1), sizeoffield, newsize)

		xx, yy = np.meshgrid(nx, ny)

		angle, norm_radius = utils.cart2pol(xx,yy)
		norm_radius = norm_radius / (self.PARAMS['3'] / 2)
		r = norm_radius

		phase = utils.computePhase(self.c, angle, r)
		waveabermap[np.where(norm_radius > self.PARAMS['2']/self.PARAMS['3'])] = float('nan')
		waveabermap[np.where(norm_radius <= self.PARAMS['2']/self.PARAMS['3'])] = phase[np.where(norm_radius <= self.PARAMS['2']/self.PARAMS['3'])]


		# #---- Austin's Method --------------------------------------------------------------
		# for ny in range(newsize):
		# 	for nx in range(newsize):
		# 		xpos = ((nx - 1) * (sizeoffield / newsize) - (sizeoffield / 2))
		# 		print(xpos)
		# 		ypos = ((ny - 1) * (sizeoffield / newsize) - (sizeoffield / 2))

		# 		angle, norm_radius = utils.cart2pol(xpos,ypos)
		# 		norm_radius = norm_radius / (self.PARAMS['3'] / 2)
		# 		r = norm_radius

		# 		if norm_radius > self.PARAMS['2']/self.PARAMS['3']:
		# 			waveabermap[nx,ny] = float('nan')
		# 		else:
		# 			phase = utils.computePhase(self.c, angle, r)
		# 			waveabermap[nx,ny] = phase
		# 			self.PARAMS['6'] += 1

		return waveabermap

	def Zphase_MahajanOSA(self):
		phasemap = np.zeros((self.PARAMS['1'],self.PARAMS['1']))
		phasemap = phasemap + phasemap*1j 
		sizeoffield = self.PARAMS['4']

		B = 0.2 # fraction if the diffuse component;
		A = 1 - B # raction of directed component;
		peakx = 0 # normalized location of peak reflectance in x-direction
		peaky = 0 # normalized location of peak reflectance in x-direction
		p = 0 # 0.047 # set to zero to turn off the amplitude factor (Values from Burns et al in mm^(-2)

		self.PARAMS['6'] = 0

		# ----------Joel's Method --------------------------------
		nx = z_adjust(np.arange(1, self.PARAMS['1'] + 1), sizeoffield, self.PARAMS['1'])
		ny = z_adjust(np.arange(1, self.PARAMS['1'] + 1), sizeoffield, self.PARAMS['1'])
		xx, yy = np.meshgrid(nx, ny)

		angle, norm_radius = utils.cart2pol(xx,yy)
		norm_radius = norm_radius / (float(self.PARAMS['2']) / 2.)
		r = norm_radius

		phase = utils.computePhase(self.c, angle, r)
		d = np.sqrt((peakx - xx)**2 + (peaky - yy)**2);
		SCfactor = B + A * 10**(-p * ((self.PARAMS['2'])**2) * d**2)

		phase_result = SCfactor * np.exp(-1j * 2 * np.pi * phase / self.PARAMS['5'])

		phasemap[np.where(norm_radius <= 1)] = phase_result[np.where(norm_radius <= 1)]

		self.PARAMS['6'] = np.sum((norm_radius <= 1).astype(int))


		# #-------- Austin's Method ---------------------------------
		# newsize = self.PARAMS['1']
		# for ny in np.arange(1, self.PARAMS['1'] + 1):
		# 	for nx in np.arange(1, self.PARAMS['1'] + 1):
		# 		xpos = (((float(nx) - 1.) * (float(sizeoffield) / float(newsize))) - (sizeoffield / 2.))
		# 		ypos = (((float(ny) - 1.) * (float(sizeoffield) / float(newsize))) - (sizeoffield / 2.))

		# 		angle, norm_radius = utils.cart2pol(xpos,ypos)	
		# 		norm_radius = float(norm_radius) / (float(self.PARAMS['2']) / 2.)
		# 		r = norm_radius

				
		# 		if norm_radius > 1:
		# 			pass
		# 		else:
		# 			phase = utils.computePhase(self.c, angle, r)
		# 			d = np.sqrt((peakx - xpos)**2 + (peaky - ypos)**2);
		# 			SCfactor = B + A * 10**(-p * ((self.PARAMS['2'])**2) * d**2)
		# 			phasemap[nx,ny] = SCfactor * np.exp(-1j * 2 * np.pi * phase / self.PARAMS['5'])
		# 			self.PARAMS['6'] += 1

		return phasemap
 def direct_branch(self):
     
     conv1_1 = convolve(layer = self.layer, ksize = 1, in_depth = self.layer_shape[-1], 
                        out_depth = self.layer_shape[-1], padding = 'VALID')    
     return conv1_1