コード例 #1
0
ファイル: simulation.py プロジェクト: rgoj/phd_code
def gen_simulation(gen_conf, num_sim=1, gen_magnitude_stddev=0):
    """Runs a single simulation of generators of ERP components.
    
    Currently only one epoch for one subject is calculated, maybe this should
    change. The generator configuration is specified as input.
    
    """
    # TODO: Remove all the scaling variables!
    # Initialisation of the PyBrainSim modelling framework with a homogeneous
    # spherical head model with a head radius set to 11.5 cm. Since we are
    # modelling only the spatical characteristics of the ERP component, we set
    # the temporal sampling frequency to 1, to obtain only one simulated value
    # per epoch.
    head = Head()
    head.setSamplingFrequency(1)
    headModel = HeadModelDipoleSphere(head, 11.5)
    
    # Initialisation of the simulated electrode array from predefined electrode
    # locations simulating the 10-20 electrode placement system.
    # TODO: This isn't elegant and should be changed!
    # TODO: This excludes simulations with a line of electrodes, which are
    # important for some applications as well, see doOneSimulation.py for
    # example implementation.
    [electrodes, topoX, topoY, thetaAngles, phiAngles] =\
        read_electrode_locations()
    for i in range(len(electrodes)):
        head.addRegistrationSite([thetaAngles[i], phiAngles[i]])
    
    # TODO: Here we are assuming that we know the generator locations!
    # (from the gen_conf variable)

    # Adding dipole generators to the head with the configuration parameters
    # given in gen_conf.
    # TODO: This is not working code
    # TODO: It would be really good if this code could fit in less lines!
    # TODO: Actually adding the generators to a list is not necessary any more,
    # maybe I could just run the constructor?
    generators = []
    for i in range(len(gen_conf)):
        # Combining the generator with the head model
        generators.append(
            GeneratorNoisy('Gen', head, 
                           position=[gen_conf[i]['depth'], 
                                     gen_conf[i]['theta'], 
                                     gen_conf[i]['phi'], 
                                     gen_conf[i]['orientation'], 
                                     gen_conf[i]['orientation_phi']], 
                           mean=gen_conf[i]['magnitude'], 
                           stddev=gen_magnitude_stddev))
    
    # Running the simulation.
    # TODO: runSimulation() should already return a numpy.array, now it returns
    # a list (checked that)!
    simulated_data = array(head.runSimulation(num_sim))

    # TODO: I should be returning something different here, perhaps?
    # TODO: I need to transpose simulated data to enable it to be used with
    # e.g. the topographic maps without transposing, like with the real data...
    # but whether this is a good idea in the long run - no idea...
    return [simulated_data.transpose(), gen_conf, electrodes]
コード例 #2
0
ファイル: lead_field.py プロジェクト: rgoj/phd_code
def initialize_electrode_locations():
    """Reads in electrode locations and transforms them to xyz coordinates, so
    that this isn't unnecessarily repeated in the main lead_field calculation
    function if not strictly necessary.
    """
    # Setting the radius of the head to 11.5 cm
    radius = 11.5

    # Reading in electrode locations from external file electrodeLocations.elp
    [el, el_x, el_y, el_thetas, el_phis] = read_electrode_locations()

    # How many electrodes do we have?
    n_el = len(el)

    # Coordinates of the electrodes (in the frame of reference associated with
    # the center of the head)
    xyz_el = zeros((n_el, 3))
    for i_el in range(n_el):
        # Calculating the coordinates of the electrode in the Cartesian coordinates associated with the head
        # The X axis points towards the right ear, while the Y axis points towards the front
        el_theta = el_thetas[i_el]
        el_phi = el_phis[i_el]
        xyz_el[i_el, 0] = radius * sin(el_theta) * cos(el_phi)
        xyz_el[i_el, 1] = radius * sin(el_theta) * sin(el_phi)
        xyz_el[i_el, 2] = radius * cos(el_theta)

    return radius, xyz_el
