Example #1
0
def voronoi(network, geometry, offset, **kwargs):
    r"""
    Offset the throat vertices effectively erroding the facet by the offset distance supplied
    """
    Nt = geometry.num_throats()
    area = sp.ndarray(Nt)
    perimeter = sp.ndarray(Nt)
    offset_verts = sp.ndarray(Nt, dtype=object)
    offset_error = sp.ndarray(Nt)
    throat_COM = sp.ndarray([Nt, 3])
    for i in range(Nt):
        offset_rand = (sp.random.rand(1) - 0.5) * offset
        throat_verts = geometry["throat.vertices"][i]
        throat_normal = geometry["throat.normal"][i]
        area[i], perimeter[i], offset_verts[i], throat_COM[i], offset_error[
            i] = vo.get_throat_geom(throat_verts, throat_normal, offset)

    for i in range(Nt):
        if offset_error[i] > 0 and len(offset_verts[i]) > 0:
            offset_verts[i] = []
    "Properties that depend on the offset vertices are the area, perimeter and the centroid or COM"
    "To speed things up we could save them all now rather than processing them individually"
    if kwargs["set_dependent"] == True:
        geometry["throat.area"] = area
        geometry["throat.perimeter"] = perimeter
        geometry["throat.centroid"] = throat_COM

    return offset_verts
def voronoi(network,
            geometry,
            offset,
              **kwargs):
    r"""
    Offset the throat vertices effectively erroding the facet by the offset distance supplied
    """    
    Nt = geometry.num_throats()
    area = sp.ndarray(Nt)
    perimeter = sp.ndarray(Nt)
    offset_verts = sp.ndarray(Nt,dtype=object)
    offset_error = sp.ndarray(Nt)
    throat_COM = sp.ndarray([Nt,3])
    for i in range(Nt):
        offset_rand = (sp.random.rand(1)-0.5)*offset            
        throat_verts=geometry["throat.vertices"][i]
        throat_normal=geometry["throat.normal"][i]
        area[i],perimeter[i],offset_verts[i],throat_COM[i],offset_error[i] = vo.get_throat_geom(throat_verts,throat_normal,offset)
    
    for i in range(Nt):
        if offset_error[i] > 0 and len(offset_verts[i]) > 0:
            offset_verts[i]=[]
    "Properties that depend on the offset vertices are the area, perimeter and the centroid or COM"
    "To speed things up we could save them all now rather than processing them individually"
    if kwargs["set_dependent"]==True:
        geometry["throat.area"]=area
        geometry["throat.perimeter"]=perimeter
        geometry["throat.centroid"]=throat_COM
    
    return offset_verts
Example #3
0
def gmres(A: sp.matrix, b: sp.matrix, x_0: sp.matrix=None):
    start = time.time() 

    m, n = A.shape
    r = b - A @ x_0
    r_0_norm = spla.norm(r)
    b_norm = spla.norm(b)
    H = sp.ndarray((1, 0))
    Q = r / spla.norm(r)
    Q.reshape((n, 1))
    k = 0

    while True:
        k += 1
        # print(H.shape)
        h = sp.ndarray((k, 1))
        j = k
        q_j = Q[:,j-1]
        z = A @ q_j
        for i in range(j):
            q_i = Q[:, i]
            h[i, 0] = (q_i.T @ z).item()
            # print(h)
            # print(q_i)
            z -= h[i, 0] * q_i 
        # h = sps.csc_matrix([h], shape=(len(h), 1))
        h_last = spla.norm(z)
        q_new = z / h_last
        # q_new.reshape((n, 1))
        # print(q_new.shape)
        
        H = sp.block([
            [H, h],
            [sp.zeros((1, H.shape[1])), h_last]
        ])

        e_1 = sp.zeros((k+1, 1)) # k+1 because it is multiplied by U_{k+1,k}^T
        e_1[0,0] = 1

        U, R = householder(H, True)
        y_j = spla.solve(R, r_0_norm * U.T @ e_1)
        # print(y_j)
        x_j = x_0 + Q @ y_j
        # print(x_j)
        # print(H)
        Q = sp.hstack([Q, q_new])
        r_j_norm = r_0_norm * sp.sqrt(1 - spla.norm(U.T @ e_1)**2)
        print(f'relative residual {k}:', r_j_norm / b_norm)

        if k > 1000:
            print('terminating from iteration limit')
            break 
        if r_j_norm / b_norm <= 10**-6:
            print('terminating from residual norm')
            break
    
    print('iterations:', k)
    print('time:', time.time() - start)
    print('x')
    print(x_j.min(), x_j.max())
Example #4
0
def make_error_figure():
  # make a figure showing the effect of control adjustment on RMS error of
  # oscillators with the incorrect frequency

  # get synthetic target data
  tFinal = _t_final_long
  omegaTarget = 2 * scipy.pi / _target_period
  dt = _target_dt
  
  (target_t, target_f) = simulateTarget(_target_dt, omegaTarget, tFinal=tFinal)
  targetN = int(1 + round(_t_final_short / _target_dt))
  
  # make test omegas
  frequencies = \
    [2**x / _target_period for x in scipy.linspace(-1, 1, _num_frequencies)]
  omegas = [2 * scipy.pi * f for f in frequencies]
  
  numOmegas = len(omegas)
  errUncontrol = scipy.ndarray((numOmegas,))
  errControl = scipy.ndarray((numOmegas,))
  
  ind = 0
  for omega in omegas:
    (fit_raw_t, fit_raw_f) = simulateTarget(_target_dt, omega, tFinal=tFinal)
    errUncontrol[ind] = rmsError(fit_raw_f, target_f)
    
    # get fit data with control
    (controlled_t, controlled_f, discarded_t, discarded_f, fit_t, fit_f) = \
      simulateFit(dt, dt, omega, target_t, target_f, tFinal=tFinal)
    errControl[ind] = rmsError(controlled_f, target_f)
    ind += 1
  
  plotErrors(frequencies, errUncontrol, errControl)
