code
stringlengths
1
18.2k
def _input_as_paths(self, data): """ Return data as a space delimited string with each path quoted data: paths or filenames, most likely as a list of strings """ return self._command_delimiter.join( map(str, map(self._input_as_path, data)))
def _absolute(self, path): """ Convert a filename to an absolute path """ path = FilePath(path) if isabs(path): return path else: # these are both Path objects, so joining with + is acceptable return self.WorkingDir + path
def _get_base_command(self): """ Returns the full command string input_arg: the argument to the command which represents the input to the program, this will be a string, either representing input or a filename to get input from tI""" command_parts = [] # Append a change directory to the beginning of the command to chan...
def _error_on_missing_application(self, params): """ Raise an ApplicationNotFoundError if the app is not accessible This method checks in the system path (usually $PATH) or for the existence of self._command. If self._command is not found in either place, an ApplicationNotFoundError is raised to inform the user that th...
" characters, in case we got a FilePath object found_in_path = which(command.strip('"')) is not None if not (exists(command) or found_in_path): raise ApplicationNotFoundError("Cannot find %s. Is it installed? " "Is it in your path?" % command)
def getTmpFilename(self, tmp_dir=None, prefix='tmp', suffix='.txt', include_class_id=False, result_constructor=FilePath): """ Return a temp filename tmp_dir: directory where temporary files will be stored prefix: text to append to start of file name suffix: text to append to end of file name include_class_id: if True, ...
strings, you must use the + operator. If this causes trouble, you can pass str as the the result_constructor. """ # check not none if not tmp_dir: tmp_dir = self.TmpDir # if not current directory, append "/" if not already on path elif not tmp_dir.endswith("/"): tmp_dir += "/" if include_class_id: # Append the classnam...
return result_constructor(tmp_dir) + result_constructor(prefix) + \ result_constructor(''.join([choice(_all_chars) for i in range(self.TmpNameLen)])) +\ result_constructor(suffix)
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for category in orm['document_library.DocumentCategory'].objects.all(): category.slug = category.documentcategorytitle_set.all()[0].title.lower() category.save()
def get_accent_char(char): """ Get the accent of an single char, if any. """ index = utils.VOWELS.find(char.lower()) if (index != -1): return 5 - index % 6 else: return Accent.NONE
def get_accent_string(string): """ Get the first accent from the right of a string. """ accents = list(filter(lambda accent: accent != Accent.NONE, map(get_accent_char, string))) return accents[-1] if accents else Accent.NONE
def add_accent(components, accent): """ Add accent to the given components. The parameter components is the result of function separate() """ vowel = components[1] last_consonant = components[2] if accent == Accent.NONE: vowel = remove_accent_string(vowel) return [components[0], vowel, last_consonant] if vowel == "": r...
def add_accent_char(char, accent): """ Add accent to a single char. Parameter accent is member of class Accent """ if char == "": return "" case = char.isupper() char = char.lower() index = utils.VOWELS.find(char) if (index != -1): index = index - index % 6 + 5 char = utils.VOWELS[index - accent] return utils.change_ca...
def add_accent_at(string, accent, index): """ Add mark to the index-th character of the given string. Return the new string after applying change. (unused) """ if index == -1: return string # Python can handle the case which index is out of range of given string return string[:index] + \ accent.accent.add_accent_char(s...
def remove_accent_string(string): """ Remove all accent from a whole string. """ return utils.join([add_accent_char(c, Accent.NONE) for c in string])
def parse_command_line_parameters(argv=None): """ Parses command line arguments """ usage =\ 'usage: %prog [options] input_sequences_filepath' version = 'Version: %prog ' + __version__ parser = OptionParser(usage=usage, version=version) parser.add_option('-o', '--output_fp', action='store', type='string', dest='output_...
def assign_taxonomy( data, min_confidence=0.80, output_fp=None, training_data_fp=None, fixrank=True, max_memory=None, tmp_dir=tempfile.gettempdir()): """Assign taxonomy to each sequence in data with the RDP classifier data: open fasta file object or list of fasta lines confidence: minimum support threshold to assign ta...
is not None: app.Parameters['-t'].on(training_data_fp) if fixrank: app.Parameters['-f'].on('fixrank') else: app.Parameters['-f'].on('allrank') app_result = app(data) assignments = {} # ShortSequenceException messages are written to stdout # Tag these ID's as unassignable for line in app_result['StdOut']: excep = parse_...
def train_rdp_classifier( training_seqs_file, taxonomy_file, model_output_dir, max_memory=None, tmp_dir=tempfile.gettempdir()): """ Train RDP Classifier, saving to model_output_dir training_seqs_file, taxonomy_file: file-like objects used to train the RDP Classifier (see RdpTrainer documentation for format of training ...
def train_rdp_classifier_and_assign_taxonomy( training_seqs_file, taxonomy_file, seqs_to_classify, min_confidence=0.80, model_output_dir=None, classification_output_fp=None, max_memory=None, tmp_dir=tempfile.gettempdir()): """ Train RDP Classifier and assign taxonomy in one fell swoop The file objects training_seqs_fil...
model_output_dir is None: # Forum user reported an error on the call to os.rmtree: # https://groups.google.com/d/topic/qiime-forum/MkNe7-JtSBw/discussion # We were not able to replicate the problem and fix it # properly. However, even if an error occurs, we would like # to return results, along with a warning. try: rmt...
def parse_rdp_assignment(line): """Returns a list of assigned taxa from an RDP classification line """ toks = line.strip().split('\t') seq_id = toks.pop(0) direction = toks.pop(0) if ((len(toks) % 3) != 0): raise ValueError( "Expected assignments in a repeating series of (rank, name, " "confidence), received %s" % toks...
def _error_on_missing_application(self, params): """Raise an ApplicationNotFoundError if the app is not accessible In this case, checks for the java runtime and the RDP jar file. """ if not (os.path.exists('java') or which('java')): raise ApplicationNotFoundError( "Cannot find java runtime. Is it installed? Is it in yo...
def _get_jar_fp(self): """Returns the full path to the JAR file. If the JAR file cannot be found in the current directory and the environment variable RDP_JAR_PATH is not set, returns None. """ # handles case where the jar file is in the current working directory if os.path.exists(self._command): return self._command #...
def _get_base_command(self): """Returns the base command plus command-line options. Does not include input file, output file, and training set. """ cd_command = ''.join(['cd ', str(self.WorkingDir), ';']) jvm_command = "java" jvm_arguments = self._commandline_join( [self.Parameters[k] for k in self._jvm_parameters]) ja...
def _commandline_join(self, tokens): """Formats a list of tokens as a shell command This seems to be a repeated pattern; may be useful in superclass. """ commands = filter(None, map(str, tokens)) return self._command_delimiter.join(commands).strip()
def _get_result_paths(self, data): """ Return a dict of ResultPath objects representing all possible output """ assignment_fp = str(self.Parameters['-o'].Value).strip('"') if not os.path.isabs(assignment_fp): assignment_fp = os.path.relpath(assignment_fp, self.WorkingDir) return {'Assignments': ResultPath(assignment_fp...
def _get_base_command(self): """Returns the base command plus command-line options. Handles everything up to and including the classpath. The positional training parameters are added by the _input_handler_decorator method. """ cd_command = ''.join(['cd ', str(self.WorkingDir), ';']) jvm_command = "java" jvm_args = self...
def ModelDir(self): """Absolute FilePath to the training output directory. """ model_dir = self.Parameters['model_output_dir'].Value absolute_model_dir = os.path.abspath(model_dir) return FilePath(absolute_model_dir)
def _input_handler_decorator(self, data): """Adds positional parameters to selected input_handler's results. """ input_handler = getattr(self, self.__InputHandler) input_parts = [ self.Parameters['taxonomy_file'], input_handler(data), self.Parameters['training_set_id'], self.Parameters['taxonomy_version'], self.Paramet...
def _get_result_paths(self, output_dir): """Return a dict of output files. """ # Only include the properties file here. Add the other result # paths in the __call__ method, so we can catch errors if an # output file is not written. self._write_properties_file() properties_fp = os.path.join(self.ModelDir, self.Propertie...
def _write_properties_file(self): """Write an RDP training properties file manually. """ # The properties file specifies the names of the files in the # training directory. We use the example properties file # directly from the rdp_classifier distribution, which lists # the default set of files created by the applicati...
def delete_old_host(self, hostname): """Remove all records for the host. :param str hostname: Hostname to remove :rtype: bool """ host = Host(self.session, name=hostname) return host.delete()
def add_new_host(self, hostname, ipv4addr, comment=None): """Add or update a host in the infoblox, overwriting any IP address entries. :param str hostname: Hostname to add/set :param str ipv4addr: IP Address to add/set :param str comment: The comment for the record """ host = Host(self.session, name=hostname) if host.i...
def align_unaligned_seqs(seqs_fp, moltype=DNA, params=None, accurate=False): """Aligns unaligned sequences Parameters ---------- seqs_fp : string file path of the input fasta file moltype : {skbio.DNA, skbio.RNA, skbio.Protein} params : dict-like type It pass the additional parameter settings to the application. Defaul...
alignment = Alignment.read(res['StdOut'], constructor=moltype) # Clean up res.cleanUp() return alignment
def add_seqs_to_alignment(seqs_fp, aln_fp, moltype=DNA, params=None, accurate=False): """Returns an Alignment object from seqs and existing Alignment. The "--seed" option can be used for adding unaligned sequences into a highly reliable alignment (seed) consisting of a small number of sequences. Parameters ---------- s...
def align_two_alignments(aln1_fp, aln2_fp, moltype, params=None): """Returns an Alignment object from two existing Alignments. Parameters ---------- aln1_fp : string file path of 1st alignment aln2_fp : string file path of 2nd alignment params : dict of parameters to pass in to the Mafft app controller. Returns -------...
def _input_as_seqs(self, data): """Format a list of seq as input. Parameters ---------- data: list of strings Each string is a sequence to be aligned. Returns ------- A temp file name that contains the sequences. See Also -------- burrito.util.CommandLineApplication """ lines = [] for i, s in enumerate(data): # will nu...
def from_config(cls, config, name, section_key="segmenters"): """ Constructs a segmenter from a configuration doc. """ section = config[section_key][name] segmenter_class_path = section['class'] Segmenter = yamlconf.import_module(segmenter_class_path) return Segmenter.from_config(config, name, section_key=section_key)
def random_hex(length): """Generates a random hex string""" return escape.to_unicode(binascii.hexlify(os.urandom(length))[length:])
def password_hash(password, password_salt=None): """Hashes a specified password""" password_salt = password_salt or oz.settings["session_salt"] salted_password = password_salt + password return "sha256!%s" % hashlib.sha256(salted_password.encode("utf-8")).hexdigest()
def bisect(func, a, b, xtol=1e-12, maxiter=100): """ Finds the root of `func` using the bisection method. Requirements ------------ - func must be continuous function that accepts a single number input and returns a single number - `func(a)` and `func(b)` must have opposite sign Parameters ---------- func : function th...
assert sign(fa) != sign(fb) for i in xrange(maxiter): c = (a + b) / 2. fc = func(c) if fc == 0. or abs(b - a) / 2. < xtol: return c if sign(fc) == sign(func(a)): a = c else: b = c else: raise RuntimeError('Failed to converge after %d iterations.' % maxiter)
def parse_string(s): ''' Parses a foreign resource URL into the URL string itself and any relevant args and kwargs ''' matched_obj = SPLIT_URL_RE.match(s) if not matched_obj: raise URLParseException('Invalid Resource URL: "%s"' % s) url_string, arguments_string = matched_obj.groups() args_as_strings = URL_ARGUMENTS_RE....
def add_experiment(experiment): """Adds a new experiment""" redis = oz.redis.create_connection() oz.bandit.add_experiment(redis, experiment)
def archive_experiment(experiment): """Archives an experiment""" redis = oz.redis.create_connection() oz.bandit.Experiment(redis, experiment).archive()
def add_experiment_choice(experiment, choice): """Adds an experiment choice""" redis = oz.redis.create_connection() oz.bandit.Experiment(redis, experiment).add_choice(choice)
def remove_experiment_choice(experiment, choice): """Removes an experiment choice""" redis = oz.redis.create_connection() oz.bandit.Experiment(redis, experiment).remove_choice(choice)
def get_experiment_results(): """ Computes the results of all experiments, stores it in redis, and prints it out """ redis = oz.redis.create_connection() for experiment in oz.bandit.get_experiments(redis): experiment.compute_default_choice() csq, confident = experiment.confidence() print("%s:" % experiment.name) print(...
def sync_experiments_from_spec(filename): """ Takes the path to a JSON file declaring experiment specifications, and modifies the experiments stored in redis to match the spec. A spec looks like this: { "experiment 1": ["choice 1", "choice 2", "choice 3"], "experiment 2": ["choice 1", "choice 2"] } """ redis = oz.redis...
def add_chapter(self, title): ''' Adds a new chapter to the report. :param str title: Title of the chapter. ''' chap_id = 'chap%s' % self.chap_counter self.chap_counter += 1 self.sidebar += '<a href="#%s" class="list-group-item">%s</a>\n' % ( chap_id, title) self.body += '<h1 id="%s">%s</h1>\n' % (chap_id, title)
def add_image(self, figure, dpi=72): ''' Adds an image to the last chapter/section. The image will be stored in the `{self.title}_files` directory. :param matplotlib.figure figure: A matplotlib figure to be saved into the report ''' name = os.path.join(self._dir, '/fig%s.png' % self.fig_counter) self.fig_counter += 1 f...
def write_report(self, force=False): ''' Writes the report to a file. ''' path = self.title + '.html' value = self._template.format( title=self.title, body=self.body, sidebar=self.sidebar) write_file(path, value, force=force) plt.ion()
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None): """Returns a tree from alignment Will check MolType of aln object """ if params is None: params = {} if moltype == DNA or moltype == RNA: params['-nt'] = True elif moltype == PROTEIN: params['-nt'] = False else: raise ValueError, \ "FastTree...
def dbsource(dbname, var, resolution=None, tscale=None): """Return which file(s) to use according to dbname, var, etc """ db_cfg = {} cfg_dir = 'datasource' cfg_files = pkg_resources.resource_listdir('oceansdb', cfg_dir) cfg_files = [f for f in cfg_files if f[-5:] == '.json'] for src_cfg in cfg_files: text = pkg_resour...
def diff(a, b): """ Performs a longest common substring diff. :Parameters: a : sequence of `comparable` Initial sequence b : sequence of `comparable` Changed sequence :Returns: An `iterable` of operations. """ a, b = list(a), list(b) opcodes = SM(None, a, b).get_opcodes() return parse_opcodes(opcodes)
async def convert_endpoint(url_string, ts, is_just_checking): ''' Main logic for HTTP endpoint. ''' response = singletons.server.response # Prep ForeignResource and ensure does not validate security settings singletons.settings foreign_res = ForeignResource(url_string) target_ts = TypeString(ts) target_resource = Typed...
def apply_command_list_template(command_list, in_path, out_path, args): ''' Perform necessary substitutions on a command list to create a CLI-ready list to launch a conversion or download process via system binary. ''' replacements = { '$IN': in_path, '$OUT': out_path, } # Add in positional arguments ($0, $1, etc) for ...
async def convert_local(path, to_type): ''' Given an absolute path to a local file, convert to a given to_type ''' # Now find path between types typed_foreign_res = TypedLocalResource(path) original_ts = typed_foreign_res.typestring conversion_path = singletons.converter_graph.find_path( original_ts, to_type) # print('...
def enqueue_conversion_path(url_string, to_type, enqueue_convert): ''' Given a URL string that has already been downloaded, enqueue necessary conversion to get to target type ''' target_ts = TypeString(to_type) foreign_res = ForeignResource(url_string) # Determine the file type of the foreign resource typed_foreign_res...
def check_path(path, otherwise): """ Checks if a path exists. If it does, print a warning message; if not, execute the `otherwise` callback argument. """ if os.path.exists(path): print("WARNING: Path '%s' already exists; skipping" % path) else: otherwise(path)
def config_maker(project_name, path): """Creates a config file based on the project name""" with open(skeleton_path("config.py"), "r") as config_source: config_content = config_source.read() config_content = config_content.replace("__PROJECT_NAME__", project_name) with open(path, "w") as config_dest: config_dest.write(...
def skeleton_path(parts): """Gets the path to a skeleton asset""" return os.path.join(os.path.dirname(oz.__file__), "skeleton", parts)
def init(project_name): """Creates a new project""" if not VALID_PROJECT_NAME.match(project_name): print("Invalid project name. It may only contain letters, numbers and underscores.", file=sys.stderr) return check_path(project_name, functools.partial(shutil.copytree, skeleton_path("plugin"))) check_path("static", os.mk...
def server(): """Runs the server""" tornado.log.enable_pretty_logging() # Get and validate the server_type server_type = oz.settings["server_type"] if server_type not in [None, "wsgi", "asyncio", "twisted"]: raise Exception("Unknown server type: %s" % server_type) # Install the correct ioloop if necessary if server_typ...
one server worker can run in debug mode.") server_workers = 1 elif (server_type == "asyncio" or server_type == "twisted"): print("WARNING: A non-default server type is being used, but multiple server workers have been configured. Only one server worker can run on a non-default server type.") server_workers = 1 # Forks ...
"twisted": from twisted.internet import reactor reactor.run() else: from tornado import ioloop ioloop.IOLoop.instance().start()
def repl(): """Runs an IPython repl with some context""" try: import IPython except: print("ERROR: IPython is not installed. Please install it to use the repl.", file=sys.stderr) raise IPython.embed(user_ns=dict( settings=oz.settings, actions=oz._actions, uimodules=oz._uimodules, routes=oz._routes, ))
def find_resource_url_basename(self, resource_url): ''' Figure out path basename for given resource_url ''' scheme = resource_url.parsed.scheme if scheme in ('http', 'https', 'file'): return _get_basename_based_on_url(resource_url) elif scheme in ('git', 'git+https', 'git+http'): if len(resource_url.args) == 2: # For n...
def find_destination_type(self, resource_url): ''' Given a resource_url, figure out what it would resolve into ''' resolvers = self.converters.values() for resolver in resolvers: # Not all resolvers are opinionated about destination types if not hasattr(resolver, 'get_destination_type'): continue destination_type = res...
async def download(self, resource_url): ''' Download given Resource URL by finding path through graph and applying each step ''' resolver_path = self.find_path_from_url(resource_url) await self.apply_resolver_path(resource_url, resolver_path)
def insert_sequences_into_tree(aln, moltype, params={}): """Returns a tree from placement of sequences """ # convert aln to phy since seq_names need fixed to run through parsinsert new_aln=get_align_for_phylip(StringIO(aln)) # convert aln to fasta in case it is not already a fasta file aln2 = Alignment(new_aln) seqs = ...
def _get_result_paths(self,data): """ Get the resulting tree""" result = {} result['Tree'] = ResultPath(Path=splitext(self._input_filename)[0] + \ '.tree') return result
async def download(resource_url): ''' Download given resource_url ''' scheme = resource_url.parsed.scheme if scheme in ('http', 'https'): await download_http(resource_url) elif scheme in ('git', 'git+https', 'git+http'): await download_git(resource_url) else: raise ValueError('Unknown URL scheme: "%s"' % scheme)
def create_folder(self, dir_name): """创建目录(https://www.qcloud.com/document/product/436/6061) :param dir_name:要创建的目录的目录的名称 :return 返回True创建成功,返回False创建失败 """ if dir_name[0] == '/': dir_name = dir_name[1:len(dir_name)] self.url = "http://<Region>.file.myqcloud.com" + "/files/v2/<appid>/<bucket_name>/<dir_name>/" self.url...
def list_folder(self, dir_name=None, prefix=None, num=1000, context=None): """列目录(https://www.qcloud.com/document/product/436/6062) :param dir_name:文件夹名称 :param prefix:前缀 :param num:查询的文件的数量,最大支持1000,默认查询数量为1000 :param context:翻页标志,将上次查询结果的context的字段传入,即可实现翻页的功能 :return 查询结果,为json格式 """ if dir_name[0] == '/': dir_name ...
def query_folder(self, dir_name): """查询目录属性(https://www.qcloud.com/document/product/436/6063) :param dir_name:查询的目录的名称 :return:查询出来的结果,为json格式 """ if dir_name[0] == '/': dir_name = dir_name[1:len(dir_name)] self.url = 'http://' + self.config.region + '.file.myqcloud.com' + '/files/v2/' + str(self.config.app_id) + '/' +...
def upload_file(self, real_file_path, file_name, dir_name=None): """简单上传文件(https://www.qcloud.com/document/product/436/6066) :param real_file_path: 文件的物理地址 :param file_name: 文件名称 :param dir_name: 文件夹名称(可选) :return:json数据串 """ if dir_name is not None and dir_name[0] == '/': dir_name = dir_name[1:len(dir_name)] if dir_na...
def upload_slice_file(self, real_file_path, slice_size, file_name, offset=0, dir_name=None): """ 此分片上传代码由GitHub用户a270443177(https://github.com/a270443177)友情提供 :param real_file_path: :param slice_size: :param file_name: :param offset: :param dir_name: :return: """ if dir_name is not None and dir_name[0] == '/': dir_name...
def upload_file_from_url(self, url, file_name, dir_name=None): """简单上传文件(https://www.qcloud.com/document/product/436/6066) :param url: 文件url地址 :param file_name: 文件名称 :param dir_name: 文件夹名称(可选) :return:json数据串 """ real_file_name = str(int(time.time()*1000)) urllib.request.urlretrieve(url, real_file_name) data = self.upl...
def sign_more(self, bucket, cos_path, expired): """多次签名(针对上传文件,创建目录, 获取文件目录属性, 拉取目录列表) :param bucket: bucket名称 :param cos_path: 要操作的cos路径, 以'/'开始 :param expired: 签名过期时间, UNIX时间戳, 如想让签名在30秒后过期, 即可将expired设成当前时间加上30秒 :return: 签名字符串 """ return self.app_sign(bucket, cos_path, expired)
def sign_download(self, bucket, cos_path, expired): """下载签名(用于获取后拼接成下载链接,下载私有bucket的文件) :param bucket: bucket名称 :param cos_path: 要下载的cos文件路径, 以'/'开始 :param expired: 签名过期时间, UNIX时间戳, 如想让签名在30秒后过期, 即可将expired设成当前时间加上30秒 :return: 签名字符串 """ return self.app_sign(bucket, cos_path, expired, False)
def strained_001(self, target): ''' Returns an instance of ``IIIVZincBlendeStrained001``, which is a biaxial-strained III-V zinc blende binary alloy grown on a (001) surface. Parameters ---------- target : Alloy with ``a`` parameter or float Growth substrate, assumed to have a (001) surface, or out-of-plane strain, whi...
def Eg(self, **kwargs): ''' Returns the bandgap, Eg, in eV at a given temperature, T, in K (default=300.). ''' return min(self.Eg_Gamma(**kwargs), self.Eg_L(**kwargs), self.Eg_X(**kwargs))
def F(self, **kwargs): ''' Returns the Kane remote-band parameter, `F`, calculated from `Eg_Gamma_0`, `Delta_SO`, `Ep`, and `meff_e_Gamma_0`. ''' Eg = self.Eg_Gamma_0(**kwargs) Delta_SO = self.Delta_SO(**kwargs) Ep = self.Ep(**kwargs) meff = self.meff_e_Gamma_0(**kwargs) return (1./meff-1-(Ep*(Eg+2.*Delta_SO/3.))/(Eg*(...
def a(self, **kwargs): ''' Returns the lattice parameter, a, in Angstroms at a given temperature, `T`, in Kelvin (default: 300 K). ''' T = kwargs.get('T', 300.) return (self.a_300K(**kwargs) + self.thermal_expansion(**kwargs) * (T - 300.))
def meff_SO(self, **kwargs): ''' Returns the split-off hole effective mass calculated from Eg_Gamma(T), Delta_SO, Ep and F. Interpolation of Eg_Gamma(T), Delta_SO, Ep and luttinger1, and then calculation of meff_SO is recommended for alloys. ''' Eg = self.Eg_Gamma(**kwargs) Delta_SO = self.Delta_SO(**kwargs) Ep = self....
def meff_e_Gamma(self, **kwargs): ''' Returns the electron effective mass in the Gamma-valley calculated from Eg_Gamma(T), Delta_SO, Ep and F. Interpolation of Eg_Gamma(T), Delta_SO, Ep and F, and then calculation of meff_e_Gamma is recommended for alloys. ''' Eg = self.Eg_Gamma(**kwargs) Delta_SO = self.Delta_SO(**kwa...
def meff_hh_110(self, **kwargs): ''' Returns the heavy-hole band effective mass in the [110] direction, meff_hh_110, in units of electron mass. ''' return 2. / (2 * self.luttinger1(**kwargs) - self.luttinger2(**kwargs) - 3 * self.luttinger3(**kwargs))
def meff_lh_110(self, **kwargs): ''' Returns the light-hole band effective mass in the [110] direction, meff_lh_110, in units of electron mass. ''' return 2. / (2 * self.luttinger1(**kwargs) + self.luttinger2(**kwargs) + 3 * self.luttinger3(**kwargs))
def nonparabolicity(self, **kwargs): ''' Returns the Kane band nonparabolicity parameter for the Gamma-valley. ''' Eg = self.Eg_Gamma(**kwargs) meff = self.meff_e_Gamma(**kwargs) T = kwargs.get('T', 300.) return k*T/Eg * (1 - meff)**2
def crop(self, lat, lon, var): """ Crop a subset of the dataset for each var Given doy, depth, lat and lon, it returns the smallest subset that still contains the requested coordinates inside it. It handels special cases like a region around greenwich and the international date line. Accepts 0 to 360 and -180 to 180 lo...
def interpolate(self, lat, lon, var): """ Interpolate each var on the coordinates requested """ subset, dims = self.crop(lat, lon, var) if np.all([y in dims['lat'] for y in lat]) & \ np.all([x in dims['lon'] for x in lon]): yn = np.nonzero([y in lat for y in dims['lat']])[0] xn = np.nonzero([x in lon for x in dims['lon...
= np.nonzero(~ma.getmaskarray(subset[v])) if idx[0].size > 0: points = np.array([ dims['lat'][idx[0]], dims['lon'][idx[1]]]).T values = subset[v][idx] # Interpolate along the dimensions that have more than one # position, otherwise it means that the output is exactly # on that coordinate. ind = np.array( [np.unique(poi...
def _setup_converter_graph(self, converter_list, prune_converters): ''' Set up directed conversion graph, pruning unavailable converters as necessary ''' for converter in converter_list: if prune_converters: try: converter.configure() except ConverterUnavailable as e: log.warning('%s unavailable: %s' % (converter.__cla...
def _setup_preferred_paths(self, preferred_conversion_paths): ''' Add given valid preferred conversion paths ''' for path in preferred_conversion_paths: for pair in pair_looper(path): if pair not in self.converters: log.warning('Invalid conversion path %s, unknown step %s' % (repr(path), repr(pair))) break else: # If i...
def _setup_profiles(self, conversion_profiles): ''' Add given conversion profiles checking for invalid profiles ''' # Check for invalid profiles for key, path in conversion_profiles.items(): if isinstance(path, str): path = (path, ) for left, right in pair_looper(path): pair = (_format(left), _format(right)) if pair no...
def _setup_direct_converter(self, converter): ''' Given a converter, set up the direct_output routes for conversions, which is used for transcoding between similar datatypes. ''' inputs = ( converter.direct_inputs if hasattr(converter, 'direct_inputs') else converter.inputs ) for in_ in inputs: for out in converter.dir...
def find_path(self, in_, out): ''' Given an input and output TypeString, produce a graph traversal, keeping in mind special options like Conversion Profiles, Preferred Paths, and Direct Conversions. ''' if in_.arguments: raise ValueError('Cannot originate path in argumented TypeString') # Determine conversion profile. ...