Example #1
0
    def SetInitialConditions(self):
        #basic stuff, evenntuallt allow this to be modofied
        self.dx=.5    #in mm default 50 microns
        self.dz=0.05    #in mm default 50 microns
        self.kx=[7.59/50,7.63/50]    #x direction diffusiom in W/mmsk [no poly, poly]
        self.kz=[0.19/1000,0.23/1000]   #zz direction diffusion in J/mmsk [no poly,poly]
        self.crho=[15.28/1000,195.8/1000]  #heat capacity [graphite,poly] J/(Kmm3)

        #self.a=0.5
        self.q=.1

        #CHECK UNITS
        self.nx=int(3.5*25.4/self.dx)
        self.nz=int(6/self.dz)
        self.nt=500

        #precalculate some things
        self.dx2=self.dx*self.dx
        self.dz2=self.dz*self.dz
        #maximum dt limited by stability criteria.
        self.dt=self.crho[0]*self.dx2*self.dz2/(2*(self.kx[0]*self.dz2+self.kz[0]*self.dx2))/2
        print(self.dt)
# Start u and ui off as zero matrices:
        self.T = sp.full([2,self.nz,self.nx],25)  #old and new values for T switch each step
        self.Coeffs=sp.full([5,self.nz,self.nx],1/self.crho[0])  #this array holds the coeffs for each volume initiall just graphite
        #polymer block is cube 20x20 in side
        self.Coeffs[0,6:116,50:130]=1/self.crho[1]

        self.newVals=0      #this holds the values for the current step
        self.u=sp.zeros([self.nx,self.nz])
        self.ui=sp.zeros([self.nx,self.nz])
    def __init__(self, param={}):
        self.param = dict(self.DefaultParam)
        self.param.update(param)
        self.check_param()

        self.x_position = self.param['x_start_position']
        self.y_position = self.param['y_start_position']
        self.x_velocity = self.param['flight_speed'] * scipy.cos(
            self.param['initial_heading'])
        self.y_velocity = self.param['flight_speed'] * scipy.sin(
            self.param['initial_heading'])

        self.mode = scipy.full((self.size, ), self.Mode_FixHeading, dtype=int)
        self.heading_error = scipy.zeros((self.size, ))
        self.t_last_cast = scipy.zeros((self.size, ))

        cast_interval = self.param['cast_interval']
        self.dt_next_cast = scipy.random.uniform(cast_interval[0],
                                                 cast_interval[0],
                                                 (self.size, ))
        self.cast_sign = scipy.random.choice([-1, 1], (self.size, ))

        self.in_trap = scipy.full((self.size, ), False, dtype=bool)
        self.trap_num = scipy.full((self.size, ), -1, dtype=int)
        self.x_trap_loc = scipy.zeros((self.size, ))
        self.y_trap_loc = scipy.zeros((self.size, ))
        self.t_in_trap = scipy.full((self.size, ), scipy.inf)
    def __init__(self,
                 wind_field,
                 param={},
                 start_type='fh'):  #default start type is fixed heading
        self.param = dict(self.DefaultParam)
        self.param.update(param)
        self.check_param()
        self.dt = self.param['dt']
        self.x_position = self.param['x_start_position']
        self.y_position = self.param['y_start_position']

        if (not (self.param['heading_data'] == None)):
            heading_data = self.param['heading_data']
            (mean, kappa) = fit_von_mises(heading_data)
            self.param['initial_heading_dist'] = scipy.stats.vonmises(
                loc=mean, kappa=kappa)
            self.param['initial_heading'] = scipy.random.vonmises(
                mean, kappa, (self.param['swarm_size'], ))
        self.x_velocity = self.param['flight_speed'] * scipy.cos(
            self.param['initial_heading'])
        self.y_velocity = self.param['flight_speed'] * scipy.sin(
            self.param['initial_heading'])
        self.mode = scipy.full((self.size, ), self.Mode_StartMode, dtype=int)
        self.heading_error = scipy.zeros((self.size, ))
        self.t_last_cast = scipy.zeros((self.size, ))

        self.increments_until_turn = scipy.ones(
            (self.size, ))  #This is for the Levy walk option.
        #self.uniform_directions_pool = scipy.radians(scipy.random.uniform(0.0,360.0,(100,)))#Again for the Levy walk option, to save time drawing.
        #self.increments_pool = scipy.stats.lognorm.rvs(0.25,size=100,scale=
        #(300/3.0)/0.25*
        #scipy.exp(0))

        cast_interval = self.param['cast_interval']
        self.dt_next_cast = scipy.random.uniform(cast_interval[0],
                                                 cast_interval[0],
                                                 (self.size, ))
        self.cast_sign = scipy.random.choice([-1, 1], (self.size, ))

        self.parallel_coeff, self.perp_coeff = self.param['wind_slippage']
        self.par_wind, self.perp_wind = self.get_par_perp_comps(0., wind_field)
        #^This is the set of 2 x time arrays of the components of each fly's velocity par/perp to wind
        self.ever_tracked = scipy.full(
            (self.size, ), False, dtype=bool
        )  #Bool that keeps track if the fly ever plume tracked (false=never tracked)
        self.trap_num = scipy.full((self.size, ), -1, dtype=int)
        self.in_trap = scipy.full((self.size, ), False, dtype=bool)
        self.x_trap_loc = scipy.zeros((self.size, ))
        self.y_trap_loc = scipy.zeros((self.size, ))
        self.t_in_trap = scipy.full((self.size, ), scipy.inf)
        self.start_type = start_type  #Either 'fh' (fixed heading) or 'rw' (random walk)
        if start_type == 'rw':
            self.rw_dist = scipy.stats.lognorm(0.25, scale=1)
        else:
            self.rw_dist = None
 def value(self, t, x, y):
     vx = self.speed * scipy.cos(self.angle)
     vy = self.speed * scipy.sin(self.angle)
     if type(x) == scipy.ndarray:
         if x.shape != y.shape:
             raise (ValueError, 'x.shape must equal y.shape')
         vx_array = scipy.full(x.shape, vx)
         vy_array = scipy.full(y.shape, vy)
         return vx_array, vy_array
     else:
         return vx, vy
