🏠 Home · ← Prev: Mork reference — overview
To solve a problem with Mork you combine a few fundamental pieces. This document describes what each one represents and what the user has to implement.
Almost all Mork classes are generic and always use the same letters:
I extends Instance— the instance type (input data).S extends Solution<S, I>— the solution type (uses a recursive self-type).M extends Move<S, I>— the move type (a change on a solution).
You will see signatures such as Objective<M, S, I>, Neighborhood<M, S, I> or Algorithm<S, I>.
Key idea in this version: the value (score) of a solution is not stored in
Solutionnor inMove. It is centralized in theObjectiveabstraction, which knows how to evaluate both a complete solution (evalSol) and the incremental impact of a move (evalMove, delta evaluation).
Root package of all classes: es.urjc.etsii.grafo.
es.urjc.etsii.grafo.io.Instance
public abstract class Instance implements Comparable<Instance>Represents the input data of a problem. Golden rule: an instance must be immutable once loaded (no setters on its data). This way it can be shared between threads without race conditions, something essential for reproducibility.
- It is identified by a
String id(name), set insuper(id)and accessible withgetId(). - It can publish numeric properties with
setProperty("name", value)/getProperty(...). These properties appear in the reports and are the basis of automatic instance selection and of complexity analysis. compareTo(byid) determines the order in which instances are solved; it can be overridden to sort by size or another property.
The user extends Instance, adds their final fields and calls super(id). There are no
mandatory abstract methods.
public class TSPInstance extends Instance {
private final Coordinate[] locations;
private final double[][] distances;
protected TSPInstance(String name, Coordinate[] locations, double[][] distances) {
super(name);
this.locations = locations;
this.distances = distances;
setProperty("cities", locations.length); // property for reports/selection
}
public int numberOfLocations() { return locations.length; }
public double getDistance(int i, int j) { return distances[i][j]; }
}es.urjc.etsii.grafo.io.InstanceImporter<I>
The user implements the parsing method:
public abstract I importInstance(BufferedReader reader, String suggestedInstanceId) throws IOException;Mork takes care of opening the file (it supports ZIP/7z/tar/tar.gz, strips the BOM, uses UTF-8), derives a suggested identifier from the file name and calls this method. The loading time does not count as the algorithm's execution time.
es.urjc.etsii.grafo.solution.Solution
public abstract class Solution<SELF extends Solution<SELF, I>, I extends Instance>Holds the mutable state that changes during optimization (the route, the assignment, the
chosen subset…). It keeps an immutable reference to its instance and internal metadata
(version, which is incremented on every executed move, and lastModifiedTime, used to compute
the time-to-best).
Mandatory abstract methods:
| Method | Responsibility |
|---|---|
SELF cloneSolution() |
Return a deep clone. "Deep clone mutable data or you will regret it." |
String toString() |
Textual representation (for logs/debugging). |
Usual pattern: two constructors — one from the instance (empty solution) and one copy constructor (for cloning) — and incremental score updates (delta evaluation).
public class TSPSolution extends Solution<TSPSolution, TSPInstance> {
private int[] route;
private double routeLength; // cached score
public TSPSolution(TSPInstance ins) { super(ins); this.route = new int[ins.numberOfLocations()]; }
public TSPSolution(TSPSolution s) { super(s); this.route = s.route.clone(); this.routeLength = s.routeLength; }
@Override public TSPSolution cloneSolution() { return new TSPSolution(this); }
public double getDistance() { return this.routeLength; } // used by the Objective
public double recalculateScore() { /* recompute from scratch, WITHOUT side effects */ }
}
getDistance()andrecalculateScore()are not methods of the base class: they are the user's own methods, named freely. The framework uses them through theObjective(to evaluate) and through theSolutionValidator(to check that the cached score is correct).
Other useful methods: getInstance(), notifyUpdate() (marks the solution as modified;
mandatory to call if the solution is modified without using a Move, e.g. in a
constructive), and customProperties() (properties to export in the reports).
es.urjc.etsii.grafo.solution.Objective
public abstract class Objective<M extends Move<S,I>, S extends Solution<S,I>, I extends Instance>Defines what is optimized and in which sense. It encapsulates two evaluations:
double evalSol(S solution)— quality of a complete solution.double evalMove(M move)— delta: how much the objective would change if the move were executed (incremental evaluation, much more efficient than cloning and recomputing).
The usual way to create it is with static factories, without subclassing:
Objective.ofMinimizing("Distance", TSPSolution::getDistance, TSPBaseMove::getDistanceDelta);
Objective.ofMaximizing("Profit", MySolution::getProfit, MyMove::getProfitDelta);
Objective.of("Custom", FMode.MINIMIZE, evalSolFn, evalMoveFn);The objective is normally declared in Main and passed to Mork.start(args, objective).
Multiple objectives are supported (multi-objective): Mork.start(args, obj1, obj2, ...).
es.urjc.etsii.grafo.algorithms.FMode
public enum FMode { MAXIMIZE, MINIMIZE }Encapsulates all the comparison logic according to the optimization sense (using
DoubleComparator, with relative tolerance): isBetter(a, b), isBetterOrEqual(a, b),
best(a, b), improves(delta) and getBadValue() (the worst possible value, to initialize
loops). Thanks to this, the same component works for both minimizing and maximizing: scores
are never compared directly with </>, but through the objective or the FMode.
es.urjc.etsii.grafo.solution.Move
public abstract class Move<S extends Solution<S, I>, I extends Instance>Represents a change applicable to a solution (swap two cities, insert an element, etc.). The user implements:
| Method | Responsibility |
|---|---|
protected S _execute(S solution) |
Actually apply the change and return the solution. |
toString(), equals(), hashCode() |
Mandatory. |
The public execution is execute(solution) (a final method, template pattern): it checks
that the solution has not changed since the move was generated, calls _execute, increments the
version and notifies the update. In Validation mode it additionally checks that the delta
declared by the objective matches the real score change.
The delta is not a method of Move: it is obtained with objective.evalMove(move). The
recommended pattern is a problem-specific base move class that exposes the delta as a getter
(e.g. TSPBaseMove::getDistanceDelta).
Optional interface RefreshableMove — a move that knows how to rebuild itself for the current
state of the solution (Optional<M> refresh(S)); required by LocalSearchCachedBestImprovement.
es.urjc.etsii.grafo.solution.neighborhood.Neighborhood
public abstract class Neighborhood<M extends Move<S,I>, S extends Solution<S,I>, I extends Instance>Generates the set of moves applicable from a solution. It is the extension point used by local searches. The user implements:
public abstract ExploreResult<M, S, I> explore(S solution);ExploreResult can be built in two ways, with performance implications:
- Eager (all moves materialized in a list):
ExploreResult.fromList(listOfMoves). - Lazy (lazy generation with a
Stream, ideal for large neighborhoods):ExploreResult.fromStream(stream, size).
This replaces the old
EagerMove/LazyMoveclasses, which no longer exist.
RandomizableNeighborhood adds Optional<M> getRandomMove(S) — needed for Simulated Annealing
and for RandomMoveShake.
There are also static combinators: Neighborhood.concat(...), interleave(...), empty() and
random(balanced, ...).
es.urjc.etsii.grafo.util.Context
It is a per-thread container (child threads inherit a copy) that centralizes the solver's cross-cutting resources, so they do not have to be passed as parameters:
- Objectives:
Context.getMainObjective(),getObjectives(). - Centralized evaluation:
evalSolution(S)→Map<String,Double>(score per objective),evalDeltas(M)→Map<String,Double>(delta per objective). - Randomness:
getRandom()(equivalent toRandomManager.getRandom()). - Validation:
Context.validate(solution)runs the user's validator (only takes effect in Validation mode). - Concurrency:
submit(...)for reproducible internal parallelization.
In algorithms and components, it is used mostly to obtain the main objective when one has not been passed explicitly.
es.urjc.etsii.grafo.solution.SolutionValidator<S, I>
public abstract ValidationResult validate(S solution);The user implements it to detect invalid solutions as early as possible. It returns
ValidationResult.ok() or accumulates failures with fail("reason"). It runs automatically
after each (instance, algorithm, repetition) and, in Validation mode, also at the
intermediate points where the algorithm calls Context.validate(...). Typical recommendation:
recompute the score from scratch and check that it matches the cached one.
| Base class | Mandatory methods | Comment |
|---|---|---|
Instance |
(none) | Add immutable data + super(id). |
InstanceImporter<I> |
importInstance(BufferedReader, String) |
Parse the input format. |
Solution<SELF,I> |
cloneSolution(), toString() |
Deep clone; two constructors (new and copy). |
Objective<M,S,I> |
(use factories) ofMinimizing/ofMaximizing/of |
Score and delta functions. |
Move<S,I> |
_execute(S), toString, equals, hashCode |
Delta exposed via a getter for the Objective. |
Neighborhood<M,S,I> |
explore(S) → ExploreResult |
Eager (fromList) or lazy (fromStream). |
SolutionValidator<S,I> |
validate(S) |
Optional but strongly recommended. |