Example #5
0
def innerRoots(matrix):
    ris = diagRoots(matrix)
    global bb,eb,dims,wb,i,j 
    bb,eb,dims,wb,i,j = findBlocks0(matrix)
    for z in range(1,j):
        for t in range(0,j-z):
            rij = matrix[bb[t]:eb[t]+1,bb[t+z]:eb[t+z]+1]
            tempsum = summ(ris,dims[t],dims[t+z],t,z)
            if (dims[t]==1 and dims[z+t]==1):
                tnoto = rij - tempsum
                ris[bb[t]:eb[t]+1,bb[t+z]:eb[t+z]+1] = tnoto/(selectBlock(t,t,ris)+selectBlock(z+t,z+t,ris))

            elif (dims[t]==2 and dims[t+z]==1):
                tnoto = rij - tempsum
                ujj = selectBlock(z+t,z+t,ris)
                uii = selectBlock(t,t,ris)
                sysris = sp.ndarray((2,1))
                coeff = sp.array(uii)
                coeff[0,0] += ujj[0,0]
                coeff[1,1] += ujj[0,0]
                sysris = np.linalg.solve(coeff,tnoto)
                ris[bb[t]:eb[t]+1,bb[t+z]:eb[t+z]+1] = sysris

            elif (dims[t]==1 and dims[t+z]==2):
                tnoto = rij - tempsum
                ujj = selectBlock(z+t,z+t,ris)
                uii = selectBlock(t,t,ris)
                sysris = sp.ndarray((2,1))
                coeff = sp.zeros((2,2))
                coeff[0,0] = uii[0,0] + ujj[0,0]
                coeff[1,1] = uii[0,0] + ujj[1,1]
                coeff[0,1] = ujj[1,0]
                coeff[1,0] = ujj[0,1]
                sysris = np.linalg.solve(coeff,tnoto.transpose())
                print tempsum
                ris[bb[t]:eb[t]+1,bb[t+z]:eb[t+z]+1] = sysris.transpose()

            else:
                tnoto = rij - tempsum
                ujj = selectBlock(z+t,z+t,ris)
                uii = selectBlock(t,t,ris)
                coeff = sp.ndarray((4,4))
                coeff[0,0] = uii[0,0]+ujj[0,0]; coeff[0,1] = uii[0,1]; coeff[0,2] = ujj[1,0]; coeff[0,3] = 0
                coeff[1,0] = uii[1,0]; coeff[1,1] = uii[1,1]+ujj[0,0]; coeff[1,2] = 0; coeff[1,3] = ujj[1,0]
                coeff[2,0] = ujj[0,1]; coeff[2,1] = 0; coeff[2,2] = uii[0,0]+ujj[1,1]; coeff[2,3] = uii[0,1]
                coeff[3,0] = 0; coeff[3,1] = ujj[0,1]; coeff[3,2]= uii[1,0]; coeff[3,3]=uii[1,1] + ujj[1,1]
                b = rij - tempsum; cc = sp.ndarray((4,1)); cc[0] = b[0,0]; cc[1] = b[1,0]; cc[2]=b[0,1]; cc[3]=b[1,1]

                temp = sp.zeros((2,2))
                FF = np.linalg.solve(coeff,cc)
                for k in range(0,2):
                    for h in range(0,2):
                        temp[h,k] = FF[2*k+h,0];
    #                      temp[0,0] = FF[0,0]; temp[0,1] = FF[2,0]; temp[1,0] = FF[1,0];temp[1,1] = FF[3,0]

                ris[bb[t]:eb[t]+1,bb[t+z]:eb[t+z]+1] = temp
                #ris[bb[t]:eb[t],bb[t+z]:eb[t+z]+1]
    return ris
def getGenerationProgress(resumeFile):
  
  def _getProgress(splitLine, _numParams):
    err = float(splitLine[-_numParams - 1])
    try:
      uniformRange = float(splitLine[-_numParams - 2])
      logRange = float(splitLine[-_numParams - 3])
      fR = float(splitLine[-_numParams - 4])
      pR = max(uniformRange, scipy.log(logRange))
    except ValueError:
      fR = float('NaN')
      pR = float('NaN')
    return (err, fR, pR)
  
  def _getNextLine(_fIn):
    # get the next non-empty, non-comment line from file
    line = next(_fIn)[:-1].split('#')[0]
    while not line:
      line = next(_fIn)[:-1].split('#')[0]
    return line
  
  with open(resumeFile, 'r') as fIn:
    # get the number of parameters from the first line
    line = _getNextLine(fIn)
    numParams = int(line.split()[0])
    
    # skim through the parameter descriptions and other uninteresting stuff
    while 'generation history' not in line:
      line = next(fIn)
    
    # get the number of generations in the history
    numGenerations = int(line.split(None)[0])
    
    # get the generation history
    errors = scipy.ndarray(numGenerations)
    fRange = scipy.ndarray(numGenerations)
    pRange = scipy.ndarray(numGenerations)
    for genNum in range(numGenerations):
      line = _getNextLine(fIn)
      (errors[genNum], fRange[genNum], pRange[genNum]) = \
        _getProgress(line.split(None), numParams)
    
    # get the distribution of current errors
    line = _getNextLine(fIn)
    populationSize = int(line.split()[0])
    currentErrors = scipy.ndarray(populationSize)
    for n in range(populationSize):
      line = _getNextLine(fIn)
      currentErrors[n] = float(line.split()[0])
  
  return (errors, fRange, pRange, currentErrors)