Example #5
0
def voronoi_edges(shape: List[int],
                  radius: int,
                  ncells: int,
                  flat_faces: bool = True):
    r"""
    Create an image of the edges in a Voronoi tessellation

    Parameters
    ----------
    shape : array_like
        The size of the image to generate in [Nx, Ny, Nz] where Ni is the
        number of voxels in each direction.

    radius : scalar
        The radius to which Voronoi edges should be dilated in the final image.

    ncells : scalar
        The number of Voronoi cells to include in the tesselation.

    flat_faces : Boolean
        Whether the Voronoi edges should lie on the boundary of the
        image (True), or if edges outside the image should be removed (False).

    Returns
    -------
    image : ND-array
        A boolean array with ``True`` values denoting the pore space

    """
    print(78 * '―')
    print('voronoi_edges: Generating', ncells, ' cells')
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((3, ), int(shape))
    im = sp.zeros(shape, dtype=bool)
    base_pts = sp.rand(ncells, 3) * shape
    if flat_faces:
        # Reflect base points
        Nx, Ny, Nz = shape
        orig_pts = base_pts
        base_pts = sp.vstack(
            (base_pts, [-1, 1, 1] * orig_pts + [2.0 * Nx, 0, 0]))
        base_pts = sp.vstack(
            (base_pts, [1, -1, 1] * orig_pts + [0, 2.0 * Ny, 0]))
        base_pts = sp.vstack(
            (base_pts, [1, 1, -1] * orig_pts + [0, 0, 2.0 * Nz]))
        base_pts = sp.vstack((base_pts, [-1, 1, 1] * orig_pts))
        base_pts = sp.vstack((base_pts, [1, -1, 1] * orig_pts))
        base_pts = sp.vstack((base_pts, [1, 1, -1] * orig_pts))
    vor = sptl.Voronoi(points=base_pts)
    vor.vertices = sp.around(vor.vertices)
    vor.vertices *= (sp.array(im.shape) - 1) / sp.array(im.shape)
    vor.edges = _get_Voronoi_edges(vor)
    for row in vor.edges:
        pts = vor.vertices[row].astype(int)
        if sp.all(pts >= 0) and sp.all(pts < im.shape):
            line_pts = line_segment(pts[0], pts[1])
            im[line_pts] = True
    im = spim.distance_transform_edt(~im) > radius
    return im
Example #6
0
    def _neutdata(self, samplename, ic50_in_name,
            nfitpoints, cextend):
        """Gets data for plotting neutralization curve.

        Returns a `pandas.DataFrame` appropriate for passing
        to :func:`dms_tools2.plot.plotFacetedNeutCurves`. The
        arguments have the meanings explained in :meth:`plot`.
        """
        concentrations = scipy.concatenate(
                [self.cs,
                 scipy.logspace(math.log10(self.cs.min() / cextend),
                                math.log10(self.cs.max() * cextend),
                                num=nfitpoints)
                ])
        n = len(concentrations)

        points = scipy.concatenate(
                [self.fs,
                 scipy.full(n - len(self.fs), scipy.nan)])

        fit = scipy.array([self.fracsurvive(c) for c in concentrations])

        if ic50_in_name:
            samplename += ' (IC50 = {0})'.format(self.ic50_str())

        return pandas.DataFrame.from_dict(collections.OrderedDict([
                ('concentration', concentrations),
                ('sample', [samplename] * n),
                ('points', points),
                ('fit', fit),
                ]))
def params(N, M, T, k, Tref, T_pk, B_g, B_rm, Ma, Ea, Ea_D):
    #Uptake
    u1 = np.zeros([M, M])  # M M
    u_temp = temp_growth(
        k, T, Tref, T_pk, N, B_g, Ma, Ea,
        Ea_D)  # uptake rates and maintenance are temp-dependant
    np.fill_diagonal(u1, u_temp)  # fill in temp dependant uptake on diagonals
    #np.fill_diagonal(u1,1) # fill in temp dependant uptake on diagonals
    u2 = np.zeros([M, M])
    np.fill_diagonal(
        u2, u_temp[M:M * 2])  # fill in temp dependant uptake on diagonals
    if N == M:
        U = u1
    else:
        U = np.concatenate((u1, u2), axis=0)

    # Maintenance Respiration
    ar_rm = temp_resp(
        k, T, Tref, T_pk, N, B_rm, Ma, Ea,
        Ea_D)  # find how varies with temperature (ar = arrhenius)
    #Rm = sc.full([N], (0.5))
    #Rm = np.array([0.4257905,0.4257905])
    Rm = ar_rm

    # Growth Respiration
    Rg = sc.full([M], (0))

    # Excretion
    l = np.zeros([M, M])
    for i in range(M - 1):
        l[i, i + 1] = 0.4
    l[M - 1, 0] = 0.4
    p = np.concatenate((np.array([1]), np.repeat(1, M - 1)))
    return U, Rm, Rg, l, p
def frequency_matrix_generator(detuning, lower, upper):
    """
    Create the frequency matrix for an atom with particular level splittings and a beam with a particular detuning.
    The (i, j)th element of the matrix represents the detuning of the i to j transition from the beam.
    The lower left of the matrix has negative frequencies for red detunings and positive frequencies for blue detunings.
    The upper right is the opposite.
    
    By default the target transition is the lowest ground state level to the lowest excited state level.
    The matrix elements corresponding to these transition will be zero for detuning=0.
    :param detuning: Float. The detuning of the beam from the target transition. Negative for red transitions, positive for blue.
    :param lower: List/Array.  Frequency splittings of the ground state. The first element is the splitting between the lowest two levels,
                  the second element is the splitting between the second and third lowest states...
    :param upper: List/Array. Same as lower except for the excited states.
    :return: Array. This array contains the frequencies that the Hamiltonian matrix elements will oscillate at.
    """
    detuning = -detuning
    nrows = len(lower) + 1
    ncols = len(upper) + 1
    intermediate = sp.full((nrows, ncols), detuning, dtype=float)
    for index_i in range(nrows):
        for index_j in range(ncols):
            intermediate[index_i,
                         index_j] = intermediate[index_i, index_j] - sum(
                             lower[0:index_i]) + sum(upper[0:index_j])
    temp1 = sp.hstack((sp.zeros((nrows, nrows)), intermediate))
    temp2 = sp.hstack((-intermediate.T, sp.zeros((ncols, ncols))))
    final = sp.vstack((temp1, temp2))
    return final
Example #9
0
    def blobs(shape, porosity, blobiness=8):
        """
        Generates an image containing amorphous blobs

        Parameters
        ----------
        shape : list
            The size of the image to generate in [Nx, Ny, Nz] where N is the
            number of voxels

        blobiness : scalar
            Controls the morphology of the image.  A higher number results in
            a larger number of smaller blobs.

        porosity : scalar
            The porosity of the final image.  This number is approximated by
            the method so the returned result may not have exactly the
            specified value.

        """
        if sp.size(shape) == 1:
            shape = sp.full((3, ), int(shape))
        [Nx, Ny, Nz] = shape
        sigma = sp.mean(shape)/(4*blobiness)
        mask = sp.rand(Nx, Ny, Nz)
        mask = spim.gaussian_filter(mask, sigma=sigma)
        hist = sp.histogram(mask, bins=1000)
        cdf = sp.cumsum(hist[0])/sp.size(mask)
        xN = sp.where(cdf >= porosity)[0][0]
        im = mask <= hist[1][xN]
        return im
Example #10
0
    def spheres(shape, radius, porosity):
        r"""
        Generate a packing of overlapping mono-disperse spheres

        Parameters
        ----------
        shape : list
            The size of the image to generate in [Nx, Ny, Nz] where N is the
            number of voxels.

        radius : scalar
            The radius of spheres in the packing

        porosity : scalar
            The porosity of the final image.  This number is approximated by
            the method so the returned result may not have exactly the
            specified value.

        Notes
        -----
        This method can also be used to generate a dispersion of hollows by
        treating ``porosity`` as solid volume fraction and inverting the
        returned image.
        """
        if sp.size(shape) == 1:
            shape = sp.full((3, ), int(shape))
        im = sp.zeros(shape, dtype=bool)
        while sp.sum(im)/sp.size(im) < (1 - porosity):
            temp = sp.rand(shape[0], shape[1], shape[2]) < 0.9995
            im = im + (spim.distance_transform_edt(temp) < radius)
        return ~im
