def test_pyphi_integration(fig4_graph): current_state = (1, 0, 0) # holi format computed_net = pyphi.Network(fig4_graph.tpm, fig4_graph.connectivity_matrix) computed_sub = pyphi.Subsystem(computed_net, current_state, range(computed_net.size)) true_net = pyphi.examples.fig4() true_sub = pyphi.Subsystem(true_net, current_state, range(true_net.size)) assert computed_net == true_net assert computed_sub == true_sub
def to_calculate_mean_phi(tpm, spin_mean,t): N = tpm.shape[-1] setting_int = np.linspace(0, np.power(2, N) - 1, num=np.power(2, N)).astype(int) M = list(map(lambda x: list(np.binary_repr(x, width=N)), setting_int)) M = np.flipud(np.fliplr(np.asarray(M).astype(np.int))) num_states = M.shape[0] phi_values = [] network = pyphi.Network(tpm) for state in range(num_states): if spin_mean[state] != 0: phi_values.append(phi(pyphi.Subsystem(network, M[state, :], range(network.size)))) #phi_values_sum = phi_values*spin_mean[state] phi_values_sqr = [phi_ * phi_ for phi_ in phi_values] weigth = spin_mean[np.where(spin_mean != 0)] phiSum = np.sum(phi_values*weigth) phiSus = (np.sum(phi_values_sqr*weigth) - (phiSum * phiSum)) / (N*t) return np.mean(phi_values), phiSum, phiSus
def get_macro_phis(micro_TPM, verbose=True, state_map=None, num_states_per_elem=None): if state_map == None or num_states_per_elem == None: # have a default state map state_map = { 0: [0, 1, 2, 4, 5, 6, 8, 9, 10], 1: [3, 7, 11], 2: [12, 13, 14], 3: [15] } num_states_per_elem = [2, 2] macro_TPM = CoarseGrainer.coarse_grain_nonbinary_TPM( micro_TPM, state_map, num_states_per_elem) network = pyphi.Network(macro_TPM, num_states_per_node=num_states_per_elem) states = Helpers.get_system_states(num_states_per_elem) phis = [] for state in states: subsystem = pyphi.Subsystem(network, state) sia = pyphi.compute.sia(subsystem) phis.append(sia.phi) if verbose: print(sia.ces) print(sia.partitioned_ces) print(sia.cut) return phis
def pyphi_subsystem(self): """Yield a PyPhi subsystem corresponding to the graph in its current state. Background elements are frozen in PyPhi. PyPhi node indicies match graph node indices.""" net = pyphi.Network(self.tpm, self.connectivity_matrix) foreground_node_indices = self.get_indices(self.foreground_nodes) return pyphi.Subsystem(net, self.state, foreground_node_indices)
def compute_phi_data(animat, state, log): log.info("\n[Animat] " + ("current state " + str(state)).center(60, " ")) main_complex = None whole_system = None elapsed = 0 animat.current_state = state #import pdb; pdb.set_trace() tic = time() main_complex = pyphi.compute.main_complex(animat.network) toc = time() log.info("\n[Animat] Found main_complex:") log.info("\n[Animat]\tNodes: " + str(main_complex.subsystem.nodes)) log.info("\n[Animat]\tPhi: " + str(main_complex.phi)) if calculate_all_complexes_and_whole_system: subsystem = pyphi.Subsystem(range(len(animat.used_nodes)), animat.network) whole_system = pyphi.compute.constellation(subsystem) #import pdb; pdb.set_trace() elapsed = toc - tic log.info('\n[Animat] Elapsed time:', elapsed) return main_complex, whole_system, elapsed
def test_factory(): # Generate the network & experiment. # This should generally be done in a separate script network = pyphi.examples.basic_network() state = (1, 0, 0) experiment = Experiment('test_factory', '1.0', network, state) experiment.initialize() port = 10030 mechanisms = pyphi.utils.powerset(network.node_indices, nonempty=True) with WorkerFactory(experiment) as factory: start_master(experiment, mechanisms, port) # Load CES ces = experiment.load_ces() print(ces) # Check results reference_ces = pyphi.compute.ces(pyphi.Subsystem(network, state)) assert ces.phis == reference_ces.phis assert ces.mechanisms == reference_ces.mechanisms print('All good!')
def calc_mean_phi(J, TPM, spinBin): M = np.array(gen_reservoir(J.shape[1]), dtype='uint8') templen = T.shape[1] print('The number of data points to calculate Phi for is ' + str(templen)) #tempstart = input('Start from data point: ') #tempstart = int(tempstart) tempstart = 0 #tempend = input('End at data point: ') #tempend = int(tempend) tempend = templen #increment = input('Increment every _ data points: ') #increment = int(increment) increment = 1 numStates = M.shape[0] ind = np.arange( tempstart, tempend, increment) # indices of data points that phi will be calculated for T2 = T[0, ind] looplen = ind.shape[0] # number of iterations of loop # phi = np.zeros([numStates,templen]) phi = np.zeros([numStates, looplen]) phiSqr = np.zeros([numStates, looplen]) count = -1 print('Calculating...') for temp in range(tempstart, tempend, increment): count += 1 print(((temp) / (tempend - tempstart)) * 100, "% Complete") for state in range(numStates): #numflips if spinBin[state, temp] != 0: start = time.time() #print("Starting state ", M[state,:], "at temp. ", T[0,temp]) network = pyphi.Network(TPM[:, :, temp]) #subsystem = pyphi.Subsystem(network, S[:,state,temp], range(network.size)) subsystem = pyphi.Subsystem(network, M[state, :], range(network.size)) #print(subsystem) phi[state, count] = pyphi.compute.big_phi(subsystem) phiSqr[state, count] = phi[state, count] * phi[state, count] print("Phi = ", phi[state, count]) #input() end = time.time() #print(end - start, "seconds elapsed") phiSum = np.sum(phi * spinBin[:, ind], 0) phiSqrSum = np.sum(phiSqr * spinBin[:, ind], 0) phiSus = (phiSqrSum - phiSum * phiSum) / (T2 * J.shape[0]) #print('Done!') return phiSum, phiSus, T2
def get_phi_from_subsystem(self, state, node_indices=(4, 5, 6, 7)): #calculate phi on specified subsystem, #4,5,6,7 all hidden nodes of the animat subsystem = pyphi.Subsystem(self.brain, state, node_indices) phi = pyphi.compute.phi(subsystem) return phi
def phi_compute(tpm): # Computes phi # Inputs: # tpm = state-by-node matrix (states x nodes) # Outputs: # Build the network and subsystem # We are assuming full connection network = pyphi.Network(tpm) print("Network built", flush=True) ######################################################################################### # Remember that the data is in the form a matrix # Matrix dimensions: sample(2250) x channel(15) # Determine number of system states n_states = tpm.shape[0] nChannels = int(math.log(n_states, 2)) # Assumes binary values # Initialise results storage structures state_sias = np.empty((n_states), dtype=object) state_phis = np.zeros((n_states)) # sys.exit() # Calculate all possible phi values (number of phi values is limited by the number of possible states) for state_index in range(0, n_states): #print('State ' + str(state_index)) # Figure out the state state = pyphi.convert.le_index2state(state_index, nChannels) # As the network is already limited to the channel set, the subsystem would have the same nodes as the full network subsystem = pyphi.Subsystem(network, state) #sys.exit() # Compute phi values for all partitions sia = pyphi.compute.sia(subsystem) #sys.exit() # Store phi and associated MIP state_phis[state_index] = sia.phi # MATLAB friendly storage format (python saves json as nested dict) # Store big_mip state_sias[state_index] = pyphi.jsonify.jsonify(sia) print('State ' + str(state_index) + ' Phi=' + str(sia.phi), flush=True) # Return ########################################################################### return state_phis, state_sias ######################################################################################################## ########################################################################################################
def get_micro_average_phi(TPM): network = pyphi.Network((TPM), num_states_per_node=[4, 4]) phis = [] states = reversed(get_nary_states(2, 4)) for state in states: subsystem = pyphi.Subsystem(network, state) sia = pyphi.compute.sia(subsystem) phis.append(sia.phi) print(sia.ces) print(sia.partitioned_ces) return phis, sum(phis) / len(phis)
def getphi(tpm): network = pyphi.Network(tpm, node_labels=labels) phis = [] for i in range(2): for j in range(2): for k in range(2): state = (i, j, k) node_indices = (0, 1, 2) if is_in(list(state), tpm): subsystem = pyphi.Subsystem(network, state, node_indices) phis += [pyphi.compute.phi(subsystem)] return phis
def nchannel_phi(matrix_array, n_channels): """ For each combination of n_channels (n_channels <= number of rows/channels in each matrix), calculates the TPM across all trials using all samples, then calculates phi at each transitioning sample Assumes that all channels are connected Inputs: matrix_array - array of 2D matrices, all with the same number of elements in the first dimension n_channels - how many channels to calculate phi over Outputs: """ combo_phis = dict() # Get the combinations of channels channels = np.arange(matrix_array[0].shape[0]) # Get list of channels channel_combos = [list(combination) for combination in itertools.combinations(channels, n_channels)] # Get combos of channels for combo in channel_combos: print(combo) # Extract relevant channels (i.e. channels specificed by the combo) across all trials samples_all = matrix_array[0][combo, :] for matrix_counter in range(1, matrix_array.size): np.concatenate((samples_all, matrix_array[matrix_counter][combo, :]), axis=1) # Build the TPM from those channels tpm_input = np.empty((1), dtype=object) tpm_input[0] = samples_all tpm = tpm_window(tpm_input, -1, 0) # We place the concatenated matrix into an array as input for tpm_window(), which takes an array of matrices print("computing phi") # Compute phi at each trial sample network = pyphi.Network(tpm) phis = np.empty((matrix_array.size), dtype=object) for trial_counter in range(matrix_array.size): phis[trial_counter] = np.empty(matrix_array[trial_counter].shape[1]) trial = matrix_array[trial_counter] for sample_counter in range(matrix_array[trial].shape[1]): print("trial" + str(trial_counter) + " sample" + str(sample_counter)) sample = trial[combo, sample_counter] print(sample) state = tuple(np.ndarray.tolist(sample)) print("state done") subsystem = pyphi.Subsystem(network, state, range(network.size)) print("subsystem done") phis[trial_counter][sample_counter] = pyphi.compute.big_phi(subsystem) print("phi = " + str(phis[trial_counter][sample_counter])) # Add combo results to dictionary combo_phis[combo] = phis return combo_phis
def test_pyphi_integration(fig4_graph): state = (1, 0, 0) fig4_graph.state = (1, 0, 0) computed_net = fig4_graph.pyphi_network() computed_sub = fig4_graph.pyphi_subsystem() true_net = pyphi.examples.fig4() true_sub = pyphi.Subsystem(true_net, state, true_net.node_indices) assert computed_net == true_net assert np.array_equal(computed_net.node_labels, ['A', 'B', 'C']) assert computed_sub == true_sub
def phi(self, statestr=None, verbose=False): """Calculate phi for net.""" if statestr is None: instatestr = choice(self.tpm.index) statestr = ''.join(f'{int(s):x}' for s in self.tpm.loc[instatestr, :]) #!print(f'DBG statestr={statestr}') state = [int(c) for c in list(statestr)] if verbose: print(f'Calculating Φ at state={state}') node_indices = tuple(range(len(self.graph))) subsystem = pyphi.Subsystem(self.pyphi_network, state, node_indices) return pyphi.compute.phi(subsystem)
def func(x,state =(0,0,0), n = 3): if len(x)==n*2**n: tpm = np.reshape(x, (2**n,n)); net = pyphi.Network(tpm); subsystem = pyphi.Subsystem(net, state,range(net.size)) phi = pyphi.compute.big_phi(subsystem); #print(how_close_to_int(x), phi) return phi else: print("Invalide input, not of the correct size to change into a TPM");
def to_calculate_mean_phi(tpm, spin_mean, eps=None): import numpy as np import pyphi from pyphi.compute import phi rows, columns = tpm.shape setting_int = np.linspace(0, rows - 1, num=rows).astype(int) M = list(map(lambda x: list(np.binary_repr(x, width=columns)), setting_int)) #M = np.flipud(np.fliplr(np.asarray(M).astype(np.int))) M = np.asarray(M).astype(np.int) #num_states = np.log2(N) phi_values = [] network = pyphi.Network(tpm) for state in range(rows): if eps == None: if spin_mean[state] != 0: phi_values.append( phi( pyphi.Subsystem(network, M[state, :], range(network.size)))) else: if spin_mean[state] < eps: phi_values.append( phi( pyphi.Subsystem(network, M[state, :], range(network.size)))) weigth = spin_mean[np.where(spin_mean != 0)] phiSum = np.sum(phi_values * weigth) return np.mean(phi_values), phiSum
def test_simple(): network = pyphi.examples.basic_network() state = (1, 0, 0) experiment = Experiment('test_simple', '1.0', network, state) experiment.initialize() mechanisms = pyphi.utils.powerset(network.node_indices, nonempty=True) print('Starting worker...') worker = subprocess.Popen([ 'work_queue_worker', '-N', experiment.project_name, '-P', experiment.password_file, # '-d', 'all' ]) try: print('Starting master...') start_master(experiment, mechanisms, port=10021, timeout=0, n_divisions=2) except: raise finally: print('Killing worker...') worker.kill() worker.wait() print('Done.') ces = experiment.load_ces() print(ces) reference_ces = pyphi.compute.ces(pyphi.Subsystem(network, state)) assert ces.phis == reference_ces.phis assert ces.mechanisms == reference_ces.mechanisms print('All good!')
def get_micro_phis(TPM, verbose=True): """ Gets the state phis for a TPM with 2 elements, each 4 states. """ network = pyphi.Network((TPM), num_states_per_node=[4, 4]) phis = [] states = Helpers.get_nary_states(2, 4) # not the TPM order! for state in states: subsystem = pyphi.Subsystem(network, state) sia = pyphi.compute.sia(subsystem) if state == (0, 1): if verbose: print(sia.ces) print(sia.partitioned_ces) print(sia.cut) phis.append(sia.phi) if verbose: print(phis) return phis
def get_macro_average_phi(micro_TPM): num_states_per_elem = [2, 2] state_map = { 0: [0, 1, 2, 4, 5, 6, 8, 9, 10], 1: [3, 7, 11], 2: [12, 13, 14], 3: [15] } macro_TPM = coarse_grain_nonbinary_TPM(micro_TPM, state_map, num_states_per_elem) # Macro analysis where bursting is one state, and everything else is another print(macro_TPM) network = pyphi.Network(macro_TPM, num_states_per_node=[2, 2]) states = reversed(get_nary_states(2, 2)) phis = [] for state in states: subsystem = pyphi.Subsystem(network, state) sia = pyphi.compute.sia(subsystem) phis.append(sia.phi) print(sia.ces) print(sia.partitioned_ces) return phis, sum(phis) / len(phis)
#print(inpt,'\n',sw,'\n',swN, '\n''------''\n') V = 0 for v in range(0, nN): V = V + istate[v] * 2**v tpm[int(V)] = tuple(swN) # Create the connectivity matrix cm = np.abs(np.where(weights != 0, 1, 0)) # Transpose our (receiving, sending) CM to use the PyPhi convention of (sending, recieving) cm = np.transpose(cm) # Create the network subsystem_labels = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T') network = pyphi.Network(tpm, cm, subsystem_labels) # In[5]: # Set state and create subsystem #A B C D E F G H I J K L M N O P Q R S T# state = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) subsystem = pyphi.Subsystem(network, state, range(network.size)) A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T = subsystem.node_indices pyphi.config.REPR_VERBOSITY = 1 experiment = Experiment('largepyr', '2.1', network, state) experiment.initialize()
import numpy as np import pyphi import scipy.io from scipy.io import loadmat from scipy.io import savemat pyphi.config.PARALLEL_CUT_EVALUATION = False tpmcell = loadmat('file path') tpm = np.array(tpmcell['TPM']) frecell = loadmat('file path') fre = np.array(frecell['fre']) phi = np.zeros([63, 63]) for num1 in range(0, 62): for num2 in range(num1 + 1, 63): network = pyphi.Network(tpm[num1, num2]) subsystem = pyphi.Subsystem(network, (0, 0)) phi00 = pyphi.compute.phi(subsystem) subsystem = pyphi.Subsystem(network, (1, 0)) phi10 = pyphi.compute.phi(subsystem) subsystem = pyphi.Subsystem(network, (0, 1)) phi01 = pyphi.compute.phi(subsystem) subsystem = pyphi.Subsystem(network, (1, 1)) phi11 = pyphi.compute.phi(subsystem) phiarray = np.array([phi00, phi10, phi01, phi11]) phi_by_state = np.array(phiarray) phibs_fre = phi_by_state * np.transpose(fre[num1][num2]) phi[num1][num2] = sum(sum(phibs_fre)) savemat('phi', {'phi': phi})
def phi_compute(tpm, state_counters, nValues, out_dir, out_file): # Assumes tpm is state-by-node # Intputs: # tpm = state-by-node TPM # state_counters = vector of state counts # nValues = number of states each element can take # out_dir = string; directory to output results file # out_name = string; name of output files # Build pyphi network network = pyphi.Network(tpm) # Determine number of system elements nChannels = np.shape(tpm)[-1] # Determine number of system states n_states = nValues**nChannels # Results structure phi = dict() # Initialise results storage structures phi_value = 0 # Doesn't need initialisation mips = np.empty((n_states), dtype=tuple) big_mips = np.empty((n_states), dtype=object) state_phis = np.zeros((n_states)) # sys.exit() # Calculate all possible phi values (number of phi values is limited by the number of possible states) for state_index in range(0, n_states): #print('State ' + str(state_index)) # Figure out the state state = pyphi.convert.loli_index2state(state_index, nChannels) # As the network is already limited to the channel set, the subsystem would have the same nodes as the full network subsystem = pyphi.Subsystem(network, state, network.node_indices) #sys.exit() # Compute phi values for all partitions big_mip = pyphi.compute.big_mip(subsystem) # Store phi and associated MIP state_phis[state_index] = big_mip.phi mips[state_index] = big_mip.cut # MATLAB friendly storage format (python saves json as nested dict) big_mip_json = big_mip.to_json() # Sort each constellation by their mechanisms big_mip_json[ 'partitioned_constellation'] = sort_constellation_by_mechanism( big_mip_json['partitioned_constellation']) big_mip_json[ 'unpartitioned_constellation'] = sort_constellation_by_mechanism( big_mip_json['unpartitioned_constellation']) # Store big_mip big_mips[state_index] = big_mip_json print('State ' + str(state_index) + ' Phi=' + str(big_mip.phi)) phi_total = 0 for state_index in range(0, n_states): if state_counters[state_index] > 0: # Add phi to total, weighted by the number of times the state occurred phi_total += state_phis[state_index] * state_counters[state_index] phi_value = phi_total / np.sum(state_counters) phi['phi'] = phi_value phi['state_counters'] = state_counters phi['big_mips'] = big_mips phi['state_phis'] = state_phis phi['tpm'] = tpm phi['mips'] = mips # Save save_mat(out_dir + out_file, {'phi': phi}) print('saved ' + out_dir + out_file) return out_file
phi_value = 0; # Doesn't need initialisation mips = np.empty((n_states), dtype=tuple) big_mips = np.empty((n_states), dtype=object) state_counters = np.zeros((n_states)) state_phis = np.zeros((n_states)) # sys.exit() # Calculate all possible phi values (number of phi values is limited by the number of possible states) for state_index in range(0, n_states): #print('State ' + str(state_index)) # Figure out the state state = pyphi.convert.loli_index2state(state_index, nChannels) # As the network is already limited to the channel set, the subsystem would have the same nodes as the full network subsystem = pyphi.Subsystem(network, state, network.node_indices) #sys.exit() # Compute phi values for all partitions big_mip = pyphi.compute.big_mip(subsystem) # Get all partition values for all mechanisms/purviews mech_list_unpartitioned = [] mech_list_partitioned = [] # Storage of the results for N nodes # number of mechanisms = powerset # number of purviews = powerset # number of mechanisms = number of purviews # vector of mechanisms
# Doesn't need initialisation mips = np.empty((n_states), dtype=tuple) big_mips = np.empty((n_states), dtype=object) state_counters = np.zeros((n_states)) state_phis = np.zeros((n_states)) # sys.exit() # Calculate all possible phi values (number of phi values is limited by the number of possible states) for state_index in range(0, n_states): #print('State ' + str(state_index)) # Figure out the state state = pyphi.convert.loli_index2state(state_index, nChannels) # As the network is already limited to the channel set, the subsystem would have the same nodes as the full network subsystem = pyphi.Subsystem(network, state, network.node_indices) #sys.exit() # Compute phi values for all partitions big_mip = pyphi.compute.big_mip(subsystem) # Store phi and associated MIP state_phis[state_index] = big_mip.phi mips[state_index] = big_mip.cut # MATLAB friendly storage format (python saves json as nested dict) big_mip_json = big_mip.to_json() # Sort each constellation by their mechanisms big_mip_json[ 'partitioned_constellation'] = sort_constellation_by_mechanism(
def sub(): return pyphi.Subsystem(net(), state, node_labels)
def independent_joint_tpm(lfp_air_binarised, 0): f, (p1) = plt.subplots(1, facecolor="white") plot1 = p1.imshow(tpm, interpolation="none", aspect="auto") p1.set_xlabel("state") p1.set_ylabel("state") plot1_cbar = f.colorbar(plot1) plot1_cbar.set_label("p") plt.rcParams.update({'font.size': 22}) plt.show(block=False) # Calculate PHI for one trial trial = lfp_air_binarised[1] network = pyphi.Network(tpm) phis = np.zeros((1, trial.shape[1])) for sample_counter in range(trial.shape[1]): print(sample_counter) sample = trial[:, sample_counter] state = tuple(np.ndarray.tolist(sample)) subsystem = pyphi.Subsystem(network, state, range(network.size)) #phis[sample_counter] = pyphi.compute.big_phi(subsystem) def nchannel_phi(matrix_array, n_channels): """ For each combination of n_channels (n_channels <= number of rows/channels in each matrix), calculates the TPM across all trials using all samples, then calculates phi at each transitioning sample Assumes that all channels are connected Inputs: matrix_array - array of 2D matrices, all with the same number of elements in the first dimension n_channels - how many channels to calculate phi over Outputs: """ combo_phis = dict() # Get the combinations of channels channels = np.arange(matrix_array[0].shape[0]) # Get list of channels channel_combos = [list(combination) for combination in itertools.combinations(channels, n_channels)] # Get combos of channels for combo in channel_combos: print(combo) # Extract relevant channels (i.e. channels specificed by the combo) across all trials samples_all = matrix_array[0][combo, :] for matrix_counter in range(1, matrix_array.size): np.concatenate((samples_all, matrix_array[matrix_counter][combo, :]), axis=1) # Build the TPM from those channels tpm_input = np.empty((1), dtype=object) tpm_input[0] = samples_all tpm = tpm_window(tpm_input, -1, 0) # We place the concatenated matrix into an array as input for tpm_window(), which takes an array of matrices print("computing phi") # Compute phi at each trial sample network = pyphi.Network(tpm) phis = np.empty((matrix_array.size), dtype=object) for trial_counter in range(matrix_array.size): phis[trial_counter] = np.empty(matrix_array[trial_counter].shape[1]) trial = matrix_array[trial_counter] for sample_counter in range(matrix_array[trial].shape[1]): print("trial" + str(trial_counter) + " sample" + str(sample_counter)) sample = trial[combo, sample_counter] print(sample) state = tuple(np.ndarray.tolist(sample)) print("state done") subsystem = pyphi.Subsystem(network, state, range(network.size)) print("subsystem done") phis[trial_counter][sample_counter] = pyphi.compute.big_phi(subsystem) print("phi = " + str(phis[trial_counter][sample_counter])) # Add combo results to dictionary combo_phis[combo] = phis return combo_phis """ Conditions at which to compute phi: View all time and trials consecutively as a line graph - one matrix View all time and trials as an image/matrix, trim as required before viewing - one matrix per trial If using this, then you can reconstruct the first option Average across trials (time is the length of a trial, trim as required before averaging) - one matrix per trial """ def recursive_phi(max_channels): """ Computes phi over the power set of channels, from using 2 channels to up to max_channels """ return 1 # phis = nchannel_phi(lfp_air_binarised, 2) def plot_mean(matrix): """ Calculates the mean and standard deviation across the first dimension (axis 0), and plots across the second dimension (axis 1) Inputs: numpy 2D array """ if len(matrix.shape) > 2: return if len(matrix.shape) == 2: # two dimensions provided x_values = np.arange(0, matrix.shape[1]) mean_values = matrix.mean(axis=0) std_values = matrix.std(axis=0) else: # only one dimension was provided x_values = np.arange(0, matrix.shape[0]) mean_values = matrix std_values = matrix plt.plot(x_values, mean_values) if len(matrix.shape) == 2: # two dimensions provided plt.fill_between(x_values, mean_values - std_values, mean_values + std_values, alpha=0.5, linewidth=0) plt.autoscale(enable=True, axis='x', tight=True) plt.show(block=False) def main(): print("main() running") lfp = fly_data["LFP"][0, 0][0, :] #plot_mean(lfp) print("main() finished") if __name__ == '__main__': main()
def calculate_phis(data, n_test_channels, channel_set, ch_group, method, **kwargs): """ Calculates and saves phi values for a given number of test_channels for a given method. Args: data (np.ndarray): (samples, channels, trials, flies, conds) array of BINARISED data. n_test_channels (int): Number of channels to consider at a time. Minimum 2. method (string): Method used to generate TPM. Must be one of: - "direct" - "logistic" (requires kwarg interaction_order) channel_set (int): A unique integer indicating an ID for the channel group. ch_group (tuple of ints): Channels to be included in phi calculation. Keyword Args: interaction_order (int): Parameter used for logistic method for TPM calculation. Returns: Nothing. Instead, saves lists of dictionaries (per channel group) as .mat files with keys: i_trial i_fly i_cond state_phis tpm state_counts channels """ print("USING {}".format(method)) n_samples, n_channels, n_trials, n_flies, n_conds = data.shape tau = 1 results_dir = "../../data/processed/phis/" if method == "direct": method_str = method elif method == "logistic": if "interaction_order" not in kwargs: raise ValueError("Must specify interaction_order if using logistic method.") interaction_order = kwargs.get("interaction_order") method_str = method + str(interaction_order) else: raise ValueError("Method specified was not recognised") # This deeply nested loop will take a long time... ch_group_results = [] data_slice = data[:, ch_group, :, :, :] for cond in range(n_conds): #print("CONDITION {}".format(cond)) for fly in range(n_flies): #print(" FLY {}".format(fly)) for trial in range(n_trials): #print(" TRIAL {}".format(trial)) if method == "direct": tpm, state_counts = build_tpm_sbn(data_slice[:, :, trial, fly, cond], tau, 2) else: tpm, state_counts = tpm_log_reg(data_slice[:, :, trial, fly, cond], tau, interaction_order) n_states = 2 ** n_test_channels # n_states = n_test_channels ** 2 # doing this for 3 channels for consistency network = pyphi.Network(tpm) phi = dict() state_sias = np.empty((n_states), dtype=object) state_phis = np.zeros((n_states)) for state_index in range(n_states): state = pyphi.convert.le_index2state(state_index, n_test_channels) subsystem = pyphi.Subsystem(network, state) #sia = pyphi.compute.sia(subsystem) phi_val = pyphi.compute.phi(subsystem) state_phis[state_index] = phi_val #print(' STATE {}, PHI = {}'.format(state, phi_val)) # Store only phi values for each state #phi['sias'] = state_sias phi['state_phis'] = state_phis phi['tpm'] = tpm phi['state_counts'] = state_counts phi['i_trial'] = trial phi['i_fly'] = fly phi['i_cond'] = cond phi['channels'] = ch_group ch_group_results.append(phi) results_file = "PHI_{}_METHOD_{}_CHSET_{}_CHS_{}.mat".format(n_test_channels, method_str, channel_set, "-".join(map(str, ch_group))) sio.savemat(results_dir + results_file, {'ch_group_results': ch_group_results}, do_compression=True, long_field_names=True) print(' SAVED {}\n'.format(results_dir + results_file))
outfile = arguments['<outfile>'] timeout = int(arguments['<timeout>']) start_time = time() def timed_out(): return time() - start_time > timeout # Should be loaded from config file # Note: CACHE_REPERTOIRES cannot be configured at runtime # and must be loaded from the config file assert pyphi.config.MEASURE == 'BLD' assert pyphi.config.CACHE_REPERTOIRES == False network = load_pickle(network_file) subsystem = pyphi.Subsystem(network, state) # PartialConcept partial = load_pickle(infile) mechanism = partial.mechanism if partial.concept is None: partial.merge_concept(subsystem.null_concept) partial.concept.time = 0 partial.concept.mechanism = mechanism if partial.remaining_cause_purviews == partial.ALL: partial.remaining_cause_purviews = subsystem.potential_purviews( pyphi.Direction.CAUSE, mechanism) if partial.remaining_effect_purviews == partial.ALL:
import scipy.io from scipy.io import loadmat from scipy.io import savemat data = loadmat( '/Users/soliyan3261/Desktop/difference_method_tao_3.9/2chan/TMOC/TPM_TMOC.mat' ) tpm = np.array(data['TPM']) state00 = (0, 0) state10 = (1, 0) state01 = (0, 1) state11 = (1, 1) phi_by_state = np.zeros([6, 4]) phi = np.zeros(6) for num1 in range(0, 6): network = pyphi.Network(tpm[0, num1]) subsystem = pyphi.Subsystem(network, state00) phi00 = pyphi.compute.phi(subsystem) subsystem = pyphi.Subsystem(network, state10) phi10 = pyphi.compute.phi(subsystem) subsystem = pyphi.Subsystem(network, state01) phi01 = pyphi.compute.phi(subsystem) subsystem = pyphi.Subsystem(network, state11) phi11 = pyphi.compute.phi(subsystem) phiarray = np.array([phi00, phi10, phi01, phi11]) phi_by_state[num1] = np.array(phiarray) phibs_fre = phi_by_state[num1] * tpm[2, num1] phi[num1] = sum(sum(phibs_fre)) print(phi) # savemat('tmWL_phicell',{'phiTMWLcell':phiTMWLcell})
# phi = np.zeros([numStates,templen]) phi = np.zeros([numStates, looplen]) phiSqr = np.zeros([numStates, looplen]) count = 0 print('Calculating...') for temp in range(tempstart, tempend, increment): print(((temp) / (tempend - tempstart)) * 100, "% Complete") for state in range(numStates): #numflips if spinBin[state, temp] != 0: start = time.time() #print("Starting state ", M[state,:], "at temp. ", T[0,temp]) network = pyphi.Network(TPM[:, :, temp], connectivity_matrix=J) #subsystem = pyphi.Subsystem(network, S[:,state,temp], range(network.size)) subsystem = pyphi.Subsystem(network, M[state, :], range(network.size)) #print(subsystem) phi[state, count] = pyphi.compute.big_phi(subsystem) phiSqr[state, count] = phi[state, count] * phi[state, count] print("Phi = ", phi[state, count]) #input() end = time.time() #print(end - start, "seconds elapsed") count += 1 phiSum = np.sum(phi * spinBin[:, ind], 0) phiSqrSum = np.sum(phiSqr * spinBin[:, ind], 0) phiSus = (phiSqrSum - phiSum * phiSum) / (T2 * J.shape[0]) #print('Done!')