Example #7
0
def getGenerationProgress(resumeFile):
    def _getProgress(splitLine, _numParams):
        err = float(splitLine[-_numParams - 1])
        try:
            uniformRange = float(splitLine[-_numParams - 2])
            logRange = float(splitLine[-_numParams - 3])
            fR = float(splitLine[-_numParams - 4])
            pR = max(uniformRange, scipy.log(logRange))
        except ValueError:
            fR = float('NaN')
            pR = float('NaN')
        return (err, fR, pR)

    def _getNextLine(_fIn):
        # get the next non-empty, non-comment line from file
        line = next(_fIn)[:-1].split('#')[0]
        while not line:
            line = next(_fIn)[:-1].split('#')[0]
        return line

    with open(resumeFile, 'r') as fIn:
        # get the number of parameters from the first line
        line = _getNextLine(fIn)
        numParams = int(line.split()[0])

        # skim through the parameter descriptions and other uninteresting stuff
        while 'generation history' not in line:
            line = next(fIn)

        # get the number of generations in the history
        numGenerations = int(line.split(None)[0])

        # get the generation history
        errors = scipy.ndarray(numGenerations)
        fRange = scipy.ndarray(numGenerations)
        pRange = scipy.ndarray(numGenerations)
        for genNum in range(numGenerations):
            line = _getNextLine(fIn)
            (errors[genNum], fRange[genNum], pRange[genNum]) = \
              _getProgress(line.split(None), numParams)

        # get the distribution of current errors
        line = _getNextLine(fIn)
        populationSize = int(line.split()[0])
        currentErrors = scipy.ndarray(populationSize)
        for n in range(populationSize):
            line = _getNextLine(fIn)
            currentErrors[n] = float(line.split()[0])

    return (errors, fRange, pRange, currentErrors)
    def extend_left_handed_spaces(self, it):
        # good_t_vec is only true if the left eigenvector just generated has as sufficiently large component
        # which is orthogonal to the space spanned by the right eigenvectors
        t_vec_l = self.get_left_evec(self.vspace_r[:, -1])
        #    t_vec_l, good_t_vec = utils.orthogonalize_v1_against_v2(t_vec_l, self.vspace_r[:, -1])
        for ii in range(self.vspace_r.shape[1]):
            t_vec_l = utils.rs_self__orthogonalize(t_vec_l, self.vspace_r[:,
                                                                          ii])

        t_vec_l_norm = sp_la.norm(t_vec_l)
        if t_vec_l_norm < 1e-8:
            good_t_vec = False
        else:
            t_vec_l = t_vec_l / t_vec_l_norm
            good_t_vec = True

        sp.savetxt("t_vec_lp_c" + str(self.cycle) + "_i", t_vec_l)

        if good_t_vec:
            if self.vspace_l is None:
                self.vspace_l = sp.ndarray((self.ndim, 1),
                                           self.complex_precision)
                self.vspace_l[:, 0] = t_vec_l

                self.wspace_l = sp.ndarray((self.ndim, 1),
                                           self.complex_precision)
                self.wspace_l[:, 0] = self.sigma_constructor(self.vspace_r[:,
                                                                           0])

                self.vspace_lp = sp.ndarray((self.ndim, 1),
                                            self.complex_precision)
                self.vspace_lp[:, 0] = self.get_pair('x', self.vspace_r[:, 0])

                self.wspace_lp = sp.ndarray((self.ndim, 1),
                                            self.complex_precision)
                self.wspace_lp[:, 0] = self.get_pair('Ax', self.wspace_r[:, 0])
            else:
                self.vspace_l = sp.c_[self.vspace_l, t_vec_l]
                self.vspace_lp = sp.c_[self.vspace_lp,
                                       self.get_pair('x', self.vspace_l[:,
                                                                        -1])]
                self.wspace_l = sp.c_[
                    self.wspace_l,
                    self.sigma_constructor(self.vspace_l[:, -1])]
                self.wspace_lp = sp.c_[self.wspace_lp,
                                       self.get_pair('Ax', self.wspace_l[:,
                                                                         -1])]

            self.zero_check_and_save_lh()
    def get_new_tvec(self, iev):
        v1 = sp.ndarray(self.ndim, self.complex_precision)  # v1 = M^{-1}*r
        v2 = sp.ndarray(self.ndim, self.complex_precision)  # v2 = M^{-1}*u
        idx = 0

        # First half of vector
        for ii in range(self.nocc):
            for jj in range(self.nvirt):
                ediff = (self.evalai(ii, jj) - sp.real(self.teta[iev]))
                if np.abs(ediff) > 1e-8:
                    dtmp = 1 / ediff
                    v1[idx] = self.r_vecs[idx, iev] * dtmp
                    v2[idx] = self.u_vecs[idx, iev] * dtmp
                else:
                    print("Warning, (E_{a}-E_{i})<1e-8")
                    v1[idx] = self.complex_precision(
                        self.real_precision(0.0) + self.real_precision(0.0j))
                    v2[idx] = self.complex_precision(
                        self.real_precision(0.0) + self.real_precision(0.0j))
                idx += 1

        # Second half of vector
        for ii in range(self.nocc):
            for jj in range(self.nvirt):
                ediff = -self.evalai(ii, jj) - sp.real(self.teta[iev])
                if abs(ediff) > 1e-8:
                    dtmp = 1 / ediff
                    v1[idx] = self.r_vecs[idx, iev] * dtmp
                    v2[idx] = self.u_vecs[idx, iev] * dtmp
                else:
                    print("Warning, (E_{a}-E_{i})<1e-8")
                    v1[idx] = self.complex_precision(
                        self.real_precision(0.0) + self.real_precision(0.0j))
                    v2[idx] = self.complex_precision(
                        self.real_precision(0.0) + self.real_precision(0.0j))
                idx += 1

        sp.savetxt("v1_c" + str(self.cycle) + "_i" + str(iev + 1) + ".txt", v1)
        sp.savetxt("v2_c" + str(self.cycle) + "_i" + str(iev + 1) + ".txt", v2)

        u_m1_u = sp.vdot(self.u_vecs[:, iev], v2)
        print("u_m1_u = ", u_m1_u)
        if abs(u_m1_u) > 1e-8:
            u_m1_r = sp.vdot(self.u_vecs[:, iev], v1)
            print("u_m1_r = ", u_m1_r)
            factor = u_m1_r / sp.real(u_m1_u)
            return factor * v2 - v1
        else:
            return -v1
    def find_pore_hulls(self, pores=None):
        r"""
        Finds the coordinates of the Voronoi pores that define the convex hull
        around the given pores.

        Parameters
        ----------
        pores : array_like
            The pores whose convex hull are sought.  The given pores should be
            from the 'delaunay' network.  If no pores are given, then the hull
            is found for all 'delaunay' pores.

        Notes
        -----
        This metod is not fully optimized as it scans through each pore in a
        for-loop, so could be slow for large networks.
        """
        if pores is None:
            pores = self.pores('delaunay')
        else:
            pores = self.filter_by_label(pores, labels='delaunay')
        if 'pore.hull_coords' not in list(self.keys()):
            self['pore.hull_coords'] = sp.ndarray((self.Np, ), dtype=object)
        tvals = self['throat.interconnect'].astype(int)
        am = self.create_adjacency_matrix(data=tvals, sprsfmt='lil')
        for p in pores:
            Ps = am.rows[p]
            if sp.size(Ps) > 0:
                self['pore.hull_coords'][p] = self['pore.coords'][Ps]
    def find_throat_facets(self, throats=None):
        r"""
        Finds the coordinates of the Voronoi pores that define the facet or
        ridge between the pore-pairs associated with the given throat.

        Parameters
        ----------
        throats : array_like
            The throats whose facets are sought.  The given throats should be
            from the 'delaunay' network. If no throats are specified, all
            'delaunay' throats are assumed.

        Notes
        -----
        The method is not well optimized as it scans through each given throat
        inside a for-loop, so it could be slow for large networks.

        """
        if throats is None:
            throats = self.throats('delaunay')
        else:
            throats = self.filter_by_label(throats, labels='delaunay')
        if 'throat.facet_coords' not in list(self.keys()):
            self['throat.facet_coords'] = sp.ndarray((self.Nt, ), dtype=object)
        tvals = self['throat.interconnect'].astype(int)
        am = self.create_adjacency_matrix(data=tvals, sprsfmt='lil')
        for t in throats:
            P12 = self['throat.conns'][t]
            Ps = list(set(am.rows[P12][0]).intersection(am.rows[P12][1]))
            if sp.size(Ps) > 0:
                self['throat.facet_coords'][t] = self['pore.coords'][Ps]
Example #12
0
def voronoi(geometry, **kwargs):
    r"""
    Calculate volume from the convex hull of the offset vertices making the throats
    
    TODO: Optimise to only calculate volume of pores in geometry rather than selecting them afterwards
    """
    network = geometry._net
    pores = geometry['pore.map']
    conns = network['throat.conns']
    verts = network['throat.offset_verts']
    Np = network.num_pores()
    value = _sp.ndarray(Np)
    for my_pore in range(Np):
        throat_vert_list = []
        num_connections = 0
        for idx, check_pores in enumerate(conns):
            if (check_pores[0] == my_pore) or (check_pores[1] == my_pore):
                num_connections += 1
                for vertex in range(len(verts[idx])):
                    throat_vert_list.append(verts[idx][vertex])
        if num_connections > 1:
            throat_array = _sp.asarray(throat_vert_list)
            value[my_pore] = _get_hull_volume(throat_array)
        else:
            value[my_pore] = 0.0
    return value[pores]
Example #13
0
def c2c(network,
        geometry,
        pore_centroid='pore.centroid',
        throat_centroid='throat.centroid',
        **kwargs):
    r"""
    Calculate the centre to centre distance from centroid of pore1 to centroid
    of throat to centroid of pore2.

    Parameters
    ----------
    pore_centroid and throat_centroid : string
        The dictionary keys to the arrays containing the pore and throat
        centroid coordinates.

    Notes
    -----
    This is tricky as connections are defined at Network level but centroids
    are stored on geometry. The pore and throat map relates the geometry index
    to the network index but we must look up the index of the map to go back
    to geometry index of the connected pores. This will probably break down
    when a throat connects two different geometries.
    """
    throats = geometry.map_throats(network, geometry.throats())
    connections = network['throat.conns'][throats]
    net_pore1 = connections[:, 0]
    net_pore2 = connections[:, 1]
    pore_centroids = network[pore_centroid]
    throat_centroids = network[throat_centroid][throats]
    v1 = throat_centroids - pore_centroids[net_pore1]
    v2 = throat_centroids - pore_centroids[net_pore2]
    value = _sp.ndarray(len(connections))
    for i in range(len(connections)):
        value[i] = _sp.linalg.norm(v1[i]) + _sp.linalg.norm(v2[i])
    return value
