Skip to content

Commit 3484e08

Browse files
author
niharika2999
committed
Adding options to call different type of constraints and renaming functions which calculate and update the norm
1 parent c0ab251 commit 3484e08

File tree

1 file changed

+106
-98
lines changed

1 file changed

+106
-98
lines changed

pysensors/optimizers/_gqr.py

Lines changed: 106 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class GQR(QR):
2727
2828
@ authors: Niharika Karnik (@nkarnik2999), Mohammad Abdo (@Jimmy-INL), and Krithika Manohar (@kmanohar)
2929
"""
30-
def __init__(self,idx_constrained,n_sensors,n_const_sensors,all_sensors):
30+
def __init__(self,idx_constrained,n_sensors,n_const_sensors,all_sensors,constraint_option):
3131
"""
3232
Attributes
3333
----------
@@ -39,13 +39,19 @@ def __init__(self,idx_constrained,n_sensors,n_const_sensors,all_sensors):
3939
Total number of sensors
4040
n_const_sensors : integer,
4141
Total number of sensors required by the user in the constrained region.
42+
all_sensors : np.ndarray, shape [n_features]
43+
Optimall placed list of sensors obtained from QR pivoting algorithm.
44+
constraint_option : string,
45+
max_n_const_sensors : The number of sensors in the constrained region should be less than or equal to n_const_sensors.
46+
exact_n_const_sensors : The number of sensors in the constrained region should be exactly equal to n_const_sensors.
4247
"""
4348
self.pivots_ = None
4449
self.optimality = None
4550
self.constrainedIndices = idx_constrained
4651
self.nSensors = n_sensors
4752
self.nConstrainedSensors = n_const_sensors
4853
self.all_sensorloc = all_sensors
54+
self.constraint_option = constraint_option
4955

5056
def fit(
5157
self,
@@ -85,8 +91,10 @@ def fit(
8591
r = R[j:, j:]
8692
# Norm of each column
8793
dlens = np.sqrt(np.sum(np.abs(r) ** 2, axis=0))
88-
dlens_updated = f_region_optimal(self.constrainedIndices,dlens,p,j, self.nConstrainedSensors,self.all_sensorloc,self.nSensors) #Handling constrained region sensor placement problem
89-
#dlens_updated = f_region(self.constrainedIndices,dlens,p,j,self.nConstrainedSensors)
94+
if self.constraint_option == "max_n_const_sensors" :
95+
dlens_updated = norm_calc_max_n_const_sensors(self.constrainedIndices,dlens,p,j, self.nConstrainedSensors,self.all_sensorloc,self.nSensors)
96+
elif self.constraint_option == "exact_n_const_sensors" :
97+
dlens_updated = norm_calc_exact_n_const_sensors(self.constrainedIndices,dlens,p,j,self.nConstrainedSensors)
9098

9199
# Choose pivot
92100
i_piv = np.argmax(dlens_updated)
@@ -121,7 +129,7 @@ def fit(
121129
## TODO: why not a part of the class?
122130

123131
#function for mapping sensor locations with constraints
124-
def f_region(lin_idx, dlens, piv, j, n_const_sensors): ##Will first force sensors into constrained region
132+
def norm_calc_exact_n_const_sensors(lin_idx, dlens, piv, j, n_const_sensors): ##Will first force sensors into constrained region
125133
#num_sensors should be fixed for each custom constraint (for now)
126134
#num_sensors must be <= size of constraint region
127135
"""
@@ -155,7 +163,7 @@ def f_region(lin_idx, dlens, piv, j, n_const_sensors): ##Will first force sensor
155163
dlens[didx] = 0
156164
return dlens
157165

