Create a System made of a series of random molecules.
    
    Parameters:
    
    total:
    molecules:
    proportions:
515209
def random_box(molecules, total=None, proportions=None, size=[1.,1.,1.], maxtries=100):
    '''
    '''
    
    # Setup proportions to be right
    if proportions is None:
        proportions = np.ones(len(molecules)) / len(molecules)
    else:
        proportions = np.array(proportions)
    
    size = np.array(size)
    
    tree = CoverTree(metric="periodic", metric_args={'cell_lengths': size})
    
    type_array = []
    result = []
    vdw_radii = []
    max_vdw = max(vdw_radius(np.concatenate([m.type_array for m in molecules])))
    
    first = True
    for l, n in enumerate((proportions * total).astype(int)):
        
        # We try to insert each molecule    
        for i in range(n):
            
            # Attempts
            for k in range(maxtries):
                template = molecules[l].copy()
                reference = np.random.uniform(0, 1, 3) * size
                r_array = template.r_array + reference

                # Find all collision candidates
                pts_list, distances_list = tree.query_ball_many(r_array, vdw_radius(template.type_array) + max_vdw)
                # print pts_list, distances_list
                # Check if there is any collision
                ok = True
                for i, (dist, pts) in enumerate(zip(distances_list, pts_list)):
                    if len(dist) == 0:
                        break

                    found_vdw = np.array([vdw_radii[p] for p in pts])
                    ok &= all(dist > found_vdw + vdw_radius(template.type_array[i]))

                if ok:
                    tree.insert_many(r_array)
                    template.r_array = r_array
                    result.append(template)
                    vdw_radii.extend(vdw_radius(template.type_array))
                    break
            if not ok:
                raise Exception("Trials exceeded")
    
    system = System(result)
    system.box_vectors[0, 0] = size[0]
    system.box_vectors[1, 1] = size[1]
    system.box_vectors[2, 2] = size[2]
    return system