Example #14
0
def voronoi(geometry, vertices='throat.centroid', **kwargs):
    r"""
    Calculate the centroid from the mean of the throat centroids

    Parameters
    ----------
    geometry : OpenPNM Geometry object
        The Geometry object which this model is associated.  This is needed to
        access the values of the ``vertices``.

    vertices : string
        The dictionary contain of the array containing the throat vertice
        coordiantes.  The default is 'throat.centroid'

    """
    network = geometry._net
    value = _sp.ndarray([geometry.num_pores(), 3])
    value.fill(0.0)
    pore_map = geometry.map_pores(target=network,
                                  pores=geometry.pores(),
                                  return_mapping=True)
    for i, net_pore in enumerate(pore_map['target']):
        geom_pore = pore_map['source'][i]
        net_throats = network.find_neighbor_throats(net_pore)
        geom_throats = network.map_throats(target=geometry,
                                           throats=net_throats,
                                           return_mapping=True)['target']
        verts = geometry[vertices][geom_throats]
        " Ignore all zero centroids "
        verts = verts[~_sp.all(verts == 0, axis=1)]
        if len(verts) > 0:
            value[geom_pore] = _sp.mean(verts, axis=0)

    return value
Example #15
0
def setTransitions(dimension):
    """ setting transitions in the state space """
    space_size = np.power(2, dimension)
    transition = np.ndarray(shape=(space_size, space_size), dtype=bool)
    transition.fill(False)  # False)

    state1 = [0 for i in range(dimension)]
    state2 = state1[:]
    for i in range(dimension):
        state2[i] = 1
        transition[st2Ind(state1)][st2Ind(state2)] = True  # forward transition
        transition[st2Ind(state2)][st2Ind(
            state1)] = True  # backward transition
        state1 = state2[:]

    state1 = [0 for i in range(dimension)]
    state2 = state1[:]
    for i in range(dimension):
        state2[dimension - i - 1] = 1
        transition[st2Ind(state1)][st2Ind(state2)] = True  # forward transition
        transition[st2Ind(state2)][st2Ind(
            state1)] = True  # backward transition
        state1 = state2[:]

    printTransitions(transition, dimension)

    return transition
