def sim(sde_system): ode_system = copy.deepcopy(sde_system) ode_system.fluctuation_vector = np.zeros(sde_system.fluctuation_vector.shape) corr_mats = [] for _ in trange(reps): sde_sol = solve_system(sde_system) ode_sol = solve_system(ode_system) sol = ode_sol - sde_sol sol_extract = sol.T[int(len(sol.T)*3/4):] # extract steady-state # filter based on ODE solution if filter_steady_state(ode_sol.T[int(len(ode_sol.T)*3/4):]): continue # compute correlations stop = False dim = sol_extract.shape[1] mat = np.empty((dim,dim)) for i in range(dim): for j in range(dim): xs, ys = sol_extract[:,i], sol_extract[:,j] try: cc, pval = scis.pearsonr(xs, ys) mat[i,j] = cc except FloatingPointError: stop = True break if stop: break if not stop: corr_mats.append(mat) return np.asarray(corr_mats)
def find_solution(sde_syst): # find fitting Jacobian cur_m = generate_motifs()[data[k]['idx']][0] param_range = np.linspace(1, 8, 10) # generate data configurations = [] for k_m in param_range: for k_23 in param_range: tmp = cur_m(k_m=k_m/2, k_23=k_23/2) sde_syst.jacobian = tmp.jacobian sde_sol = solve_system(sde_syst) ode_syst = copy.deepcopy(sde_syst) ode_syst.fluctuation_vector = np.array([0, 0, 0]) ode_syst.external_influence = np.array([0, 0, 0]) ode_sol = solve_system(ode_syst) sol = ode_sol - sde_sol sol_extract = ode_sol.T[int(len(ode_sol.T)*3/4):] if not filter_steady_state(sol_extract): return sol return None
def plot_hist(syst, ax): single_run_matrices = [] for _ in range(50): sol = solve_system(syst) sol_extract = sol.T[int(len(sol.T)*3/4):] if filter_steady_state(sol_extract): continue single_run_mat = compute_correlation_matrix(np.array([sol_extract])) if single_run_mat.shape == (4, 4): single_run_mat = single_run_mat[:-1,:-1] assert single_run_mat.shape == (3, 3) single_run_matrices.append(single_run_mat) single_run_matrices = np.asarray(single_run_matrices) # plotting cols = cycle(['b', 'r', 'g', 'c', 'm', 'y', 'k']) for i, row in enumerate(single_run_matrices.T): for j, series in enumerate(row): if i == j: break sns.distplot(series, ax=ax, label=r'$c_{{{},{}}}$'.format(i,j)) ax.set_xlim((-1,1)) ax.set_xticks([], []) ax.set_yticks([], [])
def _main(): net, prints, sets = parse_network() voltages, currents = solver.solve_system(net) def I(symbol): if symbol in currents: return currents[symbol] raise ValueError("No current information for %s" % symbol) def V(node): return voltages[str(node)] from tabulate import tabulate table_headers = ['Quantity', 'Value'] table_rows = [] for node in voltages: table_rows.append(['V(%s)' % node, voltages[node].expand().simplify()]) for sym in currents: table_rows.append(['I(%s)' % sym, currents[sym].expand().simplify()]) locals = { 'I': I, 'V': V, } for p in prints: result = sympy.sympify(p, locals=locals).subs(sets) # ratio=1 -> don't allow the expression to get too long. table_rows.append(['%s' % p, result.expand().simplify(ratio=1)]) print(tabulate(table_rows, table_headers, tablefmt='psql'))
def do(syst, ax): # data single_run_matrices = [] for _ in trange(reps): sol = solve_system(syst) sol_extract = sol.T[int(len(sol.T)*3/4):] single_run_mat = compute_correlation_matrix(np.array([sol_extract])) if single_run_mat.shape == (4, 4): single_run_mat = single_run_mat[:-1,:-1] assert single_run_mat.shape == (3, 3) single_run_matrices.append(single_run_mat) single_run_matrices = np.asarray(single_run_matrices) # plotting cols = cycle(['b', 'r', 'g', 'c', 'm', 'y', 'k']) for i, row in enumerate(single_run_matrices.T): for j, series in enumerate(row): if i == j: break plot_histogram( series[series!=1], ax, label=r'$c_{{{},{}}}$'.format(i,j), facecolor=next(cols), alpha=0.5, bins=100)
def analyze_system(system, repetition_num=100, tmax=100, filter_trivial_ss=True, filter_mask=None, plot_hist=False, save_stdev=None, use_ode_sde_diff=True): """ Generate steady states for given system. `filter_mask` is a list of nodes to be excluded from filtering. A filtered entry must have a None correlation matrix """ if use_ode_sde_diff: ode_system = copy.copy(system) ode_system.fluctuation_vector = np.zeros( system.fluctuation_vector.shape) ss_data = [] for _ in range(repetition_num): sde_sol = solve_system(system, tmax=tmax) if use_ode_sde_diff: ode_sol = solve_system(ode_system, tmax=tmax) if use_ode_sde_diff: sol = ode_sol - sde_sol else: sol = sde_sol sol_extract = sol.T[int(len(sol.T) * 3 / 4):] if use_ode_sde_diff: ode_sol_extract = ode_sol.T[int(len(ode_sol.T) * 3 / 4):] else: ode_sol_extract = sol_extract if not filter_trivial_ss or not filter_steady_state( ode_sol_extract, filter_mask): ss_data.append(sol_extract) else: return system, None, sol corr_mat = compute_correlation_matrix(np.array(ss_data), plot_hist, save_stdev) return system, corr_mat, sol
def analyze_system( system, repetition_num=100, filter_trivial_ss=True, filter_mask=None, plot_hist=False, save_stdev=None, use_ode_sde_diff=True ): """ Generate steady states for given system. `filter_mask` is a list of nodes to be excluded from filtering. A filtered entry must have a None correlation matrix """ if use_ode_sde_diff: ode_system = copy.copy(system) ode_system.fluctuation_vector = np.zeros(system.fluctuation_vector.shape) ss_data = [] for _ in range(repetition_num): sde_sol = solve_system(system, tmax=100) if use_ode_sde_diff: ode_sol = solve_system(ode_system, tmax=100) if use_ode_sde_diff: sol = ode_sol - sde_sol else: sol = sde_sol sol_extract = sol.T[int(len(sol.T)*3/4):] if use_ode_sde_diff: ode_sol_extract = ode_sol.T[int(len(ode_sol.T)*3/4):] else: ode_sol_extract = sol_extract if not filter_trivial_ss or not filter_steady_state(ode_sol_extract, filter_mask): ss_data.append(sol_extract) else: return system, None, sol corr_mat = compute_correlation_matrix(np.array(ss_data), plot_hist, save_stdev) return system, corr_mat, sol
def get_matrices(syst, entry_num=100): """ Get correlation matrices for both cases """ # multiple entries from single run single_run_matrices = [] for _ in range(entry_num): sol = solve_system(syst) extract = sol.T[-entry_num:] single_run_mat = compute_correlation_matrix(np.array([extract])) single_run_matrices.append(single_run_mat) avg_single_mat = np.mean(single_run_matrices, axis=0) # one entry from multiple runs multiple_runs = [] for _ in range(entry_num): sol = solve_system(syst) extract = sol.T[-1].T multiple_runs.append(extract) multiple_mat = compute_correlation_matrix(np.array([multiple_runs])) return avg_single_mat, multiple_mat
def lyapunov_equation(): """ Check if our experiments satisfy the lyapunov equation """ # create systems sde_system = generate_basic_system() sde_system.fluctuation_vector[-1] = 2 ode_system = copy.deepcopy(sde_system) ode_system.fluctuation_vector = np.zeros(sde_system.fluctuation_vector.shape) # generate data sde_sol = solve_system(sde_system) ode_sol = solve_system(ode_system) sol = ode_sol - sde_sol sol_extract = sol.T[int(len(sol.T)*3/4):] # extract steady-state # investigate result J = sde_system.jacobian C = np.cov(sol_extract.T) D = np.diag(sde_system.fluctuation_vector) term1 = J @ C + C @ J.T term2 = -2 * D print(term1, '\n',term2) # plot stuff #plt.plot(sol_extract) plt.scatter(term1.ravel(), term2.ravel()) plt.title(f'Fluctuation vector: {sde_system.fluctuation_vector}') plt.xlabel('J @ C + C @ J.T') plt.ylabel('-2 * D') plt.savefig('images/lyapunov_equation.pdf')
if step == 5: system, step = get_layerproperties(system, step) if step == 6: system, step = get_reactionproperties(system, step) if step == 7: system, step = get_reactioncoefficients(system, step) if step == 8: system, step = get_systemproperties(system, step) if step == 9: system, step = get_layerconditions(system, step) if step == 10: system, step = get_solidlayerconditions(system, step) if step == 11: system, step = get_solveroptions(system, step) if step == 12: system, step = get_inputoptions(system, step) if step == 13: while (1): #show the summary window system = get_summary(system, database, materials) #run the simulation if system is not None: output, main = solve_system(system) #postprocess if output is not None: main = postprocess_data(system, output) if main == 1: break else: break #Loads an existing cpsm file if option == 1: cpsmfile = open(filename, 'r') system = pickle.load(cpsmfile) cpsmfile.close() #Update the loaded input file if it is from a previous version if system.version != version and previous_version.count( system.version) == 0:
from optparse import OptionParser import solver import plotter from sys import argv, exit if __name__ == '__main__': parser = OptionParser() parser.add_option('-n', dest='n', default=10) parser.add_option('-o', '--output', dest='output_file', default='solution.txt') (options, args) = parser.parse_args() options.n = int(options.n) (A, b, x) = solver.to_linear_system(options.n) print(A.size, b.size, x.size) y = solver.solve_system(A, b) print(y) print(x) plotter.plot(y, x) print('Start solving the model...') print(b) print(A) print('Done!') f = open(options.output_file, 'w') f.close()