Example #11
0
 def value(self, t, x, y):
     if self.evolving:
         index = int(scipy.floor(t / self.wind_dt))
         vx = self.speed[index] * scipy.cos(self.angle[index])
         vy = self.speed[index] * scipy.sin(self.angle[index])
     else:
         vx = self.speed * scipy.cos(self.angle)
         vy = self.speed * scipy.sin(self.angle)
     if type(x) == scipy.ndarray:
         if x.shape != y.shape:
             raise (ValueError, 'x.shape must equal y.shape')
         vx_array = scipy.full(x.shape, vx)
         vy_array = scipy.full(y.shape, vy)
         return vx_array, vy_array
     else:
         return vx, vy
Example #12
0
    def blobs(shape, porosity, blobiness=8):
        """
        Generates an image containing amorphous blobs

        Parameters
        ----------
        shape : list
            The size of the image to generate in [Nx, Ny, Nz] where N is the
            number of voxels

        blobiness : scalar
            Controls the morphology of the image.  A higher number results in
            a larger number of smaller blobs.

        porosity : scalar
            The porosity of the final image.  This number is approximated by
            the method so the returned result may not have exactly the
            specified value.

        """
        if sp.size(shape) == 1:
            shape = sp.full((3, ), int(shape))
        [Nx, Ny, Nz] = shape
        sigma = sp.mean(shape) / (4 * blobiness)
        mask = sp.rand(Nx, Ny, Nz)
        mask = spim.gaussian_filter(mask, sigma=sigma)
        hist = sp.histogram(mask, bins=1000)
        cdf = sp.cumsum(hist[0]) / sp.size(mask)
        xN = sp.where(cdf >= porosity)[0][0]
        im = mask <= hist[1][xN]
        return im
Example #13
0
    def spheres(shape, radius, porosity):
        r"""
        Generate a packing of overlapping mono-disperse spheres

        Parameters
        ----------
        shape : list
            The size of the image to generate in [Nx, Ny, Nz] where N is the
            number of voxels.

        radius : scalar
            The radius of spheres in the packing

        porosity : scalar
            The porosity of the final image.  This number is approximated by
            the method so the returned result may not have exactly the
            specified value.

        Notes
        -----
        This method can also be used to generate a dispersion of hollows by
        treating ``porosity`` as solid volume fraction and inverting the
        returned image.
        """
        if sp.size(shape) == 1:
            shape = sp.full((3, ), int(shape))
        im = sp.zeros(shape, dtype=bool)
        while sp.sum(im) / sp.size(im) < (1 - porosity):
            temp = sp.rand(shape[0], shape[1], shape[2]) < 0.9995
            im = im + (spim.distance_transform_edt(temp) < radius)
        return ~im
Example #14
0
def blobs(shape: List[int],
          porosity: float = 0.5,
          blobiness: int = 1,
          show_images: bool = False,
          random_seed: int = None):
    blobiness = sp.array(blobiness)
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((3, ), int(shape))
    sigma = sp.mean(shape) / (40 * blobiness)
    sp.random.seed(random_seed)
    im = sp.random.random(shape).astype(sp.float32)

    im = spim.gaussian_filter(im, sigma=sigma)

    show_image(im, show_images=show_images)

    im = norm_to_uniform(im, scale=[0, 1])

    show_image(im, show_images=show_images)

    if porosity:
        im = im < porosity
    show_image(im, show_images=show_images)

    return im
Example #15
0
def E_trip(W, A_prop, Cl_max, Cd_climb, S, phi, Cl_cruise, LD, Cd0, h_cruise, V_des, t=np.array([0]), E=np.array([0]), P_arr=np.array([0]), lab=np.array([]), trip='go'):
    '''
    Calculates total energy for round trip
    '''
    
    E, E_T,t,t_t, P_arr = E_to(W, A_prop, Cd0, t, E, P_arr, V_to=6, h_trans=20)
    lab = np.append(lab, np.full((1, len(E)-len(lab)),'takeoff'+trip))
    E, E_Cl,t,t_Cl, P_arr = E_climb(W, Cl_max, Cd_climb, S, phi, A_prop, t, E, P_arr, h_cruise, h_trans=20)
    lab = np.append(lab, np.full((1, len(E)-len(lab)),'climb'+trip))
    E, E_Cr,t,t_Cr, P_arr, s_glide = E_cruise(W, S, Cl_cruise, LD, phi, A_prop, t, E, P_arr, h_cruise, h_trans=20, r=75000)
    lab = np.append(lab, np.full((1, len(E)-len(lab)),'cruise'+trip))
    E, E_g,t,t_g, P_arr = E_gliding(s_glide, 17, t, E, P_arr)
    lab = np.append(lab, np.full((1, len(E)-len(lab)),'glide'+trip))
    E, E_L,t,t_L, P_arr = E_landing(W, A_prop, Cd0, V_des, t, E, P_arr, h_landing=20)
    lab = np.append(lab, np.full((1, len(E)-len(lab)),'landing'+trip))
    
    return E, t, P_arr, lab
Example #16
0
def rows_array2(my_m, n_iter):
    my_m = asmatrix(my_m)  # not strictly needed, but should be noop
    # the following is valid as long as we assume a fixed matrix size (and not in a general function)
    v1 = asmatrix(full((my_m.shape[1], 1), 1.0 / my_m.shape[1]))
    for i in xrange(n_iter):
        #v1 = asmatrix(full( (my_m.shape[1], 1), 1.0/my_m.shape[1]))
        m1 = my_m * v1  # row means
    m1[0] = 0  # just to avoid complaints
