Skip to content

Commit

Permalink
Introduce variable name for homogenization
Browse files Browse the repository at this point in the history
  • Loading branch information
duembgen committed Jan 12, 2024
1 parent 7ce28d3 commit 59ea38f
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions lifters/state_lifter.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def unravel_multi_index_triu(flat_indices, shape):


class StateLifter(BaseClass):
HOM = "h"
# consider singular value zero below this
EPS_SVD = 1e-5

Expand Down Expand Up @@ -176,7 +177,7 @@ def sub_var_dict(self):
@property
def var_dict(self):
if self.var_dict_ is None:
self.var_dict_ = {"h": 1}
self.var_dict_ = {self.HOM: 1}
self.var_dict_.update(self.base_var_dict)
self.var_dict_.update(self.sub_var_dict)
return self.var_dict_
Expand Down Expand Up @@ -357,7 +358,7 @@ def var_list_row(self, var_subset=None, force_parameters_off=False):

label_list = []
if force_parameters_off:
param_dict = {"h": 0}
param_dict = {self.HOM: 0}
else:
param_dict = self.get_param_idx_dict(var_subset)
for idx, key in enumerate(param_dict.keys()):
Expand Down Expand Up @@ -398,7 +399,7 @@ def get_basis_from_poly_rows(self, basis_poly_list, var_subset=None):
for i, bi_poly in enumerate(basis_poly_list):
# test that this constraint holds

bi = bi_poly.get_matrix((["h"], all_dict))
bi = bi_poly.get_matrix(([self.HOM], all_dict))

if bi.shape[1] == self.get_dim_X(var_subset) * self.get_dim_P():
ai = self.get_reduced_a(bi, var_subset=var_subset)
Expand All @@ -424,13 +425,15 @@ def get_basis_from_poly_rows(self, basis_poly_list, var_subset=None):
def get_vector_dense(self, poly_row_sub):
# complete the missing variables
var_dict = self.var_dict_row()
poly_row_all = poly_row_sub.get_matrix((["h"], var_dict), output_type="poly")
poly_row_all = poly_row_sub.get_matrix(
([self.HOM], var_dict), output_type="poly"
)
vector = np.empty(0)
for param in self.get_param_idx_dict().keys():
# extract each block corresponding to a bigger matrix
sub_mat = PolyMatrix(symmetric=True)
for vari, varj in itertools.combinations_with_replacement(self.var_dict, 2):
val = poly_row_all["h", f"{param}.{vari}.{varj}"]
val = poly_row_all[self.HOM, f"{param}.{vari}.{varj}"]
if np.ndim(val) > 0:
if vari != varj:
sub_mat[vari, varj] = val.reshape(
Expand Down Expand Up @@ -464,13 +467,13 @@ def old_convert_polyrow_to_a(self, poly_row, var_subset, correct=True):
keyi_m, keyj_n = var_keys.split(".")
m = keyi_m.split(":")[-1]
n = keyj_n.split(":")[-1]
if param in ["h", "h.h"]:
if param in [self.HOM, f"{self.HOM}.{self.HOM}"]:
param_val = 1.0
else:
param_val = parameters[param_dict[param]]

# divide off-diagonal elements by sqrt(2)
newval = poly_row["h", key] * param_val
newval = poly_row[self.HOM, key] * param_val
if correct and not ((keyi_m == keyj_n) and (m == n)):
newval /= np.sqrt(2)

Expand Down Expand Up @@ -500,13 +503,13 @@ def convert_polyrow_to_Apoly(self, poly_row, correct=True):
keyi_m, keyj_n = var_keys.split(".")
m = keyi_m.split(":")[-1]
n = keyj_n.split(":")[-1]
if param in ["h", "h.h"]:
if param in [self.HOM, f"{self.HOM}.{self.HOM}"]:
param_val = 1.0
else:
param_val = parameters[param_dict[param]]

# divide off-diagonal elements by sqrt(2)
newval = poly_row["h", key] * param_val
newval = poly_row[self.HOM, key] * param_val
if correct and not ((keyi_m == keyj_n) and (m == n)):
newval /= np.sqrt(2)

Expand Down Expand Up @@ -559,7 +562,7 @@ def convert_a_to_polyrow(
for keyi, keyj in itertools.combinations_with_replacement(var_dict, 2):
if keyi in poly_mat.matrix and keyj in poly_mat.matrix[keyi]:
val = poly_mat.matrix[keyi][keyj]
labels = self.get_labels("h", keyi, keyj)
labels = self.get_labels(self.HOM, keyi, keyj)
if keyi != keyj:
vals = val.flatten()
else:
Expand All @@ -568,7 +571,7 @@ def convert_a_to_polyrow(
assert len(labels) == len(vals)
for label, v in zip(labels, vals):
if np.any(np.abs(v) > self.EPS_SPARSE):
poly_row["h", label] = v
poly_row[self.HOM, label] = v
return poly_row

def convert_b_to_polyrow(self, b, var_subset, tol=1e-10) -> PolyMatrix:
Expand All @@ -583,7 +586,7 @@ def convert_b_to_polyrow(self, b, var_subset, tol=1e-10) -> PolyMatrix:
mask = np.abs(b) > tol
var_list = [v for i, v in enumerate(self.var_list_row(var_subset)) if mask[i]]
for key, val in zip(var_list, b[mask]):
poly_row["h", key] = val
poly_row[self.HOM, key] = val
return poly_row

def apply_templates(self, basis_list, n_landmarks=None, verbose=False):
Expand Down Expand Up @@ -656,7 +659,7 @@ def apply_template(self, bi_poly, n_landmarks=None, verbose=False):
)
except ValueError as e:
pass
new_poly_row["h", key_ij] = bi_poly["h", key]
new_poly_row[self.HOM, key_ij] = bi_poly["h", key]
new_poly_rows.append(new_poly_row)
return new_poly_rows

Expand Down Expand Up @@ -762,7 +765,7 @@ def get_reduced_a(self, bi, var_subset=None, sparse=False):
if isinstance(bi, np.ndarray):
len_b = len(bi)
elif isinstance(bi, PolyMatrix):
bi = bi.get_matrix((["h"], self.var_dict_row(var_subset)))
bi = bi.get_matrix(([self.HOM], self.var_dict_row(var_subset)))
len_b = bi.shape[1]
else:
# bi can be a scipy sparse matrix,
Expand Down Expand Up @@ -870,7 +873,7 @@ def get_A0(self, var_subset=None):
else:
var_dict = self.var_dict
A0 = PolyMatrix()
A0["h", "h"] = 1.0
A0[self.HOM, self.HOM] = 1.0
return A0.get_matrix(var_dict)

def get_A_b_list(self, A_list, var_subset=None):
Expand All @@ -888,20 +891,22 @@ def get_param_idx_dict(self, var_subset=None):
- if param_level == 'ppT': {'l': 0, 'p_0:0.p_0:0': 1, ..., 'p_0:d-1:.p_0:d-1': 1}
"""
if self.param_level == "no":
return {"h": 0}
return {self.HOM: 0}

if var_subset is None:
var_subset = self.var_dict
variables = self.get_variable_indices(var_subset)
param_keys = ["h"] + [f"p_{i}:{d}" for i in variables for d in range(self.d)]
param_keys = [self.HOM] + [
f"p_{i}:{d}" for i in variables for d in range(self.d)
]
if self.param_level == "p":
param_dict = {p: i for i, p in enumerate(param_keys)}
elif self.param_level == "ppT":
i = 0
param_dict = {}
for pi, pj in itertools.combinations_with_replacement(param_keys, 2):
if pi == pj == "h":
param_dict["h"] = i
if pi == pj == self.HOM:
param_dict[self.HOM] = i
else:
param_dict[f"{pi}.{pj}"] = i
i += 1
Expand Down

0 comments on commit 59ea38f

Please sign in to comment.