コード例 #3
0
def examine_data(data, electrodes, indices, name):
    print("\n\n\n" + name)
    print("Data consists of: " + str(data.shape[0]) + " subjects and " + str(data.shape[1]) + " electrodes\n")

    # Examine values for single subjects
    column_names = [electrodes[index] for index in indices]
    column_names.insert(0, "Subject")
    column_names.append(" ")
    column_names.append(" ")
    subjectvalues = PrettyTable(column_names)
    for i in range(data.shape[0]):
        row = [str(round(data[i, index], 4))[0:8] for index in indices]
        row.insert(0, i)
        if i != data.shape[0] - 1:
            row.append(" ")
            row.append(" ")
        else:
            row.append("MEAN")
            row.append("STD DEV")
        subjectvalues.add_row(row)

    electrode_means = mean(data, 0)
    electrode_stddevs = std(data, 0)
    electrode_range = []
    for i in range(data.shape[1]):
        electrode_range.append(max(data[:, i]) - min(data[:, i]))

    row = [str(round(electrode_means[index], 4))[0:8] for index in indices]
    row.insert(0, "Mean")
    row.append(str(round(mean(electrode_means), 4))[0:8])
    row.append(str(round(std(electrode_means), 4))[0:8])
    subjectvalues.add_row(row)
    row = [str(round(electrode_stddevs[index], 4))[0:8] for index in indices]
    row.insert(0, "Std Dev")
    row.append(str(round(mean(electrode_stddevs), 4))[0:8])
    row.append(str(round(std(electrode_stddevs), 4))[0:8])
    subjectvalues.add_row(row)
    row = [str(round(electrode_range[index], 4))[0:8] for index in indices]
    row.insert(0, "Range")
    row.append(str(round(mean(electrode_range), 4))[0:8])
    row.append(str(round(std(electrode_range), 4))[0:8])
    subjectvalues.add_row(row)

    subjectvalues.printt(border=False)

    # Correlation between electrode mean and standard deviation
    figure()
    from matplotlib import pyplot

    pyplot.subplot(211)
    pyplot.plot(electrode_means, electrode_stddevs, ".")
    pyplot.xlabel("Electrode mean")
    pyplot.ylabel("Electrode standard deviation")
    pyplot.title(name)
    [coefficient, pvalue] = pearsonr(electrode_means, electrode_stddevs)
    print(
        "\nCorrelation between mean and standard deviation, coefficient: "
        + str(coefficient)
        + ", significance value: "
        + str(pvalue)
    )

    # Correlation (across subjects) between electrodes depending on distance
    # between the electrodes
    pyplot.subplot(212)
    electrode_correlations = []
    electrode_distances = []
    [electrodes_file, pos_x, pos_y, pos_theta, pos_phi] = read_electrode_locations()
    for electrode1 in range(data.shape[1]):
        for electrode2 in range(data.shape[1]):
            # if electrode1 <= electrode2:
            #    break
            [coefficient, pvalue] = pearsonr(data[:, electrode1], data[:, electrode2])
            electrode_correlations.append(coefficient)
            distance = sqrt(
                square(pos_x[electrode1] - pos_x[electrode2]) + square(pos_y[electrode1] - pos_y[electrode2])
            )
            electrode_distances.append(distance)
    pyplot.plot(electrode_distances, electrode_correlations, ".")
    pyplot.xlabel("Distance between two electrodes")
    pyplot.ylabel("Correlation between two\nelectrodes across subjects")
コード例 #4
0
def plot_variogram(data, cov_data, data_bg=None, cov_data_bg=None,
                   norm='normalized', binned=False, color='b'):
    # Correlation (across subjects) between electrodes depending on distance
    # between the electrodes
    electrode_correlations = []
    electrode_correlations_bg = []
    electrode_distances = []
    [electrodes_file, pos_x, pos_y, pos_theta, pos_phi] = \
            read_electrode_locations()
    if data_bg != None:
        color = 'r'
    for electrode1 in range(data.shape[1]):
        for electrode2 in range(data.shape[1]):
            #if electrode1 <= electrode2:
            #    break
            if norm == 'normalized':
                [coefficient, pvalue] = pearsonr(data[:,electrode1], data[:,electrode2])
                if data_bg != None:
                    [coefficient_bg, pvalue_bg] = pearsonr(data_bg[:,electrode1], data_bg[:,electrode2])
            elif norm == 'unnormalized':
                coefficient = cov_data[electrode1][electrode2]
                if cov_data_bg != None:
                    coefficient_bg = cov_data_bg[electrode1][electrode2]
            else:
                print norm + ' not recognized!!!'

            electrode_correlations.append(coefficient)
            if data_bg != None:
                electrode_correlations_bg.append(coefficient_bg)
            distance = sqrt(square(pos_x[electrode1] - pos_x[electrode2])
                            + square(pos_y[electrode1] - pos_y[electrode2]))
            electrode_distances.append(distance)

    if binned is False:
        if data_bg != None:
            pyplot.plot(electrode_distances, electrode_correlations_bg, 'b.')
        pyplot.plot(electrode_distances, electrode_correlations, color+'.')
    elif binned is True:
        (numbers,bins) = histogram(electrode_distances,20)
        corr_means = []
        corr_sems = []
        corr_means_bg = []
        corr_sems_bg = []
        dists = []
        for i in range(len(bins[:-1])):
            corr_bin = []
            corr_bin_bg = []
            for j in range(len(electrode_correlations)):
                if electrode_distances[j] >= bins[i] and electrode_distances[j] < bins[i+1]:
                    corr_bin.append(electrode_correlations[j])
                    if data_bg != None:
                        corr_bin_bg.append(electrode_correlations_bg[j])
            corr_means.append(mean(corr_bin))
            #corr_means.append(median(corr_bin))
            corr_sems.append(2*sem(corr_bin))
            #corr_sems.append(std(corr_bin))
            dists.append((bins[i+1] - bins[i])/2.0 + bins[i])
            if data_bg != None:
                corr_means_bg.append(mean(corr_bin_bg))
                #corr_means_bg.append(median(corr_bin_bg))
                corr_sems_bg.append(2*sem(corr_bin_bg))
                #corr_sems_bg.append(std(corr_bin_bg))
        if data_bg != None:
            pyplot.errorbar(dists, corr_means_bg, yerr=corr_sems_bg,fmt='bo')
        pyplot.errorbar(dists, corr_means, yerr=corr_sems,fmt=color + 'o')
        
    handle = pyplot.gca()

    pyplot.xlabel('Distance between two electrodes')
    if norm == 'normalized':
        pyplot.ylabel('Pearson\'s R Correlation between\ntwo electrodes across subjects')
        pyplot.ylim(-1.1,1.1)
    elif norm == 'unnormalized':
        pyplot.ylabel('Covariance between two\nelectrodes across subjects')

    return handle