1005350
def createCellsFixedNum (self):
        ''' '''
        from .. import sim

        cells = []
        self.rand.Random123(self.tags['numCells'], sim.net.lastGid, sim.cfg.seeds['loc'])
        self.rand.uniform(0, 1)
        vec = h.Vector(self.tags['numCells']*3)
        vec.setrand(self.rand)
        randLocs = np.array(vec).reshape(self.tags['numCells'], 3)  # create random x,y,z locations

        if sim.net.params.shape == 'cylinder':
            # Use the x,z random vales 
            rho = randLocs[:,0] # use x rand value as the radius rho in the interval [0, 1)
            phi = 2 * pi * randLocs[:,2] # use z rand value as the angle phi in the interval [0, 2*pi) 
            x = (1 + sqrt(rho) * cos(phi))/2.0
            z = (1 + sqrt(rho) * sin(phi))/2.0
            randLocs[:,0] = x
            randLocs[:,2] = z
    
        elif sim.net.params.shape == 'ellipsoid':
            # Use the x,y,z random vales 
            rho = np.power(randLocs[:,0], 1.0/3.0) # use x rand value as the radius rho in the interval [0, 1); cuberoot
            phi = 2 * pi * randLocs[:,1] # use y rand value as the angle phi in the interval [0, 2*pi) 
            costheta = (2 * randLocs[:,2]) - 1 # use z rand value as cos(theta) in the interval [-1, 1); ensures uniform dist 
            theta = arccos(costheta)  # obtain theta from cos(theta)
            x = (1 + rho * cos(phi) * sin(theta))/2.0
            y = (1 + rho * sin(phi) * sin(theta))/2.0
            z = (1 + rho * cos(theta))/2.0 
            randLocs[:,0] = x
            randLocs[:,1] = y
            randLocs[:,2] = z
        
        for icoord, coord in enumerate(['x', 'y', 'z']):
            if coord+'Range' in self.tags:  # if user provided absolute range, convert to normalized
                self.tags[coord+'normRange'] = [float(point) / getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']]
            # constrain to range set by user
            if coord+'normRange' in self.tags:  # if normalized range, rescale random locations
                minv = self.tags[coord+'normRange'][0] 
                maxv = self.tags[coord+'normRange'][1] 
                randLocs[:,icoord] = randLocs[:,icoord] * (maxv-minv) + minv

        for i in self._distributeCells(int(sim.net.params.scale * self.tags['numCells']))[sim.rank]:
            gid = sim.net.lastGid+i
            self.cellGids.append(gid)  # add gid list of cells belonging to this population - not needed?
            cellTags = {k: v for (k, v) in self.tags.items() if k in sim.net.params.popTagsCopiedToCells}  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['pop'] = self.tags['pop']
            cellTags['xnorm'] = randLocs[i,0] # set x location (um)
            cellTags['ynorm'] = randLocs[i,1] # set y location (um)
            cellTags['znorm'] = randLocs[i,2] # set z location (um)
            cellTags['x'] = sim.net.params.sizeX * randLocs[i,0] # set x location (um)
            cellTags['y'] = sim.net.params.sizeY * randLocs[i,1] # set y location (um)
            cellTags['z'] = sim.net.params.sizeZ * randLocs[i,2] # set z location (um)            
            if 'spkTimes' in self.tags:  # if VecStim, copy spike times to params
                if isinstance(self.tags['spkTimes'][0], list):
                    try:
                        cellTags['params']['spkTimes'] = self.tags['spkTimes'][i] # 2D list
                    except:
                        pass
                else:
                    cellTags['params']['spkTimes'] = self.tags['spkTimes'] # 1D list (same for all)
            cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object

            if sim.cfg.verbose: print(('Cell %d/%d (gid=%d) of pop %s, on node %d, '%(i, sim.net.params.scale * self.tags['numCells']-1, gid, self.tags['pop'], sim.rank)))
        sim.net.lastGid = sim.net.lastGid + self.tags['numCells'] 
        return cells
77010
def makeLys(segID, N, CA, C, O, geo):
    ''''''
    ##R-Group
    CA_CB_length=geo.CA_CB_length
    C_CA_CB_angle=geo.C_CA_CB_angle
    N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle

    CB_CG_length=geo.CB_CG_length
    CA_CB_CG_angle=geo.CA_CB_CG_angle
    N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle

    CG_CD_length=geo.CG_CD_length
    CB_CG_CD_angle=geo.CB_CG_CD_angle
    CA_CB_CG_CD_diangle=geo.CA_CB_CG_CD_diangle

    CD_CE_length=geo.CD_CE_length
    CG_CD_CE_angle=geo.CG_CD_CE_angle
    CB_CG_CD_CE_diangle=geo.CB_CG_CD_CE_diangle

    CE_NZ_length=geo.CE_NZ_length
    CD_CE_NZ_angle=geo.CD_CE_NZ_angle
    CG_CD_CE_NZ_diangle=geo.CG_CD_CE_NZ_diangle
    
    carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)
    CB= Atom("CB", carbon_b, 0.0 , 1.0, " "," CB", 0,"C")
    carbon_g= calculateCoordinates(N, CA, CB, CB_CG_length, CA_CB_CG_angle, N_CA_CB_CG_diangle)
    CG= Atom("CG", carbon_g, 0.0, 1.0, " ", " CG", 0, "C")
    carbon_d= calculateCoordinates(CA, CB, CG, CG_CD_length, CB_CG_CD_angle, CA_CB_CG_CD_diangle)
    CD= Atom("CD", carbon_d, 0.0, 1.0, " ", " CD", 0, "C")
    carbon_e= calculateCoordinates(CB, CG, CD, CD_CE_length, CG_CD_CE_angle, CB_CG_CD_CE_diangle)
    CE= Atom("CE", carbon_e, 0.0, 1.0, " ", " CE", 0, "C")
    nitrogen_z= calculateCoordinates(CG, CD, CE, CE_NZ_length, CD_CE_NZ_angle, CG_CD_CE_NZ_diangle)
    NZ= Atom("NZ", nitrogen_z, 0.0, 1.0, " ", " NZ", 0, "N")

    ##Create Residue Data Structure
    res= Residue((' ', segID, ' '), "LYS", '    ')
    res.add(N)
    res.add(CA)
    res.add(C)
    res.add(O)
    res.add(CB)
    res.add(CG)
    res.add(CD)
    res.add(CE)
    res.add(NZ)
    return res
