Commit 4cf66568 authored by alexander.dornheim's avatar alexander.dornheim
Browse files

Started working one phase.py: not yet complete

Changed comments in JWST_in and deleted duplicate
Modified Phase_JWST_demo.py to test phase.py
parent 5844c173
......@@ -2,4 +2,9 @@ import sys
sys.path.append('proxtoolbox/Problems/Phase')
import JWST_data_processor
import JWST_in
JWST_data_processor.JWST_data_processor(JWST_in.new_config)
from phase import Phase
print(JWST_in.new_config);
JWST = Phase(JWST_in.new_config);
JWST.solve();
# -*- coding: utf-8 -*-
new_config = {
'''We start very general.
What type of problem is being solved? Classification
is according to the geometry: Affine, Cone, Convex,
Phase, Affine-sparsity, Nonlinear-sparsity, Sudoku'''
'problem_family' : 'Phase',
'''==========================================
Problem parameters
==========================================
What is the name of the data file?'''
'data_filename' : 'JWST_data_processor',
''' What type of object are we working with?
Options are: 'phase', 'real', 'nonnegative', 'complex' '''
'object' : 'complex',
''' What type of constraints do we have?
Options are: 'support only', 'real and support', 'nonnegative and support',
'amplitude only', 'sparse real', 'sparse complex', and 'hybrid' '''
'constraint' : 'amplitude only',
''' What type of measurements are we working with?
Options are: 'single diffraction', 'diversity diffraction',
'ptychography', and 'complex' '''
'experiment' : 'JWST',
''' Next we move to things that most of our users will know
better than we will. Some of these may be overwritten in the
data processor file which the user will most likely write.
Are the measurements in the far field or near field?
Options are: 'far field' or 'near field' '''
'distance' : 'far field',
# What are the dimensions of the measurements?
'Nx' : 128,
'Ny' : 128,
'Nz' : 1, # do not formulate in the product space
#if 'distance' =='near field':
# 'fresnel_nr' : 1*2*pi*config['Nx'],
# 'use_farfield_formula' : 0,
#else:
'fresnel_nr' : 0, #1*2*pi*prbl.Nx;
'use_farfield_formula' : 1,
# What are the noise characteristics (Poisson or Gaussian or none)?
'noise' : 'Poisson', #'Poisson',
'''==========================================
Algorithm parameters
==========================================
Now set some algorithm parameters that the user should be
able to control (without too much damage)'''
# Algorithm:
'method' : 'RAAR', #'Accelerated_AP_product_space';
'numruns' : 1, # the only time this parameter will
# be different than 1 is when we are
# benchmarking...not something a normal user
# would be doing.
# The following are parameters specific to RAAR, HPR, and HAAR that the
# user should be able to set/modify. Surely
# there will be other algorithm specific parameters that a user might
# want to play with. Don't know how best
# to do this. Thinking of a GUI interface, we could hard code all the
# parameters the user might encounter and have the menu options change
# depending on the value of the prbl.method field.
# do different things depending on the chosen algorithm:
#maximum number of iterations and tolerances
'MAXIT' : 500,
'TOL' : 1e-8,
# relaxaton parameters in RAAR, HPR and HAAR
'beta_0' : 1.0, # starting relaxation prameter (only used with
# HAAR, HPR and RAAR)
'beta_max' : 1.0, # maximum relaxation prameter (only used with
# HAAR, RAAR, and HPR)
'beta_switch' : 20, # iteration at which beta moves from beta_0 -> beta_max
# parameter for the data regularization
# need to discuss how/whether the user should
# put in information about the noise
'data_ball' : 1e-15,
# the above is the percentage of the gap
# between the measured data and the
# initial guess satisfying the
# qualitative constraints. For a number
# very close to one, the gap is not expected
# to improve much. For a number closer to 0
# the gap is expected to improve a lot.
# Ultimately the size of the gap depends
# on the inconsistency of the measurement model
# with the qualitative constraints.
#==========================================
# parameters for plotting and diagnostics
#==========================================
'verbose' : 1, # options are 0 or 1
'graphics' : 1, # whether or not to display figures, options are 0 or 1.
# default is 1.
'anim' : 2, # whether or not to disaply ``real time" reconstructions
# options are 0=no, 1=yes, 2=make a movie
# default is 1.
'graphics_display' : 'JWST_graphics' # unless specified, a default
# plotting subroutine will generate
# the graphics. Otherwise, the user
# can write their own plotting subroutine
#======================================================================
# Technical/software specific parameters
#======================================================================
# Given the parameter values above, the following technical/algorithmic
# parameters are automatically set. The user does not need to know
# about these details, and so probably these parameters should be set in
# a module one level below this one.
}
......@@ -2,43 +2,43 @@
new_config = {
'''We start very general.
What type of problem is being solved? Classification
is according to the geometry: Affine, Cone, Convex,
Phase, Affine-sparsity, Nonlinear-sparsity, Sudoku'''
#We start very general.
#What type of problem is being solved? Classification
#is according to the geometry: Affine, Cone, Convex,
#Phase, Affine-sparsity, Nonlinear-sparsity, Sudoku'''
'problem_family' : 'Phase',
'''==========================================
Problem parameters
==========================================
What is the name of the data file?'''
#==========================================
#Problem parameters
#==========================================
#What is the name of the data file?'''
'data_filename' : 'JWST_data_processor',
''' What type of object are we working with?
Options are: 'phase', 'real', 'nonnegative', 'complex' '''
#What type of object are we working with?
#Options are: 'phase', 'real', 'nonnegative', 'complex' '''
'object' : 'complex',
''' What type of constraints do we have?
Options are: 'support only', 'real and support', 'nonnegative and support',
'amplitude only', 'sparse real', 'sparse complex', and 'hybrid' '''
#What type of constraints do we have?
#Options are: 'support only', 'real and support', 'nonnegative and support',
# 'amplitude only', 'sparse real', 'sparse complex', and 'hybrid' '''
'constraint' : 'amplitude only',
''' What type of measurements are we working with?
Options are: 'single diffraction', 'diversity diffraction',
'ptychography', and 'complex' '''
#What type of measurements are we working with?
#Options are: 'single diffraction', 'diversity diffraction',
# 'ptychography', and 'complex' '''
'experiment' : 'JWST',
''' Next we move to things that most of our users will know
better than we will. Some of these may be overwritten in the
data processor file which the user will most likely write.
Are the measurements in the far field or near field?
Options are: 'far field' or 'near field' '''
#Next we move to things that most of our users will know
#better than we will. Some of these may be overwritten in the
#data processor file which the user will most likely write.
#Are the measurements in the far field or near field?
#Options are: 'far field' or 'near field' '''
'distance' : 'far field',
......@@ -60,14 +60,14 @@ What is the name of the data file?'''
# What are the noise characteristics (Poisson or Gaussian or none)?
'noise' : 'Poisson', #'Poisson',
'''==========================================
Algorithm parameters
==========================================
Now set some algorithm parameters that the user should be
able to control (without too much damage)'''
#==========================================
# Algorithm parameters
#==========================================
# Now set some algorithm parameters that the user should be
# able to control (without too much damage)'''
# Algorithm:
'method' : 'RAAR', #'Accelerated_AP_product_space';
'algorithm' : 'RAAR', #'Accelerated_AP_product_space';
'numruns' : 1, # the only time this parameter will
# be different than 1 is when we are
# benchmarking...not something a normal user
......
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 16 10:15:22 2014
@author: stefan
"""
from numpy import amax, argmax, array, float32, int32, zeros, zeros_like
from matplotlib import pyplot
from .problems import Problem
from proxtoolbox.Problems.problems import Problem
from proxtoolbox import Algorithms
from proxtoolbox import ProxOperators
from proxtoolbox.ProxOperators.proxoperators import ProxOperator
#__all__ = ["Sudoku"]
class ProjGiven(ProxOperator):
class Phase(Problem):
"""
Projection onto the given entries in a Sudoku problem
"""
def __init__(self,config):
"""
Initialization method
Parameters
----------
config : dict - Dictionary containing the problem configuration. It must have the key 'sudoku' mapping to the input Sudoku.
"""
self.given = config['sudoku'].copy()
def work(self,u):
"""
Applies the prox operator to the input data
Parameters
----------
u : array_like - Input data for the operator
Returns
-------
array_like - Result of the operation
"""
A = zeros((9,9,9),dtype=u.dtype)
for x in range(9):
for y in range(9):
z = self.given[x,y]
if z > 0:
A[x,y,z-1] = 1
else:
A[x,y,argmax(u[x,y,:])] = 1
return A
class ProjSquare(ProxOperator):
"""
Projection onto the box constraints in a Sudoku problem
"""
def __init__(self,config=None):
"""
Initialization
Parameters
-----------
config : dict, optional - Not used here
"""
return
def work(self,u):
"""
Applies the prox operator to the input data
Parameters
----------
u : array_like - Input data for the operator
Returns
-------
array_like - Result of the operation
"""
Q = zeros((9,9,9),dtype=u.dtype)
for z in range(9):
for x in range(0,9,3):
for y in range(0,9,3):
v = argmax(u[x:(x+3),y:(y+3),z],axis=0)
w = argmax(amax(u[x:(x+3),y:(y+3),z],axis=0))
Q[x+v[w],y+w,z] = 1
return Q
class ProjColumn(ProxOperator):
"""
Projection onto the column constraints in a Sudoku problem
"""
def __init__(self,config):
"""
Initialization
Parameters
----------
config : dict, optional - Not used here
"""
return
def work(self,u):
"""
Applies the prox operator to the input data
Parameters
----------
u : array_like - Input data for the operator
Returns
-------
array_like - Result of the operation
"""
C = zeros((9,9,9),dtype=u.dtype)
for x in range(9):
for z in range(9):
y = argmax(u[x,:,z])
C[x,y,z] = 1
return C
class ProjRow(ProxOperator):
"""
Projection onto the row constraints in a Sudoku problem
"""
def __init__(self,config):
"""
Initialization
Parameters
----------
config : dict, optional - Not used here
"""
return
def work(self,u):
"""
Applies the prox operator to the input data
Parameters
----------
u : array_like - Input data for the operator
Returns
-------
array_like - Result of the operation
"""
R = zeros((9,9,9),dtype=u.dtype)
for y in range(9):
for z in range(9):
x = argmax(u[:,y,z])
R[x,y,z] = 1
return R
class Sudoku(Problem):
"""
Sudoku Problem
The goal of a standard Sudoku puzzle is to fill a 9x9 array with the numbers
from 1 to 9. Every row, every column and each of the 9 3x3 subblocks should
contain each number only once.
Starting point is a grid that already contains several numbers.
Usually, there exists a unique solution.
Phase Problem
"""
config = {
# This is the algorithm we use. RAAR and HPR will work.
'algorithm':'RAAR',
# RAAR requires 2 ProxOperators
'proxoperators':('P_diag','P_parallel'),
# P_parallel requires a sequence of projectors
'projectors':('ProjRow','ProjColumn','ProjSquare','ProjGiven'),
# Relaxation parameters for RAAR/HPR
'beta0':1,
'beta_max':1,
'beta_switch':1,
# Any algorithm requires these
'maxiter':2000,
'tol':1e-9,
# Dimension parameters
# which are the same for every standard Sudoku
'Nx':9,
'Ny':9,
'Nz':9,
'dim':4,
'normM':81,
# Just a random Sudoku. Not too easy, but no challenge for
# the mighty ProxToolbox!
'sudoku':((2,0,0,0,0,1,0,3,0),
(4,0,0,0,8,6,1,0,0),
(0,0,0,0,0,0,0,0,0),
(0,0,0,0,1,0,0,0,0),
(0,0,0,0,0,0,9,0,0),
(0,0,5,0,0,3,0,0,7),
(0,0,0,0,0,0,0,0,0),
(1,0,0,0,0,7,4,9,0),
(0,2,4,1,0,0,0,0,0))
}
def __init__(self, new_config={}):
"""
The initialization of a Sudoku instance takes the default configuration
The initialization of a Phase instance takes the default configuration
and updates the parameters with the arguments in new_config.
Parameters
......@@ -224,42 +23,15 @@ class Sudoku(Problem):
new_config : dict, optional - Parameters to initialize the problem. If unspecified, the default config is used.
"""
self.config.update(new_config)
print(new_config['algorithm']);
self.algorithm = getattr(Algorithms, self.config['algorithm'])(new_config)
add_config = self.config.copy()
add_config['proxoperators'] = []
for prox in self.config['proxoperators']:
add_config['proxoperators'].append(getattr(ProxOperators, prox))
# add_config.update({'prox1':getattr(ProxOperators, self.config['proj1']),
# 'prox2':getattr(ProxOperators, self.config['proj2'])})
# self.config['algorithm'] = getattr(Algorithms, self.config['algorithm'])
# self.config['proj1'] = getattr(ProxOperators, self.config['proj1'])
# self.config['proj2'] = getattr(ProxOperators, self.config['proj2'])
add_config['projectors'] = []
for p in self.config['projectors']:
add_config['projectors'].append(globals()[p])
add_config['sudoku'] = array(self.config['sudoku'],dtype=float32)
self.algorithm = getattr(Algorithms, self.config['algorithm'])(add_config)
self.config['sudoku'] = array(self.config['sudoku'],dtype=float32)
def _presolve(self):
"""
Prepares argument for actual solving routine
"""
u = zeros((9,9,9,4),dtype=self.config['sudoku'].dtype)
for x in range(9):
for y in range(9):
z = self.config['sudoku'][x,y]-1
if z >= 0:
u[x,y,z,:] = 1
self.u = u
def _solve(self):
......@@ -276,59 +48,11 @@ class Sudoku(Problem):
"""
Processes the solution and generates the output
"""
solution = zeros_like(self.config['sudoku'])
A = self.u1[:,:,:,0]
for x in range(9):
for y in range(9):
for z in range(9):
if A[x,y,z] > 0:
solution[x,y] = z+1
break
self.solution = solution
def show(self):
"""
Generates graphical output from the solution
"""
fig = pyplot.figure('Sudoku')
# plot plain Sudoku puzzle
ax = pyplot.subplot(2,2,1)
ax.title.set_text('Given Sudoku')
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
table = ax.table(cellText=self.config['sudoku'].astype(int32),loc='center')
for cell in table.properties()['child_artists']:
cell.set_height(0.1)
cell.set_width(0.1)
txt = cell.get_text()
if txt.get_text() == '0':
txt.set_text('')
# plot solution
ax = pyplot.subplot(2,2,2)
ax.title.set_text('Solution')
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
table = ax.table(cellText=self.solution.astype(int32),loc='center')
for cell in table.properties()['child_artists']:
cell.set_height(0.1)
cell.set_width(0.1)
# plot the change from one iterate to the next
ax = pyplot.subplot(2,2,3)
ax.xaxis.label.set_text('Iterations')
ax.yaxis.label.set_text('Change')
pyplot.semilogy(self.change)
# plot the gap
ax = pyplot.subplot(2,2,4)
ax.xaxis.label.set_text('Iterations')
ax.yaxis.label.set_text('Gap')
pyplot.semilogy(self.gap)
fig.tight_layout()
fig.show()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment