# Extending 1: Writing Your Own Components

Source: https://obsvra.com/learn/modeling-201/extending-lesson-writing-your-own-components

Every business object in SpiceGrinder Pro — the SSN with a real allocatable-range check, the NPI with a real Luhn digit, the routing number with a real ABA checksum — is written the same way you'd write your own. There's no private interface the built-in library gets that a custom component doesn't. If you can describe the shape of the data you need, you can build the generator that produces it.

This is the friendly version of [`Customization.md`](https://obsvra.com/docs/customization), which stays the full reference. Consider this the on-ramp. Same disclosure that doc leads with: writing your own generators and filters is a Pro feature. The interfaces below compile the same on both tiers; loading anything beyond the built-in library is checked at model-load time, and Free says so plainly rather than letting you find out after you've written and compiled something.

## Why Java, and what "dynamic loading" actually means

SpiceGrinder is written in Java specifically so it can load your code without being rebuilt around it. A model file can name a class — `<MyGenerator name="Thing"/>`, or a fully-qualified class name inside `<definitions>` — and the engine finds it at runtime via `Class.forName`, the same mechanism any Java application uses to load a plugin.

That has a real, structural consequence worth knowing before you write a line of code: **a class can only be loaded if it's already on the CLASSPATH the process was started with.** A model can't add anything to that list. If your custom class isn't compiled and placed where the running SpiceGrinder process can already see it, the model that names it fails to load with a plain `ClassNotFoundException` — the same error you'd get for a typo. Nothing about how this works lets a model file smuggle in code that wasn't already deployed there deliberately. [Security 1](https://obsvra.com/learn/ops-101/ops-lesson-security-1) covers the operational side of this in more depth if you're deciding what to actually put there.

## Discovery is annotations, not a config file

You don't register a new component anywhere. Put your class in a package SpiceGrinder already scans (or tell it to scan yours), and two annotations do the rest:

```java
@ComponentInfo(
    name        = "MyGenerator",
    description = "Short human description",
    category    = "generator"
)
public class MyGenerator extends Generator {

    @Parameter(
        name         = "rate",
        description  = "Event rate (must be > 0)",
        defaultValue = "1.0"
    )
    private double rate = 1.0;

    // ...
}
```

`@ComponentInfo` is what makes `<MyGenerator .../>` a legal tag in a model file. `@Parameter` is what makes `rate="2.5"` a legal attribute on it — and it does more than document the field. Simple scalar parameters (`String`, numbers, `boolean`) bind themselves automatically; you don't write parsing code for them unless you need validation beyond "is this a number." The same metadata is what a GUI property panel or an agent skill reads to know what your component takes, without either one having to open your source.

## Custom data points

Every generator returns an observation full of data points, which are the actual values. The interface is compact on purpose:

```java
public interface IDataPoint {
    String stringValue();
    IDataPoint copy();
}
```

If your value is inherently numeric, implement `INumericDataPoint` instead, which just adds two accessors that allow them to be safely used as numbers within the model:

```java
public interface INumericDataPoint extends IDataPoint {
    double doubleValue();
    int intValue();
}
```

The built-in `IntDataPoint` is about as minimal as this gets:

```java
public class IntDataPoint implements INumericDataPoint {
    private final int value;
    public IntDataPoint(int v) { this.value = v; }
    public double doubleValue() { return value; }
    public int intValue()      { return value; }
    public String stringValue() { return Integer.toString(value); }
    public IDataPoint copy()    { return new IntDataPoint(value); }
}
```

A data point can carry more than one value out, too, which is what makes a business object more than a formatted string. `RoutingNumberDataPoint` — a real, shipped component — carries the whole nine-digit number, but also hands back its Federal Reserve routing symbol and its check digit separately, and can tell you on its own whether it's checksum-valid:

```java
public class RoutingNumberDataPoint implements IDataPoint {
    private final String routingNumber;

    public String getFederalReserveSymbol() {
        return routingNumber.substring(0, 2);
    }

    public boolean isChecksumValid() {
        int[] weights = {3, 7, 1, 3, 7, 1, 3, 7, 1};
        int sum = 0;
        for (int i = 0; i < 9; i++) {
            sum += (routingNumber.charAt(i) - '0') * weights[i];
        }
        return sum % 10 == 0;
    }

    public String stringValue() { return routingNumber; }
    public IDataPoint copy() { return new RoutingNumberDataPoint(routingNumber); }
}
```

A downstream filter that needs to check the value, not just print it, can call `isChecksumValid()` directly instead of re-parsing the string it already has. That's the whole reason to write your own data point type instead of just returning a plain string: the shape of your domain object becomes a real Java type other components can work with.

## Custom generators

A generator's job is one method: produce the next observation.

```java
public interface IGenerator {
    String getName();
    int getDimension();
    boolean isSynchronous();
    IObservation getNextObservation() throws SpiceGrinderException;
}
```

You almost never implement that from scratch — extend `com.obsvra.spicegrinder.core.defaults.Generator`, which handles the bookkeeping (name, dimension, the synchronous flag) so your class only has to override `getNextObservation()`. 

Let's take a look at `Skellam` — the difference of two independent Poisson variables — which is a real distribution shipped in the core library, trimmed here for length but otherwise its actual source:

```java
@ComponentInfo(name = "Skellam",
    description = "Difference of two independent Poisson variables (P1 - P2)",
    category = "generator")
public class Skellam extends Generator {

    private IRandom random;

    @Parameter(name = "lambda1", aliases = {"rate1"}, defaultValue = "1.0")
    private double lambda1 = 1.0;
    @Parameter(name = "lambda2", aliases = {"rate2"}, defaultValue = "1.0")
    private double lambda2 = 1.0;

    public Skellam(String name) {
        super(name);
        this.random = Randoms.get();
    }

    @Override
    public void configure(Collection<Pair<String,String>> settings, NodeMap registry) throws Exception {
        for (Pair<String, String> pair : settings) {
            String key = pair.getKey().toLowerCase();
            if ("lambda1".equals(key) || "rate1".equals(key)) lambda1 = Double.parseDouble(pair.getValue());
            if ("lambda2".equals(key) || "rate2".equals(key)) lambda2 = Double.parseDouble(pair.getValue());
        }
        if (lambda1 < 0.0 || lambda2 < 0.0) {
            throw new Exception("Skellam '" + getName() + "': lambda1 and lambda2 must both be >= 0");
        }
    }

    @Override
    public IObservation getNextObservation() throws SpiceGrinderException {
        int value = samplePoisson(lambda1) - samplePoisson(lambda2);
        IObservation obs = new Observation();
        obs.add(new IntDataPoint(value));
        return obs;
    }

    private int samplePoisson(double lambda) {
        double L = Math.exp(-lambda);
        int k = 0;
        double p = 1.0;
        do { k++; p *= random.getNextUniform(); } while (p > L);
        return k - 1;
    }
}
```

Worth noticing what this buys you over the automatic scalar binding `@Parameter` gives you for free: real validation (`lambda1`/`lambda2` must be non-negative), and aliases (`rate1` works as well as `lambda1` in a model file), neither of which the reflective default can do on its own. And `Randoms.get()` is the one line worth internalizing before you write your own generator: it's the actual process-wide RNG handle, seeded from the model's own seed. Reach for `java.util.Random` instead and your component's output stops being reproducible — the whole reason anyone uses this tool in the first place.

## Custom filters

A filter is a generator that also consumes other generators. `Append`, `Mix`, `Redimension` are all filters. So is anything you write that needs to combine, transform, or route values from other nodes in the model.

```java
Collection<IGenerator> getInputs();
void addInput(IGenerator input) throws NotImplementedException;
void addInputs(Collection<IGenerator> inputs) throws NotImplementedException;
```

Extend `Filter` and its default `configure()` wires up `<input name="..."/>` children for you. That's enough when your inputs are interchangeable — a list of things to append, a set of weighted branches to pick from. It's not enough when the inputs play genuinely different *roles*. `PersonAssembler` — real, shipped, Pro — needs a `[gender, givenName]` source and a `surname` source, and they are not interchangeable; swap them and you get nonsense, not just a different result. Trimmed below for length (the required loader constructor and a positional-fallback branch for when roles aren't given are both omitted — see `Customization.md` §9.2 for the complete file):

```java
@ComponentInfo(name = "PersonAssembler",
    description = "Assembles a [gender, givenName] source and a surname source into a Person",
    category = "filter")
public class PersonAssembler extends Filter {

    private IGenerator genderGivenGen;
    private IGenerator surnameGen;

    @Override
    public void configure(Collection<Pair<String, String>> settings, NodeMap registry) throws Exception {
        super.configure(settings, registry);   // scalar binding + populates this.inputs

        Map<String, IGenerator> byRole = new HashMap<>();
        for (Pair<String, String> p : settings) {
            String key = p.getKey();
            if (key != null && key.startsWith("input.") && key.endsWith(".role")) {
                String refName = key.substring(6, key.length() - 5);
                byRole.put(p.getValue().toLowerCase(), registry.getNode(refName));
            }
        }
        genderGivenGen = byRole.get("gendergiven");
        surnameGen = byRole.get("surname");
        this.dimension = 1;
    }

    @Override
    public IObservation getNextObservation() throws SpiceGrinderException {
        IObservation gg = genderGivenGen.getNextObservation();
        String surname = surnameGen.getNextObservation().getAt(0).stringValue();

        IObservation obs = new Observation();
        obs.add(new PersonDataPoint(gg.getAt(0).stringValue(), gg.getAt(1).stringValue(), surname));
        return obs;
    }
}
```

Wired up in XML, the roles are explicit rather than positional:

```xml
<PersonAssembler name="Person">
  <input name="GenderGiven" role="genderGiven"/>
  <input name="Surname" role="surname"/>
</PersonAssembler>
```

## A short note on `synchronous`

There's one piece of state every generator carries that's easy to overlook: whether it needs to keep advancing even on a cycle where its own output isn't the one actually used. A counter hidden behind a `Mix` is the classic case — if it only advances when `Mix` happens to pick it, its value silently desyncs from what a straight read would expect the moment `Mix` picks the other branch instead.

Extending `Filter` gets you the right default behavior for free in the common case: your filter inherits `isSynchronous() == true` automatically if any of its resolved inputs is itself synchronous, so the need to keep advancing propagates through however many filters sit between a stateful generator and whatever selects it, with nothing extra written anywhere. You only have to think about this yourself when your filter's inputs play genuinely different roles — some are real branches, others are meta-parameters (a schedule, a threshold) whose synchronicity shouldn't count. `Customization.md` §9.1 walks through that case, using the built-in `Perturb` filter as the worked example, in the depth this isn't.

## Where to go from here

Everything above is trimmed for length. The full reference — overriding a built-in component, custom random sources, importing external objects with `ISerializable`, giving your component a complexity-scoring weight — is in [`Customization.md`](https://obsvra.com/docs/customization). And once you've got the shape of a custom component down, the natural next question is how two of them talk to each other without being wired together as input and output — that's `Collaborate`, and it gets its own post.
