How to use _interpolate method in Gherkin-python

Best Python code snippet using gherkin-python

fabfile.py

Source:fabfile.py Github

copy

Full Screen

...75 env.project['environment'] = environment76def _require_environment():77 """Checks if env.environment and env.host exist"""78 require('environment', 'host', provided_by=ENVS.keys())79def _interpolate(string):80 """Interpolates string with dictionary provided by ENVS"""81 return string % env.project82def _parse_alias(command):83 """84 Mimics a bash alias: if command starts with a word that is present in ALIASES85 dictionary, substitutes that word for the value found, and maintains the rest.86 """87 words = command.split(' ')88 if not words or words[0] not in ALIASES.keys():89 return command90 else:91 return '%s %s' % (ALIASES[words[0]], ' '.join(words[1:]))92def _generate_conf(conf_file, variables, django_version):93 """Generates conf file from template, and optionally saves it"""94 if not django_version:95 django_version = DJANGO_LATEST_VERSION96 # File names97 part = conf_file.split('.')98 input_file = os.path.join(templates_dir, '%s_django%s.%s' % (part[0], django_version, part[1]))99 output_file = '%s/%s_%s.%s' % (env.project['project'], part[0], env.environment, part[1])100 # Generate conf file from template101 conf = ''102 output = io.StringIO()103 try:104 with open(input_file, 'r') as input:105 for line in input:106 output.write(line % variables)107 conf = output.getvalue()108 finally:109 output.close()110 # Shows conf file and optionally saves it111 print(conf)112 if console.confirm('Save to %s?' % output_file, default=False):113 with open(output_file, 'w') as output:114 output.write(conf)115###########116# Vagrant #117###########118def _vagrant():119 """(work in progress)"""120 # change from the default user to 'vagrant'121 env.user = 'vagrant'122 # connect to the port-forwarded ssh123 env.hosts = ['127.0.0.1:2222']124 # use vagrant ssh key125 result = local('vagrant ssh_config | grep IdentityFile', capture=True)126 env.key_filename = result.split()[1]127##################128# Linux commands #129##################130def adduser(username, password):131 """Creates remote user (with required username/password) and uploads ~/.ssh/id_rsa.pub as authorized_keys"""132 _require_environment()133 # New user to be created134 env.remote_user = username135 env.remote_password = password136 env.remote_home = '/home/%(remote_user)s' % env137 # Needs to connect as root (or sudoer)138 env.user = prompt('Remote root or sudoer?', default=env.user)139 env.password = None140 # Creates user, if it doesn't exist already141 if files.exists(env.remote_home):142 print('User %(remote_user)s already exists on %(environment)s!' % env)143 else:144 sudo('useradd -d%(remote_home)s -s/bin/bash -m -U %(remote_user)s' % env)145 sudo('echo "%(remote_user)s:%(remote_password)s" | sudo chpasswd' % env)146 # TODO: not all distributions use group sudo for sudoers (e.g.: old Ubuntu uses admin)147 # TODO: sudoers should not have to use password148 sudo('adduser %(remote_user)s sudo' % env)149 sudo('mkdir %(remote_home)s/.ssh' % env)150 put('~/.ssh/id_rsa.pub', '%(remote_home)s/.ssh/authorized_keys' % env, use_sudo=True, mode=0o644)151 sudo('chown -R %(remote_user)s:%(remote_user)s %(remote_home)s/.ssh' % env)152 # Continues as newly created user153 env.user = env.remote_user154 env.password = None155def install_git():156 """Installs (most recent) git from source"""157 local_git_version = sudo(LOCAL_GIT_VERSION)158 newest_git_version = run(NEWEST_GIT_VERSION)159 if local_git_version != newest_git_version:160 git_file = 'git-%s' % newest_git_version161 apt_get_update()162 sudo('apt-get -y -qq install build-essential')163 sudo('apt-get -y -qq install git-core')164 sudo('apt-get -y -qq install libcurl4-gnutls-dev')165 sudo('apt-get -y -qq install libexpat1-dev')166 sudo('apt-get -y -qq install gettext')167 sudo('apt-get -y -qq install libz-dev')168 sudo('apt-get -y -qq install libssl-dev')169 sudo('wget --quiet https://www.kernel.org/pub/software/scm/git/%s.tar.gz' % git_file)170 sudo('tar -xzf %s.tar.gz' % git_file)171 with cd(git_file):172 sudo('make --silent prefix=/usr/local all > /dev/null')173 sudo('make --silent prefix=/usr/local install > /dev/null')174def apt_get_update():175 """Updates apt-get repositories, if needed"""176 temp_dir = run('echo ${TMPDIR:-"/tmp/"}')177 temp_file = os.path.join(temp_dir, 'apt-get-update-done')178 today = datetime.date.today().strftime('%d/%m/%y')179 if files.exists(temp_file):180 last_date_run = run('cat %s' % temp_file)181 else:182 last_date_run = ''183 if last_date_run != today:184 sudo('apt-get update')185 run('echo %s > %s' % (today, temp_file))186def hostname(name):187 """Updates server /etc/hosts and /etc/hostname"""188 files.sed('/etc/hosts', '.*', '127.0.0.1 %s' % name, limit='^127.0.0.1 ', use_sudo=True)189 sudo('mv /etc/hostname /etc/hostname.bak && echo %s > /etc/hostname' % name)190 sudo('hostname %s' % name)191def check_cpu():192 """Check CPU usage"""193 with settings(warn_only=True):194 run('mpstat')195 run('ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10')196def check_memory():197 """Check memory usage"""198 with settings(warn_only=True):199 run('free -m')200def check_disk():201 """Check disk usage"""202 with settings(warn_only=True):203 run('df -h')204def check_io():205 """Check I/O statistics"""206 with settings(warn_only=True):207 run('iostat')208##################209# MySQL commands #210##################211def install_mysql():212 """Installs MySQL"""213 password = prompt('Password for MySQL root?', default='')214 apt_get_update()215 sudo('DEBIAN_FRONTEND=noninteractive apt-get -y -qq install mysql-server libmysqlclient-dev')216 with settings(warn_only=True):217 sudo('mysqladmin -u root password %s' % password)218 sudo(MYSQL_PREFIX % "\"ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '%s';\"" % password)219def _get_database_name():220 """Gets database dictionary either from ENVS or form Django settings.py"""221 _require_environment()222 database = env.project.get('database', None)223 if not database:224 django.settings_module(_interpolate('%(project)s.%(settings)s'))225 database = django_settings.DATABASES['default']226 return database227def _database_exists():228 """Checks for existence of database"""229 _require_environment()230 database = _get_database_name()231 with settings(hide('warnings'), warn_only=True):232 result = run(MYSQL_PREFIX % "\"SHOW DATABASES LIKE '%(NAME)s';\"" % database)233 if database['NAME'] in result:234 return True235 else:236 print('Database %(NAME)s does not exist' % database)237 return False238def drop_database():239 """CAREFUL! - Destroys (DROP) MySQL database according to env's settings.py"""240 _require_environment()241 database = _get_database_name()242 if _database_exists():243 if console.confirm('ATTENTION! This will destroy current database! Confirm?', default=False):244 with settings(hide('warnings'), warn_only=True):245 result = run(MYSQL_PREFIX % "\"DROP DATABASE %(NAME)s;\"" % database)246def create_database():247 """Creates MySQL database according to env's settings.py, if not already there"""248 database = _get_database_name()249 with settings(hide('warnings'), warn_only=True):250 result = run(MYSQL_PREFIX % "\"CREATE DATABASE %(NAME)s DEFAULT CHARACTER SET utf8;\"" % database)251 if result.succeeded:252 run(MYSQL_PREFIX % "\"GRANT ALL ON %(NAME)s.* TO '%(USER)s'@'localhost' IDENTIFIED BY '%(PASSWORD)s';\"" % database)253 run(MYSQL_PREFIX % "\"ALTER USER '%(USER)s'@'localhost' IDENTIFIED WITH mysql_native_password BY '%(PASSWORD)s';\"" % database)254def backup_database():255 """256 Backup server's database and copy tar.gz to local ../backup dir257 """258 _require_environment()259 database = _get_database_name()260 with prefix(_django_prefix()):261 with cd(_django_project_dir()):262 # Creates dir to store backup, avoiding existing similar names263 dirname = '../backup/%s_%s' % (datetime.date.today().strftime('%Y%m%d'), env.environment)264 path = dirname265 index = 0266 while files.exists(path) or files.exists('%s.tar.gz' % path):267 index += 1268 path = '%s.%s' % (dirname, index)269 run('mkdir -p %s' % path)270 # Backup MySQL271 run('mysqldump %s -u %s -p%s %s > %s/%s.sql' % (272 '-h %s' % database['HOST'] if database.get('HOST', None) else '',273 database['USER'],274 database['PASSWORD'],275 database['NAME'],276 path,277 env.project['project'],278 ))279 # Backup extra files280 extra_backup_files = env.project.get('extra_backup_files', [])281 for file in extra_backup_files:282 run('cp -R %s %s/' % (file, path))283 # Create .tar.gz and removes uncompressed files284 with hide('stdout'):285 run('tar -czvf %s.tar.gz %s/' % (path, path))286 run('rm -rf %s/' % path)287 # Download backup?288 if console.confirm('Download backup?'):289 return get('%s.tar.gz' % path, '../backup')290def restore_database(filename):291 """292 Restore server's database with .sql file contained in filename293 """294 _require_environment()295 database = _get_database_name()296 with prefix(_django_prefix()):297 with cd(_django_project_dir()):298 # Uploads tar file299 tarfile = os.path.basename(filename)300 basename = tarfile[:tarfile.index('.tar.gz')]301 if console.confirm('Upload backup?'):302 put(filename, '../backup/%s' % tarfile)303 # Drop and recreate current database304 drop_database()305 create_database()306 # Restore MySQL307 # To avoid silly mistakes, instead of using project's user & password, uses root's308 with cd('../'):309 run('tar -xzvf backup/%s' % tarfile)310 run('mysql -u root -p %s < backup/%s/%s.sql' % (311 #database['USER'],312 #database['PASSWORD'],313 database['NAME'],314 basename,315 env.project['project'],316 ))317 # Restore extra files318 extra_backup_files = env.project.get('extra_backup_files', [])319 for file in extra_backup_files:320 run('cp -R ../backup/%s/%s ./%s' % (basename, os.path.basename(file), os.path.dirname(file)))321 # Removes uncompressed files, but leaves .tar.gz322 run('rm -rf ../backup/%s' % basename)323###################324# Apache commands #325###################326def install_apache():327 """Installs Apache and mod_wsgi"""328 apt_get_update()329 sudo ('apt-get -y -qq install apache2 apache2-mpm-worker libapache2-mod-wsgi')330def setup_apache():331 """Configures Apache"""332 if files.exists(_interpolate('/etc/apache2/sites-enabled/%(virtualenv)s.conf')):333 print('Apache conf for %(environment)s already exists' % env)334 else:335 sudo(_interpolate('ln -s %s /etc/apache2/sites-enabled/%%(virtualenv)s.conf' % APACHE_CONF))336 sudo('apache2ctl restart')337def generate_apache_conf(django_version=None):338 """Generates Apache conf file. Requires: path to WSGI conf file."""339 _require_environment()340 site_packages_dir = '%s/%s' % (_interpolate(VIRTUALENV_DIR), SITE_PACKAGES_DIR % _get_python_version())341 config_dir = _interpolate(CONFIG_DIR)342 host_aliases = env.project.get('host_aliases', '')343 if host_aliases:344 host_aliases = 'ServerAlias %s' % host_aliases345 _generate_conf('apache.conf', {346 'host': env.project['host'],347 'host_aliases': host_aliases,348 'site_packages_dir': site_packages_dir,349 'static_admin_dir': '%s/django/contrib/admin/media' % site_packages_dir,350 'project_dir': _interpolate(DJANGO_PROJECT_DIR),351 'media_dir': _interpolate(MEDIA_DIR),352 'static_dir': _interpolate(STATIC_DIR),353 'config_dir': config_dir,354 'wsgi_file': 'wsgi_%s.py' % env.environment,355 }, django_version)356def generate_wsgi_conf(django_version=None):357 """Generates WSGI conf file"""358 _require_environment()359 _generate_conf('wsgi.py', {360 'project': env.project['project'],361 'settings': env.project['settings'],362 'site_packages': SITE_PACKAGES_DIR % _get_python_version(),363 }, django_version)364 local(_interpolate('cp %(project)s/wsgi_%(environment)s.py %(project)s/wsgi.py'))365def apache_restart():366 """367 Restarts Apache368 """369 _require_environment()370 sudo('apache2ctl restart')371###################372# Python commands #373###################374def install_python():375 """Installs Python 2.7, setuptools, pip, virtualenv, virtualenvwrapper"""376 _require_environment()377 # TODO: Install Python from source, regardless of Linux distribution378 apt_get_update()379 sudo('apt-get -y -qq install python python2.7 python2.7-dev pkg-config gcc')380 sudo('apt-get -y -qq install python-setuptools python-bs4')381 sudo('easy_install pip')382 sudo('pip install virtualenv')383 sudo('pip install virtualenvwrapper')384 with settings(warn_only=True):385 sudo(_interpolate('mkdir -p %(workon)s'))386 sudo(_interpolate('chmod g+w %(workon)s'))387 sudo(_interpolate('chown %%(user)s:%%(user)s %(workon)s') % env)388def _get_python_version():389 """Checks python version on remote virtualenv"""390 with settings(hide('commands', 'warnings'), warn_only=True):391 # First tries to check python within virtualenv392 with prefix(_django_prefix()):393 result = run(GET_PYTHON_VERSION)394 # If that fails, checks global python395 if result.failed:396 result = run(GET_PYTHON_VERSION)397 # if it still fails, something is wrong!398 if result.failed:399 abort(_interpolate('Could not determine Python version at virtualenv %(virtualenv)s'))400 return result401def _virtualenvwrapper_prefix():402 """Prefix to be able to invoke virtualenvwrapper commands"""403 return VIRTUALENVWRAPPER_PREFIX % {404 'workon': env.project['workon'],405 'script': VIRTUALENVWRAPPER_SCRIPT,406 }407def _setup_virtualenv():408 """Creates virtualenv for environment"""409 if files.exists(_interpolate(VIRTUALENV_DIR)):410 print(_interpolate('virtualenv %(virtualenv)s already exists'))411 else:412 with prefix(_virtualenvwrapper_prefix()):413 run(_interpolate('mkvirtualenv --no-site-packages %(virtualenv)s'))414 with hide('commands'):415 print('virtualenv %s created with python %s\n' % (env.project['virtualenv'], run(GET_PYTHON_VERSION)))416def python_version():417 """Tries to figure out Python version on server side"""418 _require_environment()419 print('Python version on virtualenv %s: %s' % (env.project['virtualenv'], _get_python_version()))420#############################421# (Django) project commands #422#############################423def _django_prefix():424 """Prefix to wrap commands with necessary virtualenv and variables"""425 return _interpolate(DJANGO_PREFIX)426def _django_project_dir():427 """Path to current project' directory"""428 return _interpolate(DJANGO_PROJECT_DIR)429def _clone_gitrepo():430 """Clones project git repo into virtualenv"""431 # Puts git repo in ~/.ssh/config to avoid interaction due to missing known_hosts432 git_server = urllib.splituser(urllib.splittype(env.project['git_repo'])[0])[1]433 if not files.exists('~/.ssh/config') or not files.contains('~/.ssh/config', git_server):434 files.append('~/.ssh/config', ['host %s' % git_server, ' StrictHostKeyChecking no'])435 branch = env.project.get('git_branch', 'master')436 if files.exists(_interpolate(DJANGO_PROJECT_DIR)):437 print(_interpolate('project %(project)s already exists, updating'))438 remote('git pull origin %s' % branch)439 else:440 with cd(_interpolate(VIRTUALENV_DIR)):441 run(_interpolate('git clone %(git_repo)s %(project)s'))442 if branch != 'master':443 remote('git fetch origin %s:%s' % (branch, branch))444 remote('git checkout %s' % branch)445def extra_commands():446 """Issue commands contained in env.project['EXTRA_COMMANDS']"""447 _require_environment()448 extra_commands = env.project.get('extra_commands', [])449 with settings(hide('warnings'), warn_only=True):450 for command in extra_commands:451 remote(command)452def remote(command):453 """Issues a generic command at project's directory level"""454 _require_environment()455 with prefix(_django_prefix()):456 with cd(_django_project_dir()):457 if command.startswith('sudo '):458 sudo(_parse_alias(command[5:]))459 else:460 run(_parse_alias(command))461def setup_project():462 """Sets up a new environment"""463 _require_environment()464 # Checks if needed conf files for this environment already exist465 settings_file = _interpolate('%(project)s/%(settings)s.py')466 apache_file = _interpolate('%(project)s/apache_%(environment)s.conf')467 wsgi_file = _interpolate('%(project)s/wsgi_%(environment)s.py')468 if not os.path.exists(settings_file):469 abort('There is no %s - create one, and commit' % settings_file)470 if not os.path.exists(apache_file):471 abort('There is no Apache conf %s - use task "generate_apache_conf" to generate one, and commit' % apache_file)472 if not os.path.exists(wsgi_file):473 abort('There is no WSGI conf %s - use task "generate_wsgi_conf" to generate one, and commit' % wsgi_file)474 # Configures virtualenv and clones git repo475 _setup_virtualenv()476 _clone_gitrepo()477 # Issues extra commands at project's level, if any478 extra_commands()479 # Sets up Apache, MySQL480 setup_apache()481 if _database_exists():482 database = _get_database_name()483 print('Database %(NAME)s already exists' % database)484 else:485 drop_database()486 create_database()487 # Install Python packages & Django488 pip_install()489 update_project()490def pip_install():491 """Uses pip to install needed requirements"""492 _require_environment()493 remote(_interpolate(PIP_INSTALL_PREFIX))494def touch_project():495 """Touches WSGI file to reset Apache"""496 remote(_interpolate('touch %s' % WSGI_CONF))497def status_project():498 """Checks git log and status"""499 remote('glogg -n 20 && echo "" && git status')500def update_project():501 """Updates server from git pull"""502 _require_environment()503 # Grants write rights on log dir for the admin group504 log_dir = '%s/log' % _interpolate(VIRTUALENV_DIR)505 if files.exists(log_dir):506 sudo('chmod -R g+w %s' % log_dir)507 # Updates from git, issues Django syncdb, South migrate, Collecstatic and resets Apache508 branch = env.project.get('git_branch', 'master')509 with prefix(_django_prefix()):510 with cd(_django_project_dir()):511 with settings(hide('warnings'), warn_only=True):512 run('git fetch origin %s:%s' % (branch, branch))513 run('git checkout %s' % branch)514 with settings(hide('warnings'), warn_only=True):515 run('git pull origin %s' % branch)516 # run('django-admin.py syncdb') deprecated since Django 1.9517 run('django-admin.py migrate')518 run(_interpolate('touch %s' % WSGI_CONF))519 run('django-admin.py collectstatic --noinput')520def check_log():521 """Tails Django log"""522 _require_environment()523 with prefix(_django_prefix()):524 with cd(_django_project_dir()):525 logfile = '../log/%s.log' % env.project['project']526 run('tail -100f %s' % logfile)527def find_in_log(string):528 """Finds string parameter in Django logs"""529 _require_environment()530 with prefix(_django_prefix()):531 with cd(_django_project_dir()):532 run('grep -i %s ../log/*' % string)...

