How a blend of nested stocks becomes a weighed batch.

I am developing a perfumery business. This notebook works out the arithmetic under a blend: how nested dilutions resolve to raw materials, and how a batch is weighed so that its total stays exact while every stock keeps to its cap.

A fitted one gram blend at the centre and, ring by ring outward, what each stock was made from, a line to every five milligrams of aromatic material. Rose marks the raw aromatics; the thinning and the two empty chambers are carrier.

Nested stocks and a target profile

Each stock is a mix of raw materials (leaves) and other stocks. The page follows those dilutions down to the leaves, weighs a batch to the exact target mass, and fits a capped blend of stocks to a target descriptor profile. Every number below is recomputed from the source you edit.

The descriptor profiles add linearly by mass. That linearity is a convenience for the arithmetic and predicts nothing about smell.

The stock graph and the batch

The materials, profiles and costs are made up, none of it is a formula from the business, and everything runs in your browser: nothing you type is stored or sent.

Profiles, mass parts, stock weights, caps, inventory and costs are all editable in the JSON source. Loading an example or resetting replaces your edits and clears the results.

Edit the stock graph, blend target and balance resolution

Edit formulation[].weight for relative stock weights; targetBatchMg and incrementMg for scaling; cap for each stock's maximum mass fraction. Edit leaf descriptors and targetDescriptor for the design problem. Array order defines descriptor axes and rounding ties.

3 to 5 descriptors; 1 to 12 leaves; 1 to 10 stocks, including nested stocks; 50,000 source characters. Batch: 0.001 to 1,000,000 mg. Batch and increment: at most 3 decimal places. Caps: 0 to 1, at most 6 decimal places. Unknown and duplicate JSON fields are refused.

JavaScript is required to compute. No calculation has run.

Method and limits

Graph and batch arithmetic

Each stock contains positive relative mass parts referencing leaves or other stocks. Parts are normalized within that stock. Recursive leaf fraction = sum of component fraction times the child's leaf fraction. Every graph ID is unique; duplicate component references, missing references and cycles fail closed, even in unused definitions. A repeated stock across different parents is valid and its leaf demand is pooled.

Formulation weights are dimensionless relative masses, normalized by their positive sum. Weights: 0 or 1e-9 to 1,000,000. Parts: 1e-9 to 1,000,000. Batch and increment are represented as integer micrograms; divisibility is checked exactly. At most one billion balance units. Desired stock units are floored, then remaining units go in descending fractional-remainder order, with source-order ties and integer cap checks. The ranked pass repeats until every unit is placed, so a stock already at its integer cap passes its share to the next in rank; the export records the number of passes. No mass is allocated to zero desired weights. An infeasible capped resolution is rejected with one of two reasons, and the caps stay as written. Integer caps too tight: at this increment the capped stocks with a share cannot hold the batch, and the message gives both unit counts. Could not place units: the ranked passes stopped with units left over, which the first check exists to prevent, and the message gives the units left and the passes made. Tiny positive stocks and leaves that round to zero are disclosed.

Stock caps constrain each stock's share of the total mass, a number you set for the arithmetic. Scaling rejects an over-cap current blend; optimization may start from one and projects it onto the feasible set. Rounded caps are rechecked with integer arithmetic. Inventory is checked again after rounding; any shortage above 0.000001 mg is flagged. The optimizer ignores inventory; a shortage is reported and nothing more. A plan with sufficient continuous inventory may have insufficient rounded inventory.

Rounding quotas use exact integer fractions from each Number's canonical decimal representation after JSON parsing. Scale uses the original input weights before floating-point normalization; Optimize uses its computed solver fractions. Those values are renormalized to the exact target for rounding. Equal rational remainders follow source order, without treating merely close remainders as ties. The export records the integer numerators, denominator and remainders. This does not recover digits already lost when JSON numbers were parsed.

Leaf fractions and costs use IEEE-754 double precision. Fraction conservation tolerance: 1e-12. Mass reconciliation and inventory comparison tolerance: 0.000001 mg. Fixed-decimal input conversion allows only four machine-epsilon units of scaled representation error. Display values are rounded; full numerical values remain in the audit. Conservation holds for the arithmetic; measurement accuracy, mixing yield and material recovery belong to the bench.

Convex blend optimizer

Let D contain the recursively resolved stock descriptor columns. The fixed objective is f(x) = 0.5 * ||D x - target||², subject to sum(x) = 1 and 0 <= x[j] <= cap[j]. All descriptor axes have equal weight. That is the whole objective: cost, inventory, odor and closeness to a reference blend play no part. Profiles and targets are supplied values in [0,1]; abstract carriers have zero profiles. The descriptor blend uses total mass, carrier included.

Projected gradient uses a fixed step 1 / max(1, ||D||_F²). Projection onto the capped simplex uses x[j] = clip(v[j] - tau, 0, cap[j]), 80 bisection steps and a final floating-sum correction. The initial iterate is the projection of your normalized current weights. The reported residual is ||x - project(x - step * gradient)||_infinity / step. Its requested tolerance is 1e-9 to 1e-3; the iteration budget is 1 to 2,000.

With this step the objective cannot rise in exact arithmetic. If floating-point error ever makes it rise by more than 1e-12, the iteration and the size of the rise are recorded, the fit continues, a warning names the first rise, and the history marks each one. Only residual-tolerance termination is labeled numerically converged; a run that reaches the iteration limit says so, and its blend may not be the best fit. Convexity allows several equally good blends, and the residual measures stationarity rather than the gap to the optimum. The complete objective and fraction history is exported. Rounding is a separate discrete step and can move the fit away from the continuous optimum. All-zero or indistinguishable profiles may have many equivalent solutions.

Source schema and units

Required top-level fields: fictional: true, scenario, descriptors, targetDescriptor, leaves, stocks, formulation, targetBatchMg, incrementMg, solver. The loaded examples are complete and editable. Unknown, missing or duplicate fields are errors. JSON nesting is limited to 16 levels.

Each leaf requires id, label, kind, descriptors, unitCostPerGram, inventoryMg, evidence. Kind is aromatic or carrier. Each stock requires id, label, components, evidence; each component requires ref, parts. Each formulation row requires stockId, weight, cap. Solver requires maxIterations, tolerance. IDs are case sensitive, start with an ASCII letter, and have at most 24 letters, digits, underscores or hyphens. Stock and leaf IDs share one namespace. BATCH is reserved for the root of the batch.

Scenario: up to 120 characters; labels: 80; evidence notes: 240; descriptor names: 32. Text cannot contain control characters or unpaired Unicode surrogates. Leaf inventory: 0 to 1,000,000,000 mg. Leaf cost: 0 to 1,000,000 CU/g. Cost = leaf mass in mg divided by 1,000 times CU/g. Stock cost is its recursively weighted leaf cost. Labor, packaging, taxes, losses, volume conversion, premade-stock inventory and procurement are outside the model.

Real materials, implementation and checks

Real materials need supplier documents, verified identity, the applicable restrictions and review by a qualified professional. A blend that computes cleanly can still be unsafe or noncompliant, and an IFRA certificate of conformity sits beside a safety assessment, never in its place. IFRA: understanding the Standards.

The engine and the interface are plain JavaScript with no dependencies; the same engine runs in Node and the browser. Edits disappear on reload. A download contains the complete supplied JSON and every iteration.

I checked the engine against hand-worked cases (a known two-stock optimum, nested dilution, pooling, cost units and integer rounding), against an independent grid search, and against the projection's own invariants. Those checks cover the arithmetic alone.