Example #17
0
def params(N, M, T, k, Tref, T_pk, B_g, B_rm, Ma, Ea_U, Ea_R, Ea_D):
    #Uptake
    u1 = np.zeros([M, M])  # M M
    #u_temp = temp_growth(k, T, Tref, T_pk, N, B_g, Ma, Ea_U, Ea_D) # uptake rates and maintenance are temp-dependant
    u_temp = np.array([10, 20, 30, 40, 50])
    np.fill_diagonal(u1, u_temp)  # fill in temp dependant uptake on diagonals
    #np.fill_diagonal(u1,1) # fill in temp dependant uptake on diagonals
    u2 = np.zeros([M, M])
    u3 = np.zeros([M, M])
    u4 = np.zeros([M, M])
    u5 = np.zeros([M, M])
    if N == M:
        U = u1
    elif M == N / 2:
        np.fill_diagonal(
            u2, u_temp[M:M * 2])  # fill in temp dependant uptake on diagonals
        U = np.concatenate((u1, u2), axis=0)
    elif M == N / 3:
        np.fill_diagonal(
            u2, u_temp[M:M * 2])  # fill in temp dependant uptake on diagonals
        np.fill_diagonal(u3, u_temp[M + 1:M * 3])
        U = np.concatenate((u1, u2, u3), axis=0)
    elif M == N / 4:
        np.fill_diagonal(
            u2, u_temp[M:M * 2])  # fill in temp dependant uptake on diagonals
        np.fill_diagonal(u3, u_temp[M + 1:M * 3])
        np.fill_diagonal(u4, u_temp[M + 2:M * 4])
        U = np.concatenate((u1, u2, u3, u4), axis=0)
    else:
        np.fill_diagonal(
            u2, u_temp[M:M * 2])  # fill in temp dependant uptake on diagonals
        np.fill_diagonal(u3, u_temp[M + 1:M * 3])
        np.fill_diagonal(u4, u_temp[M + 2:M * 4])
        np.fill_diagonal(u5, u_temp[M + 3:M * 5])
        U = np.concatenate((u1, u2, u3, u4, u5), axis=0)

    # Maintenance respiration
    ar_rm = temp_resp(
        k, T, Tref, T_pk, N, B_rm, Ma, Ea_R,
        Ea_D)  # find how varies with temperature (ar = arrhenius)
    #Rm = sc.full([N], (0.5))
    #Rm = ar_rm
    Rm = np.array([1.1, 2])  #np.array([1.1, 2, 3.2, 4, 5])

    # Growth respiration
    Rg = sc.full([M], (0))

    # Excretion
    l = np.zeros([M, M])
    for i in range(M - 1):
        l[i, i + 1] = 0.4
    l[M - 1, 0] = 0.4

    # External resource input
    p = np.concatenate((np.array([1]), np.repeat(1, M - 1)))  #np.ones(M)

    return U, Rm, Rg, l, p
Example #18
0
def cylinders(shape: List[int],
              radius: int,
              nfibers: int,
              phi_max: float = 0,
              theta_max: float = 90):
    r"""
    Generates a binary image of overlapping cylinders.  This is a good
    approximation of a fibrous mat.

    Parameters
    ----------
    phi_max : scalar
        A value between 0 and 90 that controls the amount that the fibers
        lie out of the XY plane, with 0 meaning all fibers lie in the XY
        plane, and 90 meaning that fibers are randomly oriented out of the
        plane by as much as +/- 90 degrees.

    theta_max : scalar
        A value between 0 and 90 that controls the amount rotation in the
        XY plane, with 0 meaning all fibers point in the X-direction, and
        90 meaning they are randomly rotated about the Z axis by as much
        as +/- 90 degrees.

    Returns
    -------
    image : ND-array
        A boolean array with ``True`` values denoting the pore space
    """
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((3, ), int(shape))
    elif sp.size(shape) == 2:
        raise Exception("2D fibers don't make sense")
    im = sp.zeros(shape)
    R = sp.sqrt(sp.sum(sp.square(shape)))
    n = 0
    while n < nfibers:
        x = sp.rand(3) * shape
        phi = sp.deg2rad(90 + 90 * (0.5 - sp.rand()) * phi_max / 90)
        theta = sp.deg2rad(180 - 90 * (0.5 - sp.rand()) * 2 * theta_max / 90)
        X0 = R * sp.array([
            sp.sin(theta) * sp.cos(phi),
            sp.sin(theta) * sp.sin(phi),
            sp.cos(theta)
        ])
        [X0, X1] = [X0 + x, -X0 + x]
        crds = line_segment(X0, X1)
        lower = ~sp.any(sp.vstack(crds).T < [0, 0, 0], axis=1)
        upper = ~sp.any(sp.vstack(crds).T >= shape, axis=1)
        valid = upper * lower
        if sp.any(valid):
            im[crds[0][valid], crds[1][valid], crds[2][valid]] = 1
            n += 1
    im = sp.array(im, dtype=bool)
    dt = spim.distance_transform_edt(~im) < radius
    return ~dt
Example #19
0
def polydisperse_spheres(shape: List[int],
                         porosity: float,
                         dist,
                         nbins: int = 5,
                         r_min: int = 5):
    r"""
    Create an image of randomly place, overlapping spheres with a distribution
    of radii.

    Parameters
    ----------
    shape : list
        The size of the image to generate in [Nx, Ny, Nz] where Ni is the
        number of voxels in each direction.  If shape is only 2D, then an
        image of polydisperse disks is returns

    porosity : scalar
        The porosity of the image, defined as the number of void voxels
        divided by the number of voxels in the image. The specified value
        is only matched approximately, so it's suggested to check this value
        after the image is generated.

    dist : scipy.stats distribution object
        This should be an initialized distribution chosen from the large number
        of options in the ``scipy.stats`` submodule.  For instance, a normal
        distribution with a mean of 20 and a standard deviation of 10 can be
        obtained with ``dist = scipy.stats.norm(loc=20, scale=10)``

    nbins : scalar
        The number of discrete sphere sizes that will be used to generate the
        image.  This function generates  ``nbins`` images of monodisperse
        spheres that span 0.05 and 0.95 of the possible values produced by the
        provided distribution, then overlays them to get polydispersivity.

    Returns
    -------
    image : ND-array
        A boolean array with ``True`` values denoting the pore space
    """
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((3, ), int(shape))
    Rs = dist.interval(sp.linspace(0.05, 0.95, nbins))
    Rs = sp.vstack(Rs).T
    Rs = (Rs[:-1] + Rs[1:]) / 2
    Rs = sp.clip(Rs.flatten(), a_min=r_min, a_max=None)
    phi_desired = 1 - (1 - porosity) / (len(Rs))
    im = sp.ones(shape, dtype=bool)
    for r in Rs:
        phi_im = im.sum() / sp.prod(shape)
        phi_corrected = 1 - (1 - phi_desired) / phi_im
        temp = overlapping_spheres(shape=shape,
                                   radius=r,
                                   porosity=phi_corrected)
        im = im * temp
    return im
Example #20
0
def cols_array2(my_m, n_iter):
    my_m = asmatrix(my_m)  # not strictly needed, but should be noop
    # the following is valid as long as we assume a fixed matrix size (and not in a general function)
    #v1 = asmatrix(full( (1, my_m.shape[0]), 1.0/my_m.shape[0]))
    v1 = full((1, my_m.shape[0]), 1.0 / my_m.shape[0])
    for i in xrange(n_iter):
        #v1 = asmatrix(full( (1, my_m.shape[0]), 1.0/my_m.shape[0]))
        #m1 = v1 * my_m
        m1 = np.dot(v1, my_m)
    m1[0] = 0  # just to avoid complaints