684145
def rand(self, unique_pstates, random_state=None):
        
        self._init_pstates(unique_pstates)
        self._init_random(random_state=random_state)
        self._compute_marginals()
        return self
176762
def makeMet(segID, N, CA, C, O, geo):
    ''''''
    ##R-Group
    CA_CB_length=geo.CA_CB_length
    C_CA_CB_angle=geo.C_CA_CB_angle
    N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle

    CB_CG_length=geo.CB_CG_length
    CA_CB_CG_angle=geo.CA_CB_CG_angle
    N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
    
    CG_SD_length=geo.CG_SD_length
    CB_CG_SD_angle=geo.CB_CG_SD_angle
    CA_CB_CG_SD_diangle=geo.CA_CB_CG_SD_diangle
    
    SD_CE_length=geo.SD_CE_length
    CG_SD_CE_angle=geo.CG_SD_CE_angle
    CB_CG_SD_CE_diangle=geo.CB_CG_SD_CE_diangle
    
    carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)
    CB= Atom("CB", carbon_b, 0.0 , 1.0, " "," CB", 0,"C")
    carbon_g= calculateCoordinates(N, CA, CB, CB_CG_length, CA_CB_CG_angle, N_CA_CB_CG_diangle)
    CG= Atom("CG", carbon_g, 0.0, 1.0, " ", " CG", 0, "C")
    sulfur_d= calculateCoordinates(CA, CB, CG, CG_SD_length, CB_CG_SD_angle, CA_CB_CG_SD_diangle)
    SD= Atom("SD", sulfur_d, 0.0, 1.0, " ", " SD", 0, "S")
    carbon_e= calculateCoordinates(CB, CG, SD, SD_CE_length, CG_SD_CE_angle, CB_CG_SD_CE_diangle)
    CE= Atom("CE", carbon_e, 0.0, 1.0, " ", " CE", 0, "C")

    ##Create Residue Data Structure
    res= Residue((' ', segID, ' '), "MET", '    ')
    res.add(N)
    res.add(CA)
    res.add(C)
    res.add(O)
    res.add(CB)
    res.add(CG)
    res.add(SD)
    res.add(CE)
    return res
781567
def refill_random(self):
        '''  '''
        self.random_umis = np.random.choice(
            list(self.umis.keys()), self.random_fill_size, p=self.prob)
        self.random_ix = 0
773567
def create_model(self):
        
        properties = {
            'name': self.name,
            'default_flux_limit': 1000
        }

        # Load objective as biomass reaction
        objective = self.get_active_objective()
        if objective is not None:
            reactions = dict(objective.reactions)
            if len(reactions) == 1:
                reaction, value = next(iteritems(reactions))
                if ((value < 0 and objective.type == 'minimize') or
                        (value > 0 and objective.type == 'maximize')):
                    properties['biomass'] = reaction

        model = NativeModel(properties)

        # Load compartments into model
        for compartment in self.compartments:
            model.compartments.add_entry(compartment)

        # Load compounds into model
        for compound in self.species:
            model.compounds.add_entry(compound)

        # Load reactions into model
        for reaction in self.reactions:
            model.reactions.add_entry(reaction)

        # Create model reaction set
        for reaction in model.reactions:
            model.model[reaction.id] = None

        # Convert reaction limits properties to proper limits
        for reaction in model.reactions:
            props = reaction.properties
            if 'lower_flux' in props or 'upper_flux' in props:
                lower = props.get('lower_flux')
                upper = props.get('upper_flux')
                model.limits[reaction.id] = reaction.id, lower, upper

        # Load model limits from FBC V1 bounds if present, i.e. if FBC V1 is
        # used instead of V2.
        limits_lower = {}
        limits_upper = {}
        for bounds in self.flux_bounds:
            reaction = bounds.reaction
            if reaction in model.limits:
                continue

            if bounds.operation == SBMLFluxBoundEntry.LESS_EQUAL:
                if reaction not in limits_upper:
                    limits_upper[reaction] = bounds.value
                else:
                    raise ParseError(
                        'Conflicting bounds for {}'.format(reaction))
            elif bounds.operation == SBMLFluxBoundEntry.GREATER_EQUAL:
                if reaction not in limits_lower:
                    limits_lower[reaction] = bounds.value
                else:
                    raise ParseError(
                        'Conflicting bounds for {}'.format(reaction))
            elif bounds.operation == SBMLFluxBoundEntry.EQUAL:
                if (reaction not in limits_lower and
                        reaction not in limits_upper):
                    limits_lower[reaction] = bounds.value
                    limits_upper[reaction] = bounds.value
                else:
                    raise ParseError(
                        'Conflicting bounds for {}'.format(reaction))

        for reaction in model.reactions:
            if reaction.id in limits_lower or reaction.id in limits_upper:
                lower = limits_lower.get(reaction.id, None)
                upper = limits_upper.get(reaction.id, None)
                model.limits[reaction.id] = reaction.id, lower, upper

        return model
