Skip to content

Commit

Permalink
Repair wrappedJsonStringify, modify reformDefinitionCode (#2178)
Browse files Browse the repository at this point in the history
* fix: Repair wrappedJsonStringify, modify reformDefinitionCode

* chore: Lint
  • Loading branch information
anth-volk authored Nov 4, 2024
1 parent 218662c commit c2334ea
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
35 changes: 33 additions & 2 deletions src/data/reformDefinitionCode.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ export function getHeaderCode(type, metadata, policy) {
lines.push("from policyengine_core.reforms import Reform");
}

// If either baseline or reform contains Infinity or -Infinity,
// add the following Python imports
const allValues = getAllPolicyValues(policy);
if (allValues.some((value) => value === Infinity || value === -Infinity)) {
lines.push("import numpy as np");
}

return lines;
}

Expand Down Expand Up @@ -260,6 +267,30 @@ export function doesParamNameContainNumber(paramName) {
return false;
}

/**
* Given a standard "policy" object, get all individual
* values for both the baseline and reform policies
* @param {Object} policy
* @returns {Array<Number | String >} An array of values
*/
export function getAllPolicyValues(policy) {
const { baseline, reform } = policy;

/** @type {Array<Object>} */
let valueSettings = [];

for (const policy of [baseline, reform]) {
const values = Object.values(policy.data);
valueSettings = valueSettings.concat(values);
}

const output = valueSettings.reduce((accu, item) => {
return accu.concat(...Object.values(item));
}, []);

return output;
}

/**
* Utility function to sanitize a string and ensure that it's valid Python;
* currently converts JS 'null', 'true', 'false', '"Infinity"', and '"-Infinity"' to Python
Expand All @@ -271,6 +302,6 @@ export function sanitizeStringToPython(string) {
.replace(/true/g, "True")
.replace(/false/g, "False")
.replace(/null/g, "None")
.replace(/"Infinity"/g, ".inf")
.replace(/"-Infinity"/g, "-.inf");
.replace(/"Infinity"/g, "np.inf")
.replace(/"-Infinity"/g, "-np.inf");
}
10 changes: 9 additions & 1 deletion src/data/wrappedJson.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,15 @@ export function wrappedJsonParse() {
}

export function wrappedJsonStringify() {
return JSON.stringify(...arguments, JsonReplacer);
// json.stringify's second argument is a replacer function
// Because JS doesn't allow passing params by name (akin to Python),
// we need to specifically override the second arg to allow
// callers of wrappedJsonStringify to pass later args,
// such as JSON.stringify's 3rd arg, the space arg.

let modifiedArgs = [...arguments];
modifiedArgs[1] = JsonReplacer;
return JSON.stringify(...modifiedArgs);
}

/**
Expand Down

0 comments on commit c2334ea

Please sign in to comment.