Example #21
0
	def get_chisq(self, pops, writeback=False):
		"""Extends the base MSExperiment class to overwrite the PopFits attribute on the first call"""

		if not self.initialized:
			self.PopIntens = scipy.absolute(scipy.random.normal(pops,self.sigma))
			self.PopSigmas = scipy.full(self.PopIntens.shape,self.sigma**2)
			self.PopFits = scipy.zeros(self.PopIntens.shape)
			self.npoints, self.npops = self.PopIntens.shape
			self.npoints = self.npoints*self.npops
			self.initialized = True

		return MSExperiment.get_chisq(self, pops, writeback)
    def update_for_odor_loss(self, t, dt, odor, wind_uvecs, masks):
        """
         Update simulation for flies which lose odor or have lost odor and are
         casting.
         * Find flies in FlyUpWind mode where the odor value <= lower threshold.
         * Test if they lose odor (roll dice and compare with probabilty).
         * If they lose odor change mode to CastForOdor.
         * Update velocties for flies in CastForOdor mode.
        """

        x_wind_unit = wind_uvecs['x']
        y_wind_unit = wind_uvecs['y']
        mask_flyupwd = masks['flyupwd']
        mask_castfor = masks['castfor']

        mask_lt_lower = odor <= self.param['odor_thresholds']['lower']
        mask_candidates = mask_lt_lower & mask_flyupwd
        dice_roll = scipy.full((self.size, ), scipy.inf)
        dice_roll[mask_candidates] = scipy.rand(mask_candidates.sum())

        # Convert probabilty/sec to probabilty for time step interval dt
        odor_probability_lower = 1.0 - (
            1.0 - self.param['odor_probabilities']['lower'])**dt
        mask_change = dice_roll < odor_probability_lower
        self.mode[mask_change] = self.Mode_CastForOdor

        # Lump together flies changing to CastForOdor mode with casting flies which are
        # changing direction (e.g. time to make cast direction change)
        mask_change |= mask_castfor & (t >
                                       (self.t_last_cast + self.dt_next_cast))

        # Computer new heading errors for flies which change mode
        self.heading_error[mask_change] = self.param[
            'heading_error_std'] * scipy.randn(mask_change.sum())

        # Set new cast intervals and directions for flies chaning to CastForOdor or starting a new cast
        cast_interval = self.param['cast_interval']
        self.dt_next_cast[mask_change] = scipy.random.uniform(
            cast_interval[0], cast_interval[0], (mask_change.sum(), ))
        self.t_last_cast[mask_change] = t
        self.cast_sign[mask_change] = scipy.random.choice(
            [-1, 1], (mask_change.sum(), ))

        # Set x and y velocities for new CastForOdor flies
        x_unit_change, y_unit_change = rotate_vecs(
            x_wind_unit[mask_change], -y_wind_unit[mask_change],
            self.heading_error[mask_change])
        speed = self.param['flight_speed'][mask_change]
        self.x_velocity[
            mask_change] = self.cast_sign[mask_change] * speed * x_unit_change
        self.y_velocity[
            mask_change] = self.cast_sign[mask_change] * speed * y_unit_change
Example #23
0
def sorted_parameters(args,
                      return_sort=False,
                      keys=[
                          'qpar', 'qper', 'qiso', 'eps', 'f', 'b1', 'b2', 'A',
                          'sigmav', 'sigma8'
                      ]):
    indices = scipy.full(len(args), scipy.inf)
    for iarg, arg in enumerate(args):
        for ipar, par in enumerate(keys):
            if par in arg: indices[iarg] = ipar
    sort = scipy.argsort(indices)
    if return_sort: return scipy.array(args)[sort], sort
    return scipy.array(args)[sort].tolist()
Example #24
0
    def get_chisq(self, pops, writeback=False):
        """Extends the base MSExperiment class to overwrite the PopFits attribute on the first call"""

        if not self.initialized:
            self.PopIntens = scipy.absolute(
                scipy.random.normal(pops, self.sigma))
            self.PopSigmas = scipy.full(self.PopIntens.shape, self.sigma**2)
            self.PopFits = scipy.zeros(self.PopIntens.shape)
            self.npoints, self.npops = self.PopIntens.shape
            self.npoints = self.npoints * self.npops
            self.initialized = True

        return MSExperiment.get_chisq(self, pops, writeback)
Example #25
0
def blobs(shape,
          k,
          porosity: float = 0.5,
          blobiness: int = 1,
          show_figs: bool = False):

    blobiness = sp.array(blobiness)
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((3, ), int(shape))
    sigma = sp.mean(shape) / (40 * blobiness)
    sigma = sp.array(k) * sigma
    im = sp.random.random(shape)

    im = spim.gaussian_filter(im, sigma=sigma)

    im = norm_to_uniform(im, scale=[0, 1])
    im_test, _ = image_histogram_equalization(im)
    im_test -= np.min(im_test)
    im_test *= 1.0 / np.max(im_test)

    im_test_opencv = opencv_histogram_equalization(im)
    im_test_opencv -= np.min(im_test_opencv)
    im_test_opencv = im_test_opencv / np.max(im_test_opencv)

    im_test_clahe = opencv_clahe_hist_equal(im)
    im_test_clahe -= np.min(im_test_clahe)
    im_test_clahe = im_test_clahe / np.max(im_test_clahe)

    if porosity:
        im = im < porosity
        im_test = im_test < porosity
        im_test_opencv = im_test_opencv < porosity
        im_test_clahe = im_test_clahe < porosity

    print(np.sum(im) / im.ravel().shape[0])
    print(np.sum(im_test) / im_test.ravel().shape[0])
    print(np.sum(im_test_opencv) / im_test_opencv.ravel().shape[0])
    print(np.sum(im_test_clahe) / im_test_clahe.ravel().shape[0])

    if show_figs:
        show_image_and_histogram(im, 'Porespy norm2uniform')
        show_image_and_histogram(im_test, 'numpy hist eq')
        show_image_and_histogram(im_test_opencv, 'opencv hist eq')
        show_image_and_histogram(im_test_clahe, 'opencv clahe hist eq')

    if show_figs:
        plt.show()

    return im
Example #26
0
def bundle_of_tubes(shape: List[int], spacing: int):
    r"""
    Create a 3D image of a bundle of tubes, in the form of a rectangular
    plate with randomly sized holes through it.

    Parameters
    ----------
    shape : list
        The size the image, with the 3rd dimension indicating the plate
        thickness.  If the 3rd dimension is not given then a thickness of
        1 voxel is assumed.

    spacing : scalar
        The center to center distance of the holes.  The hole sizes will be
        randomly distributed between this values down to 3 voxels.

    Returns
    -------
    image : ND-array
        A boolean array with ``True`` values denoting the pore space
    """
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((3, ), int(shape))
    if sp.size(shape) == 2:
        shape = sp.hstack((shape, [1]))
    temp = sp.zeros(shape=shape[:2])
    Xi = sp.ceil(sp.linspace(spacing/2,
                             shape[0]-(spacing/2)-1,
                             int(shape[0]/spacing)))
    Xi = sp.array(Xi, dtype=int)
    Yi = sp.ceil(sp.linspace(spacing/2,
                             shape[1]-(spacing/2)-1,
                             int(shape[1]/spacing)))
    Yi = sp.array(Yi, dtype=int)
    temp[tuple(sp.meshgrid(Xi, Yi))] = 1
    inds = sp.where(temp)
    for i in range(len(inds[0])):
        r = sp.random.randint(1, (spacing/2))
        try:
            s1 = slice(inds[0][i]-r, inds[0][i]+r+1)
            s2 = slice(inds[1][i]-r, inds[1][i]+r+1)
            temp[s1, s2] = ps_disk(r)
        except ValueError:
            odd_shape = sp.shape(temp[s1, s2])
            temp[s1, s2] = ps_disk(r)[:odd_shape[0], :odd_shape[1]]
    im = sp.broadcast_to(array=sp.atleast_3d(temp), shape=shape)
    return im
