Index: framspy/evolalg/dissimilarity/archive.py
===================================================================
--- framspy/evolalg/dissimilarity/archive.py	(revision 1182)
+++ framspy/evolalg/dissimilarity/archive.py	(revision 1182)
@@ -0,0 +1,36 @@
+import copy
+from typing import Union
+
+from evolalg.base.step import Step
+from evolalg.dissimilarity.dissimilarity import Dissimilarity
+from evolalg.dissimilarity.frams_dissimilarity import FramsDissimilarity
+from evolalg.statistics.halloffame_custom import HallOfFameCustom
+
+# TODO not fully tested. Verify if works OK, in particular test adding new individuals.
+class ArchiveDissimilarity(Step):
+
+    def __init__(self, archive_size, dissim: Union[Dissimilarity, FramsDissimilarity], order="max", field="dissim"):
+        self.name= "archive"
+        self.archive_size = archive_size
+        self.archive = []
+        self.dissim = dissim
+        self.order = order
+        self.field = field
+        if self.order not in ["min", "max"]:
+            raise ValueError("Order must be min or max")
+
+        if self.archive_size < 0:
+            raise ValueError(f"Archive size must be integer greater than or equal to 0. Got {self.archive_size}")
+
+    def call(self, population):
+        super(ArchiveDissimilarity, self).call(population)
+        population_archive = population + self.archive
+        population_archive = self.dissim(population_archive)
+
+        population = population_archive[:len(population)]
+        order = 1
+        if self.order == "max":
+            order *= -1
+        sorted_archive = sorted(population_archive, key=lambda x: getattr(x, self.field) * order)
+        self.archive = copy.deepcopy(sorted_archive[:self.archive_size])
+        return population
Index: framspy/evolalg/dissimilarity/dissimilarity.py
===================================================================
--- framspy/evolalg/dissimilarity/dissimilarity.py	(revision 1149)
+++ framspy/evolalg/dissimilarity/dissimilarity.py	(revision 1182)
@@ -11,26 +11,39 @@
 
         self.output_field = output_field
-        self.fn_reduce = None
+        self.fn_reduce = Dissimilarity.get_reduction_by_name(reduction)
         self.knn = knn
-        if reduction == "mean": # TODO change this 'elif' sequence to dictionary?
-            self.fn_reduce = np.mean
-        elif reduction == "max":
-            self.fn_reduce = np.max
-        elif reduction == "min":
-            self.fn_reduce = np.min
-        elif reduction == "sum":
-            self.fn_reduce = np.sum
-        elif reduction == "knn_mean":
-            self.fn_reduce = self.knn_mean
-        elif reduction == "none" or reduction is None:
-            self.fn_reduce = None
+
+
+    @staticmethod
+    def reduce(dissim_matrix, fn_reduce, knn):
+        if fn_reduce is None:
+            return dissim_matrix
+        elif fn_reduce is Dissimilarity.knn_mean:
+            return fn_reduce(dissim_matrix, 1, knn)
         else:
-            raise ValueError("Unknown reduction type. Supported: mean, max, min, sum, knn_mean, none")
+            return fn_reduce(dissim_matrix, axis=1)
 
-    def reduce(self, dissim_matrix):
-        if self.fn_reduce is None:
-            return dissim_matrix
-        return self.fn_reduce(dissim_matrix, axis=1)
 
