E.g., "Let f(x)=2x+1, g(x)=3x+2. What is 5*f(x) - 7*g(x)?".
(value, sample_args, context=None)
| 192 | # TODO(b/124039290): merge with compose? both add and compose do similar things. |
| 193 | @composition.module(composition.is_integer_polynomial) |
| 194 | def add(value, sample_args, context=None): |
| 195 | """E.g., "Let f(x)=2x+1, g(x)=3x+2. What is 5*f(x) - 7*g(x)?".""" |
| 196 | is_question = context is None |
| 197 | if context is None: |
| 198 | context = composition.Context() |
| 199 | |
| 200 | entropy, sample_args = sample_args.peel() |
| 201 | |
| 202 | if value is None: |
| 203 | max_degree = 3 |
| 204 | degree = random.randint(1, max_degree) |
| 205 | entropy -= math.log10(max_degree) |
| 206 | entropy_value = entropy / 2 |
| 207 | entropy -= entropy_value |
| 208 | value = polynomials.sample_coefficients( |
| 209 | degree, entropy=entropy_value, min_non_zero=random.randint(1, 3)) |
| 210 | value = composition.Polynomial(value) |
| 211 | |
| 212 | c1, c2, coeffs1, coeffs2 = polynomials.coefficients_linear_split( |
| 213 | value.coefficients, entropy) |
| 214 | coeffs1 = polynomials.trim(coeffs1) |
| 215 | coeffs2 = polynomials.trim(coeffs2) |
| 216 | |
| 217 | c1, c2, fn1, fn2 = context.sample( |
| 218 | sample_args, |
| 219 | [c1, c2, composition.Polynomial(coeffs1), composition.Polynomial(coeffs2)] |
| 220 | ) |
| 221 | |
| 222 | var = sympy.var(context.pop()) |
| 223 | |
| 224 | expression = ( |
| 225 | c1.handle * fn1.handle.apply(var) + c2.handle * fn2.handle.apply(var)) |
| 226 | |
| 227 | if is_question: |
| 228 | answer = polynomials.coefficients_to_polynomial(value.coefficients, var) |
| 229 | answer = answer.sympy() |
| 230 | template = random.choice(_TEMPLATES) |
| 231 | return example.Problem( |
| 232 | question=example.question(context, template, composed=expression), |
| 233 | answer=answer) |
| 234 | else: |
| 235 | intermediate_symbol = context.pop() |
| 236 | intermediate = sympy.Function(intermediate_symbol)(var) |
| 237 | return composition.Entity( |
| 238 | context=context, |
| 239 | value=value, |
| 240 | description='Let {intermediate} = {composed}.', |
| 241 | handle=composition.FunctionHandle(intermediate_symbol), |
| 242 | intermediate=intermediate, |
| 243 | composed=expression) |
| 244 | |
| 245 | |
| 246 | def expand(value, sample_args, context=None): |