Example #27
0
def circle_pack(shape, radius, offset=0, packing='square'):
    r"""
    Generates a 2D packing of circles

    Parameters
    ----------
    shape : list
        The size of the image to generate in [Nx, Ny] where N is the
        number of voxels in each direction

    radius : scalar
        The radius of circles in the packing (in pixels)

    offset : scalar
        The amount offset (+ or -) to add between pore centers (in pixels).

    packing : string
        Specifies the type of cubic packing to create.  Options are
        'square' (default) and 'triangular'.

    Returns
    -------
    A boolean array with True values denoting the pore space
    """
    r = radius
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((2, ), int(shape))
    elif (sp.size(shape) == 3) or (1 in shape):
        raise Exception("This function only produces 2D images, " +
                        "try \'sphere_pack\'")
    im = sp.zeros(shape, dtype=bool)
    if packing.startswith('s'):
        spacing = 2 * r
        s = int(spacing / 2) + sp.array(offset)
        coords = sp.mgrid[r:im.shape[0] - r:2 * s, r:im.shape[1] - r:2 * s]
        im[coords[0], coords[1]] = 1
    if packing.startswith('t'):
        spacing = 2 * sp.floor(sp.sqrt(2 * (r**2))).astype(int)
        s = int(spacing / 2) + offset
        coords = sp.mgrid[r:im.shape[0] - r:2 * s, r:im.shape[1] - r:2 * s]
        im[coords[0], coords[1]] = 1
        coords = sp.mgrid[s + r:im.shape[0] - r:2 * s,
                          s + r:im.shape[1] - r:2 * s]
        im[coords[0], coords[1]] = 1
    im = spim.distance_transform_edt(~im) >= r
    return im
Example #28
0
def blobs(shape: List[int], porosity: float = 0.5, blobiness: int = 1):
    """
    Generates an image containing amorphous blobs

    Parameters
    ----------
    shape : list
        The size of the image to generate in [Nx, Ny, Nz] where N is the
        number of voxels

    porosity : float
        If specified, this will threshold the image to the specified value
        prior to returning.  If no value is given (the default), then the
        scalar noise field is returned.

    blobiness : array_like (default = 1)
        Controls the morphology of the blobs.  A higher number results in
        a larger number of small blobs.  If a vector is supplied then the blobs
        are anisotropic.

    Returns
    -------
    If porosity is given, then a boolean array with ``True`` values denoting
    the pore space is returned.  If not, then normally distributed and
    spatially correlated randomly noise is returned.

    See Also
    --------
    norm_to_uniform

    """
    blobiness = sp.array(blobiness)
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((3, ), int(shape))
    sigma = sp.mean(shape) / (40 * blobiness)
    im = sp.random.random(shape)
    im = spim.gaussian_filter(im, sigma=sigma)
    if porosity:
        im = norm_to_uniform(im, scale=[0, 1])
        im = im < porosity
    return im
Example #29
0
def blobs(shape: List[int], porosity: float = 0.5, blobiness: int = 1):
    """
    Generates an image containing amorphous blobs

    Parameters
    ----------
    shape : list
        The size of the image to generate in [Nx, Ny, Nz] where N is the
        number of voxels

    porosity : float
        If specified, this will threshold the image to the specified value
        prior to returning.  If ``None`` is specified, then the scalar noise
        field is converted to a uniform distribution and returned without
        thresholding.

    blobiness : int or list of ints(default = 1)
        Controls the morphology of the blobs.  A higher number results in
        a larger number of small blobs.  If a list is supplied then the blobs
        are anisotropic.

    Returns
    -------
    image : ND-array
        A boolean array with ``True`` values denoting the pore space

    See Also
    --------
    norm_to_uniform

    """
    blobiness = sp.array(blobiness)
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((3, ), int(shape))
    sigma = sp.mean(shape)/(40*blobiness)
    im = sp.random.random(shape)
    im = spim.gaussian_filter(im, sigma=sigma)
    im = norm_to_uniform(im, scale=[0, 1])
    if porosity:
        im = im < porosity
    return im
Example #30
0
def frequency_matrix_generator(detuning, lower, upper):
    """

    :param detuning:
    :param lower:
    :param upper:
    :return:
    """
    nrows = len(lower) + 1
    ncols = len(upper) + 1
    intermediate = sp.full((nrows, ncols), detuning, dtype=float)
    for index_i in range(nrows):
        for index_j in range(ncols):
            print(sum(lower[0:index_i]) / 1e6, sum(upper[0:index_j]) / 1e6)
            intermediate[index_i, index_j] = intermediate[index_i, index_j] - sum(lower[0:index_i]) + sum(upper[0:index_j])
    temp1 = sp.hstack((sp.zeros((nrows, nrows + 1)), intermediate))
    temp2 = sp.vstack((temp1, sp.zeros((1, nrows + ncols + 1))))
    temp3 = sp.hstack((-intermediate.T, sp.zeros((ncols, ncols + 1))))
    final = sp.vstack((temp2, temp3))
    return final
Example #31
0
def overlapping_spheres(shape: List[int], radius: int, porosity: float):
    r"""
    Generate a packing of overlapping mono-disperse spheres

    Parameters
    ----------
    shape : list
        The size of the image to generate in [Nx, Ny, Nz] where Ni is the
        number of voxels in the i-th direction.

    radius : scalar
        The radius of spheres in the packing.

    porosity : scalar
        The porosity of the final image.  This number is approximated by
        the method so the returned result may not have exactly the
        specified value.

    Returns
    -------
    image : ND-array
        A boolean array with ``True`` values denoting the pore space

    Notes
    -----
    This method can also be used to generate a dispersion of hollows by
    treating ``porosity`` as solid volume fraction and inverting the
    returned image.
    """
    shape = sp.array(shape)
    if sp.size(shape) == 1:
        shape = sp.full((3, ), int(shape))
    if sp.size(shape) == 2:
        s_vol = sp.sum(disk(radius))
    if sp.size(shape) == 3:
        s_vol = sp.sum(ball(radius))
    bulk_vol = sp.prod(shape)
    N = int(sp.ceil((1 - porosity) * bulk_vol / s_vol))
    im = sp.random.random(size=shape) > (N / bulk_vol)
    im = spim.distance_transform_edt(im) < radius
    return ~im