Full Screen

Full Screen

iii_v_zinc_blende_mixed_alloy.py

Source:iii_v_zinc_blende_mixed_alloy.py Github

copy

Full Screen

...30 Used to specify the alloy composition.31 '''32 raise NotImplementedError()33 34 def _interpolate(self, name, kwargs):35 raise NotImplementedError()36 37 @method_parameter(dependencies=['Delta_SO'],38 units='eV')39 def Delta_SO(self, **kwargs):40 return self._interpolate('Delta_SO', kwargs)41 42 @method_parameter(dependencies=['Eg_Gamma'],43 units='eV')44 def Eg_Gamma(self, **kwargs):45 return self._interpolate('Eg_Gamma', kwargs)46 47 @method_parameter(dependencies=['Eg_L'],48 units='eV')49 def Eg_L(self, **kwargs):50 return self._interpolate('Eg_L', kwargs)51 52 @method_parameter(dependencies=['Eg_X'],53 units='eV')54 def Eg_X(self, **kwargs):55 return self._interpolate('Eg_X', kwargs)56 57 @method_parameter(dependencies=['Ep'],58 units='eV', references=[vurgaftman_2001])59 def Ep(self, **kwargs):60 '''61 Linear interpolation is recommended for alloys.62 '''63 return self._interpolate('Ep', kwargs)64 65 @method_parameter(dependencies=['F'],66 units='dimensionless', references=[vurgaftman_2001])67 def F(self, **kwargs):68 '''69 Linear interpolation is recommended for alloys.70 '''71 return self._interpolate('F', kwargs)72 73 @method_parameter(dependencies=['VBO'],74 units='eV')75 def VBO(self, **kwargs):76 return self._interpolate('VBO', kwargs)77 @method_parameter(dependencies=['a_300K'],78 units='angstrom')79 def a_300K(self, **kwargs):80 '''81 Returns the lattice parameter, a, in Angstroms at 300 K.82 '''83 return self._interpolate('a_300K', kwargs)84 85 @method_parameter(dependencies=['a_c'],86 units='eV')87 def a_c(self, **kwargs):88 return self._interpolate('a_c', kwargs)89 90 @method_parameter(dependencies=['a_v'],91 units='eV')92 def a_v(self, **kwargs):93 return self._interpolate('a_v', kwargs)94 95 @method_parameter(dependencies=['b'],96 units='eV')97 def b(self, **kwargs):98 return self._interpolate('b', kwargs)99 100 @method_parameter(dependencies=['c11'],101 units='eV')102 def c11(self, **kwargs):103 return self._interpolate('c11', kwargs)104 105 @method_parameter(dependencies=['c12'],106 units='eV')107 def c12(self, **kwargs):108 return self._interpolate('c12', kwargs)109 110 @method_parameter(dependencies=['c44'],111 units='eV')112 def c44(self, **kwargs):113 return self._interpolate('c44', kwargs)114 115 @method_parameter(dependencies=['d'],116 units='eV')117 def d(self, **kwargs):118 return self._interpolate('d', kwargs)119 120 @method_parameter(dependencies=['dielectric'],121 units='dimensionless')122 def dielectric(self, **kwargs):123 return self._interpolate('dielectric', kwargs)124 125 @method_parameter(dependencies=['dielectric_high_frequency'],126 units='dimensionless')127 def dielectric_high_frequency(self, **kwargs):128 return self._interpolate('dielectric_high_frequency', kwargs)129 130 @method_parameter(dependencies=['meff_hh_100', 'meff_lh_100'],131 units='dimensionless')132 def luttinger1(self, **kwargs):133 return ((1. / self.meff_lh_100(**kwargs) +134 1. / self.meff_hh_100(**kwargs) ) / 2.)135 136 @method_parameter(dependencies=['meff_hh_100', 'meff_lh_100'],137 units='dimensionless')138 def luttinger2(self, **kwargs):139 return ((1. / self.meff_lh_100(**kwargs) -140 1. / self.meff_hh_100(**kwargs) ) / 4.)141 142 @method_parameter(dependencies=['luttinger2', 'luttinger32'],143 units='dimensionless')144 def luttinger3(self, **kwargs):145 return self.luttinger32(**kwargs) + self.luttinger2(**kwargs)146 147 @method_parameter(dependencies=['luttinger32'],148 units='dimensionless')149 def luttinger32(self, **kwargs):150 '''151 Returns the difference between the third and second Luttinger152 parameters, i.e. `luttinger3 - luttinger2`.153 154 Linear interpolation of luttinger32 is the recommended way to155 estimate the valance band warping in alloys.156 '''157 return self._interpolate('luttinger32', kwargs)158 159 @method_parameter(dependencies=['meff_e_L_DOS'],160 units='m_e', references=[vurgaftman_2001])161 def meff_e_L_DOS(self, **kwargs):162 '''163 Linear interpolation of meff_e_L_DOS is recommended for alloys.164 '''165 return self._interpolate('meff_e_L_DOS', kwargs)166 167 @method_parameter(dependencies=['meff_e_L_long'],168 units='m_e', references=[vurgaftman_2001])169 def meff_e_L_long(self, **kwargs):170 '''171 Linear interpolation of meff_e_L_long is recommended for alloys.172 '''173 return self._interpolate('meff_e_L_long', kwargs)174 175 @method_parameter(dependencies=['meff_e_L_trans'],176 units='m_e', references=[vurgaftman_2001])177 def meff_e_L_trans(self, **kwargs):178 '''179 Linear interpolation of meff_e_L_trans is recommended for alloys.180 '''181 return self._interpolate('meff_e_L_trans', kwargs)182 183 @method_parameter(dependencies=['meff_e_X_DOS'],184 units='m_e', references=[vurgaftman_2001])185 def meff_e_X_DOS(self, **kwargs):186 '''187 Linear interpolation of meff_e_X_DOS is recommended for alloys.188 '''189 return self._interpolate('meff_e_X_DOS', kwargs)190 191 @method_parameter(dependencies=['meff_e_X_long'],192 units='m_e', references=[vurgaftman_2001])193 def meff_e_X_long(self, **kwargs):194 '''195 Linear interpolation of meff_e_X_long is recommended for alloys.196 '''197 return self._interpolate('meff_e_X_long', kwargs)198 199 @method_parameter(dependencies=['meff_e_X_trans'],200 units='m_e', references=[vurgaftman_2001])201 def meff_e_X_trans(self, **kwargs):202 '''203 Linear interpolation of meff_e_X_trans is recommended for alloys.204 '''205 return self._interpolate('meff_e_X_trans', kwargs)206 207 @method_parameter(dependencies=['meff_hh_100'], units='m_e')208 def meff_hh_100(self, **kwargs):209 '''210 Returns the light-hole band effective mass in the [100] direction,211 meff_hh_100, in units of electron mass.212 Linear interpolation of meff_hh_100 is recommended for alloys.213 '''214 return self._interpolate('meff_hh_100', kwargs)215 216 @method_parameter(dependencies=['meff_lh_100'], units='m_e')217 def meff_lh_100(self, **kwargs):218 '''219 Returns the heavy-hole band effective mass in the [100] direction,220 meff_hh_100, in units of electron mass.221 Linear interpolation of meff_lh_100 is recommended for alloys.222 '''223 return self._interpolate('meff_lh_100', kwargs)224 225 @method_parameter(dependencies=['meff_SO'],226 units='m_e', references=[vurgaftman_2001])227 def meff_SO(self, **kwargs):228 '''229 Linear interpolation of meff_SO is recommended for alloys.230 '''231 return self._interpolate('meff_SO', kwargs)232 @method_parameter(dependencies=['thermal_expansion'],233 units='angstrom/K')234 def thermal_expansion(self, **kwargs):235 '''236 Returns the thermal expansion coefficient.237 '''...

Full Screen

Full Screen

interpolate_wrapper.py

Source:interpolate_wrapper.py Github

copy

Full Screen

1""" helper_funcs.py.2 scavenged from enthought,interpolate3"""4from __future__ import division, print_function, absolute_import5import numpy as np6from . import _interpolate # C extension. Does all the real work.7def atleast_1d_and_contiguous(ary, dtype = np.float64):8 return np.atleast_1d( np.ascontiguousarray(ary, dtype) )9def nearest(x, y, new_x):10 """11 Rounds each new x to nearest input x and returns corresponding input y.12 Parameters13 ----------14 x : array_like15 Independent values.16 y : array_like17 Dependent values.18 new_x : array_like19 The x values to return the interpolate y values.20 Returns21 -------22 nearest : ndarray23 Rounds each `new_x` to nearest `x` and returns the corresponding `y`.24 """25 shifted_x = np.concatenate(( np.array([x[0]-1]) , x[0:-1] ))26 midpoints_of_x = atleast_1d_and_contiguous( .5*(x + shifted_x) )27 new_x = atleast_1d_and_contiguous(new_x)28 TINY = 1e-1029 indices = np.searchsorted(midpoints_of_x, new_x+TINY)-130 indices = np.atleast_1d(np.clip(indices, 0, np.Inf).astype(np.int))31 new_y = np.take(y, indices, axis=-1)32 return new_y33def linear(x, y, new_x):34 """35 Linearly interpolates values in new_x based on the values in x and y36 Parameters37 ----------38 x : array_like39 Independent values40 y : array_like41 Dependent values42 new_x : array_like43 The x values to return the interpolated y values.44 """45 x = atleast_1d_and_contiguous(x, np.float64)46 y = atleast_1d_and_contiguous(y, np.float64)47 new_x = atleast_1d_and_contiguous(new_x, np.float64)48 if y.ndim > 2:49 raise ValueError("`linear` only works with 1-D or 2-D arrays.")50 if len(y.shape) == 2:51 new_y = np.zeros((y.shape[0], len(new_x)), np.float64)52 for i in range(len(new_y)): # for each row53 _interpolate.linear_dddd(x, y[i], new_x, new_y[i])54 else:55 new_y = np.zeros(len(new_x), np.float64)56 _interpolate.linear_dddd(x, y, new_x, new_y)57 return new_y58def logarithmic(x, y, new_x):59 """60 Linearly interpolates values in new_x based in the log space of y.61 Parameters62 ----------63 x : array_like64 Independent values.65 y : array_like66 Dependent values.67 new_x : array_like68 The x values to return interpolated y values at.69 """70 x = atleast_1d_and_contiguous(x, np.float64)71 y = atleast_1d_and_contiguous(y, np.float64)72 new_x = atleast_1d_and_contiguous(new_x, np.float64)73 if y.ndim > 2:74 raise ValueError("`linear` only works with 1-D or 2-D arrays.")75 if len(y.shape) == 2:76 new_y = np.zeros((y.shape[0], len(new_x)), np.float64)77 for i in range(len(new_y)):78 _interpolate.loginterp_dddd(x, y[i], new_x, new_y[i])79 else:80 new_y = np.zeros(len(new_x), np.float64)81 _interpolate.loginterp_dddd(x, y, new_x, new_y)82 return new_y83def block_average_above(x, y, new_x):84 """85 Linearly interpolates values in new_x based on the values in x and y.86 Parameters87 ----------88 x : array_like89 Independent values.90 y : array_like91 Dependent values.92 new_x : array_like93 The x values to interpolate y values.94 """95 bad_index = None96 x = atleast_1d_and_contiguous(x, np.float64)97 y = atleast_1d_and_contiguous(y, np.float64)98 new_x = atleast_1d_and_contiguous(new_x, np.float64)99 if y.ndim > 2:100 raise ValueError("`linear` only works with 1-D or 2-D arrays.")101 if len(y.shape) == 2:102 new_y = np.zeros((y.shape[0], len(new_x)), np.float64)103 for i in range(len(new_y)):104 bad_index = _interpolate.block_averave_above_dddd(x, y[i],105 new_x, new_y[i])106 if bad_index is not None:107 break108 else:109 new_y = np.zeros(len(new_x), np.float64)110 bad_index = _interpolate.block_average_above_dddd(x, y, new_x, new_y)111 if bad_index is not None:112 msg = "block_average_above cannot extrapolate and new_x[%d]=%f "\113 "is out of the x range (%f, %f)" % \114 (bad_index, new_x[bad_index], x[0], x[-1])115 raise ValueError(msg)116 return new_y117def block(x, y, new_x):118 """119 Essentially a step function.120 For each `new_x`, finds largest j such that``x[j] < new_x[j]`` and121 returns ``y[j]``.122 Parameters123 ----------124 x : array_like125 Independent values.126 y : array_like127 Dependent values.128 x_new : array_like129 The x values used to calculate the interpolated y.130 Returns131 -------132 block : ndarray133 Return array, of same length as `x_new`.134 """135 # find index of values in x that preceed values in x136 # This code is a little strange -- we really want a routine that137 # returns the index of values where x[j] < x[index]138 TINY = 1e-10139 indices = np.searchsorted(x, new_x+TINY)-1140 # If the value is at the front of the list, it'll have -1.141 # In this case, we will use the first (0), element in the array.142 # take requires the index array to be an Int143 indices = np.atleast_1d(np.clip(indices, 0, np.Inf).astype(np.int))144 new_y = np.take(y, indices, axis=-1)...

Full Screen

Full Screen

symbolic_opset11.py

Source:symbolic_opset11.py Github

copy

Full Screen

...27 dims = self.type().sizes()28 if len(dims) != 4:29 return _unimplemented("pixel_shuffle", "only support 4d input")30 return g.op("DepthToSpace", self, blocksize_i=upscale_factor, mode_s="CRD")31def _interpolate(name, dim, interpolate_mode):32 def symbolic_fn(g, input, output_size, align_corners=None):33 align_corners = sym_help._maybe_get_scalar(align_corners)34 output_size = sym_help._maybe_get_const(output_size, 'is')35 if sym_help._is_value(output_size):36 offsets = g.op("Constant", value_t=torch.ones(2, dtype=torch.int64))37 output_size = g.op("Cast", output_size, to_i=sym_help.cast_pytorch_to_onnx["Long"])38 output_size = g.op("Concat", offsets, output_size, axis_i=0)39 else:40 output_size = [1 if i < 2 else output_size[-(dim - i)] for i in range(0, dim)]41 output_size = g.op("Constant", value_t=torch.tensor(output_size))42 coordinate_transformation_mode = "asymmetric" if interpolate_mode == "nearest" \43 else "align_corners" if align_corners else "pytorch_half_pixel"44 empty_tensor = g.op("Constant", value_t=torch.tensor([], dtype=torch.float32))45 return g.op("Resize",46 input,47 empty_tensor, # roi only takes effect whith coordinate_transformation_mode="tf_crop_and_resize"48 empty_tensor, # scales is not needed since we are sending out_size49 output_size,50 coordinate_transformation_mode_s=coordinate_transformation_mode,51 cubic_coeff_a_f=-0.75, # only valid when mode="cubic"52 mode_s=interpolate_mode, # nearest, linear, or cubic53 nearest_mode_s="floor") # only valid when mode="nearest"54 return symbolic_fn55upsample_nearest1d = _interpolate('upsample_nearest1d', 3, "nearest")56upsample_nearest2d = _interpolate('upsample_nearest2d', 4, "nearest")57upsample_nearest3d = _interpolate('upsample_nearest3d', 5, "nearest")58upsample_linear1d = _interpolate('upsample_linear1d', 3, "linear")59upsample_bilinear2d = _interpolate('upsample_bilinear2d', 4, "linear")60upsample_trilinear3d = _interpolate('upsample_trilinear3d', 5, "linear")61upsample_bicubic2d = _interpolate('upsample_bicubic2d', 4, "cubic")62@parse_args('v', 'i', 'v', 'v')63def gather(g, self, dim, index, sparse_grad=False):64 if sym_help._maybe_get_const(sparse_grad, 'i'):65 return _unimplemented("gather", "sparse_grad == True")66 if sym_help._operator_export_type == torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK:67 return g.op("ATen", self, dim, index, sparse_grad, operator_s="gather")68 return g.op("GatherElements", self, index, axis_i=dim)69@parse_args('v', 'i', 'v', 'v')70def scatter(g, self, dim, index, src):71 if sym_help._operator_export_type == torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK:72 return g.op("ATen", self, dim, index, src, operator_s="scatter")73 return g.op("ScatterElements", self, index, src, axis_i=dim)74@parse_args('v', 'i', 'none')75def cumsum(g, self, dim, dtype=None):...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Gherkin-python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful