Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions causalml/optimize/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,20 @@ def get_treatment_costs(treatment, control_name, cc_dict, ic_dict):
A list of experimental conditions.
"""

# Set the conversion costs of the treatments
conversion_cost = np.zeros((len(treatment), len(cc_dict.keys())))
for idx, dict_key in enumerate(cc_dict.keys()):
conversion_cost[:, idx] = cc_dict.get(dict_key)

# Set the impression costs of the treatments
impression_cost = np.zeros((len(treatment), len(ic_dict.keys())))
for idx, dict_key in enumerate(ic_dict.keys()):
impression_cost[:, idx] = ic_dict.get(dict_key)

# Get a sorted list of conditions
conditions = list(set(treatment))
conditions.remove(control_name)
conditions_sorted = sorted(conditions)
conditions_sorted.insert(0, control_name)

# One column per condition, in the same order as conditions_sorted, because
# callers read column j as the cost of conditions[j].
conversion_cost = np.zeros((len(treatment), len(conditions_sorted)))
impression_cost = np.zeros((len(treatment), len(conditions_sorted)))
for idx, condition in enumerate(conditions_sorted):
conversion_cost[:, idx] = cc_dict[condition]
impression_cost[:, idx] = ic_dict[condition]

return conversion_cost, impression_cost, conditions_sorted


Expand Down
28 changes: 28 additions & 0 deletions tests/test_value_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,31 @@ def test_counterfactual_value_optimization():
cve_value = actual_value.loc[test_idx][actual_is_cve_best].mean()

assert cve_value > random_allocation_value


def test_get_treatment_costs_column_order_matches_conditions():
# The returned cost columns are read positionally against the returned
# conditions list, so the same costs written in a different dict order must
# still charge each unit its own treatment's cost.
treatment = pd.Series(["control", "treatment1", "treatment2"] * 2)
outcome = pd.Series(np.ones(6))
value = np.full(6, 100.0)
costs = {"treatment1": 2.0, "treatment2": 7.0, "control": 0.0}

cc_array, ic_array, conditions = get_treatment_costs(
treatment=treatment,
control_name="control",
cc_dict=costs,
ic_dict={key: 0.0 for key in costs},
)
actual_value = get_actual_value(
treatment=treatment,
observed_outcome=outcome,
conversion_value=value,
conditions=conditions,
conversion_cost=cc_array,
impression_cost=ic_array,
)

expected = np.array([100.0 - costs[group] for group in treatment])
np.testing.assert_allclose(np.asarray(actual_value), expected)
Loading