def solve(X, y, w, m, b0=None, lambd=30, check=False):
    def f(b, *args):
        yhat = sp.exp(X @ b)
        return .5 * w @ (y - yhat)**2 + lambd * m @ sp.fabs(b)

    def grad(b, *args):
        yhat = sp.exp(X @ b)
        # Fun fact: if you do `X.T @ v` here instead of `v @ X`, it's x10 slower
        return -(yhat * w * (y - yhat)) @ X + lambd * m * sp.sign(b)

    i = 0

    def callback(b):
        nonlocal i
        i = i + 1
        log.info(f'Step {i}: loss is {f(b):.1f}')

    #TODO: My instinct is that this should this be constant in l2 norm rather than l1?
    b0 = sp.full(len(m), 1e-3 / len(m)) if b0 is None else b0

    if check:
        check_grad(f, grad, b0)

    #TODO: Evaluating the full hessian is infeasible, but is there any way we could generate the `hessp` arg?
    #TODO: Why does the original use BFGS-B rather than BFGS? There are no constraints here
    #TODO: Oh lord this is slow. Can we parallelize it anyhow?
    # I actually don't know any parallel quasi-Newton methods, worth reading up on.
    # Expect this to take ~100 odd iterations to converge on the 'good' stars.
    result = sp.optimize.minimize(f,
                                  b0,
                                  method='BFGS',
                                  jac=grad,
                                  callback=callback,
                                  options={
                                      'disp': True,
                                      'maxiter': 1000
                                  })
    assert result.success, 'Optimizer failed'

    bstar = result.x
    return bstar
Example #33
0
def artificial_basis_method(A, b, c, eps):
    count_vars = A.shape[1]
    addition_vars = A.shape[0]
    count_all_vars = count_vars + addition_vars
    _A = sc.resize(A, (A.shape[0], count_all_vars))
    _A[:, :count_vars] = A
    _A[:, count_vars:] = sc.eye(addition_vars)
    _c = sc.resize(c, (count_all_vars, 1))
    _c[:count_vars, :] = sc.zeros((count_vars, 1))
    _c[count_vars:, :] = sc.full((addition_vars, 1), -1)
    # if I is None:
    I = range(count_vars, count_vars+addition_vars)
    # pprint.pprint((_A, b, _c ,I))
    Res = simplex_method(_A, b, _c, I, eps)
    if Res[2] < -eps:
        return None, None, None
    Real_I = [i for i in range(count_vars) if i not in Res[1]]

    for i in range(len(Res[1])):
        if Res[1][i] >= count_vars:
            Res[1][i] = Real_I.pop(0)

    return Res
    def update_for_odor_detection(self, dt, odor, wind_uvecs, masks):
        """
         Update simulation for odor detection
         * Find flies in StartMode and CastForOdor modes where the odor value >= upper threshold.
         * Test if they detect odor (roll dice and compare with dection probabilty).
         * If they do detect odor change their  mode to FlyUpWind.
         * set x and y velocities to upwind at speed
        """
        x_wind_unit = wind_uvecs['x']
        y_wind_unit = wind_uvecs['y']
        mask_startmode = masks['startmode']
        mask_castfor = masks['castfor']

        mask_gt_upper = odor >= self.param['odor_thresholds']['upper']
        mask_candidates = mask_gt_upper & (mask_startmode | mask_castfor)
        dice_roll = scipy.full((self.size, ), scipy.inf)
        dice_roll[mask_candidates] = scipy.rand(mask_candidates.sum())

        # Convert probabilty/sec to probabilty for time step interval dt
        odor_probability_upper = 1.0 - (
            1.0 - self.param['odor_probabilities']['upper'])**dt
        mask_change = dice_roll < odor_probability_upper
        self.mode[mask_change] = self.Mode_FlyUpWind

        # Compute new heading error for flies which change mode
        heading_error_std = self.param['heading_error_std']
        self.heading_error[mask_change] = heading_error_std * scipy.randn(
            mask_change.sum())

        # Set x and y velocities for the flies which just changed to FlyUpWind.
        x_unit_change, y_unit_change = rotate_vecs(
            x_wind_unit[mask_change], y_wind_unit[mask_change],
            self.heading_error[mask_change])
        speed = self.param['flight_speed'][mask_change]
        self.x_velocity[mask_change] = -speed * x_unit_change
        self.y_velocity[mask_change] = -speed * y_unit_change
Example #35
0
    def SetInitialConditions(self):
        #basic stuff, evenntuallt allow this to be modofied
        self.T0=25
        self.dx=0.05    #in mm default 50 microns
        self.zy=0.05
        self.dz=0.05    #in mm default 50 microns
        self.Lx=3.5*25.4
        self.Ly=3.5*25.4
        self.Lz=120*self.dx
        self.nx=int(self.Lx/self.dx)
        self.ny=int(self.Ly/self.dy)
        self.nz=int(self.Lz/self.dz)

        #create the array for temps, note old and new values alternate each step initializ at 25C
        self.T = sp.full([2,self.nz,self.ny,self.nx],self.T0)

        #set material matrix


        #use this to create the basic property matrices
        self.Material=sp.zeros_like(self.T[0,:,:,:],dtype=sp.bool_)
        self.Coeffs=sp.zeros([5,self.nz,self.ny,self.nx])
        self.k=sp.zeros([3,self.nz,self.ny,self.nx])
        #UpdateCoeffs


        #initiallized coefficient matrices




        #expelicit, we will generaly use the fastest time available initially
        self.dt=1  #seconds

        #material Properties for PA12 SHC=1.2     density=1.01 mg/mm3 Volume fraction ~15.2%
        # for Carbon SHC=072  denisty=1.79  volume fraction ~3.8%




        self.kx=[7.6,7.65]*1000     #x direction diffusiom in J/(mmks) [no poly, poly]
        self.kz=[.2,.3]*1000    #zz direction diffusion in J/(mmks) [no poly,poly]
        self.crho=[015,195]  #heat capacity [graphite,poly] J/(Kmm3)


        self.UpdateCoefficients()







        #self.a=0.5
        self.q=0

        #CHECK UNITS

        self.nt=500

        #precalculate some things
        self.dx2=self.dx*self.dx
        self.dz2=self.dz*self.dz
        self.dt=self.crho[0]*self.dx2*self.dz2/(2*(self.kx[0]*self.dz2+self.kz[0]*self.dx2))/2
# Start u and ui off as zero matrices:
        self.T = sp.full([2,self.nz,self.nx],25)  #old and new values for T switch each step
        self.Coeffs=sp.full([5,self.nz,self.nx],1/self.crho[0])  #this array holds the coeffs for each volume initiall just graphite
        #polymer block is cube 20x20 in side
        self.Coeffs[0,6:116,100:800]=1/self.crho[1]

        self.newVals=0      #this holds the values for the current step
        self.u=sp.zeros([self.nx,self.nz])
        self.ui=sp.zeros([self.nx,self.nz])
Example #36
0
imputer = preprocessing.Imputer(missing_values="NaN", strategy="mean", axis=0)
imputer.fit(d_x)
scaler.fit(imputer.transform(d_x))
d_x_scaled = scaler.transform(imputer.transform(d_x))

print "Data scaled and imputed"

clf = svm.SVC()
clf.fit(d_x_scaled, d_y)

print "SVM fit"

xx, yy = np.meshgrid(np.linspace(0.5, 1.0, 200),
            np.linspace(0.5, 1.0, 200))

zz = scipy.full(xx.shape, 0.0)

Z_pre = clf.decision_function(scaler.transform(np.c_[xx.ravel(), yy.ravel(), zz.ravel()]))

print "Decision function calculated. Plotting..."

Z = Z_pre.reshape(xx.shape)

# To show in imshow below, just take an example slice through the middle of the correlation axis
# ::UPDATE:: Now we're just generating Z_pre as a slice through corr axis, set using the scipy.full call up there.
Z_show = Z

