Best Python code snippet using pyatom_python
evolve.py
Source:evolve.py  
...192		if (not all([(isinstance(x, list) or isinstance(x, tuple)) and (len(x)==2) for x in indices])) and (len(indices) == 2):193			indices = [indices]194		assert all([(isinstance(x, list) or isinstance(x, tuple)) and (len(x)==2) for x in indices])195		return [self.sequences[g, c] for g, c in indices]196	def _generateChildren(self, generation_index, verbose=0, firstChild=0):197		# parallel generation of children within a single generation198		# call recombine survivors here since natural variation should not199		# replace structures from recombination...200		firstParent = self._propogateParent201		if firstParent: firstParent = self.parent202		with Parallel(backend='loky', n_jobs=self._nThreads, verbose=verbose) as parallel:203			results = parallel(delayed(_variationKernel)204				(205					filenames=self._findSurvivors(generation_index-1),206					workdir=self._workdir,207					generation_index=generation_index, 208					child_index=i, 209					sites=self._sites, 210					# seq_db=self.sequences, 211					# score_db=self.scores,212					mutationOpts={213						'degree': self._mutationDegree,214						'library': self._library,215					}, 216					refinementOpts=self._refinementOpts, 217					optimizationOpts=self._optimizationOpts, 218					retain_models=self._retain_models,219					percentRecombination=self._percentRecombination,220					firstParent=firstParent221				) for i in range(firstChild, self._nChildren)222			)223			scores = []224			sequences = []225			for result in results:226				scores.append(result[0])227				sequences.append(result[1])228			self.scores[generation_index, firstChild:] = scores229			self.sequences[generation_index, firstChild:] = sequences230		with open(self._checkpoint, 'wb') as h:231			p.dump(self, h)232		return233	def _findSurvivors(self, generation_index):234		k = self._boltzmannFactor235		if generation_index < 0:236			return [self.parent]237		elif k > 0.:238			try:239				scores = self.scores[generation_index, :]240				p = boltzmann_p(scores, k=k)241				order = np.argsort(p)[::-1]242				total = np.asarray([np.sum(p[0:i+1]) for i in order], dtype=float)243				last_order_idx = np.argwhere(total >= self._survivalCutoff)[0][0]244				survivors = [order[i] for i in range(last_order_idx+1)]245				survivors = [mutant_filename_constructor(self._workdir, generation_index, x) for x in survivors]246				return survivors247			except:248				print('WARNING: could not calculate Boltzmann probabilities, only propagating most fit sequence')249				scores = self.scores[generation_index, :]250				indmin = np.argmin(scores)251				return [mutant_filename_constructor(self._workdir, generation_index, indmin)]252		elif k <= 0.:253			scores = self.scores[generation_index, :]254			indmin = np.argmin(scores)255			return [mutant_filename_constructor(self._workdir, generation_index, indmin)]256	def run(self, verbose=0):257		# if reset:258		# 	self.survivors = [self.parent]259		for i in range(self._nGenerations):260			if verbose != 0:261				print('*** Protean:Evolve - Generating and Evaluating Children for Generation %d ***' % (i))262			self._generateChildren(generation_index=i)263			# if verbose:264			# 	print('*** Protean:Evolve - Identifying Survivors for Generation %d ***' % i)265			# survivors = self._findSurvivors(generation_index=i)266		if verbose != 0:267			print('*** Protean:Evolve - Genetic Algorithm Complete! ***')268		self._notRun = False269		return270	def restart(self, verbose=0, generation_index=None, child_index=None):271		if generation_index is None:272			genMask = [any([x is None for x in self.sequences[i,:]]) for i in range(self._nGenerations)]273			genIdx = [i for i, flag in enumerate(genMask) if flag][0]274		else:275			genIdx = generation_index276		if child_index is None:277			childMask = [self.sequences[genIdx, j] is None for j in range(self._nChildren)]278			childIdx = [i for i, flag in enumerate(childMask) if flag][0]279		else:280			childIdx = child_index281		for i in range(genIdx, self._nGenerations):282			if verbose != 0:283				print('*** Protean:Evolve - Generating and Evaluating Children for Generation %d ***' % (i))284			if i == genIdx:285				self._generateChildren(generation_index=i, firstChild=childIdx)286			else:287				self._generateChildren(generation_index=i)288		if verbose != 0:289			print('*** Protean:Evolve - Genetic Algorithm Complete! ***')290		self._notRun = False291		return292	def p(self):293		p = boltzmann_p(self.scores[:,:], k=self._boltzmannFactor)294		return p295	def rank(self, n=0):296		# p = self.p(T=T)297		scores = self.scores298		order = np.argsort(scores, axis=None)#[::-1]299		indices = [(i, j) for i, j in zip(*np.unravel_index(order, dims=scores.shape))]300		if n <= 0:301			return indices...DecisionTree.py
Source:DecisionTree.py  
...93			self.classification = self.targetPlus94		else:95			self.classification = self.targetMinus96		# generateChildren can return all None if no children generated97		(branchAttr, children) = self._generateChildren()98		self.branchAttr		   = branchAttr # attribute for this node's split,99		self.children 		   = children	# dict mapping attr val to correct branch100											# children are also Node objs101	#=================================================================102	# Generating children and helpers103	#=================================================================104	def _entropy(self, examples):105		"""calculate entropy of examples: H(Y)106			returns float"""107		nElems = float(len(examples))108		nPlusElems  = sum( [1 for e in examples if (e[self.targetKey] == self.targetPlus)] )109		nMinusElems = nElems - nPlusElems110		probP = nPlusElems / nElems111		probM = nMinusElems / nElems112		# dealing with case of zero prob113		# entropy is 0 as one prob is 0 then the other is 1114		# and log2(1) = 0115		if (probM < FLOAT_EPSILON) or (probP< FLOAT_EPSILON):116			return 0.0117		return -probP * math.log(probP, 2) - probM * math.log(probM, 2)118	def _condEntropy(self, examples, attr):119		"""calculate conditional entropy of examples: H(Y|A)120			returns float"""121		nElems = float(len(examples))122		splitExamples = self._split(examples, attr)123		# calculate entropy conditioned on attr values124		condEntropy = 0.0125		for val in splitExamples:126			probVal = len(splitExamples[val]) / nElems127			entropyCondOnVal = self._entropy(splitExamples[val])128			condEntropy += probVal * entropyCondOnVal129		return condEntropy130	def _mutualInfo(self, examples, attr):131		"""determine the mutual information between the examples and the given attribute.132			I(Y;A) = H(Y) - H(Y|A) where Y is examples (data) and A is attribute. 133			returns float"""134		return self._entropy(examples) - self._condEntropy(examples, attr)135	def _split(self, examples, attr):136		"""split the examples on an attribute's values (v1, v2, ...)137			returns {v1 : examples_v1, v2 : examples_v2, ...} """138		# split examples by attr values139		splitExamples = {}140		for ex in examples:141			val = ex[self.attrKey][attr]142			# add val as key in split examples143			if val not in splitExamples:144				splitExamples[val] = []145			# add example to split by attr val146			splitExamples[val].append(ex)147		return splitExamples148	def _generateChildren(self):149		"""generate child nodes based on maximizing information gain.150			Returns (branchAttr, children) whose values can be None if no split"""151		# no children generated if at max depth or no more training examples or no more attributes152		if ( (self.depth == self.maxDepth) or (len(self.examples) == 0) or 153			 (len(self.examples[0][self.attrKey]) == 0) ):154			return (None, None)155		# find attribute to branch on156		maxMutualInfo = 0.0 # mutual info is pos for these cases157		maxAttr = None158		# know at least one example from above conditional159		for attr in self.examples[0][self.attrKey]:160			mutualInfo = self._mutualInfo(self.examples, attr)161			# update maximum162			if mutualInfo >= maxMutualInfo:...test.py
Source:test.py  
...27					'restraintConstant': 5.0*unit.kilojoules/(unit.angstrom**2)28	}29	evolver = Evolve(parent=pdbfile, nGenerations=5, nChildren=5, atom_indices=indices, nThreads=1,30		optimizationOpts=optimizationOpts)31	# evolver._generateChildren(0, verbose=50)32	# survivors = evolver._findSurvivors(0)33	# print('These children survive:')34	# print(survivors)35	evolver.run(verbose=50)36	p.dump(evolver, open('evolver_object.p', 'wb'))37# if __name__ is "__main__":38# 	evolver = main()39# 	scores = evolver.scores[:,:]40# 	p = boltzmann_p(scores)41# 	idx = np.argmax(p)42# 	idx = np.unravel_index(idx, scores.shape)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
