Inline cheap functions into larger operations Examples -------- >>> inc = lambda x: x + 1 >>> add = lambda x, y: x + y >>> double = lambda x: x * 2 >>> dsk = {'out': (add, 'i', 'd'), # doctest: +SKIP ... 'i': (inc, 'x'), ... 'd': (double, 'y'), ...
(
dsk, output, fast_functions=None, inline_constants=False, dependencies=None
)
| 305 | |
| 306 | |
| 307 | def inline_functions( |
| 308 | dsk, output, fast_functions=None, inline_constants=False, dependencies=None |
| 309 | ): |
| 310 | """Inline cheap functions into larger operations |
| 311 | |
| 312 | Examples |
| 313 | -------- |
| 314 | >>> inc = lambda x: x + 1 |
| 315 | >>> add = lambda x, y: x + y |
| 316 | >>> double = lambda x: x * 2 |
| 317 | >>> dsk = {'out': (add, 'i', 'd'), # doctest: +SKIP |
| 318 | ... 'i': (inc, 'x'), |
| 319 | ... 'd': (double, 'y'), |
| 320 | ... 'x': 1, 'y': 1} |
| 321 | >>> inline_functions(dsk, [], [inc]) # doctest: +SKIP |
| 322 | {'out': (add, (inc, 'x'), 'd'), |
| 323 | 'd': (double, 'y'), |
| 324 | 'x': 1, 'y': 1} |
| 325 | |
| 326 | Protect output keys. In the example below ``i`` is not inlined because it |
| 327 | is marked as an output key. |
| 328 | |
| 329 | >>> inline_functions(dsk, ['i', 'out'], [inc, double]) # doctest: +SKIP |
| 330 | {'out': (add, 'i', (double, 'y')), |
| 331 | 'i': (inc, 'x'), |
| 332 | 'x': 1, 'y': 1} |
| 333 | """ |
| 334 | if not fast_functions: |
| 335 | return dsk |
| 336 | |
| 337 | output = set(output) |
| 338 | |
| 339 | fast_functions = set(fast_functions) |
| 340 | |
| 341 | if dependencies is None: |
| 342 | dependencies = {k: get_dependencies(dsk, k) for k in dsk} |
| 343 | dependents = reverse_dict(dependencies) |
| 344 | |
| 345 | def inlinable(key, task): |
| 346 | if ( |
| 347 | not isinstance(task, GraphNode) |
| 348 | and istask(task) |
| 349 | and key not in output |
| 350 | and dependents[key] |
| 351 | ): |
| 352 | try: |
| 353 | if functions_of(task).issubset(fast_functions) and not any( |
| 354 | isinstance(dsk[d], GraphNode) for d in dependents[key] |
| 355 | ): |
| 356 | return True |
| 357 | except TypeError: |
| 358 | pass |
| 359 | return False |
| 360 | |
| 361 | keys = [k for k, v in dsk.items() if inlinable(k, v)] |
| 362 | |
| 363 | if keys: |
| 364 | dsk = inline( |
searching dependent graphs…