File size: 5,335 Bytes
86694c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import json
import random
from dataclasses import dataclass
from pickle import dump
from typing import Dict, List, Sequence, Tuple

import numpy as np

"""
A setting for a parameter, with its oneHOT encoding
"""


@dataclass
class ParamValue:
    name: str
    value: float
    encoding: List[float]


"""
A sample point - the parameter values, the oneHOT encoding and the audio
"""


@dataclass
class Sample:
    # parameter_values: List[Tuple[str,float]]
    # parameter_encoding:List[List[float]]
    parameters: List[ParamValue]
    # length:float=0.1
    # sample_rate:int = 44100
    # audio:np.ndarray = np.zeros(1)

    def value_list(self) -> List[Tuple[str, float]]:
        return [(p.name, p.value) for p in self.parameters]

    def encode(self) -> List[float]:
        return np.hstack([p.encoding for p in self.parameters])


class Parameter:
    def __init__(self, name: str, levels: list, id=""):
        self.name = name
        self.levels = levels
        self.id = id

    def get_levels(self) -> List[ParamValue]:
        return [self.get_value(i) for i in range(len(self.levels))]

    def sample(self) -> ParamValue:
        index: int = random.choice(range(len(self.levels)))
        return self.get_value(index)

    def get_value(self, index: int) -> ParamValue:
        encoding = np.zeros(len(self.levels)).astype(float)
        encoding[index] = 1.0
        return ParamValue(
            name=self.name,
            # Actual value
            value=self.levels[index],
            # One HOT encoding
            encoding=encoding,
        )

    def decode(self, one_hot: List[float]) -> ParamValue:
        ind = np.array(one_hot).argmax()
        # ind = tf.cast(tf.argmax(one_hot, axis=-1), "int32")
        return self.get_value(ind)

    def from_output(
        self, current_output: List[float]
    ) -> Tuple[ParamValue, List[float]]:
        param_data = current_output[: len(self.levels)]
        remaining = current_output[len(self.levels) :]
        my_val = self.decode(param_data)
        return (my_val, remaining)

    def to_json(self):
        return {"name": self.name, "levels": self.levels, "id": self.id}


class ParameterSet:
    def __init__(self, parameters: List[Parameter], fixed_parameters: dict = {}):
        self.parameters = parameters
        self.fixed_parameters = fixed_parameters

    def sample_space(self, sample_size=2000) -> Sequence[Sample]:
        print("Sampling {} points from parameter space".format(sample_size))
        dataset = []
        for i in range(sample_size):
            params = [p.sample() for p in self.parameters]
            dataset.append(Sample(params))
            if i % 1000 == 0:
                print("Sampling iteration: {}".format(i))
        return dataset

    # Runs through the whole parameter space, setting up parameters and calling the generation function
    # Excuse slightly hacky recusions - sure there's a more numpy-ish way to do it!
    def recursively_generate_all(
        self, parameter_list: list = None, parameter_set=[], return_list=[]
    ) -> Sequence[Sample]:
        print("Generating entire parameter space")
        if parameter_list is None:
            parameter_list = self.parameters
        param = parameter_list[0]
        remaining = parameter_list[1:]
        for p in param.levels:
            ps = parameter_set.copy()
            ps.append((param.name, p))
            if len(remaining) == 0:
                return_list.append(ps)
            else:
                self.recursively_generate_all(remaining, ps, return_list)
        return return_list

    def to_settings(self, p: Sample):
        params = self.fixed_parameters.copy()
        params.update(dict(p.value_list()))
        return params

    def encoding_to_settings(self, output: List[float]) -> Dict[str, float]:
        params = self.fixed_parameters.copy()
        for p in self.decode(output):
            params[p.name] = p.value
        return params

    def decode(self, output: List[float]) -> List[ParamValue]:
        values = []
        for p in self.parameters:
            v, output = p.from_output(output)
            values.append(v)
        if len(output) > 0:
            print("Leftover output!: {}".format(output))
        return values

    def save(self, filename):
        with open(filename, "wb") as file:
            dump(self, file)

    def save_json(self, filename):
        dump = self.to_json()
        with open(filename, "w") as file:
            json.dump(dump, file, indent=2)

    def explain(self):
        levels = 0
        for p in self.parameters:
            levels += len(p.levels)
        return {
            "n_variable": len(self.parameters),
            "n_fixed": len(self.fixed_parameters),
            "levels": levels,
        }

    def to_json(self):
        return {
            "parameters": [p.to_json() for p in self.parameters],
            "fixed": self.fixed_parameters,
        }


"""
Generates evenly spaced parameter values
paper:
The rest of the synthesizer parameters ranges are quantized evenly to 16
classes according to the following ranges ...
For each parameter, the first and last classes correspond to its range limits
"""


def param_range(steps, min, max):
    ext = float(max - min)
    return [n * ext / (steps - 1) + min for n in range(steps)]