-    def knn_mean(self, dissim_matrix,axis):
-        return np.mean(np.partition(dissim_matrix, self.knn)[:,:self.knn],axis=axis)
+    @staticmethod
+    def knn_mean(dissim_matrix, axis, knn):
+        return np.mean(np.partition(dissim_matrix, knn)[:, :knn], axis=axis)
+
+
+    @staticmethod
+    def get_reduction_by_name(reduction: str):
+
+        if reduction not in REDUCTION_FUNCTION:
+            raise ValueError(f"Unknown reduction type '{reduction}'. Supported: {','.join(REDUCTION_FUNCTION.keys())}")
+
+        return REDUCTION_FUNCTION[reduction]
+
+
+
+REDUCTION_FUNCTION = {
+            "mean": np.mean,
+            "max": np.max,
+            "min": np.min,
+            "sum": np.sum,
+            "knn_mean": Dissimilarity.knn_mean,
+            "none": None
+        }
Index: framspy/evolalg/dissimilarity/frams_dissimilarity.py
===================================================================
--- framspy/evolalg/dissimilarity/frams_dissimilarity.py	(revision 1149)
+++ framspy/evolalg/dissimilarity/frams_dissimilarity.py	(revision 1182)
@@ -6,34 +6,14 @@
 from evolalg.dissimilarity.dissimilarity import Dissimilarity
 
-#TODO eliminate overlap with dissimilarity.py
-
 
 class FramsDissimilarity(FramsStep):
 
-    def __init__(self, frams_lib, reduction="mean", output_field="dissim", knn=None, *args, **kwargs):
+    def __init__(self, frams_lib, reduction="mean", output_field="dissim",knn=None, *args, **kwargs):
         super(FramsDissimilarity, self).__init__(frams_lib, *args, **kwargs)
 
         self.output_field = output_field
-        self.fn_reduce = None
+        self.fn_reduce = Dissimilarity.get_reduction_by_name(reduction)
         self.knn = knn
-        if reduction == "mean":
-            self.fn_reduce = np.mean
-        elif reduction == "max":
-            self.fn_reduce = np.max
-        elif reduction == "min":
-            self.fn_reduce = np.min
-        elif reduction == "sum":
-            self.fn_reduce = np.sum
-        elif reduction == "knn_mean":
-            self.fn_reduce = self.knn_mean
-        elif reduction == "none" or reduction is None:
-            self.fn_reduce = None
-        else:
-            raise ValueError("Unknown reduction type. Supported: mean, max, min, sum, knn_mean, none")
 
-    def reduce(self, dissim_matrix):
-        if self.fn_reduce is None:
-            return dissim_matrix
-        return self.fn_reduce(dissim_matrix, axis=1)
 
     def call(self, population):
@@ -41,10 +21,7 @@
         if len(population) == 0:
             return []
-        dissim_matrix = self.frams.dissimilarity([_.genotype for _ in population])
-        dissim = self.reduce(dissim_matrix)
+        dissim_matrix = self.frams.dissimilarity([_.genotype for _ in population], 1)
+        dissim = Dissimilarity.reduce(dissim_matrix, self.fn_reduce, self.knn)
         for d,ind in zip(dissim, population):
             setattr(ind, self.output_field, d)
         return population
-
-    def knn_mean(self, dissim_matrix,axis):
-        return np.mean(np.partition(dissim_matrix, self.knn)[:,:self.knn],axis=axis)
Index: framspy/evolalg/dissimilarity/levenshtein.py
===================================================================
--- framspy/evolalg/dissimilarity/levenshtein.py	(revision 1149)
+++ framspy/evolalg/dissimilarity/levenshtein.py	(revision 1182)
@@ -18,5 +18,5 @@
                 gen_dis.append(lev.distance(p.genotype, p2.genotype))
             dissim.append(gen_dis)
-        dissim = self.reduce(dissim)
+        dissim = self.reduce(dissim, self.fn_reduce, self.knn)
         for d, ind in zip(dissim, population):
             setattr(ind, self.output_field, d)
Index: framspy/evolalg/examples/niching_novelty.py
===================================================================
--- framspy/evolalg/examples/niching_novelty.py	(revision 1149)
+++ framspy/evolalg/examples/niching_novelty.py	(revision 1182)
@@ -11,4 +11,5 @@
 from evolalg.base.lambda_step import LambdaStep
 from evolalg.base.step import Step