Example #16
0
    def test_computer_example11(self):
        n = 1000
        A = sp.zeros((n, n), dtype=float)
        b = sp.ndarray((n))
        expect = sp.ones((n), dtype=float)

        for i in range(n):
            A[n - i - 1][i] = 0.5
            A[i][i] = 3
            b[i] = 1.5

        for i in range(n - 1):
            A[i + 1][i] = -1
            A[i][i + 1] = -1
        b[0] = 2.5
        b[-1] = 2.5
        b[n // 2] = 1.0

        self._test_cg(self.test_computer_example11.__name__, linalg.solve, A,
                      b, expect)
        self._test_cg(self.test_computer_example11.__name__, BookCG, A, b,
                      expect)
        self._test_cg(self.test_computer_example11.__name__, WikiCG, A, b,
                      expect)
        self._test_cg(self.test_computer_example11.__name__, ScipyCG,
                      csc_matrix(A), b, expect)
        self._test_cg(self.test_computer_example11.__name__, ScipyCGS,
                      csc_matrix(A), b, expect)
        self._test_cg(self.test_computer_example11.__name__, ScipyBicG,
                      csc_matrix(A), b, expect)
        self._test_cg(self.test_computer_example11.__name__, ScipyBicGStab,
                      csc_matrix(A), b, expect)
        self._test_cg(self.test_computer_example11.__name__, ScipySpSolve,
                      csc_matrix(A), b, expect)
Example #17
0
def c2c(network, geometry, pore_centroid='pore.centroid',
        throat_centroid='throat.centroid', **kwargs):
    r"""
    Calculate the centre to centre distance from centroid of pore1 to centroid
    of throat to centroid of pore2.

    Parameters
    ----------
    pore_centroid and throat_centroid : string
        The dictionary keys to the arrays containing the pore and throat
        centroid coordinates.

    Notes
    -----
    This is tricky as connections are defined at Network level but centroids
    are stored on geometry. The pore and throat map relates the geometry index
    to the network index but we must look up the index of the map to go back
    to geometry index of the connected pores. This will probably break down
    when a throat connects two different geometries.
    """
    throats = geometry.map_throats(network, geometry.throats())
    connections = network['throat.conns'][throats]
    net_pore1 = connections[:, 0]
    net_pore2 = connections[:, 1]
    pore_centroids = network[pore_centroid]
    throat_centroids = network[throat_centroid][throats]
    v1 = throat_centroids-pore_centroids[net_pore1]
    v2 = throat_centroids-pore_centroids[net_pore2]
    value = _sp.ndarray(len(connections))
    for i in range(len(connections)):
        value[i] = _sp.linalg.norm(v1[i])+_sp.linalg.norm(v2[i])
    return value
    def find_pore_hulls(self, pores=None):
        r"""
        Finds the coordinates of the Voronoi pores that define the convex hull
        around the given pores.

        Parameters
        ----------
        pores : array_like
            The pores whose convex hull are sought.  The given pores should be
            from the 'delaunay' network.  If no pores are given, then the hull
            is found for all 'delaunay' pores.

        Notes
        -----
        This metod is not fully optimized as it scans through each pore in a
        for-loop, so could be slow for large networks.
        """
        if pores is None:
            pores = self.pores('delaunay')
        else:
            pores = self.filter_by_label(pores, labels='delaunay')
        if 'pore.hull_coords' not in self.keys():
            self['pore.hull_coords'] = sp.ndarray((self.Np, ), dtype=object)
        tvals = self['throat.interconnect'].astype(int)
        am = self.create_adjacency_matrix(data=tvals, sprsfmt='lil')
        for p in pores:
            Ps = am.rows[p]
            if sp.size(Ps) > 0:
                self['pore.hull_coords'][p] = self['pore.coords'][Ps]
Example #19
0
def voronoi(network, geometry, **kwargs):
    r"""
    Calculate the centre to centre distance from centroid of pore1 to centroid of throat to centroid of pore2
    This is tricky as connections are defined at network level but centroids are stored on geometry.
    The pore and throat map relates the geometry index to the network index but we must look up the index of the map
    to go back to geometry index of the connected pores.
    This will probably break down when a throat connects two different geometries 
    """
    throats = geometry['throat.map']
    connections = network['throat.conns'][throats]
    net_pore1 = connections[:, 0]
    net_pore2 = connections[:, 1]
    geom_pore1 = []
    geom_pore2 = []
    for net_pore in net_pore1:
        geom_pore1.append(geometry['pore.map'].tolist().index(net_pore))
    for net_pore in net_pore2:
        geom_pore2.append(geometry['pore.map'].tolist().index(net_pore))

    pore_centroids = geometry['pore.centroid']
    throat_centroids = geometry['throat.centroid']
    v1 = throat_centroids - pore_centroids[geom_pore1]
    v2 = throat_centroids - pore_centroids[geom_pore2]
    value = _sp.ndarray(len(connections))
    for i in range(len(connections)):
        value[i] = _sp.linalg.norm(v1[i]) + _sp.linalg.norm(v2[i])
    return value
    def find_throat_facets(self, throats=None):
        r"""
        Finds the coordinates of the Voronoi pores that define the facet or
        ridge between the pore-pairs associated with the given throat.

        Parameters
        ----------
        throats : array_like
            The throats whose facets are sought.  The given throats should be
            from the 'delaunay' network. If no throats are specified, all
            'delaunay' throats are assumed.

        Notes
        -----
        The method is not well optimized as it scans through each given throat
        inside a for-loop, so it could be slow for large networks.

        """
        if throats is None:
            throats = self.throats('delaunay')
        else:
            throats = self.filter_by_label(throats, labels='delaunay')
        if 'throat.facet_coords' not in self.keys():
            self['throat.facet_coords'] = sp.ndarray((self.Nt, ), dtype=object)
        tvals = self['throat.interconnect'].astype(int)
        am = self.create_adjacency_matrix(data=tvals, sprsfmt='lil')
        for t in throats:
            P12 = self['throat.conns'][t]
            Ps = list(set(am.rows[P12][0]).intersection(am.rows[P12][1]))
            if sp.size(Ps) > 0:
                self['throat.facet_coords'][t] = self['pore.coords'][Ps]
 def _generate_masked_mesh(self, cell_mask=None):
     r"""
     Generates the mesh based on the cell mask provided
     """
     #
     if cell_mask is None:
         cell_mask = sp.ones(self.data_map.shape, dtype=bool)
     #
     # initializing arrays
     self._edges = sp.ones(0, dtype=str)
     self._merge_patch_pairs = sp.ones(0, dtype=str)
     self._create_blocks(cell_mask)
     #
     # building face arrays
     mapper = sp.ravel(sp.array(cell_mask, dtype=int))
     mapper[mapper == 1] = sp.arange(sp.count_nonzero(mapper))
     mapper = sp.reshape(mapper, (self.nz, self.nx))
     mapper[~cell_mask] = -sp.iinfo(int).max
     #
     boundary_dict = {
         'bottom':
             {'bottom': mapper[0, :][cell_mask[0, :]]},
         'top':
             {'top': mapper[-1, :][cell_mask[-1, :]]},
         'left':
             {'left': mapper[:, 0][cell_mask[:, 0]]},
         'right':
             {'right': mapper[:, -1][cell_mask[:, -1]]},
         'front':
             {'front': mapper[cell_mask]},
         'back':
             {'back': mapper[cell_mask]},
         'internal':
             {'bottom': [], 'top': [], 'left': [], 'right': []}
     }
     #
     # determining cells linked to a masked cell
     cell_mask = sp.where(~sp.ravel(cell_mask))[0]
     inds = sp.in1d(self._field._cell_interfaces, cell_mask)
     inds = sp.reshape(inds, (len(self._field._cell_interfaces), 2))
     inds = inds[:, 0].astype(int) + inds[:, 1].astype(int)
     inds = (inds == 1)
     links = self._field._cell_interfaces[inds]
     #
     # adjusting order so masked cells are all on links[:, 1]
     swap = sp.in1d(links[:, 0], cell_mask)
     links[swap] = links[swap, ::-1]
     #
     # setting side based on index difference
     sides = sp.ndarray(len(links), dtype='<U6')
     sides[sp.where(links[:, 1] == links[:, 0]-self.nx)[0]] = 'bottom'
     sides[sp.where(links[:, 1] == links[:, 0]+self.nx)[0]] = 'top'
     sides[sp.where(links[:, 1] == links[:, 0]-1)[0]] = 'left'
     sides[sp.where(links[:, 1] == links[:, 0]+1)[0]] = 'right'
     #
     # adding each block to the internal face dictionary
     inds = sp.ravel(mapper)[links[:, 0]]
     for side, block_id in zip(sides, inds):
         boundary_dict['internal'][side].append(block_id)
     self.set_boundary_patches(boundary_dict, reset=True)
Example #22
0
def setTransitions(dimension):
    """ setting transitions in the state space """
    space_size = np.power(2, dimension)
    transition = np.ndarray(shape=(space_size, space_size), dtype=bool)
    transition.fill(False)  # False)

    state1 = [0 for i in range(dimension)]
    state2 = state1[:]
    for i in range(dimension):
        state2[i] = 1
        transition[st2Ind(state1)][st2Ind(state2)] = True  # forward transition
        transition[st2Ind(state2)][st2Ind(state1)] = True  # backward transition
        state1 = state2[:]

    state1 = [0 for i in range(dimension)]
    state2 = state1[:]
    for i in range(dimension):
        state2[dimension-i-1] = 1
        transition[st2Ind(state1)][st2Ind(state2)] = True  # forward transition
        transition[st2Ind(state2)][st2Ind(state1)] = True  # backward transition
        state1 = state2[:]

    printTransitions(transition, dimension)

    return transition
Example #23
0
def remove_column_path(img, path):
    (n, m) = img.shape[0:2]
    ret = ndarray((n, m - 1, 3), dtype=img.dtype)
    for i in range(n):
        assert i in path
        j = path[i]
        ret[i] = numpy.concatenate((img[i][0:j], img[i][j + 1:m]), axis=0)
    return ret
Example #24
0
def voronoi(network, geometry, **kwargs):
    r"""
    Update the pore vertices from the voronoi vertices
    """
    pores = geometry.map_pores(network, geometry.pores())
    value = _sp.ndarray(len(pores), dtype=object)
    for i in range(len(pores)):
        value[i] = _sp.asarray(list(network['pore.vert_index'][pores[i]].values()))
    return value
Example #25
0
def centre_of_mass(geometry, vertices='throat.offset_vertices', **kwargs):
    r"""
    Calculate the centre of mass of the throat from the voronoi vertices.
    """
    Nt = geometry.num_throats()
    outer_verts = geometry['throat.vertices']
    offset_verts = geometry[vertices]
    normal = geometry['throat.normal']
    z_axis = [0, 0, 1]
    value = _sp.ndarray([Nt, 3])
    for i in range(Nt):
        if len(offset_verts[i]) > 2:
            verts = offset_verts[i]
        elif len(outer_verts[i]) > 2:
            verts = outer_verts[i]
        else:
            verts = []
        if len(verts) > 0:
            # For boundaries some facets will already be aligned with the axis -
            # if this is the case a rotation is unnecessary and could also cause
            # problems
            angle = tr.angle_between_vectors(normal[i], z_axis)
            if angle == 0.0 or angle == _sp.pi:
                "We are already aligned"
                rotate_input = False
                facet = verts
            else:
                rotate_input = True
                M = tr.rotation_matrix(
                    tr.angle_between_vectors(normal[i], z_axis),
                    tr.vector_product(normal[i], z_axis))
                facet = _sp.dot(verts, M[:3, :3].T)
            # Now we have a rotated facet aligned with the z axis - make 2D
            facet_2D = _sp.column_stack((facet[:, 0], facet[:, 1]))
            z = _sp.unique(_sp.around(facet[:, 2], 10))
            if len(z) == 1:
                # We need the vertices arranged in order so perform a convex hull
                hull = ConvexHull(facet_2D)
                ordered_facet_2D = facet_2D[hull.vertices]
                # Call the routine to calculate an area wighted centroid from the
                # 2D polygon
                COM_2D = vo.PolyWeightedCentroid2D(ordered_facet_2D)
                COM_3D = _sp.hstack((COM_2D, z))
                # If we performed a rotation we need to rotate back
                if (rotate_input):
                    MI = tr.inverse_matrix(M)
                    # Unrotate the offset coordinates using the inverse of the
                    # original rotation matrix
                    value[i] = _sp.dot(COM_3D, MI[:3, :3].T)
                else:
                    value[i] = COM_3D
            else:
                logger.error('Rotation Failed: ' +
                             str(_sp.unique(facet[:, 2])))

    return value
Example #26
0
def voronoi(network, geometry, **kwargs):
    r"""
    Update the pore vertices from the voronoi vertices
    """
    throats = geometry.map_throats(network, geometry. throats())
    value = _sp.ndarray(len(throats), dtype=object)
    for i in range(len(throats)):
        value[i] = \
            _sp.asarray(list(network['throat.vert_index'][throats[i]].values()))
    return value
Example #27
0
def voronoi(geometry, pore_vertices='pore.vertices', **kwargs):
    r"""
    Calculate the centroid of the pore from the voronoi vertices - C.O.M
    """
    verts = geometry[pore_vertices]
    value = _sp.ndarray([len(verts), 3])
    for i, vert in enumerate(verts):
        value[i] = _sp.array(
            [vert[:, 0].mean(), vert[:, 1].mean(), vert[:, 2].mean()])
    return value
Example #28
0
def debug_path(energy, path):
    (n, m) = energy.shape[0:2]
    dest = ndarray((n, m), dtype=energy.dtype)
    for i in range(n):
        for j in range(m):
            dest[i][j] = energy[i][j]
        j = path[i]
        dest[i][j] = 1
    plt.imshow(dest)
    plt.show()
Example #29
0
def voronoi(network, geometry, **kwargs):
    r"""
    Update the pore vertices from the voronoi vertices
    """
    pores = geometry.map_pores(network, geometry.pores())
    value = _sp.ndarray(len(pores), dtype=object)
    for i in range(len(pores)):
        value[i] = _sp.asarray(
            list(network["pore.vert_index"][pores[i]].values()))
    return value
Example #30
0
def centre_of_mass(geometry, vertices='throat.offset_vertices', **kwargs):
    r"""
    Calculate the centre of mass of the throat from the voronoi vertices.
    """
    Nt = geometry.num_throats()
    outer_verts = geometry['throat.vertices']
    offset_verts = geometry[vertices]
    normal = geometry['throat.normal']
    z_axis = [0, 0, 1]
    value = _sp.ndarray([Nt, 3])
    for i in range(Nt):
        if len(offset_verts[i]) > 2:
            verts = offset_verts[i]
        elif len(outer_verts[i]) > 2:
            verts = outer_verts[i]
        else:
            verts = []
        if len(verts) > 0:
            # For boundaries some facets will already be aligned with the axis -
            # if this is the case a rotation is unnecessary and could also cause
            # problems
            angle = tr.angle_between_vectors(normal[i], z_axis)
            if angle == 0.0 or angle == _sp.pi:
                "We are already aligned"
                rotate_input = False
                facet = verts
            else:
                rotate_input = True
                M = tr.rotation_matrix(tr.angle_between_vectors(normal[i], z_axis),
                                       tr.vector_product(normal[i], z_axis))
                facet = _sp.dot(verts, M[:3, :3].T)
            # Now we have a rotated facet aligned with the z axis - make 2D
            facet_2D = _sp.column_stack((facet[:, 0], facet[:, 1]))
            z = _sp.unique(_sp.around(facet[:, 2], 10))
            if len(z) == 1:
                # We need the vertices arranged in order so perform a convex hull
                hull = ConvexHull(facet_2D)
                ordered_facet_2D = facet_2D[hull.vertices]
                # Call the routine to calculate an area wighted centroid from the
                # 2D polygon
                COM_2D = vo.PolyWeightedCentroid2D(ordered_facet_2D)
                COM_3D = _sp.hstack((COM_2D, z))
                # If we performed a rotation we need to rotate back
                if (rotate_input):
                    MI = tr.inverse_matrix(M)
                    # Unrotate the offset coordinates using the inverse of the
                    # original rotation matrix
                    value[i] = _sp.dot(COM_3D, MI[:3, :3].T)
                else:
                    value[i] = COM_3D
            else:
                print('Rotation Failed: ' + str(_sp.unique(facet[:, 2])))

    return value
Example #31
0
def householder(A, reduced=False) -> Tuple[sp.matrix, sp.matrix]:
    '''
    Given a matrix A, computes its QR factorisation using Householder
    reflections.

    Returns (Q, R) such that A = QR, Q is orthogonal and R is triangular.
    '''
    m, n = A.shape

    A_full = sp.ndarray(A.shape)
    A_sub = A.copy()

    Q_full = sp.identity(m)
    # iterate over smaller dimension of A
    for i in range(min(A.shape)):
        # leftmost vector of A submatrix
        v = A_sub[:, 0]
        # vector with 1 in the first position.
        e_i = sp.zeros(v.shape[0])
        e_i[0] = 1

        # compute householder vector for P
        u = v + sign(v.item(0)) * spla.norm(v) * e_i
        # normalise
        u = u / spla.norm(u)
        # compute submatrix _P
        _P = sp.identity(v.shape[0]) - 2 * sp.outer(u, u)

        # embed this submatrix _P into the full size P
        P = spla.block_diag(sp.identity(i), _P)

        # compute next iteration of Q
        Q_full = P @ Q_full

        # compute next iteration of R
        A_sub = _P @ A_sub

        # copy first rows/cols to A_full
        A_full[i, i:] = A_sub[0, :]
        A_full[i:, i] = A_sub[:, 0]

        # iterate into submatrix
        A_sub = A_sub[1:, 1:]

    # Q_full is currently the inverse because it is applied to A.
    # thus, Q = Q_full^T.
    Q_full = Q_full.T
    if reduced:
        Q_full = Q_full[:, :n]
        A_full = A_full[:n, :]

    # A = QR
    # note that A has been reduced to R by applying the P's.
    return (Q_full, A_full)
Example #32
0
def findBlocks0(matrix):
    dim = matrix.shape[0]
    i=j=0; eb = sp.ndarray(dim,sp.integer); bb = sp.ndarray(dim,sp.integer)
    dims = sp.ndarray(dim,sp.int8); wb = sp.ndarray(dim)
    while (i<dim):
        if (i<dim-1 and matrix[i+1,i]!=0):
            bb[j] = i
            eb[j] = i+1
            dims[j] = 2; wb[i] = wb[i+1]=j
            i+=1

        else:
            bb[j] = eb[j] = i
            dims[j] = 1
            wb[i] = j

        i+=1
        j+=1

    return bb,eb,dims,wb,i,j #i,wb dims maybe are useless
    def get_esorted_general(self):
        # Build sorted list of eigval differences without imposing any symmetry constraints
        self.esorted = sp.ndarray((self.nocc, self.nvirt),
                                  dtype=self.real_precision)
        for ii in range(self.nocc):
            for jj in range(self.nvirt):
                self.esorted[ii, jj] = self.evalai(ii, jj)

        self.esorted = sp.reshape(self.esorted, self.nov)
        self.eindex = sp.argsort(self.esorted)
        self.esorted = self.esorted[self.eindex]
Example #34
0
def twobytworoot(matrix):
    if (matrix.shape[0]==2):
        a = sp.sqrt(sp.linalg.eigvals(matrix)[0]).real
        ris=sp.ndarray(shape=(2,2))
        ris[0,0] = a + (1/(4*a))*(matrix[0,0] - matrix[1,1])
        ris[1,1] = a - (1/(4*a))*(matrix[0,0] - matrix[1,1])
        ris[0,1] = (1/(2*a))*matrix[0,1]
        ris[1,0] = (1/(2*a))*matrix[1,0]
    else:
        return sp.sqrt(matrix)
    return ris
Example #35
0
def voronoi(geometry,
            pore_vertices='pore.vertices',
            **kwargs):
    r"""
    Calculate the centroid of the pore from the voronoi vertices - C.O.M
    """
    verts = geometry[pore_vertices]
    value = _sp.ndarray([len(verts),3])
    for i,vert in enumerate(verts):
        value[i] = _sp.array([vert[:,0].mean(),vert[:,1].mean(),vert[:,2].mean()])
    return value
Example #36
0
 def dloglikarray(self):
     """Derivative of `loglik` with respect to `paramsarray`."""
     assert self.dparamscurrent, "dloglikarray requires paramscurrent == True"
     nparams = len(self._index_to_param)
     dloglikarray = scipy.ndarray(shape=(nparams, ), dtype='float')
     for (i, param) in self._index_to_param.items():
         if isinstance(param, str):
             dloglikarray[i] = self.dloglik[param]
         elif isinstance(param, tuple):
             dloglikarray[i] = self.dloglik[param[0]][param[1]]
     return dloglikarray
Example #37
0
def voronoi(geometry, pore_vertices='pore.vertices', **kwargs):
    r"""
    Calculate the centroid of the pore from the voronoi vertices - C.O.M
    """
    network = geometry._net
    pores = geometry['pore.map']
    verts = network[pore_vertices][pores]
    value = _sp.ndarray(len(verts), dtype=object)
    for i, vert in enumerate(verts):
        value[i] = _sp.array(
            [vert[:, 0].mean(), vert[:, 1].mean(), vert[:, 2].mean()])
    return value
Example #38
0
def findGrad(imagePixels):
	dx = ndimage.sobel(imagePixels, 0) # horizontal derivative
	dy = ndimage.sobel(imagePixels, 1) # vertical derivative
	# mag = numpy.hypot(dx, dy)  # magnitude
	# mag *= 255.0 / numpy.max(mag)  # normalize (Q&D)
	# scipy.misc.imshow(mag)
	grad = scipy.ndarray((dx.shape[0],dx.shape[1], 2), dtype=float)
	for y in range(dx.shape[0]):
		for x in range(dx.shape[1]):
			grad[y][x][0] = dx[y][x]
			grad[y][x][1] = dy[y][x]
	return grad
Example #39
0
def voronoi(geometry, **kwargs):
    r"""
    Calculate the centroid of the throat from the voronoi vertices - C.O.M
    """
    network = geometry._net
    throats = geometry['throat.map']
    verts = network['throat.offset_verts'][throats]
    value = _sp.ndarray(len(verts), dtype=object)
    for i, vert in enumerate(verts):
        value[i] = _sp.array(
            [vert[:, 0].mean(), vert[:, 1].mean(), vert[:, 2].mean()])
    return value
Example #40
0
def blockRoot(matrix):
    if (matrix.shape[0]==2):
        a = csr3(gev(matrix)).real
        ris=sp.ndarray(shape=(2,2))
        ris[0,0] = a + (1/(4*a))*(matrix[0,0] - matrix[1,1])
        ris[1,1] = a - (1/(4*a))*(matrix[0,0] - matrix[1,1])
        ris[0,1] = (1/(2*a))*matrix[0,1]
        ris[1,0] = (1/(2*a))*matrix[1,0]
    else:
        #print(sp.sqrt(matrix))
        return sp.sqrt(matrix)
    return ris
Example #41
0
def voronoi2(geometry,
             vertices='throat.centroid',
             **kwargs):
    r"""
    Calculate the centroid from the mean of the throat centroids
    """
    value = _sp.ndarray([geometry.num_pores(),3])
    pore_map = geometry.map_pores(geometry.pores(),geometry._net)
    for geom_pore,net_pore in pore_map:
        net_throats = geometry._net.find_neighbor_throats(net_pore)
        geom_throats = geometry._net.map_throats(net_throats,geometry)[:,1]
        verts = geometry[vertices][geom_throats]
        value[geom_pore]=_sp.array([verts[:,0].mean(),verts[:,1].mean(),verts[:,2].mean()])
    return value
Example #42
0
    def __init__(self,KF_gen,KF_init,KF_prior,optF,upper,lower,dim):
	self.KF_gen=KF_gen
	self.KF_hyp=KF_init
	self.KF_prior=KF_prior
        self.KFs=[KF_gen(self.KF_hyp)]
        self.optF=optF
        self.upper=upper
        self.lower=lower
        self.nsam=0
        self.X=sp.matrix(sp.ndarray([0,dim]))
        self.Y=sp.matrix(sp.ndarray([0,1]))
        self.best=[None,sp.Inf]
        self.dim=dim
        self.Ky=[]
        self.KyRs=[]
        self.llks=[]
        self.renorm=1.
	self.cc=0
	self.finished=False
	self.fudgelimit=32
	self.hyp_trace=sp.matrix(KF_init)
	
        return
    def Optimize(self):
        """
        Performs the optimization.
        """
        self.result=optimize.fmin(self.wrapper, 
                                      x0=ndarray((self.num_inputs,),buffer=array(self.starting_points),offset=0,dtype=float), 
#                                      x0=ndarray( (self.num_inputs,1) ,buffer=array([0.784318808, 4.540607953, -11.919391073,-100]),dtype=float),
                                      args=[[]],  
                                      maxiter= self.max_evaluation,
                                      xtol= self.xtol,
                                      ftol= self.ftol,
                                      full_output=True
                                      )
        
        self.final_pop=[my_candidate(self.result[0],self.result[1])]
Example #44
0
 def _get_labels(self,element,locations,mode='union',flatten=False):
     r'''
     This is the actual label getter method, but it should not be called directly.  
     Wrapper methods have been created.  Use get_pore_labels and get_throat_labels
     
     See Also
     --------
     get_pore_labels, get_throat_labels
     
     '''
     if element == 'pore':
         element_info = self._pore_info
         labels = self.list_pore_labels()
     elif element == 'throat':
         element_info = self._throat_info
         labels = self.list_throat_labels()
     arr = sp.ndarray((sp.shape(locations,)[0],len(labels)),dtype=bool)
     col = 0
     for item in labels:
         arr[:,col] = element_info[item][locations]
         col = col + 1
     if flatten == True:
         if mode == 'count':
             return sp.sum(arr,axis=1)
         if mode == 'union':
             return labels[sp.sum(arr,axis=0)>0]
         if mode == 'intersection':
             return labels[sp.sum(arr,axis=0)==sp.shape(locations,)[0]]
     else:
         if mode == 'raw':
             return arr
         else:
             temp = sp.ndarray((sp.shape(locations,)[0],),dtype=object)
             for i in sp.arange(0,sp.shape(locations,)[0]):
                 temp[i] = list(labels[arr[i,:]])
             return temp
Example #45
0
def voronoi(geometry,
            **kwargs):
    r"""
    Use the Voronoi verts and throat normals to work out the perimeter
    """
    Nt = geometry.num_throats()    
    verts = geometry['throat.offset_vertices']
    normals = geometry['throat.normal']
    perimeter = _sp.ndarray(Nt)
    for i in range(Nt):
        if len(verts[i]) > 2:
            verts_2D = tr.rotate_and_chop(verts[i],normals[i],[0,0,1])
            perimeter[i] = vo.PolyPerimeter2D(verts_2D)
        else:
            perimeter[i] = 0.0
    return perimeter
Example #46
0
  def __init__(self,
               outputConfig,
               signalSources,
               noiseParams,
               tcxo,
               signalFilters,
               groupDelays,
               bands,
               generateDebug):
    '''
    Task object constructor.

    Parameters
    ----------
    outputConfig : object
      Output profile
    signalSources : array-like
      List of satellites
    noiseParams : NoiseParameters
      Noise parameters container
    tcxo : object
      TCXO control object
    signalFilters : array-like
      Output signal filter objects
    groupDelays : bool
      Flag if group delays are enabled
    bands : list
      List of bands to generate
    generateDebug : bool
      Flag if additional debug output is required
    '''

    self.outputConfig = outputConfig
    self.signalSources = signalSources
    self.signalFilters = signalFilters
    self.generateDebug = generateDebug
    self.noiseParams = noiseParams
    self.tcxo = tcxo
    self.signals = scipy.ndarray(shape=(outputConfig.N_GROUPS,
                                        outputConfig.SAMPLE_BATCH_SIZE),
                                 dtype=numpy.float)
    self.nSamples = outputConfig.SAMPLE_BATCH_SIZE
    self.noise = self.createNoise()
    self.groupDelays = groupDelays
    self.bands = bands
    self.firstSampleIndex = 0l
    self.userTime0_s = 0.
Example #47
0
def setTransitions(dimension):
    """ setting transitions in the state space """
    space_size = np.power(2, dimension)
    transition = np.ndarray(shape=(space_size, space_size), dtype=bool)
    transition.fill(False)
    state1 = [0 for i in range(dimension)]
    state2 = state1[:]
    for i in range(dimension):
        state2[i] = 1
        transition[st2Ind(state1)][st2Ind(state2)] = True  # forward transition
        transition[st2Ind(state2)][st2Ind(state1)] = True  # backward transition
        state1 = state2[:]
    for i in range(space_size):
        for j in range(space_size):
            if transition[i][j]:
                print str(bin(i))[2:], '->', str(bin(j))[2:]
    return transition
Example #48
0
def voronoi(geometry, **kwargs):
    r"""
    Use the Voronoi verts and throat normals to work out the perimeter
    """
    Nt = geometry.num_throats()
    verts = geometry['throat.offset_vertices']
    normals = geometry['throat.normal']
    perimeter = _sp.ndarray(Nt)
    for i in range(Nt):
        if len(verts[i]) > 2:
            verts_2D = tr.rotate_and_chop(verts[i], normals[i], [0, 0, 1])
            # Get in hull order
            hull = ConvexHull(verts_2D, qhull_options='QJ Pp')
            verts_2D = verts_2D[hull.vertices]
            perimeter[i] = vo.PolyPerimeter2D(verts_2D)
        else:
            perimeter[i] = 0.0
    return perimeter
    def Optimize(self):
        """
        Performs the optimization.
        """
        self.result=optimize.fmin_l_bfgs_b(self.wrapper, 
                                      x0=ndarray((self.num_inputs,),buffer=array(self.starting_points),offset=0,dtype=float), 
#                                      x0=ndarray( (self.num_inputs,1) ,buffer=array([0.784318808, 4.540607953, -11.919391073,-100]),dtype=float),
                                      args=[[]], 
                                      bounds= [(0,1)]*len(self.min_max[0]),
                                      maxfun= self.max_evaluation,
                                      fprime= None,
                                      approx_grad= True,
                                      factr= self.accuracy, #1e7 moderate acc, 10.0 ext high acc
                                      iprint= 2, #>1 creates log file
                                      pgtol= 1e-06
                                      )
        print self.result[-1]['warnflag']
        self.final_pop=[my_candidate(self.result[0],self.result[1])]
Example #50
0
def voronoi(network, geometry, **kwargs):
    r"""
    Update the throat normals from the voronoi vertices
    """
    verts = geometry["throat.vertices"]
    value = sp.ndarray([len(verts), 3])
    for i in range(len(verts)):
        if len(sp.unique(verts[i][:, 0])) == 1:
            verts_2d = sp.vstack((verts[i][:, 1], verts[i][:, 2])).T
        elif len(sp.unique(verts[i][:, 1])) == 1:
            verts_2d = sp.vstack((verts[i][:, 0], verts[i][:, 2])).T
        else:
            verts_2d = sp.vstack((verts[i][:, 0], verts[i][:, 1])).T
        hull = ConvexHull(verts_2d, qhull_options='QJ Pp')
        sorted_verts = verts[i][hull.vertices]
        v1 = sorted_verts[1]-sorted_verts[0]
        v2 = sorted_verts[-1]-sorted_verts[0]
        value[i] = sp.cross(v1, v2)

    return value
Example #51
0
def gen(kf,upper,lower,r=25):

	X=sp.matrix(sp.ndarray([0,2]))

	xv=sp.linspace(lower[0],upper[0],r)
	yv=sp.linspace(lower[1],upper[1],r)

	for y in yv:
    		for x in xv:
        
        		p=sp.matrix([[x,y]])
        		X=sp.vstack([X,p])

	K= sp.array(buildKsym(kf,X))
	m=sp.zeros([K.shape[0]])

	zv = sp.random.multivariate_normal(m,K)

	f=spi.interp2d(xv,yv,sp.vstack(sp.split(zv,r)))
	g = lambda x:f(x[0,0],x[0,1])[0]
	return g
Example #52
0
def voronoi(network,
            geometry,
            **kwargs):
    r"""
    Calculate the centre to centre distance from centroid of pore1 to centroid of throat to centroid of pore2
    This is tricky as connections are defined at network level but centroids are stored on geometry.
    The pore and throat map relates the geometry index to the network index but we must look up the index of the map
    to go back to geometry index of the connected pores.
    This will probably break down when a throat connects two different geometries 
    """
    throats = geometry.map_throats(network,geometry.throats())
    connections = network['throat.conns'][throats]
    net_pore1 = connections[:,0]
    net_pore2 = connections[:,1]    
    pore_centroids = network['pore.centroid']
    throat_centroids = network['throat.centroid'][throats]
    v1 = throat_centroids-pore_centroids[net_pore1]
    v2 = throat_centroids-pore_centroids[net_pore2]
    value = _sp.ndarray(len(connections))
    for i in range(len(connections)):
        value[i] = _sp.linalg.norm(v1[i])+_sp.linalg.norm(v2[i])
    return value
Example #53
0
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
    r"""
    Calculate the centroid from the mean of the throat centroids
    """
    value = _sp.ndarray([geometry.num_pores(), 3])
    value.fill(0.0)
    pore_map = geometry.map_pores(target=network,
                                  pores=geometry.pores(),
                                  return_mapping=True)
    for i, net_pore in enumerate(pore_map['target']):
        geom_pore = pore_map['source'][i]
        net_throats = network.find_neighbor_throats(net_pore)
        geom_throats = network.map_throats(target=geometry,
                                           throats=net_throats,
                                           return_mapping=True)['target']
        verts = geometry[vertices][geom_throats]
        " Ignore all zero centroids "
        verts = verts[~_sp.all(verts == 0, axis=1)]
        if len(verts) > 0:
            value[geom_pore] = _sp.mean(verts, axis=0)

    return value