def __init__(self, circuit, **kwargs): if "params" not in kwargs: raise ValueError("Need parameter values!") if isinstance(kwargs["params"], list): if "parameter_names" not in kwargs: raise ValueError("Need list of parameter names") else: sim_dict = dict( zip(kwargs["params"], kwargs["parameter_names"])) elif isinstance(kwargs["params"], dict): sim_dict = kwargs["params"] netlist_maker = EIS() netlist = EIS(circuit=circuit, construct_netlist=True) netlist_keys = list(netlist.netlist_dict.keys()) net_dict = netlist.netlist_dict cpe_num = 0 for key in netlist_keys: if "Q" in key: cpe_num += 1 if "gamma1" in netlist_keys: raise ValueError("Not valid for finite Warburg element") f = open("temp_netlist.net", "w") f.write("V1 0 1 1\n") for key in netlist_keys: if "R" in key or "C" in key: if key != "R0": write_string = "{0} {1} {2} 1 \n".format( key, net_dict[key]["left"], net_dict[key]["right"]) else: write_string = "R0 {1} 0 1 \n".format( key, net_dict[key]["left"]) f.write(write_string) elif "Q" in key: write_string = "H{0} {1} {2} V1 1\n".format( key[1], net_dict[key]["left"], net_dict[key]["right"]) f.write(write_string) elif "W" in key: current_num = int(key[1]) warburg_num = cpe_num + current_num w_val = sim_dict[key] del sim_dict[key] sim_dict["alpha" + str(warburg_num)] = 0.5 sim_dict["Q" + str(warburg_num)] = 1 / (np.sqrt(2) * w_val) print(sim_dict) write_string = "H{0} {1} {2} V1 1\n".format( warburg_num, net_dict[key]["left"], net_dict[key]["right"]) f.write(write_string) f.close() param_dict_str = "{" for key in sim_dict.keys(): param_dict_str += "\"" + key + "\":" + str(sim_dict[key]) + "," param_dict_str += "}" print(param_dict_str) model_creator(0.0001, "dt*1000", "0.3*np.sin(math.pi*2*8*t)", param_dict_str)
def tree_simulation(self, circuit_tree, frequencies, data, param_vals): translator = EIS() dictionary, params = translator.translate_tree(circuit_tree, get_param_list=True) sim_class = self.assess_score(dictionary, params, frequencies, data, get_simulator=True) return sim_class.simulate(param_vals, frequencies)
def plot_generation(self, windex, loser_idx, scores, sim_array, generation, data, axes, plot_count): idxes = [windex, loser_idx] titles = ["Winner", "Loser"] dict_constructor = EIS() for i in range(0, len(idxes)): circuit_ax = axes[0][plot_count + i] idx = idxes[i] circuit_dict = dict_constructor.translate_tree(generation[idx]) circuit_artist(circuit_dict, circuit_ax) circuit_ax.set_title(titles[i]) circuit_ax.set_axis_off() data_ax = axes[1][plot_count + i] data_ax.plot(data[:, 0], -data[:, 1]) sim_data = sim_array[idx] data_ax.plot(sim_data[:, 0], -sim_data[:, 1]) data_ax.set_title(round(scores[idx], 3))
def __init__(self, **kwargs): if "initial_circuit" not in kwargs: kwargs["initial_circuit"] = False if "initial_tree_size" not in kwargs: kwargs["initial_tree_size"] = 4 if "maximum_mutation_size" not in kwargs: kwargs["maximum_mutation_size"] = 3 if "minimum_replacement_depth" not in kwargs: kwargs["minimum_replacement_depth"] = 1 if "generation_size" not in kwargs: kwargs["generation_size"] = 4 if "generation_test" not in kwargs: kwargs["generation_test"] = False elif "generation_test_save" not in kwargs: kwargs["generation_test_save"] = False elif kwargs["generation_size"] % 2 != 0: kwargs["generation_size"] += 1 if "selection" not in kwargs: kwargs["selection"] = "bayes_factors" if "best_record" not in kwargs: kwargs["best_record"] = False elif kwargs["best_record"] == True: self.best_array = [] self.best_circuits = [] if "num_top_circuits" not in kwargs: kwargs["num_top_circuits"] = 10 if kwargs["initial_circuit"] == False: initial_generation = [] # random_constructor = EIS() for i in range(0, kwargs["generation_size"]): initial_generation.append( random_constructor.random_circuit_tree( kwargs["initial_tree_size"])) self.options = kwargs self.initial_generation = initial_generation self.best_candidates = { "scores": np.array([]), "models": [], "parameters": [], "data": [] } self.count = 0
def get_generation_score(self, generation, frequencies, data, selection): dictionary_constructor = EIS() generation_scores = np.zeros(len(generation)) returned_params = [] if self.options["generation_test"] == True: returned_data = [] for i in range(0, len(generation)): circuit_dict, param_list = dictionary_constructor.translate_tree( generation[i], get_param_list=True) if len(param_list) == 1: meaningful_circuit = False while meaningful_circuit == False: new_try = dictionary_constructor.random_circuit_tree( self.options["initial_tree_size"]) circuit_dict, param_list = dictionary_constructor.translate_tree( new_try, get_param_list=True) if len(param_list) > 1: meaningful_circuit = True generation[i] = new_try if self.options["generation_test"] == True: generation_scores[i], params, sim_data = self.assess_score( circuit_dict, param_list, frequencies, data, score_func=selection) else: generation_scores[i], params = self.assess_score( circuit_dict, param_list, frequencies, data, score_func=selection) returned_params.append(params) if self.options["generation_test"] == True: returned_data.append(sim_data) if self.options["generation_test"] == True: return generation_scores, returned_params, returned_data else: return generation_scores, returned_params,
def reproduce(self, winning_generation, **methods): crossover_generation = [] next_generation = [] mutator = EIS() if "keep_winners" not in methods: methods["keep_winners"] = False if "num_elites" in methods: elites = copy.deepcopy(winning_generation[:methods["num_elites"]]) if methods["keep_winners"] == False: num_shuffles = 4 elif "num_elites" in methods: num_shuffles = 4 if methods["num_elites"] > len(winning_generation): raise ValueError( "{0} is greater than generation size {1}".format( methods["num_elites"], len(winning_generation))) else: num_shuffles = 2 for i in range(0, num_shuffles): random.shuffle(winning_generation) for j in range(0, len(winning_generation), 2): original = copy.deepcopy(winning_generation[j]) target = copy.deepcopy(winning_generation[j + 1]) child = mutator.crossover( original, target, self.options["minimum_replacement_depth"]) crossover_generation.append(child) for j in range(0, len(crossover_generation)): new_mutator = EIS() original = copy.deepcopy(crossover_generation[j]) next_generation.append( new_mutator.mutation( original, max_mutant_size=self.options["maximum_mutation_size"], min_depth=self.options["minimum_replacement_depth"])) if methods["keep_winners"] == True: if "num_elites" not in methods: next_generation += winning_generation else: next_generation[:methods["num_elites"]] = elites return next_generation
import os import sys dir = os.getcwd() dir_list = dir.split("/") source_list = dir_list[:-1] + ["src"] source_loc = ("/").join(source_list) sys.path.append(source_loc) from EIS_class import EIS import numpy as np import matplotlib.pyplot as plt from EIS_optimiser import EIS_optimiser, EIS_genetics from circuit_drawer import circuit_artist randles = {"z1": "R0", "z2": {"p1": ("Q1", "alpha1"), "p2": ["R2", "W1"]}} translator = EIS() circuit_artist(randles) ax = plt.gca() ax.set_axis_off() plt.show() frequency_powers = np.arange(1, 6, 0.1) frequencies = [10**x for x in frequency_powers] bounds = { "R1": [0, 1000], "Q1": [0, 1e-2], "alpha1": [0.1, 0.9], "R2": [0, 1000], "W1": [1, 200] } true_params = { "R1": 100, "Q1": 1e-3, "alpha1": 0.5,
init_test = { "z1": { "p1": [ "R1", { "p1_1": "C1", "p1_2": [ "R9", { "p1": "C8", "p2": ["R14", { "p1": "C-1", "p2": "C-2" }] } ] }, { "p1_1": "C2", "p1_2": "C3" } ], "p2": "R2" }, "z2": { "p1": "R3", "p2": "C4" }, "z3": "R5" } eis = EIS(circuit=init_test, construct_netlist=True)
} } #Randles={"z1":"R1","z2":{"p_1":"R2", "p_2":"C1"}, "z3":{"p_1":"R3", "p_2":"C2"}}# randles = { "z1": "R1", "z2": { "p_1": ("Q1", "alpha1"), "p_2": ["R2", "W1"] }, "z4": { "p_1": "R3", "p_2": "C2" } } #debeye={"z1":{"p_1":"C1", "p_2":["R1", ("Q1", "alpha1")]}} test = EIS(circuit=randles) #test.write_model(circuit=Randles) frequency_powers = np.arange(-1.5, 5, 0.01) frequencies = [10**x for x in frequency_powers] spectra = np.zeros((2, len(frequencies)), dtype="complex") def double_randles(**kwargs): R1 = kwargs["R1"] R2 = kwargs["R2"] R3 = kwargs["R3"] jfC1 = 1j * kwargs["omega"] * kwargs["C1"] jfC2 = 1j * kwargs["omega"] * kwargs["C2"] return R1 + 1 / (1 / (R2) + (jfC1)) + 1 / (1 / (R3) + (jfC2))
for i in range(2, 6): file_name = "Best_candidates/round_3/{1}/Best_candidates_dict_{0}_12_gen.npy".format( i, "None") results_dict = np.load(file_name, allow_pickle=True).item() #print(results_dict[0]["scores"]) fig = plt.figure() ax = [[0 for x in range(0, 6)] for y in range(0, 3)] gs = fig.add_gridspec(3, 6) for m in range(0, 2): for j in range(0, 6): ax[m][j] = fig.add_subplot(gs[m, j]) td_ax = fig.add_subplot(gs[2, :]) #plt.show() for j in range(0, len(results_dict["scores"])): translator = EIS() simulator = EIS_genetics() translated_circuit, params = translator.translate_tree( results_dict["models"][j], get_param_list=True) #translated_circuit={'z1': {'p1': [['C1', ("Q1", "alpha1")], ['R1', "C6"]], # 'p2': {'p1': [{'p1': "C7", 'p2': 'R2'}, [{'p1': 'C8', 'p2': 'R3'}, {'p1': 'C2', 'p2': ("Q2", "alpha2")}]], 'p2': ["C5", 'C3']}}, # 'z2': 'C4', 'z0': 'R0'} print(translated_circuit) #print(translated_circuit) #print(len(results_dict["parameters"][j])) #print(len(params)) circuit_artist(translated_circuit, ax[0][j]) ax[0][j].set_axis_off() sim_data = simulator.tree_simulation(results_dict["models"][j],
import os import sys dir=os.getcwd() dir_list=dir.split("/") source_list=dir_list[:-1] + ["src"] source_loc=("/").join(source_list) sys.path.append(source_loc) from EIS_class import EIS import time test=EIS() from circuit_drawer import circuit_artist hard_tree={"root_series":{"left_paralell":{ "left_series":{"left_element":"R", "right_element":"C"}, "right_paralell":{"left_series":{"right_element":"R", "left_element":"R"}, "right_element":"R"}},"right_element":"C"}, } triple_randles={"root_series":{"left_paralell":{"left_element":"R", "right_element":"R"}, "right_series": {"left_paralell":{"left_element":"R", "right_element":"R"}, "right_series": {"left_paralell":{"left_element":"R", "right_element":"R"}, "right_paralell":{"left_element":"R", "right_element":"R"}}}}} z=test.construct_dict_from_tree(triple_randles["root_series"], "root_series") #print(test.random_circuit_tree(3)) random_tree=test.random_circuit_tree(4) #top_key=list(random_tree.keys())[0] #random_dict=test.construct_dict_from_tree(random_tree[top_key], top_key) circuit_artist(test.translate_tree(random_tree)) top_key=test.get_top_key(random_tree) #print(random_tree) #print(random_dict)
source_list=dir_list[:-1] + ["src"] source_loc=("/").join(source_list) sys.path.append(source_loc) from EIS_class import EIS import numpy as np import matplotlib.pyplot as plt import time import copy test_dict={"z1":{"p1":{"p1_1":"R18", "p1_2":"C13"}, "p2":{"p2_1":"R8", "p2_2":"Cl3"}, "p3":{"p3_1":["R14", "R18"], "p3_2":{"p3_2_1":"R2", "p3_2_2":"Cdl1"}}}, "z2":"R1", "z3":{"p1":"R3", "p2":{"p2_1":"R4", "p2_2":"Cdl2"}}} #Randles={"z1":"R1","z2":{"p_1":"R2", "p_2":"C1"}, "z3":{"p_1":"R3", "p_2":"C2"}}# randles={"z1":"R1", "z2":{"p_1":("Q1", "alpha1"), "p_2":["R2", "W1"]}}#, "z4":{"p_1":"R3", "p_2":"C2"} } #debeye={"z1":{"p_1":"C1", "p_2":["R1", ("Q1", "alpha1")]}} test=EIS(circuit=randles) #test.write_model(circuit=Randles) frequency_powers=np.arange(-1.5, 5, 0.1) frequencies=[10**x for x in frequency_powers] spectra=np.zeros((2, len(frequencies)), dtype="complex") times=[0,0] fig, ax=plt.subplots(2, 4) plt.rcParams.update({'font.size': 16}) param_dict={"R1": [10, 50, 100, 150, 200, 250], "R2":[10, 50, 100, 150, 200, 250], "R3":[10, 50, 100, 150, 200, 250], "C2":[1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1], "W1":[1, 10, 50, 100, 200], "Q1":[1e-4, 5e-4, 1e-3, 5e-3, 1e-2], "alpha1":[0.1, 0.3, 0.5, 0.7, 1]} params={"R1":10, "R3":100, "C2":0.01,"R2":250, "Q1":2e-3, "omega":0, "C1":1e-6, "W1":40, "alpha1":1} spectra=np.zeros(len(frequencies), dtype="complex") param_keys=list(param_dict.keys()) for j in range(0, len(param_keys)): for q in range(0, len(param_dict[param_keys[j]]), 2): sens_params=copy.deepcopy(params)
sys.path.append(source_loc) from EIS_class import EIS import numpy as np import matplotlib.pyplot as plt from EIS_optimiser import EIS_optimiser, EIS_genetics from circuit_drawer import circuit_artist frequency_powers = np.arange(1, 6, 0.1) frequencies = [10**x for x in frequency_powers] file_name = "AIC_best_scores.npy" scores = np.load(file_name, allow_pickle=True).item() for i in range(0, len(scores["scores"])): #print(scores["scores"][i]) plt.plot(scores["scores"][i]) #plt.axhline(scores["true_score"][i]) plt.show() translator = EIS() print(scores["circuits"][i]) circuit_artist(translator.translate_tree(scores["circuits"][i][0])) plt.show() for i in range(1, 6): file_name = "Best_candidates/AIC_best_candidates_dict_{0}_8_gen_3.npy".format( i) results_dict = np.load(file_name, allow_pickle=True).item() #print(results_dict[0]["scores"]) fig, ax = plt.subplots(2, 5) for j in range(0, len(results_dict["scores"])): translator = EIS() simulator = EIS_genetics() translated_circuit, params = translator.translate_tree( results_dict["models"][j], get_param_list=True)
frequency_powers = np.arange(0, 6, 0.2) frequencies = [10**x for x in frequency_powers] omegas = np.multiply(frequencies, 2 * math.pi) bounds = { "R1": [0, 1000], "Q1": [0, 1e-2], "alpha1": [0.1, 0.9], "R2": [0, 1000], "W1": [1, 200] } true_params = {"R1": 10, "Q1": 0.001, "alpha1": 0.8} param_names = ["R1", "Q1", "alpha1"] sim = EIS_genetics() normaliser = EIS(circuit=ZARC, parameter_bounds=bounds, parameter_names=param_names, test=True, fitting=True) sim1 = normaliser.simulate([true_params[x] for x in param_names], omegas) fig, ax = plt.subplots(1, 2) #sim.plot_data(sim.dict_simulation(ZARC, omegas, [], [true_params[x] for x in param_names], param_names),ax[0], label="Analytic frequency simulation") num_oscillations = 3 time_start = 0 sampling_rate = 200 def cpe1(denom, i, charge_array, time_array, dt): total = 0 if i != 0: time_array = np.flip(time_array) total = np.sum(np.multiply(time_array, charge_array))
def selection(self, generation, frequencies, data, method): if self.options["generation_test"] == True: generation_score, param_array, sim_array = self.get_generation_score( generation, frequencies, data, method) if self.options["generation_size"] > 8: end = 8 fig, ax = plt.subplots(2, end) else: end = self.options["generation_size"] fig, ax = plt.subplots(2, end) plot_count = 0 else: generation_score, param_array = self.get_generation_score( generation, frequencies, data, method) if method == "bayes_factors": scores = list(enumerate(generation_score)) winners = [0] * int(len(scores) / 2) random.shuffle(scores) for i in range(0, len(scores), 2): bayes_factor = scores[i][1] / scores[i + 1][1] if bayes_factor > 1: windex = i loser = i + 1 else: windex = i + 1 loser = i winners[int(i / 2)] = scores[windex][0] if self.options["generation_test"] == True: if i < end: self.plot_generation(scores[windex][0], scores[loser][0], generation_score, sim_array, generation, data, ax, plot_count) plot_count += 2 elif method == "BIC" or method == "AIC" or method == "None": rank = np.argsort(generation_score) winners = np.flip(rank[int(self.options["generation_size"]) // 2:]) losers = np.flip(rank[:int(self.options["generation_size"]) // 2]) if self.options["generation_test"] == True: for i in range(0, int(end // 2)): self.plot_generation(winners[i], losers[i], generation_score, sim_array, generation, data, ax, plot_count) plot_count += 2 if self.options["best_record"] == True: windex = winners[0] if len(self.best_array) == 0: self.best_array.append(generation_score[windex]) self.best_circuits.append(generation[windex]) elif generation_score[windex] > self.best_array[-1]: self.best_array.append(generation_score[windex]) self.best_circuits.append(generation[windex]) else: self.best_array.append(self.best_array[-1]) self.best_circuits.append(self.best_circuits[-1]) winning_candidates = [generation[x] for x in winners] winning_params = [param_array[x] for x in winners] winning_scores = [generation_score[x] for x in winners] translator = EIS() num_entries = len(self.best_candidates["scores"]) if num_entries == 0: self.best_candidates["scores"] = winning_scores self.best_candidates["models"] = winning_candidates self.best_candidates["parameters"] = winning_params elif num_entries < self.options["num_top_circuits"]: discrepancy = self.options["num_top_circuits"] - num_entries for i in range(0, min(len(winners), discrepancy)): model = copy.deepcopy(winning_candidates[i]) param_vals = copy.deepcopy(winning_params[i]) self.best_candidates["scores"].append( copy.deepcopy(winning_scores[i])) self.best_candidates["models"].append(model) self.best_candidates["parameters"].append(param_vals) else: for i in range(0, len(winning_scores)): self.best_candidates["scores"] = np.array( self.best_candidates["scores"]) if winning_candidates[i] == self.best_candidates["models"][i]: if self.best_candidates["scores"][i] < winning_scores[i]: self.best_candidates["scores"][i] = winning_scores[i] self.best_candidates["parameters"][i] = winning_params[ i] continue better_loc = tuple( np.where( self.best_candidates["scores"] < winning_scores[i])) if len(better_loc[0]) != 0: better_idx = np.where( self.best_candidates["scores"] == min( self.best_candidates["scores"][better_loc]))[0][0] model = copy.deepcopy(winning_candidates[i]) param_vals = copy.deepcopy(winning_params[i]) self.best_candidates["scores"][better_idx] = copy.deepcopy( winning_scores[i]) self.best_candidates["models"][better_idx] = model self.best_candidates["parameters"][better_idx] = param_vals if self.options["generation_test"] == True: if self.options["generation_test_save"] == False: plt.show() else: plt.subplots_adjust(top=0.88, bottom=0.11, left=0.04, right=0.99, hspace=0.0, wspace=0.2) fig.set_size_inches(28, 18) fig.savefig(self.options["generation_test_save"] + "Generation{0}.png".format(self.generation_num)) plt.clf() plt.close() return copy.deepcopy(winning_candidates), copy.deepcopy(winning_params)
sys.path.append(source_loc) from EIS_class import EIS import numpy as np import matplotlib.pyplot as plt from EIS_optimiser import EIS_optimiser, EIS_genetics from circuit_drawer import circuit_artist frequency_powers = np.arange(1, 6, 0.1) frequencies = [10**x for x in frequency_powers] for i in range(1, 6): file_name = "Best_candidates/round_2/{1}/Best_candidates_dict_{0}_12_gen.npy".format( i, "AIC") results_dict = np.load(file_name, allow_pickle=True).item() #print(results_dict[0]["scores"]) for j in range(0, len(results_dict["scores"])): translator = EIS() simulator = EIS_genetics() translated_circuit, params = translator.translate_tree( results_dict["models"][j], get_param_list=True) #translated_circuit={'z1': {'p1': {'p1': [[{'p1': {'p1': ['C1', 'R1'], 'p2': {'p1': 'R2', 'p2': 'C2'}}, 'p2': {'p1': 'W1', 'p2': 'R3'}}, {'p1': 'W2', 'p2': 'C3'}], ["C12", "C13"]], 'p2': ['W3', 'C4']}, 'p2': {'p1': ('Q1', 'alpha1'), 'p2': 'R4'}}, 'z2': {'p1': 'R5', 'p2': {'p1': "C14", 'p2': 'W4'}}, 'z0': 'R0'} print(len(results_dict["parameters"][j])) print(len(params)) circuit_artist(translated_circuit) netlist = EIS(circuit=translated_circuit, construct_netlist=True) netlist_keys = list(netlist.netlist_dict.keys()) net_dict = netlist.netlist_dict cpe_num = 0
frequency_powers = np.arange(0, 6, 0.2) frequencies = [10**x for x in frequency_powers] omegas = np.multiply(frequencies, 2 * math.pi) bounds = { "R1": [0, 1000], "Q1": [0, 1e-2], "alpha1": [0.1, 0.9], "R2": [0, 1000], "W1": [1, 200] } true_params = {"R1": 10, "Q1": 0.001, "alpha1": 0.8} param_names = ["R1", "Q1", "alpha1"] sim = EIS_genetics() normaliser = EIS(circuit=ZARC, parameter_bounds=bounds, parameter_names=param_names, test=True, fitting=True) sim1 = normaliser.simulate([true_params[x] for x in param_names], omegas) fig, ax = plt.subplots(1, 2) sim.plot_data(sim.dict_simulation(ZARC, omegas, [], [true_params[x] for x in param_names], param_names), ax[1], label="Analytic frequency simulation") num_oscillations = 3 time_start = 0 sampling_rate = 200 def cpe1(denom, i, charge_array, time_array, dt):
"i": [np.divide(potential, x) for x in variables["R1"]["vals"]] }, "C1": { "t": t, "e": potential, "i": [amp * x * np.cos(t) for x in variables["C1"]["vals"]] }, "alpha1": { "t": interval_times, "e": interval_potential, "i": cpes } } for i in range(0, len(thesis_circuits)): sim_class = EIS(circuit=thesis_circuits[i]) #circuit_pic= for j in range(0, len(variables[variable_key[i]]["vals"])): val = variables[variable_key[i]]["vals"][j] params[variable_key[i]] = val spectra = sim_class.test_vals(params, frequencies) img = mpimg.imread(image_files[i]) sim_class.nyquist(spectra, ax=ax[0, i], scatter=2, label="{0}={1} {2}".format( variables[variable_key[i]]["sym"], val, variables[variable_key[i]]["unit"])) #print(["10^{0}".format(round(x,3)) for x in np.log10(frequencies[0::2])]) key = variable_key[i]