+from evolalg.dissimilarity.archive import ArchiveDissimilarity
 from evolalg.dissimilarity.frams_dissimilarity import FramsDissimilarity
 from evolalg.dissimilarity.levenshtein import LevenshteinDissimilarity
@@ -56,5 +57,6 @@
         description='Run this program with "python -u %s" if you want to disable buffering of its output.' % sys.argv[
             0])
-    parser.add_argument('-path', type=ensureDir, required=True, help='Path to the Framsticks library without trailing slash.')
+    parser.add_argument('-path', type=ensureDir, required=True,
+                        help='Path to the Framsticks library without trailing slash.')
     parser.add_argument('-opt', required=True,
                         help='optimization criteria: vertpos, velocity, distance, vertvel, lifespan, numjoints, numparts, numneurons, numconnections (or other as long as it is provided by the .sim file and its .expdef). For multiple criteria optimization, see multicriteria.py.')
@@ -63,10 +65,12 @@
     parser.add_argument('-genformat', required=False, default="1",
                         help='Genetic format for the demo run, for example 4, 9, or B. If not given, f1 is assumed.')
-    parser.add_argument('-sim', required=False, default="eval-allcriteria.sim", help="Name of the .sim file with all parameter values. If you want to provide more files, separate them with a semicolon ';'.")
+    parser.add_argument('-sim', required=False, default="eval-allcriteria.sim",
+                        help="Name of the .sim file with all parameter values. If you want to provide more files, separate them with a semicolon ';'.")
     parser.add_argument('-fit', required=False, default=Fitness.raw, type=Fitness,
                         help=' Fitness criteria, default: raw', choices=list(Fitness))
     parser.add_argument('-dissim', required=False, type=Dissim, default=Dissim.frams,
                         help='Dissimilarity measure, default: frams', choices=list(Dissim))
-    parser.add_argument('-knn', type=int, help="'k' value for knn-based fitness criteria (knn-niching and knn-novelty).")
+    parser.add_argument('-knn', type=int,
+                        help="'k' value for knn-based fitness criteria (knn-niching and knn-novelty).")
     parser.add_argument('-popsize', type=int, default=50, help="Population size, default: 50.")
     parser.add_argument('-generations', type=int, default=5, help="Number of generations, default: 5.")
@@ -77,10 +81,12 @@
     parser.add_argument('-max_numneurons', type=int, default=None, help="Maximum number of Neurons. Default: no limit")
     parser.add_argument('-max_numconnections', type=int, default=None, help="Maximum number of Neural connections. Default: no limit")
-
+    parser.add_argument('-max_numgenochars', type=int, default=10000, help="Maximum number of characters in genotype, to disable this option set it to -1. Default: 10 000")
     parser.add_argument('-hof_size', type=int, default=10, help="Number of genotypes in Hall of Fame. Default: 10.")
-    parser.add_argument('-hof_evaluations', type=int, default=20, help="Number of final evaluations of each genotype in Hall of Fame to obtain reliable (averaged) fitness. Default: 20.")
+    parser.add_argument('-hof_evaluations', type=int, default=20,
+                        help="Number of final evaluations of each genotype in Hall of Fame to obtain reliable (averaged) fitness. Default: 20.")
     parser.add_argument('-checkpoint_path', required=False, default=None, help="Path to the checkpoint file")
     parser.add_argument('-checkpoint_interval', required=False, type=int, default=100, help="Checkpoint interval")
     parser.add_argument('-debug', dest='debug', action='store_true', help="Prints names of steps as they are executed")
+    parser.add_argument('-archive_size', type=int, default=0, help="Size of the archive size for dissimilarity calculation")
     parser.set_defaults(debug=False)
     return parser.parse_args()
@@ -131,4 +137,11 @@
         return individual.numconnections > self.max_number
 