plt.imshow(Z_show, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto', origin='lower', cmap=plt.cm.PuOr_r)
contours = plt.contour(xx, yy, Z_show, levels=[0], linewidths=2, linetypes='--')

Example #37
0
ref = '196750'  #'100307'
print(ref + '.reduce' + str(r_factor) + '.LR_mask.mat')
fn1 = ref + '.reduce' + str(r_factor) + '.LR_mask.mat'
fname1 = os.path.join(ref_dir, fn1)
msk = scipy.io.loadmat(fname1)  # h5py.File(fname1);
dfs_left = readdfs(
    os.path.join(p_dir_ref, 'reference', ref + '.aparc\
.a2009s.32k_fs.reduce3.left.dfs'))
dfs_left_sm = readdfs(
    os.path.join(p_dir_ref, 'reference', ref + '.aparc\
.a2009s.32k_fs.reduce3.very_smooth.left.dfs'))

ind_subsample = sp.arange(start=0, stop=dfs_left.labels.shape[0], step=1)
ind_rois_orig = sp.in1d(dfs_left.labels, [46, 3, 4, 28, 29, 68, 69, 70])
ind_rois = sp.full(ind_rois_orig.shape[0], False, dtype=bool)
ind_rois = ind_rois_orig.copy()
ind_rois[ind_subsample] = True

surf1 = dfs_left_sm
X = surf1.vertices[:, 0]
Y = surf1.vertices[:, 1]
Z = surf1.vertices[:, 2]
NumTri = surf1.faces.shape[0]
#    NumVertx = X.shape[0]
vertx_1 = surf1.faces[:, 0]
vertx_2 = surf1.faces[:, 1]
vertx_3 = surf1.faces[:, 2]
V1 = np.column_stack((X[vertx_1], Y[vertx_1], Z[vertx_1]))
V2 = np.column_stack((X[vertx_2], Y[vertx_2], Z[vertx_2]))
V3 = np.column_stack((X[vertx_3], Y[vertx_3], Z[vertx_3]))
Example #38
0
	def __init__(self, path, T=298.15, sigma=0.05, title=None, lattice_name="Lattice", ligand_name="Ligand"):
		"""Constructor for the MSExperiment object.

		Arguments
		---------
		path : string
			A path to a file containing experimental populations in the format "[Lattice] [Ligand] [population state 0] [population state 1]..."
		T : float
			An uncertainty in the measured population state abundances (default is 5%).
		sigma : float
			An uncertainty in the measured population state abundances (default is 5%). If None, read uncertainties from the experimental file.
		title : string
			A descriptive title for the experiment (default is the trimmed filename).
		"""
		
		assert os.path.isfile(path)

		# relevant file parameters. TODO: replace using getattr with defaults?
		keypairs = {
			"Lattice":lattice_name,
			"Ligand":ligand_name,
			"Temperature":T,
			"Error":sigma,
			"Title":title,
		}

		# dummy vars to execute the ITCExperimentBase base class constructor.
		V0, injections, dQ = 1.0, [1.0], [1.0]
		Cell, Syringe = {keypairs['Lattice']:1.0},{keypairs['Ligand']:1.0}
		ITCExperimentBase.__init__(self, keypairs['Temperature'], V0, injections, dQ, Cell, Syringe)

		# reset relevant attributes
		self.path = path
		self.Concentrations = []
		self.npops, self.npoints = None, 0

		data = []
		with open(path) as fh:
			for i, line in enumerate(fh):

				# ignore empty and comment lines
				if line.strip() == "":
					continue
				elif line[0] in _FILE_COMMENT: # comment
					if line[1] in _FILE_KEYPAIR: # convert "#@" to "@" to play nice with some plotting scripts
						line = line[1:]
					else:
						continue

				if line[0] in _FILE_KEYPAIR: # set a variable
					tmp = line.split()
					try:
						assert len(tmp) > 2
					except AssertionError:
						raise Exception("Found malformed experiment parameter specification at line %i, should be of the form \"@param = value\""%(i+1))

					try:
						assert tmp[0][1:] in keypairs
					except AssertionError:
						raise Exception("Found unknown parameter specification \"%s\" at line %i."%(tmp[0][1:],i+1))
					
					try:
						if type(keypairs[tmp[0][1:]]) is str or keypairs[tmp[0][1:]] is None: # title
							keypairs[tmp[0][1:]] = " ".join(tmp[2:])
						else:
							keypairs[tmp[0][1:]] = float(tmp[2])
					except ValueError:
						raise Exception("Found malformed parameter value (could not convert \"%s\" to float) at line %i"%(tmp[2],i+1))
					continue

				arr = line.split()
				if len(arr) < 3:
					raise Exception("Found malformed titration point (less than three columns) at line %i"%(i+1))		
				elif self.npops == None:
					self.npops = len(arr) -2
				elif self.npops != len(arr) -2:
					raise Exception("Found malformed titration point (inconsistent number of columns) at line %i"%(i+1))
				
				try:
					tmp = map(float,arr)
				except ValueError:
					raise Exception("Found malformed titration point (could not convert column values to floats) at line %i"%(i+1))

				data.extend(tmp[2:]) # strip the lattice/ligand concentration columns

				self.Concentrations.append({})
				self.Concentrations[-1][keypairs['Lattice']] = tmp[0]
				self.Concentrations[-1][keypairs['Ligand']] = tmp[1]

				self.npoints += self.npops

		if keypairs['Title'] is None:
			self.title = os.path.splitext(os.path.basename(self.path))[0]
		else:
			self.title = keypairs['Title']
		
		self.lattice_name, self.ligand_name = keypairs['Lattice'], keypairs['Ligand']

		if keypairs['Error'] is None:
			try:
				assert self.npoints % 2 == 0
				assert min(data[self.npoints/2:]) > 0.0
			except AssertionError:
				raise Exception("If sigma == None, must provide nonzero experimental uncertainties in the experimental file.")
				
			self.npoints /= 2 # first half of points matrix are experimental values, second half are uncertainties
			self.Concentrations = self.Concentrations[:self.npoints] # discard the duplicated concentration columns for sigmas
			self.PopIntens = scipy.array(data[:self.npoints]).reshape((self.npoints/self.npops,self.npops))
			self.PopSigmas = scipy.array(data[self.npoints:]).reshape((self.npoints/self.npops,self.npops))
		else:
			self.sigma = keypairs['Error']
			self.PopIntens = scipy.array(data).reshape((self.npoints/self.npops,self.npops))
			self.PopSigmas = scipy.full(self.PopIntens.shape,self.sigma)

		# normalize intensities to 1, accordingly scale their sigmas
		totals = self.PopIntens.sum(axis=1,keepdims=True)
		self.PopIntens /= totals
		self.PopSigmas /= totals

		# precompute variance (s**2) from sigmas
		self.PopSigmas = scipy.square(self.PopSigmas)
		self.sigma = scipy.sqrt(scipy.mean(self.PopSigmas))

		self.PopFits = scipy.zeros(self.PopIntens.shape)

		self.chisq = None
		self.initialized = True