source: framspy/evolalg/utils/population_save.py @ 1113

Last change on this file since 1113 was 1113, checked in by Maciej Komosinski, 19 months ago

Added a framework for evolutionary algorithms cooperating with FramsticksLib?.py

File size: 1.5 KB
Line 
1from evolalg.base.step import Step
2import os
3from framsfiles import writer as framswriter
4
5
6class PopulationSave(Step):
7    def __init__(self, path, fields, provider=None):
8        self.path = path
9        self.provider = provider
10        self.fields = fields
11
12    @staticmethod
13    def ensure_dir(path):
14        directory = os.path.dirname(path)
15        if directory == "":
16            return
17        if not os.path.exists(directory):
18            os.makedirs(directory)
19
20    def call(self, population):
21        PopulationSave.ensure_dir(self.path)
22        provider = self.provider
23        if provider is None:
24            provider = population
25
26        #TODO instead of "fitness", write all fields used as fitness source with their original names (e.g. "velocity", "vertpos" etc.). In evaluation, set all attributes we get from Framsticks so that here we get all original names and values. Or, even better, introduce a dict field in Individual and assign to it everything that we get from Framsticks on evaluation (and add a filtering ability, i.e. when None - save all, when a list of field names - save only the enumerated fields)
27        with open(self.path, "w") as outfile:
28            for ind in provider:
29                keyval = {}
30                for k in self.fields: # construct a dictionary with criteria names and their values
31                    keyval[k] = getattr(ind, self.fields[k])
32                outfile.write(framswriter.from_collection({"_classname": "org", **keyval}))
33                outfile.write("\n")
34
35        return population
Note: See TracBrowser for help on using the repository browser.