46699
def random_product(*args, repeat=1):
    ""
    pools = [tuple(pool) for pool in args] * repeat
    return tuple(random.choice(pool) for pool in pools)
589221
def make_random(cls):
        """"""
        self = object.__new__(cls)
        self.rank = Rank.make_random()
        self.suit = Suit.make_random()
        return self
373850
def _adjust_stoichiometry(self):
        
        num_O = len(list(self.particles_by_name('O')))
        num_Si = len(list(self.particles_by_name('Si')))
        n_deletions = num_O - 2*num_Si

        bottom_Os = [atom for atom in self.particles()
                     if atom.name == 'O' and
                        atom.pos[2] < self._O_buffer and
                        len(self.bond_graph.neighbors(atom)) == 1]

        for _ in range(n_deletions):
            O1 = random.choice(bottom_Os)
            bottom_Os.remove(O1)
            self.remove(O1)
823246
def random(cls):
        
        r1, r2, r3 = np.random.random(3)

        q1 = sqrt(1.0 - r1) * (sin(2 * pi * r2))
        q2 = sqrt(1.0 - r1) * (cos(2 * pi * r2))
        q3 = sqrt(r1)       * (sin(2 * pi * r3))
        q4 = sqrt(r1)       * (cos(2 * pi * r3))

        return cls(q1, q2, q3, q4)
159596
def get_random(min_pt, max_pt):
        """"""
        result = Point(random.random(), random.random())
        return result.get_component_product(max_pt - min_pt) + min_pt
1242795
def make_data(n,width):
    """"""
    x = dict([(i,100*random.random()) for i in range(1,n+1)])
    y = dict([(i,100*random.random()) for i in range(1,n+1)])
    c = {}
    for i in range(1,n+1):
        for j in range(1,n+1):
            if j != i:
                c[i,j] = distance(x[i],y[i],x[j],y[j])

    e = {1:0}
    l = {1:0}
    start = 0
    delta = int(76.*math.sqrt(n)/n * width)+1
    for i in range(1,n):
        j = i+1
        start += c[i,j]
        e[j] = max(start-delta,0)
        l[j] = start + delta

    return c,x,y,e,l
1371213
def create_random_ind_grow(self, depth=0):
        ""
        lst = []
        self._depth = depth
        self._create_random_ind_grow(depth=depth, output=lst)
        return lst
719580
def createRandomObjects(self,
                          numObjects,
                          numPoints,
                          numLocations=None,
                          numFeatures=None):
    
    if numObjects > 0:
      if numLocations is None:
        numLocations = numPoints
      if numFeatures is None:
        numFeatures = numPoints

      assert(numPoints <= numLocations), ("Number of points in object cannot be "
            "greater than number of locations")

      locationArray = numpy.array(range(numLocations))
      numpy.random.seed(self.seed)
      for _ in xrange(numObjects):
        # Permute the number of locations and select points from it
        locationArray = numpy.random.permutation(locationArray)
        self.addObject(
          [(locationArray[p],
            numpy.random.randint(0, numFeatures)) for p in xrange(numPoints)],
        )
115516
def make_population(population_size, solution_generator, *args, **kwargs):
    """"""
    return [
        solution_generator(*args, **kwargs) for _ in range(population_size)
    ]
708339
def random_sample(self, elements=('a', 'b', 'c'), length=None):
        
        return self.random_elements(elements, length, unique=True)