+class NumCharsHigher(Remove):
+    def __init__(self, max_number):
+        super(NumCharsHigher, self).__init__()
+        self.max_number = max_number
+
+    def remove(self, individual):
+        return len(individual.genotype) > self.max_number
 
 class ReplaceWithHallOfFame(Step):
@@ -136,4 +149,5 @@
         super(ReplaceWithHallOfFame, self).__init__(*args, **kwargs)
         self.hof = hof
+
     def call(self, population, *args, **kwargs):
         super(ReplaceWithHallOfFame, self).call(population)
@@ -166,5 +180,5 @@
     parsed_args = parseArguments()
     frams_lib = FramsticksLib(parsed_args.path, parsed_args.lib,
-                          parsed_args.sim.split(";"))
+                              parsed_args.sim.split(";"))
     # Steps for generating first population
     init_stages = [
@@ -187,13 +201,12 @@
 
     fitness_raw = FitnessStep(frams_lib, fields={parsed_args.opt: "fitness_raw",
-                                             "numparts": "numparts",
-                                             "numjoints": "numjoints",
-                                             "numneurons": "numneurons",
-                                             "numconnections": "numconnections"},
+                                                 "numparts": "numparts",
+                                                 "numjoints": "numjoints",
+                                                 "numneurons": "numneurons",
+                                                 "numconnections": "numconnections"},
                               fields_defaults={parsed_args.opt: None, "numparts": float("inf"),
                                                "numjoints": float("inf"), "numneurons": float("inf"),
                                                "numconnections": float("inf")},
                               evaluation_count=1)
-
 
     fitness_end = FitnessStep(frams_lib, fields={parsed_args.opt: "fitness_raw"},
@@ -213,4 +226,6 @@
     if parsed_args.max_numconnections is not None:
         remove.append(NumConnectionsHigher(parsed_args.max_numconnections))
+    if parsed_args.max_numgenochars is not -1:
+        remove.append(NumCharsHigher(parsed_args.max_numgenochars))
 
     remove_step = UnionStep(remove)
@@ -245,7 +260,8 @@
         generation_modifications.append(raw)
 
-    if parsed_args.fit == Fitness.niching: # TODO reduce redundancy in the four cases below: dictionary?
+    if parsed_args.fit == Fitness.niching:  # TODO reduce redundancy in the four cases below: dictionary?
+
         niching = UnionStep([
-            dissim,
+            ArchiveDissimilarity(parsed_args.archive_size, dissim),
             LambdaStep(func_niching)
         ])
@@ -255,21 +271,21 @@
     if parsed_args.fit == Fitness.novelty:
         novelty = UnionStep([
-            dissim,
+            ArchiveDissimilarity(parsed_args.archive_size, dissim),
             LambdaStep(func_novelty)
         ])
         init_stages.append(novelty)
         generation_modifications.append(novelty)
-    
+
     if parsed_args.fit == Fitness.knn_niching:
         knn_niching = UnionStep([
-            dissim,
+            ArchiveDissimilarity(parsed_args.archive_size, dissim),
             LambdaStep(func_knn_niching)
         ])
         init_stages.append(knn_niching)
         generation_modifications.append(knn_niching)
-    
+
     if parsed_args.fit == Fitness.knn_novelty:
         knn_novelty = UnionStep([
-            dissim,
+            ArchiveDissimilarity(parsed_args.archive_size, dissim),
             LambdaStep(func_knn_novelty)
         ])
@@ -302,13 +318,10 @@
         fitness_end,
         PopulationSave("halloffame.gen", provider=hall_of_fame.halloffame, fields={"genotype": "genotype",
-                                                                                  "fitness": "fitness_raw"})]
+                                                                                   "fitness": "fitness_raw"})]
     # ...but custom fields can be added, e.g. "custom": "recording"
 
     # -------------------------------------------------
 
-
-
     # Experiment creation
-
 
     experiment = Experiment(init_population=init_stages,
@@ -354,6 +367,4 @@
 
 
-
 if __name__ == '__main__':
-
     main()
