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 json2pyphi(network): """Load a network from a json file""" tpm = network['tpm'] current_state = network['currentState'] cm = network['cm'] network = pyphi.Network(tpm, connectivity_matrix=cm) return (network, current_state)
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 quantify_network(cm, probs, k): TPM, CM = buildTPM(cm,probs, k); #check that TPM is valid! if (np.sum(transform_tpm(TPM),1)==1).all(): net = phi.Network(TPM, CM) dat = np.zeros([2**8, 2]) j= 0; for state in states: state = state[::-1] waste = (classical(TPM, team_skill_map, state,costs)) cmplxs = phi.compute.condensed(net,state); phis = [] for i in range(len(cmplxs)): phis.append(cmplxs[i].phi) dat[j,:] = np.array([waste, np.sum(phis)]) #print(j,waste, phis) j+=1 dist = np.real(stat_dist(transform_tpm(TPM))); return dist.dot(dat) else:
def test_blackbox_and_coarse_grain_external(): # Larger, with external nodes, blackboxed and coarse-grained tpm = np.zeros((2**6, 6)) network = pyphi.Network(tpm) state = (0, 0, 0, 0, 0, 0) blackbox = macro.Blackbox(( (1, 4), (2, ), (3, ), (5, ), ), (1, 2, 3, 5)) partition = ((1, ), (2, ), (3, 5)) grouping = (((0, ), (1, )), ((1, ), (0, )), ((0, ), (1, 2))) coarse_grain = macro.CoarseGrain(partition, grouping) ms = macro.MacroSubsystem(network, state, (1, 2, 3, 4, 5), blackbox=blackbox, coarse_grain=coarse_grain) answer_tpm = np.array([[[[0, 1, 0], [0, 1, 0]], [[0, 1, 0], [0, 1, 0]]], [[[0, 1, 0], [0, 1, 0]], [[0, 1, 0], [0, 1, 0]]]]) assert np.array_equal(ms.tpm, answer_tpm) assert np.array_equal(ms.cm, np.ones((3, 3))) assert ms.node_indices == (0, 1, 2) assert ms.size == 3 assert ms.state == (0, 1, 0)
def macro_subsystem(): tpm = np.zeros((16, 4)) + 0.3 tpm[12:, 0:2] = 1 tpm[3, 2:4] = 1 tpm[7, 2:4] = 1 tpm[11, 2:4] = 1 tpm[15, 2:4] = 1 # fmt: off cm = np.array([ [0, 0, 1, 1], [0, 0, 1, 1], [1, 1, 0, 0], [1, 1, 0, 0], ]) # fmt: on state = (0, 0, 0, 0) network = pyphi.Network(tpm, cm=cm, node_labels="ABCD") partition = ((0, 1), (2, 3)) grouping = (((0, 1), (2, )), ((0, 1), (2, ))) coarse_grain = macro.CoarseGrain(partition, grouping) return macro.MacroSubsystem(network, state, network.node_indices, coarse_grain=coarse_grain)
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 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 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 save_brain(self, TPM, cm, node_labels=[]): ''' Function for giving the animat a brain (pyphi network) and a graph object Inputs: TPM: a transition probability matrix readable for pyPhi cm: a connectivity matrix readable for pyPhi node_labels: list of labels for nodes (if empty, standard labels are used) Outputs: no output, just an update of the animat object ''' if not len(node_labels) == self.n_nodes: node_labels = [] # standard labels for up to 10 nodes of each kind sensor_labels = [ 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'S10' ] motor_labels = [ 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10' ] hidden_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] # defining labels for each node type s = [sensor_labels[i] for i in list(range(self.n_sensors))] m = [motor_labels[i] for i in list(range(self.n_motors))] h = [hidden_labels[i] for i in list(range(self.n_hidden))] # combining the labels node_labels.extend(s) node_labels.extend(m) node_labels.extend(h) # defining the network using pyphi network = pyphi.Network(TPM, cm, node_labels=node_labels) self.brain = network self.TPM = TPM self.cm = cm self.connected_nodes = sum(np.sum(cm, 0) * np.sum(cm, 1) > 0) # defining a graph object based on the connectivity using networkx G = nx.from_numpy_matrix(cm, create_using=nx.DiGraph()) mapping = {key: x for key, x in zip(range(self.n_nodes), node_labels)} G = nx.relabel_nodes(G, mapping) self.brain_graph = G # saving the labels and indices of sensors, motors, and hidden to animats self.node_labels = node_labels self.sensor_ixs = list(range(self.n_sensors)) self.sensor_labels = [node_labels[i] for i in self.sensor_ixs] self.motor_ixs = list( range(self.n_sensors, self.n_sensors + self.n_motors)) self.motor_labels = [node_labels[i] for i in self.motor_ixs] self.hidden_ixs = list( range(self.n_sensors + self.n_motors, self.n_sensors + self.n_motors + self.n_hidden)) self.hidden_labels = [node_labels[i] for i in self.hidden_ixs]
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): 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 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 saveBrain(self, TPM, cm): if self.n_nodes == 8 and self.n_sensors == 2: node_labels = ['S1', 'S2', 'M1', 'M2', 'A', 'B', 'C', 'D'] elif self.n_nodes == 7 and self.n_sensors == 1: node_labels = ['S1', 'M1', 'M2', 'A', 'B', 'C', 'D'] else: print('Problem saving brain.') network = pyphi.Network(TPM, cm, node_labels=node_labels) self.brain = network G = nx.from_numpy_matrix(cm, create_using=nx.DiGraph()) mapping = {key: x for key, x in zip(range(self.n_nodes), node_labels)} G = nx.relabel_nodes(G, mapping) self.brain_graph = G
def ocx_net(): tpm = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1], [1, 1, 1], [1, 1, 0]]) cm = np.array([[0, 0, 1], [1, 0, 1], [1, 1, 0]]) node_labels = ('P', 'Q', 'R') return pyphi.Network(tpm, cm, node_labels)
def test_list_all_partitions(): empty_net = pyphi.Network(np.array([]), (), ()) net = pyphi.examples.macro_network() assert macro.list_all_partitions(empty_net) == [] assert macro.list_all_partitions(net) == [ [[0, 1, 2], [3]], [[0, 1, 3], [2]], [[0, 1], [2, 3]], [[0, 1], [2], [3]], [[0, 2, 3], [1]], [[0, 2], [1, 3]], [[0, 2], [1], [3]], [[0, 3], [1, 2]], [[0], [1, 2, 3]], [[0], [1, 2], [3]], [[0, 3], [1], [2]], [[0], [1, 3], [2]], [[0], [1], [2, 3]], [[0, 1, 2, 3]] ]
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 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 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(cms[i], a, b) dat = np.array(dat) #%% TPM, CM = buildTPM(cms[1005], probs, k) net = phi.Network(TPM, CM); #%% dat = np.zeros([2**8, 2]) j= 0; for state in states: state = state[::-1] waste = (classical(TPM, team_skill_map, state,costs)) cmplxs = phi.compute.condensed(net,state); phis = [] for i in range(len(cmplxs)): phis.append(cmplxs[i].phi) dat[j,:] = np.array([waste, np.sum(phis)]) print(waste, phis) j+=1
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})
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 = 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)
import pyphi import numpy as np from pprint import pprint import scipy.io as sio mm_state = (1,1,1,1) m_state = (1,1) tpm_mm = sio.loadmat('./MM2_TemporalExample_Noisy_Ors_Micro.mat') tpm_m = sio.loadmat('./Noisy_Ors_1timestep_micro.mat') # ============================================================================ if __name__ == "__main__": # micro results net_m = pyphi.Network(tpm_m['tpm']) mc_m = pyphi.compute.major_complex(net_m, m_state) print(mc_m) # Macro results net_mm = pyphi.Network(tpm_mm['tpm']) #M = pyphi.macro.emergence(net_mm, mm_state) #This does not work here, as there are many spatial coarse grainings that are not allowed temporally grains = list(pyphi.macro.all_coarse_grains(net_mm.node_indices)) print(grains[41]) coarse_grain = grains[41] print(coarse_grain.macro_tpm(net_mm.tpm).reshape([4]+[2], order = 'F')) macro_subsystem = pyphi.macro.MacroSubsystem(net_mm, mm_state, coarse_grain=coarse_grain)
#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
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()
# tau_step = tau # # Binarise by median split # fly_data, n_values, medians = binarise_trial_median(fly_data[:, :, None, None, None]) # fly_data = fly_data[:, :, 0, 0, 0] # Get rid of those appended singleton dimensions # # Build TPM # tpm = build_tpm(fly_data[:, :, None], tau_step, n_values) # tpm_formatted = pyphi.convert.state_by_state2state_by_node(tpm) # #tpm = build_tpm(np.flip(fly_data[:, :, None], 0), tau_step, n_values) # #tpm, tmp = build_tpm_sbn_normalise(fly_data[:, :, None], tau_step, n_values, 9000) # print("TPM built") # Build the network and subsystem # We are assuming full connection network = pyphi.Network(tpm_formatted) print("Network built") ######################################################################################### # Remember that the data is in the form a matrix # Matrix dimensions: sample(2250) x channel(15) # Determine number of system states n_states = n_values**len(channel_set) # Results structure phi = dict() phi['nChannels'] = nChannels phi['channel_set'] = channel_set + 1 # Save 1-indexed values phi['tau'] = tau