158-
def f_region_optimal(lin_idx, dlens, piv, j, const_sensors,all_sensors,n_sensors): ##Optimal sensor placement with constraints (will place sensors in the order of QR)
166+
def norm_calc_max_n_const_sensors(lin_idx, dlens, piv, j, const_sensors,all_sensors,n_sensors): ##Optimal sensor placement with constraints (will place sensors in the order of QR)
159167
"""
160168
Function for mapping constrained sensor locations with the QR procedure (Optimally).
161169
@@ -196,96 +204,96 @@ def f_region_optimal(lin_idx, dlens, piv, j, const_sensors,all_sensors,n_sensors
196204

197205

198206

199-
# if __name__ == '__main__':
200-
# faces = datasets.fetch_olivetti_faces(shuffle=True)
201-
# X = faces.data
202-
203-
# n_samples, n_features = X.shape
204-
# print('Number of samples:', n_samples)
205-
# print('Number of features (sensors):', n_features)
206-
207-
# # Global centering
208-
# X = X - X.mean(axis=0)
209-
210-
# # Local centering
211-
# X -= X.mean(axis=1).reshape(n_samples, -1)
212-
213-
# n_row, n_col = 2, 3
214-
# n_components = n_row * n_col
215-
# image_shape = (64, 64)
216-
# nx = 64
217-
# ny = 64
218-
219-
# def plot_gallery(title, images, n_col=n_col, n_row=n_row, cmap=plt.cm.gray):
220-
# '''Function for plotting faces'''
221-
# plt.figure(figsize=(2. * n_col, 2.26 * n_row))
222-
# plt.suptitle(title, size=16)
223-
# for i, comp in enumerate(images):
224-
# plt.subplot(n_row, n_col, i + 1)
225-
# vmax = max(comp.max(), -comp.min())
226-
# plt.imshow(comp.reshape(image_shape), cmap=cmap,
227-
# interpolation='nearest',
228-
# vmin=-vmax, vmax=vmax)
229-
# plt.xticks(())
230-
# plt.yticks(())
231-
# plt.subplots_adjust(0.01, 0.05, 0.99, 0.93, 0.04, 0.)
232-
233-
# # plot_gallery("First few centered faces", X[:n_components])
234-
235-
# #Find all sensor locations using built in QR optimizer
236-
# max_const_sensors = 230
237-
# n_const_sensors = 2
238-
# n_sensors = 200
239-
# optimizer = ps.optimizers.QR()
240-
# model = ps.SSPOR(optimizer=optimizer, n_sensors=n_sensors)
241-
# model.fit(X)
242-
243-
# all_sensors = model.get_all_sensors()
244-
245-
# ##Constrained sensor location on the grid:
246-
# xmin = 20
247-
# xmax = 40
248-
# ymin = 25
249-
# ymax = 45
250-
# sensors_constrained = getConstraindSensorsIndices(xmin,xmax,ymin,ymax,nx,ny,all_sensors) #Constrained column indices
251-
252-
# # didx = np.isin(all_sensors,sensors_constrained,invert=False)
253-
# # const_index = np.nonzero(didx)
254-
# # j =
255-
256-
257-
# ##Plotting the constrained region
258-
# # ax = plt.subplot()
259-
# # #Plot constrained space
260-
# # img = np.zeros(n_features)
261-
# # img[sensors_constrained] = 1
262-
# # im = plt.imshow(img.reshape(image_shape),cmap=plt.cm.binary)
263-
# # # create an axes on the right side of ax. The width of cax will be 5%
264-
# # # of ax and the padding between cax and ax will be fixed at 0.05 inch.
265-
# # divider = make_axes_locatable(ax)
266-
# # cax = divider.append_axes("right", size="5%", pad=0.05)
267-
# # plt.colorbar(im, cax=cax)
268-
# # plt.title('Constrained region');
269-
270-
# ## Fit the dataset with the optimizer GQR
271-
# optimizer1 = GQR(sensors_constrained,n_sensors,n_const_sensors,all_sensors)
272-
# model1 = ps.SSPOR(optimizer = optimizer1, n_sensors = n_sensors)
273-
# model1.fit(X)
274-
# all_sensors1 = model1.get_all_sensors()
275-
276-
# top_sensors = model1.get_selected_sensors()
277-
# print(top_sensors)
278-
# ## TODO: this can be done using ravel and unravel more elegantly
279-
# #yConstrained = np.floor(top_sensors[:n_const_sensors]/np.sqrt(n_features))
280-
# #xConstrained = np.mod(top_sensors[:n_const_sensors],np.sqrt(n_features))
281-
282-
# img = np.zeros(n_features)
283-
# img[top_sensors] = 16
284-
# #plt.plot(xConstrained,yConstrained,'*r')
285-
# plt.plot([xmin,xmin],[ymin,ymax],'r')
286-
# plt.plot([xmin,xmax],[ymax,ymax],'r')
287-
# plt.plot([xmax,xmax],[ymin,ymax],'r')
288-
# plt.plot([xmin,xmax],[ymin,ymin],'r')
289-
# plt.imshow(img.reshape(image_shape),cmap=plt.cm.binary)
290-
# plt.title('n_sensors = {}, n_constr_sensors = {}'.format(n_sensors,n_const_sensors))
291-
# plt.show()
207+
if __name__ == '__main__':
208+
faces = datasets.fetch_olivetti_faces(shuffle=True)
209+
X = faces.data
210+
211+
n_samples, n_features = X.shape
212+
print('Number of samples:', n_samples)
213+
print('Number of features (sensors):', n_features)
214+
215+
# Global centering
216+
X = X - X.mean(axis=0)
217+
218+
# Local centering
219+
X -= X.mean(axis=1).reshape(n_samples, -1)
220+
221+
n_row, n_col = 2, 3
222+
n_components = n_row * n_col
223+
image_shape = (64, 64)
224+
nx = 64
225+
ny = 64
226+
227+
def plot_gallery(title, images, n_col=n_col, n_row=n_row, cmap=plt.cm.gray):
228+
'''Function for plotting faces'''
229+
plt.figure(figsize=(2. * n_col, 2.26 * n_row))
230+
plt.suptitle(title, size=16)
231+
for i, comp in enumerate(images):
232+
plt.subplot(n_row, n_col, i + 1)
233+
vmax = max(comp.max(), -comp.min())
234+
plt.imshow(comp.reshape(image_shape), cmap=cmap,
235+
interpolation='nearest',
236+
vmin=-vmax, vmax=vmax)
237+
plt.xticks(())
238+
plt.yticks(())
239+
plt.subplots_adjust(0.01, 0.05, 0.99, 0.93, 0.04, 0.)
240+
241+
# plot_gallery("First few centered faces", X[:n_components])
242+
243+
#Find all sensor locations using built in QR optimizer
244+
max_const_sensors = 230
245+
n_const_sensors = 2
246+
n_sensors = 200
247+
optimizer = ps.optimizers.QR()
248+
model = ps.SSPOR(optimizer=optimizer, n_sensors=n_sensors)
249+
model.fit(X)
250+
251+
all_sensors = model.get_all_sensors()
252+
253+
##Constrained sensor location on the grid:
254+
xmin = 20
255+
xmax = 40
256+
ymin = 25
257+
ymax = 45
258+
sensors_constrained = ps.utils._constraints.get_constraind_sensors_indices(xmin,xmax,ymin,ymax,nx,ny,all_sensors) #Constrained column indices
259+
260+
# didx = np.isin(all_sensors,sensors_constrained,invert=False)
261+
# const_index = np.nonzero(didx)
262+
# j =
263+
264+
265+
##Plotting the constrained region
266+
# ax = plt.subplot()
267+
# #Plot constrained space
268+
# img = np.zeros(n_features)
269+
# img[sensors_constrained] = 1
270+
# im = plt.imshow(img.reshape(image_shape),cmap=plt.cm.binary)
271+
# # create an axes on the right side of ax. The width of cax will be 5%
272+
# # of ax and the padding between cax and ax will be fixed at 0.05 inch.
273+
# divider = make_axes_locatable(ax)
274+
# cax = divider.append_axes("right", size="5%", pad=0.05)
275+
# plt.colorbar(im, cax=cax)
276+
# plt.title('Constrained region');
277+
278+
## Fit the dataset with the optimizer GQR
279+
optimizer1 = GQR(sensors_constrained,n_sensors,n_const_sensors,all_sensors, constraint_option = "exact_n_const_sensors")
280+
model1 = ps.SSPOR(optimizer = optimizer1, n_sensors = n_sensors)
281+
model1.fit(X)
282+
all_sensors1 = model1.get_all_sensors()
283+
284+
top_sensors = model1.get_selected_sensors()
285+
print(top_sensors)
286+
## TODO: this can be done using ravel and unravel more elegantly
287+
#yConstrained = np.floor(top_sensors[:n_const_sensors]/np.sqrt(n_features))
288+
#xConstrained = np.mod(top_sensors[:n_const_sensors],np.sqrt(n_features))
289+
290+
img = np.zeros(n_features)
291+
img[top_sensors] = 16
292+
#plt.plot(xConstrained,yConstrained,'*r')
293+
plt.plot([xmin,xmin],[ymin,ymax],'r')
294+
plt.plot([xmin,xmax],[ymax,ymax],'r')
295+
plt.plot([xmax,xmax],[ymin,ymax],'r')
296+
plt.plot([xmin,xmax],[ymin,ymin],'r')
297+
plt.imshow(img.reshape(image_shape),cmap=plt.cm.binary)
298+
plt.title('n_sensors = {}, n_constr_sensors = {}'.format(n_sensors,n_const_sensors))
299+
plt.show()

0 commit comments

Comments
 (0)