code stringlengths 1 18.2k |
|---|
def next_state_fluent_ordering(self) -> List[str]: '''The list of next state-fluent names in canonical order. Returns: List[str]: A list of fluent names. ''' key = lambda x: x.name return [cpf.name for cpf in sorted(self.state_cpfs, key=key)] |
def send(self): """ self.data format: {metric_name: [(t1, val1), (t2, val2)]} """ buf_sz = 500 to_send = {} for mn in self.data.iterkeys(): while len(self.data[mn]) > 0: l = len(to_send) if l < buf_sz: to_send.setdefault(mn, []) to_send[mn].append(self.data[mn].pop()) else: try: self._send(to_send) to_send = {} to_send... |
def DKL(arrays): """ Compute the Kullback-Leibler divergence from one distribution Q to another P, where Q and P are represented by a set of samples. Parameters ---------- arrays: tuple(1D numpy.array,1D numpy.array) samples defining distributions P & Q respectively Returns ------- float: Kullback Leibler divergence. "... |
def compute_dkl(fsamps, prior_fsamps, **kwargs): """ Compute the Kullback Leibler divergence for function samples for posterior and prior pre-calculated at a range of x values. Parameters ---------- fsamps: 2D numpy.array Posterior function samples, as computed by :func:`fgivenx.compute_samples` prior_fsamps: 2D numpy.... |
cache.save(fsamps, prior_fsamps, dkls) return dkls |
def current_site_url(): """Returns fully qualified URL (no trailing slash) for the current site.""" protocol = getattr(settings, 'MY_SITE_PROTOCOL', 'https') port = getattr(settings, 'MY_SITE_PORT', '') url = '%s://%s' % (protocol, settings.SITE_DOMAIN) if port: url += ':%s' % port return url |
def record(self, person, event, properties=None, timestamp=None, path=KISSmetrics.RECORD_PATH): """Record `event` for `person` with any `properties`. :param person: the individual performing the `event` :param event: the `event` name that was performed :param properties: any additional data to include :type properties:... |
def set(self, person, properties=None, timestamp=None, path=KISSmetrics.SET_PATH): """Set a property (or properties) for a `person`. :param person: individual to associate properties with :param properties: key-value pairs to associate with `person` :type properties: dict :param timestamp: when the `event` was performe... |
def alias(self, person, identity, path=KISSmetrics.ALIAS_PATH): """Map `person` to `identity`; actions done by one resolve to other. :param person: consider as same individual ``identity``; the source of the alias operation :type person: str or unicode :param identity: consider as an alias of ``person``; the target of ... |
to use a session identifier or any other value that is not relatively stable (a value that will not change per request or per session). For more information see the API Specifications on `Aliasing <http://support.kissmetrics.com/apis/specifications.html#aliasing-users>`_. """ this_request = request.alias(self.key, pers... |
def CopyRecord(record, **field_overrides): """Copies a record and its fields, recurses for any field that is a Record. For records that have nested mutable fields, use copy.deepcopy. Args: record: A Record instance to be copied. **field_overrides: Fields and their values to override in the new copy. Returns: A copy of ... |
def saveAs(self, path): """ save to file under given name """ if not path: path = self._dialogs.getSaveFileName(filter='*.csv') if path: self._setPath(path) with open(str(self._path), 'wb') as stream: writer = csv.writer(stream) table = self.table() for row in table: writer.writerow(row) |
def _textToTable(self, text, separator='\t'): """ format csv, [[...]], ((..)) strings to a 2d table """ table = None if text.startswith('[[') or text.startswith('(('): try: # maybe it's already formated as a list e.g. "[['1','2'],[...]]" # check it: t = eval(text) # has to be a 2d-list: if isinstance(t, list) and isins... |
def main(): """The main function of the module. These are the steps: 1. Reads the population file (:py:func:`readPopulations`). 2. Extract the MDS data (:py:func:`extractData`). 3. Plots the MDS data (:py:func:`plotMDS`). """ # Getting and checking the options args = parseArgs() checkArgs(args) # Reads the population f... |
def readPopulations(inputFileName): """Reads a population file. :param inputFileName: the name of the population file. :type inputFileName: str :returns: a :py:class:`dict` of population for each of the samples. """ populations = {} with open(inputFileName, "r") as inputFile: for line in inputFile: row = line.rstrip("\... |
def plotMDS(data, theOrders, theLabels, theColors, theSizes, theMarkers, options): """Plot the MDS data. :param data: the data to plot (MDS values). :param theOrders: the order of the populations to plot. :param theLabels: the names of populations to plot. :param theColors: the colors of the populations to plot. :param... |
fig.add_subplot(111) # The plot plotObject = [] labels = [] for i, index in enumerate(theOrders): tmp, = ax.plot(data[0][index], data[1][index], theMarkers[i], color=theColors[i], mec=theColors[i], markersize=theSizes[i]) plotObject.append(tmp) labels.append(theLabels[index]) # The legend prop = mpl.font_manager.FontPr... |
def extractData(fileName, populations): """Extract the C1 and C2 columns for plotting. :param fileName: the name of the MDS file. :param populations: the population of each sample in the MDS file. :type fileName: str :type fileName: dict :returns: the MDS data with information about the population of each sample. The f... |
= len(possibleLabels) c1 = [[] for i in xrange(nbPossibleLabels)] c2 = [[] for i in xrange(nbPossibleLabels)] with open(fileName, 'r') as inputFile: headerIndex = None for i, line in enumerate(inputFile): row = createRowFromPlinkSpacedOutput(line) if i == 0: # This is the header headerIndex = dict([(row[j], j) for j in... |
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t... |
def parseArgs(): # pragma: no cover """Parses the command line options and arguments. :returns: A :py:class:`argparse.Namespace` object created by the :py:mod:`argparse` module. It contains the values of the different options. ===================== ====== ========================================= Options Type Descripti... |
required=True, help="The MBS file.") parser.add_argument("--population-file", type=str, metavar="FORMAT", required=True, help="A file containing population information. " "There must be three columns: famID, indID " "and population information.") # The graphical options group = parser.add_argument_group("Graphical Opti... |
def addCustomOptions(parser): """Adds custom options to a parser. :param parser: the parser. :type parser: argparse.parser """ parser.add_argument("--format", type=str, metavar="FORMAT", default="png", choices=["png", "ps", "pdf", "X11"], help="The output file format (png, ps, pdf, or X11 " "formats are available). [de... |
def list(self, options=None, **kwds): """ Endpoint: /activities[/<options>]/list.json Returns a list of Activity objects. The options parameter can be used to narrow down the activities. Eg: options={"type": "photo-upload"} """ option_string = self._build_option_string(options) activities = self._client.get("/activitie... |
def view(self, activity, **kwds): """ Endpoint: /activity/<id>/view.json Requests all properties of an activity. Returns the requested activity object. """ result = self._client.get("/activity/%s/view.json" % self._extract_id(activity), **kwds)["result"] # TBD: Why is the result enclosed/encoded like this? result = res... |
def _generate_placeholder(readable_text=None): """Generate a placeholder name to use while updating WeldObject. Parameters ---------- readable_text : str, optional Appended to the name for a more understandable placeholder. Returns ------- str Placeholder. """ name = '_interm_' + str(Cache._counter) Cache._counter += 1... |
def cache_intermediate_result(cls, result, readable_name=None): """Add result to the cached data. Parameters ---------- result : LazyResult Data to cache. readable_name : str Will be used when generating a name for this intermediate result. Returns ------- str A generated placeholder name uniquely identifying this inte... |
def create_fake_array_input(cls, dependency, readable_name, index=None): """Create fake Weld inputs to be used in future WeldObjects. Parameters ---------- dependency : str The Weld input name of the actual intermediate result, obtained from cache_intermediate_result. readable_name : str User-friendly string that will ... |
assert dependency in Cache._intermediate_results assert isinstance(readable_name, str) name = Cache._generate_placeholder(readable_name) if index is None: fake_weld_input = _FakeArray(dependency, name) else: assert isinstance(index, tuple) fake_weld_input = _FakeStructMember(dependency, index, name) return fake_weld_in... |
def cache_fake_input(cls, weld_input_id, fake_weld_input): """Cache the fake Weld input to be seen by LazyResult.evaluate Parameters ---------- weld_input_id : str Generated when registering the fake_weld_input in WeldObject.update. fake_weld_input : _FakeWeldInput The fake Weld input previously generated by create_fak... |
def get(cls, key): """Retrieve a fake Weld input. Evaluate its intermediate result dependency if not yet done. Parameters ---------- key : str Weld input name previously obtained through create_fake_array_input. Returns ------- numpy.ndarray or tuple The corresponding data. """ assert isinstance(key, str) data = cls._c... |
def _add_advices(target, advices): """Add advices on input target. :param Callable target: target from where add advices. :param advices: advices to weave on input target. :type advices: routine or list. :param bool ordered: ensure advices to add will be done in input order """ interception_fn = _get_function(target) t... |
def _remove_advices(target, advices, ctx): """Remove advices from input target. :param advices: advices to remove. If None, remove all advices. """ # if ctx is not None if ctx is not None: # check if intercepted ctx is ctx _, intercepted_ctx = get_intercepted(target) if intercepted_ctx is None or intercepted_ctx is not... |
def get_advices(target, ctx=None, local=False): """Get element advices. :param target: target from where get advices. :param ctx: ctx from where get target. :param bool local: If ctx is not None or target is a method, if True (False by default) get only target advices without resolving super target advices in a super c... |
targets intercepted_target, intercepted_ctx = get_intercepted(_target) # if ctx is not a class if not isclass(_target_ctx): if intercepted_ctx is _target_ctx: interception_fn = _get_function(_target) advices = getattr(interception_fn, _ADVICES, []) result += advices _target_ctx = _target_ctx.__class__ _target = getattr... |
getattr(_target_ctx, target_name, None) else: # else, intercepted_fn is _target function intercepted_fn = _get_function(_target) _target, _target_ctx = super_method( name=target_name, ctx=_target_ctx ) # if intercepted are different, stop iteration if intercepted_target is not intercepted_fn: break if local: # break if... |
def _namematcher(regex): """Checks if a target name matches with an input regular expression.""" matcher = re_compile(regex) def match(target): target_name = getattr(target, '__name__', '') result = matcher.match(target_name) return result return match |
def weave( target, advices, pointcut=None, ctx=None, depth=1, public=False, pointcut_application=None, ttl=None ): """Weave advices on target with input pointcut. :param callable target: target from where checking pointcut and weaving advices. :param advices: advices to weave on target. :param ctx: target ctx (class or... |
called target and its related function called function. Its result is the interception function. :param float ttl: time to leave for weaved advices. :return: the intercepted functions created from input target or a tuple with intercepted functions and ttl timer. :rtype: list :raises: AdviceError if pointcut is not None... |
right_msg = "Not {0}".format(type(pointcut)) raise AdviceError( "{0} {1} {2}".format(error_msg, advice_msg, right_msg) ) if ctx is None: ctx = find_ctx(elt=target) _weave( target=target, advices=advices, pointcut=pointcut, depth=depth, depth_predicate=_publiccallable if public else callable, ctx=ctx, intercepted=result... |
def _weave( target, advices, pointcut, ctx, depth, depth_predicate, intercepted, pointcut_application ): """Weave deeply advices in target. :param callable target: target from where checking pointcut and weaving advices. :param advices: advices to weave on target. :param ctx: target ctx (class or instance). :param poin... |
function called function. Its result is the interception function. """ # if weaving has to be done if pointcut is None or pointcut(target): # get target interception function interception_fn = _get_function(target) # does not handle not python functions if interception_fn is not None: # flag which specifies if poincut ... |
intercepted_ctx: # apply pointcut apply_poincut = True # and update interception_fn interception_fn = intercepted_fn # if weave has to be done if apply_poincut: # instantiate a new joinpoint if pointcut_application is None if pointcut_application is None: pointcut_application = _Joinpoint().apply_pointcut interception_... |
def unweave( target, advices=None, pointcut=None, ctx=None, depth=1, public=False, ): """Unweave advices on target with input pointcut. :param callable target: target from where checking pointcut and weaving advices. :param pointcut: condition for weaving advices on joinpointe. The condition depends on its type. :type ... |
# do nothing if pointcut is None or is callable if pointcut is None or callable(pointcut): pass # in case of str, use a name matcher elif isinstance(pointcut, string_types): pointcut = _namematcher(pointcut) else: error_msg = "Wrong pointcut to check weaving on {0}.".format(target) advice_msg = "Must be None, or be a s... |
def _unweave(target, advices, pointcut, ctx, depth, depth_predicate): """Unweave deeply advices in target.""" # if weaving has to be done if pointcut is None or pointcut(target): # do something only if target is intercepted if is_intercepted(target): _remove_advices(target=target, advices=advices, ctx=ctx) # search ins... |
def weave_on(advices, pointcut=None, ctx=None, depth=1, ttl=None): """Decorator for weaving advices on a callable target. :param pointcut: condition for weaving advices on joinpointe. The condition depends on its type. :param ctx: target ctx (instance or class). :type pointcut: - NoneType: advices are weaved on target.... |
def _compute_path(self, name): """ Compute the file path in the filesystem from the given name. :param name: the filename for which the to compute the path :raises FileNotWithinStorage: if the computed path is not within :attr:`base_directory`. """ path = self._normalize_path(os.path.join(self.base_directory, name)) if... |
def weld_groupby_aggregate_dictmerger(arrays, weld_types, by_indices, operation): """Groups by the columns in by. Parameters ---------- arrays : list of (numpy.ndarray or WeldObject) Entire DataFrame data. weld_types : list of WeldType Corresponding to data. by_indices : list of int Indices of which arrays to group by.... |
"""map( tovec( result( for( {arrays}, dictmerger[{by_types}, {column_types}, {operation}], |b: dictmerger[{by_types}, {column_types}, {operation}], i: i64, e: {all_types}| merge(b, {{{by_select}, {column_select}}}) ) ) ), |e: {{{by_types}, {column_types}}}| {res} )""" weld_obj.weld_code = weld_template.format(arrays=ob... |
def weld_groupby_aggregate(grouped_df, weld_types, by_indices, aggregation, result_type=None): """Perform aggregation on grouped data. Parameters ---------- grouped_df : WeldObject DataFrame which has been grouped through weld_groupby. weld_types : list of WeldType Corresponding to data. by_indices : list of int Indice... |
is None else [result_type for _ in column_weld_types] by_types = struct_of('{e}', by_weld_types) column_types = struct_of('{e}', column_weld_types) new_column_types = struct_of('{e}', new_column_weld_types) grouped_df_types = '{{{}, {}}}'.format(by_types, column_types) res = '{{{}}}'.format(', '.join(['e.$0.${}'.format... |
def asynloop(self, auto_connect=False, timeout=10, detached_delay=0.2): """ Non-blocking event loop consuming messages until connection is lost, or shutdown is requested. :param int timeout: number of secs for asyncore timeout :param float detached_delay: float secs to sleep when exiting asyncore loop and execution det... |
def main(argString=None): """Check for duplicated samples in a tfam/tped file. :param argString: the options :type argString: list Here are the steps for the duplicated samples step. 1. Prints the options. 2. Reads the ``tfam`` file (:py:func:`readTFAM`). 3. Separate the duplicated samples from the unique samples (:py:... |
8. Prints statistics (concordance and completion) (:py:func:`printStatistics`). 9. We print the concordance matrix for each duplicated samples (:py:func:`printConcordance`). 10. We print the ``tped`` and the ``tfam`` file for the duplicated samples (``prefix.duplicated_samples``) (:py:func:`printDuplicatedTPEDandTFAM`)... |
logger.info("Finding duplicated samples") uniqueSamples, duplicatedSamples = findDuplicates(tfam) # Prints the unique tfam logger.info("Creating TFAM for unique samples") printUniqueTFAM(tfam, uniqueSamples, args.out) # Process the TPED file logger.info("Reading TPED (and creating TPED for unique samples)") tped, tpedS... |
# Print the statistics logger.info("Printing the statistics") completion_percentage = printStatistics(completion, concordance, tpedSamples, duplicatedSamples, args.out) # Print the concordance file logger.info("Printing the concordance file") concordance_percentage = printConcordance(concordance, args.out) # Print the ... |
def addToTPEDandTFAM(tped, tfam, prefix, toAddPrefix): """Append a tfile to another, creating a new one. :param tped: the ``tped`` that will be appended to the other one. :param tfam: the ``tfam`` that will be appended to the other one. :param prefix: the prefix of all the files. :param toAddPrefix: the prefix of the f... |
``tfam`` variables need to contain at least one sample. """ # First, writing the chosen tped tpedFile = None try: tpedFile = open(prefix + ".chosen_samples.tped", "w") except IOError: msg = "%(prefix)s.chosen_samples.tped: can't write file" % locals() raise ProgramError(msg) for row in tped: print >>tpedFile, "\t".join... |
append" % locals() raise ProgramError(msg) for row in tfam: print >>newTFAM, "\t".join(row) newTFAM.close() # The final TPED file newTPED = None try: newTPED = open(prefix + ".final.tped", "w") except IOError: msg = "%(prefix)s.final.tped: can't write file" % locals() raise ProgramError(msg) try: with open(toAddPrefix ... |
def createAndCleanTPED(tped, tfam, samples, oldSamples, chosenSamples, prefix, completion, completionT, concordance, concordanceT): """Complete a TPED for duplicate samples. :param tped: the ``tped`` containing the duplicated samples. :param tfam: the ``tfam`` containing the duplicated samples. :param samples: the upda... |
dict :type concordanceT: float Using a ``tped`` containing duplicated samples, it creates a ``tped`` containing unique samples by completing a chosen sample with the other replicates. .. note:: A chosen sample is not completed using bad replicates (those that don't have a concordance or a completion higher than a certa... |
snpInfo = tped[:, :4] genotypes = tped[:, 4:] # Getting the completion and concordance indexes completionSampleID = {} concordanceSampleID = {} for sampleID, indexes in samples.iteritems(): # Checking the completion completionToKeep = np.where(completion[indexes] >= completionT)[0] completionToRemove = np.where(complet... |
curGenotypes[np.intersect1d(concordanceToKeep, completionToKeep)] # Removing the no call from the genotypes cleanedCurGenotype = curGenotypes[np.where(curGenotypes != "0 0")] # Checking the number of unique genotypes uniqueGenotypes = np.unique(cleanedCurGenotype) # Checking the number of unique genotypes (except 0 0) ... |
genotype to no call tped[i][chosenOne+4] = "0 0" print >>zeroedOutFile, "\t".join([sampleID[0], sampleID[1], snpInfo[i][1]]) else: # Do we want to complete the chosen sample's genotype??? pass # Writing the not good enough file for key, value in notGoodEnoughSamples.iteritems(): print >>notGoodEnoughFile, "\t".join(lis... |
def chooseBestDuplicates(tped, samples, oldSamples, completion, concordance_all, prefix): """Choose the best duplicates according to the completion rate. :param tped: the ``tped`` containing the duplicated samples. :param samples: the updated position of the samples in the tped containing only duplicated samples. :para... |
duplicated sample: 1. Sort the list of concordances. 2. Sort the list of completions. 3. Choose the best of the concordance and put in a set. 4. Choose the best of the completion and put it in a set. 5. Compute the intersection of the two sets. If there is one sample or more, then randomly choose one sample. 6. If the ... |
raise ProgramError(msg) print >>chosenFile, "\t".join(["origIndex", "dupIndex", "famID", "indID"]) excludedFile = None try: excludedFile = open(prefix + ".excluded_samples.info", "w") except IOError: msg = "%(prefix)s.excluded_samples.info: can't write file" % locals() raise ProgramError(msg) print >>excludedFile, "\t"... |
= None while nbToCheck <= len(indexes): # Getting the `nbToCheck` best value (higher to lower) completionValue = currCompletion[ sortedCompletionIndexes[nbToCheck*-1] ] concordanceValue = currConcordance[ sortedConcordanceIndexes[nbToCheck*-1] ] # Getting the indexes to consider completionToConsider = set( np.where(cur... |
sampleConcordance |
def printDuplicatedTPEDandTFAM(tped, tfam, samples, oldSamples, prefix): """Print the TPED and TFAM of the duplicated samples. :param tped: the ``tped`` containing duplicated samples. :param tfam: the ``tfam`` containing duplicated samples. :param samples: the updated position of the samples in the tped containing only... |
= len(tped[0][4:]) newTFAM = [0 for i in xrange(nbSamples)] for samples, indexes in samples.iteritems(): oldIndexes = oldSamples[samples] for i, index in enumerate(indexes): oldIndex = oldIndexes[i] newTFAM[index] = tfam[oldIndex] outputTFAM = None try: outputTFAM = open(prefix + ".duplicated_samples.tfam", "w") except... |
def printConcordance(concordance, prefix): """Print the concordance. :param concordance: the concordance of each sample. :param prefix: the prefix of all the files. :type concordance: dict :type prefix: str :returns: the concordance percentage (dict) The concordance is the number of genotypes that are equal when compar... |
"#%s\t%s" % key # Doing the division none_zero = concordance[key][1] != 0 true_concordance = np.zeros(np.multiply(*concordance[key][1].shape)) true_concordance[np.ravel(none_zero)] = np.true_divide( concordance[key][0][none_zero], concordance[key][1][none_zero], ) true_concordance.shape = concordance[key][1].shape true... |
def printStatistics(completion, concordance, tpedSamples, oldSamples, prefix): """Print the statistics in a file. :param completion: the completion of each duplicated samples. :param concordance: the concordance of each duplicated samples. :param tpedSamples: the updated position of the samples in the tped containing o... |
The output file containing the summary statistics (for each of the # duplicated samples, print the mean concordance and the completion). outputFile = None try: outputFile = open(prefix + ".summary", "w") except IOError: msg = "%(prefix)s.summary: can't write file" % locals() raise ProgramError(msg) print >>outputFile, ... |
np.mean(currConcordance) toPrint.append("%.8f" % currConcordance) print >>outputFile, "\t".join(toPrint) # Closing the output file outputFile.close() return completionPercentage |
def computeStatistics(tped, tfam, samples, oldSamples, prefix): """Computes the completion and concordance of each samples. :param tped: the ``tped`` containing duplicated samples. :param tfam: the ``tfam`` containing duplicated samples. :param samples: the updated position of the samples in the tped containing only du... |
is a female. .. note:: A missing genotype is encoded by ``0``. .. note:: No percentage is computed here, only the numbers. Percentages are computing in other functions: :py:func:`printStatistics`, for completion, and :py:func:`printConcordance`, for concordance. **Completion** Computes the completion of none zero value... |
For each marker, if both genotypes are not missing, we add one to the total number of compared markers. If both genotypes are the same, we add one to the number of concordant calls. We write the observed genotype difference in the file ``prefix.diff``. The concordance between sample :math:`i` and :math:`j` (*i.e.* :mat... |
"w") except IOError: msg = "%(prefix)s.diff: can't write file" % locals() raise ProgramError(msg) print >>diffOutput, "\t".join(["name", "famID", "indID", "dupIndex_1", "dupIndex_2", "genotype_1", "genotype_2"]) # The completion data type completion = np.array([[0 for i in xrange(len(tped[0][4:]))], [0 for i in xrange(... |
["23", "24"]): if ("0" not in genotype1) and (len(genotype1) != 2): completion[0][index] += 1 elif "0" not in genotype1: completion[0][index] += 1 completion[1][index] += 1 # Updating the concordance for j in xrange(i + 1, len(indexes)): genotype2 = set(genotype[indexes[j]].split(" ")) # This is for man on chr 23 and 2... |
== 1: # toPrint[-1] += " %s" % toPrint[-1] # toPrint.append(" ".join(genotype2)) # if len(genotype2) == 1: # toPrint[-1] += " %s" % toPrint[-1] # print >>diffOutput, "\t".join(toPrint) # # elif ("0" not in genotype1) and ("0" not in genotype2): if ("0" not in genotype1) and ("0" not in genotype2): # Both have calls con... |
i] = 1 return completion, concordance |
def processTPED(uniqueSamples, duplicatedSamples, fileName, prefix): """Process the TPED file. :param uniqueSamples: the position of unique samples. :param duplicatedSamples: the position of duplicated samples. :param fileName: the name of the file. :param prefix: the prefix of all the files. :type uniqueSamples: dict ... |
to file" % prefix + ".unique_samples.tped" raise ProgramError with open(fileName, 'r') as inputFile: for line in inputFile: row = line.rstrip("\r\n").split("\t") snpInfo = row[:4] genotype = row[4:] # Printing the new TPED file (unique samples only) print >>outputFile, "\t".join(snpInfo + [genotype[i] for i in uI]) # S... |
def printUniqueTFAM(tfam, samples, prefix): """Prints a new TFAM with only unique samples. :param tfam: a representation of a TFAM file. :param samples: the position of the samples :param prefix: the prefix of the output file name :type tfam: list :type samples: dict :type prefix: str """ fileName = prefix + ".unique_s... |
def findDuplicates(tfam): """Finds the duplicates in a TFAM. :param tfam: representation of a ``tfam`` file. :type tfam: list :returns: two :py:class:`dict`, containing unique and duplicated samples position. """ uSamples = {} dSamples = defaultdict(list) for i, row in enumerate(tfam): sampleID = tuple(row[:2]) if samp... |
def checkArgs(args): """Checks the arguments and options. :param args: a :py:class:`argparse.Namespace` object containing the options of the program. :type args: :py:class:`argparse.Namespace` :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`Prog... |
1)): msg = "sample-completion-threshold: must be between 0 and 1 " \ "(not %f)" % args.sample_completion_threshold raise ProgramError(msg) return True |
def default( self, o ): """If o is a datetime object, convert it to an ISO string. If it is an exception, convert it to a string. If it is a numpy int, coerce it to a Python int. :param o: the field to serialise :returns: a string encoding of the field""" if isinstance(o, datetime): # date/time, return an ISO formatted... |
def _load( self, fn ): """Retrieve the notebook from the given file. :param fn: the file name""" # if file is empty, create an empty notebook if os.path.getsize(fn) == 0: self._description = None self._results = dict() self._pending = dict() else: # load the JSON object with open(fn, "r") as f: s = f.read() # parse bac... |
def _patchDatetimeMetadata( self, res, mk ): """Private method to patch an ISO datetime string to a datetime object for metadata key mk. :param res: results dict :param mk: metadata key""" t = res[epyc.Experiment.METADATA][mk] res[epyc.Experiment.METADATA][mk] = dateutil.parser.parse(t) |
def patch( self ): """Patch the results dict. The default processes the :attr:`Experiment.START_TIME` and :attr:`Experiment.END_TIME` metadata fields back into Python `datetime` objects from ISO strings. This isn't strictly necessary, but it makes notebook data structure more Pythonic.""" for k in self._results.keys():... |
def _save( self, fn ): """Persist the notebook to the given file. :param fn: the file name""" # create JSON object j = json.dumps({ 'description': self.description(), 'pending': self._pending, 'results': self._results }, indent = 4, cls = MetadataEncoder) # write to file with open(fn, 'w') as f: f.write(j) |
def Barati_high(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_. .. math:: C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right] - 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4) -2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9.9867\}/Re) +0.1357\exp(-[(Re/1620)^2 ... |
Estimation of Drag Coefficient of Flow around a Smooth Sphere: An Evolutionary Approach." Powder Technology 257 (May 2014): 11-19. doi:10.1016/j.powtec.2014.02.045. ''' Cd = (8E-6*((Re/6530.)**2 + tanh(Re) - 8*log(Re)/log(10.)) - 0.4119*exp(-2.08E43/(Re+Re**2)**4) - 2.1344*exp(-((log(Re**2 + 10.7563)/log(10))**2 + 9.98... |
def Morsi_Alexander(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left\{ \begin{array}{ll} \frac{24}{Re} & \mbox{if $Re < 0.1$}\\ \frac{22.73}{Re}+\frac{0.0903}{Re^2} + 3.69 & \mbox{if $0.1 < Re < 1$}\\ \frac{29.1667}{Re}-\frac{3.8889}{Re^2} + 1.... |
was reviewed, and confirmed to contain the cited equations. Examples -------- >>> Morsi_Alexander(200) 0.7866 References ---------- .. [1] Morsi, S. A., and A. J. Alexander. "An Investigation of Particle Trajectories in Two-Phase Flow Systems." Journal of Fluid Mechanics 55, no. 02 (September 1972): 193-208. doi:10.101... |
< 1000: Cd = 98.33/Re - 2778./Re**2 + 0.3644 elif Re < 5000: Cd = 148.62/Re - 4.75E4/Re**2 + 0.357 elif Re < 10000: Cd = -490.546/Re + 57.87E4/Re**2 + 0.46 else: Cd = -1662.5/Re + 5.4167E6/Re**2 + 0.5191 return Cd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.