repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
mdsol/rwslib | rwslib/extras/local_cv.py | BaseDBAdapter.processFormData | def processFormData(self, data, dataset_name):
"""Take a string of form data as CSV and convert to insert statements, return template and data values"""
# Get the cols for this dataset
cols = self.datasets[dataset_name]
reader = self.getCSVReader(data, reader_type=csv.reader)
# Get fieldnames from first line of reader, what is left is set of rows
fieldnames = next(reader)
# Check columns
for col in cols:
varname = col["varname"]
if varname not in fieldnames:
raise ValueError("Column %s not found in data for dataset %s" % (varname, dataset_name,))
# Now call overrideen methods of base classes to process this data
self._processDML(dataset_name, cols, reader) | python | def processFormData(self, data, dataset_name):
"""Take a string of form data as CSV and convert to insert statements, return template and data values"""
# Get the cols for this dataset
cols = self.datasets[dataset_name]
reader = self.getCSVReader(data, reader_type=csv.reader)
# Get fieldnames from first line of reader, what is left is set of rows
fieldnames = next(reader)
# Check columns
for col in cols:
varname = col["varname"]
if varname not in fieldnames:
raise ValueError("Column %s not found in data for dataset %s" % (varname, dataset_name,))
# Now call overrideen methods of base classes to process this data
self._processDML(dataset_name, cols, reader) | [
"def",
"processFormData",
"(",
"self",
",",
"data",
",",
"dataset_name",
")",
":",
"# Get the cols for this dataset",
"cols",
"=",
"self",
".",
"datasets",
"[",
"dataset_name",
"]",
"reader",
"=",
"self",
".",
"getCSVReader",
"(",
"data",
",",
"reader_type",
"... | Take a string of form data as CSV and convert to insert statements, return template and data values | [
"Take",
"a",
"string",
"of",
"form",
"data",
"as",
"CSV",
"and",
"convert",
"to",
"insert",
"statements",
"return",
"template",
"and",
"data",
"values"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/local_cv.py#L79-L96 | train | 50,300 |
mdsol/rwslib | rwslib/extras/local_cv.py | SQLLiteDBAdapter._processDDL | def _processDDL(self):
"""Generate and process table SQL, SQLLite version"""
sql_statements = self._generateDDL()
logging.info('Generating sqllite tables')
for stmt in sql_statements:
c = self.conn.cursor()
c.execute(stmt)
self.conn.commit() | python | def _processDDL(self):
"""Generate and process table SQL, SQLLite version"""
sql_statements = self._generateDDL()
logging.info('Generating sqllite tables')
for stmt in sql_statements:
c = self.conn.cursor()
c.execute(stmt)
self.conn.commit() | [
"def",
"_processDDL",
"(",
"self",
")",
":",
"sql_statements",
"=",
"self",
".",
"_generateDDL",
"(",
")",
"logging",
".",
"info",
"(",
"'Generating sqllite tables'",
")",
"for",
"stmt",
"in",
"sql_statements",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cur... | Generate and process table SQL, SQLLite version | [
"Generate",
"and",
"process",
"table",
"SQL",
"SQLLite",
"version"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/local_cv.py#L111-L119 | train | 50,301 |
mdsol/rwslib | rwslib/extras/local_cv.py | SQLLiteDBAdapter._processDML | def _processDML(self, dataset_name, cols, reader):
"""Overridden version of create DML for SQLLite"""
sql_template = self._generateInsertStatement(dataset_name, cols)
# Now insert in batch, reader is a list of rows to insert at this point
c = self.conn.cursor()
c.executemany(sql_template, reader)
self.conn.commit() | python | def _processDML(self, dataset_name, cols, reader):
"""Overridden version of create DML for SQLLite"""
sql_template = self._generateInsertStatement(dataset_name, cols)
# Now insert in batch, reader is a list of rows to insert at this point
c = self.conn.cursor()
c.executemany(sql_template, reader)
self.conn.commit() | [
"def",
"_processDML",
"(",
"self",
",",
"dataset_name",
",",
"cols",
",",
"reader",
")",
":",
"sql_template",
"=",
"self",
".",
"_generateInsertStatement",
"(",
"dataset_name",
",",
"cols",
")",
"# Now insert in batch, reader is a list of rows to insert at this point",
... | Overridden version of create DML for SQLLite | [
"Overridden",
"version",
"of",
"create",
"DML",
"for",
"SQLLite"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/local_cv.py#L147-L154 | train | 50,302 |
mdsol/rwslib | rwslib/extras/local_cv.py | SQLLiteDBAdapter._generateInsertStatement | def _generateInsertStatement(self, dataset_name, cols):
"""Generates a sql INSERT template"""
col_names = [col["varname"] for col in cols]
# Generate question mark placeholders
qms = ','.join(['?' for x in col_names])
return 'INSERT INTO %s (%s) values (%s)' % (dataset_name, ','.join(col_names), qms) | python | def _generateInsertStatement(self, dataset_name, cols):
"""Generates a sql INSERT template"""
col_names = [col["varname"] for col in cols]
# Generate question mark placeholders
qms = ','.join(['?' for x in col_names])
return 'INSERT INTO %s (%s) values (%s)' % (dataset_name, ','.join(col_names), qms) | [
"def",
"_generateInsertStatement",
"(",
"self",
",",
"dataset_name",
",",
"cols",
")",
":",
"col_names",
"=",
"[",
"col",
"[",
"\"varname\"",
"]",
"for",
"col",
"in",
"cols",
"]",
"# Generate question mark placeholders",
"qms",
"=",
"','",
".",
"join",
"(",
... | Generates a sql INSERT template | [
"Generates",
"a",
"sql",
"INSERT",
"template"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/local_cv.py#L156-L163 | train | 50,303 |
mdsol/rwslib | rwslib/extras/local_cv.py | LocalCVBuilder.execute | def execute(self):
"""Generate local DB, pulling metadata and data from RWSConnection"""
logging.info('Requesting view metadata for project %s' % self.project_name)
project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name))
# Process it into a set of tables
self.db_adapter.processMetaData(project_csv_meta)
# Get the data for the study
for dataset_name in self.db_adapter.datasets.keys():
logging.info('Requesting data from dataset %s' % dataset_name)
form_name, _type = self.name_type_from_viewname(dataset_name)
form_data = self.rws_connection.send_request(
FormDataRequest(self.project_name, self.environment, _type, form_name))
# Now process the form_data into the db of choice
logging.info('Populating dataset %s' % dataset_name)
self.db_adapter.processFormData(form_data, dataset_name)
logging.info('Process complete') | python | def execute(self):
"""Generate local DB, pulling metadata and data from RWSConnection"""
logging.info('Requesting view metadata for project %s' % self.project_name)
project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name))
# Process it into a set of tables
self.db_adapter.processMetaData(project_csv_meta)
# Get the data for the study
for dataset_name in self.db_adapter.datasets.keys():
logging.info('Requesting data from dataset %s' % dataset_name)
form_name, _type = self.name_type_from_viewname(dataset_name)
form_data = self.rws_connection.send_request(
FormDataRequest(self.project_name, self.environment, _type, form_name))
# Now process the form_data into the db of choice
logging.info('Populating dataset %s' % dataset_name)
self.db_adapter.processFormData(form_data, dataset_name)
logging.info('Process complete') | [
"def",
"execute",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Requesting view metadata for project %s'",
"%",
"self",
".",
"project_name",
")",
"project_csv_meta",
"=",
"self",
".",
"rws_connection",
".",
"send_request",
"(",
"ProjectMetaDataRequest",
"(",... | Generate local DB, pulling metadata and data from RWSConnection | [
"Generate",
"local",
"DB",
"pulling",
"metadata",
"and",
"data",
"from",
"RWSConnection"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/local_cv.py#L183-L203 | train | 50,304 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | typeof_rave_data | def typeof_rave_data(value):
"""Function to duck-type values, not relying on standard Python functions because, for example,
a string of '1' should be typed as an integer and not as a string or float
since we're trying to replace like with like when scrambling."""
# Test if value is a date
for format in ['%d %b %Y', '%b %Y', '%Y', '%d %m %Y', '%m %Y', '%d/%b/%Y', '%b/%Y', '%d/%m/%Y', '%m/%Y']:
try:
datetime.datetime.strptime(value, format)
if len(value) == 4 and (int(value) < 1900 or int(value) > 2030):
break
return ('date', format)
except ValueError:
pass
except TypeError:
pass
# Test if value is a time
for format in ['%H:%M:%S', '%H:%M', '%I:%M:%S', '%I:%M', '%I:%M:%S %p', '%I:%M %p']:
try:
datetime.datetime.strptime(value, format)
return ('time', format)
except ValueError:
pass
except TypeError:
pass
# Test if value is a integer
try:
if ((isinstance(value, str) and isinstance(int(value), int)) \
or isinstance(value, int)):
return ('int', None)
except ValueError:
pass
except TypeError:
pass
# Test if value is a float
try:
float(value)
return ('float', None)
except ValueError:
pass
except TypeError:
pass
# If no match on anything else, assume its a string
return ('string', None) | python | def typeof_rave_data(value):
"""Function to duck-type values, not relying on standard Python functions because, for example,
a string of '1' should be typed as an integer and not as a string or float
since we're trying to replace like with like when scrambling."""
# Test if value is a date
for format in ['%d %b %Y', '%b %Y', '%Y', '%d %m %Y', '%m %Y', '%d/%b/%Y', '%b/%Y', '%d/%m/%Y', '%m/%Y']:
try:
datetime.datetime.strptime(value, format)
if len(value) == 4 and (int(value) < 1900 or int(value) > 2030):
break
return ('date', format)
except ValueError:
pass
except TypeError:
pass
# Test if value is a time
for format in ['%H:%M:%S', '%H:%M', '%I:%M:%S', '%I:%M', '%I:%M:%S %p', '%I:%M %p']:
try:
datetime.datetime.strptime(value, format)
return ('time', format)
except ValueError:
pass
except TypeError:
pass
# Test if value is a integer
try:
if ((isinstance(value, str) and isinstance(int(value), int)) \
or isinstance(value, int)):
return ('int', None)
except ValueError:
pass
except TypeError:
pass
# Test if value is a float
try:
float(value)
return ('float', None)
except ValueError:
pass
except TypeError:
pass
# If no match on anything else, assume its a string
return ('string', None) | [
"def",
"typeof_rave_data",
"(",
"value",
")",
":",
"# Test if value is a date",
"for",
"format",
"in",
"[",
"'%d %b %Y'",
",",
"'%b %Y'",
",",
"'%Y'",
",",
"'%d %m %Y'",
",",
"'%m %Y'",
",",
"'%d/%b/%Y'",
",",
"'%b/%Y'",
",",
"'%d/%m/%Y'",
",",
"'%m/%Y'",
"]",... | Function to duck-type values, not relying on standard Python functions because, for example,
a string of '1' should be typed as an integer and not as a string or float
since we're trying to replace like with like when scrambling. | [
"Function",
"to",
"duck",
"-",
"type",
"values",
"not",
"relying",
"on",
"standard",
"Python",
"functions",
"because",
"for",
"example",
"a",
"string",
"of",
"1",
"should",
"be",
"typed",
"as",
"an",
"integer",
"and",
"not",
"as",
"a",
"string",
"or",
"f... | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L14-L61 | train | 50,305 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_float | def scramble_float(self, length, sd=0):
"""Return random float in specified format"""
if sd == 0:
return str(fake.random_number(length))
else:
return str(fake.pyfloat(length - sd, sd, positive=True)) | python | def scramble_float(self, length, sd=0):
"""Return random float in specified format"""
if sd == 0:
return str(fake.random_number(length))
else:
return str(fake.pyfloat(length - sd, sd, positive=True)) | [
"def",
"scramble_float",
"(",
"self",
",",
"length",
",",
"sd",
"=",
"0",
")",
":",
"if",
"sd",
"==",
"0",
":",
"return",
"str",
"(",
"fake",
".",
"random_number",
"(",
"length",
")",
")",
"else",
":",
"return",
"str",
"(",
"fake",
".",
"pyfloat",
... | Return random float in specified format | [
"Return",
"random",
"float",
"in",
"specified",
"format"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L76-L81 | train | 50,306 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_date | def scramble_date(self, value, format='%d %b %Y'):
"""Return random date """
# faker method signature changed
if value == '':
# handle the empty string by defaulting to 'now' and 1 year ago
end_date = 'now'
start_date = '-1y'
else:
# specified end date, and one year prior
end_date = datetime.datetime.strptime(value, format).date()
start_date = end_date - datetime.timedelta(days=365)
fake_date = fake.date_time_between(start_date=start_date,
end_date=end_date).strftime(format).upper()
return fake_date | python | def scramble_date(self, value, format='%d %b %Y'):
"""Return random date """
# faker method signature changed
if value == '':
# handle the empty string by defaulting to 'now' and 1 year ago
end_date = 'now'
start_date = '-1y'
else:
# specified end date, and one year prior
end_date = datetime.datetime.strptime(value, format).date()
start_date = end_date - datetime.timedelta(days=365)
fake_date = fake.date_time_between(start_date=start_date,
end_date=end_date).strftime(format).upper()
return fake_date | [
"def",
"scramble_date",
"(",
"self",
",",
"value",
",",
"format",
"=",
"'%d %b %Y'",
")",
":",
"# faker method signature changed",
"if",
"value",
"==",
"''",
":",
"# handle the empty string by defaulting to 'now' and 1 year ago",
"end_date",
"=",
"'now'",
"start_date",
... | Return random date | [
"Return",
"random",
"date"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L83-L96 | train | 50,307 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_string | def scramble_string(self, length):
"""Return random string"""
return fake.text(length) if length > 5 else ''.join([fake.random_letter() for n in range(0, length)]) | python | def scramble_string(self, length):
"""Return random string"""
return fake.text(length) if length > 5 else ''.join([fake.random_letter() for n in range(0, length)]) | [
"def",
"scramble_string",
"(",
"self",
",",
"length",
")",
":",
"return",
"fake",
".",
"text",
"(",
"length",
")",
"if",
"length",
">",
"5",
"else",
"''",
".",
"join",
"(",
"[",
"fake",
".",
"random_letter",
"(",
")",
"for",
"n",
"in",
"range",
"("... | Return random string | [
"Return",
"random",
"string"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L102-L104 | train | 50,308 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_value | def scramble_value(self, value):
"""Duck-type value and scramble appropriately"""
try:
type, format = typeof_rave_data(value)
if type == 'float':
i, f = value.split('.')
return self.scramble_float(len(value) - 1, len(f))
elif type == 'int':
return self.scramble_int(len(value))
elif type == 'date':
return self.scramble_date(value, format)
elif type == 'time':
return self.scramble_time(format)
elif type == 'string':
return self.scramble_string(len(value))
else:
return value
except:
return "" | python | def scramble_value(self, value):
"""Duck-type value and scramble appropriately"""
try:
type, format = typeof_rave_data(value)
if type == 'float':
i, f = value.split('.')
return self.scramble_float(len(value) - 1, len(f))
elif type == 'int':
return self.scramble_int(len(value))
elif type == 'date':
return self.scramble_date(value, format)
elif type == 'time':
return self.scramble_time(format)
elif type == 'string':
return self.scramble_string(len(value))
else:
return value
except:
return "" | [
"def",
"scramble_value",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"type",
",",
"format",
"=",
"typeof_rave_data",
"(",
"value",
")",
"if",
"type",
"==",
"'float'",
":",
"i",
",",
"f",
"=",
"value",
".",
"split",
"(",
"'.'",
")",
"return",
"... | Duck-type value and scramble appropriately | [
"Duck",
"-",
"type",
"value",
"and",
"scramble",
"appropriately"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L106-L124 | train | 50,309 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_codelist | def scramble_codelist(self, codelist):
"""Return random element from code list"""
# TODO: External code lists
path = ".//{0}[@{1}='{2}']".format(E_ODM.CODELIST.value, A_ODM.OID.value, codelist)
elem = self.metadata.find(path)
codes = []
for c in elem.iter(E_ODM.CODELIST_ITEM.value):
codes.append(c.get(A_ODM.CODED_VALUE.value))
for c in elem.iter(E_ODM.ENUMERATED_ITEM.value):
codes.append(c.get(A_ODM.CODED_VALUE.value))
return fake.random_element(codes) | python | def scramble_codelist(self, codelist):
"""Return random element from code list"""
# TODO: External code lists
path = ".//{0}[@{1}='{2}']".format(E_ODM.CODELIST.value, A_ODM.OID.value, codelist)
elem = self.metadata.find(path)
codes = []
for c in elem.iter(E_ODM.CODELIST_ITEM.value):
codes.append(c.get(A_ODM.CODED_VALUE.value))
for c in elem.iter(E_ODM.ENUMERATED_ITEM.value):
codes.append(c.get(A_ODM.CODED_VALUE.value))
return fake.random_element(codes) | [
"def",
"scramble_codelist",
"(",
"self",
",",
"codelist",
")",
":",
"# TODO: External code lists",
"path",
"=",
"\".//{0}[@{1}='{2}']\"",
".",
"format",
"(",
"E_ODM",
".",
"CODELIST",
".",
"value",
",",
"A_ODM",
".",
"OID",
".",
"value",
",",
"codelist",
")",... | Return random element from code list | [
"Return",
"random",
"element",
"from",
"code",
"list"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L134-L145 | train | 50,310 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_itemdata | def scramble_itemdata(self, oid, value):
"""If metadata provided, use it to scramble the value based on data type"""
if self.metadata is not None:
path = ".//{0}[@{1}='{2}']".format(E_ODM.ITEM_DEF.value, A_ODM.OID.value, oid)
elem = self.metadata.find(path)
# for elem in self.metadata.iter(E_ODM.ITEM_DEF.value):
datatype = elem.get(A_ODM.DATATYPE.value)
codelist = None
for el in elem.iter(E_ODM.CODELIST_REF.value):
codelist = el.get(A_ODM.CODELIST_OID.value)
length = 1 if not A_ODM.LENGTH in elem else int(elem.get(A_ODM.LENGTH.value))
if A_ODM.SIGNIFICANT_DIGITS.value in elem.keys():
sd = elem.get(A_ODM.SIGNIFICANT_DIGITS.value)
else:
sd = 0
if A_ODM.DATETIME_FORMAT.value in elem.keys():
dt_format = elem.get(A_ODM.DATETIME_FORMAT.value)
for fmt in [('yyyy', '%Y'), ('MMM', '%b'), ('dd', '%d'), ('HH', '%H'), ('nn', '%M'), ('ss', '%S'),
('-', '')]:
dt_format = dt_format.replace(fmt[0], fmt[1])
if codelist is not None:
return self.scramble_codelist(codelist)
elif datatype == 'integer':
return self.scramble_int(length)
elif datatype == 'float':
return self.scramble_float(length, sd)
elif datatype in ['string', 'text']:
return self.scramble_string(length)
elif datatype in ['date', 'datetime']:
return self.scramble_date(value, dt_format)
elif datatype in ['time']:
return self.scramble_time(dt_format)
else:
return self.scramble_value(value)
else:
return self.scramble_value(value) | python | def scramble_itemdata(self, oid, value):
"""If metadata provided, use it to scramble the value based on data type"""
if self.metadata is not None:
path = ".//{0}[@{1}='{2}']".format(E_ODM.ITEM_DEF.value, A_ODM.OID.value, oid)
elem = self.metadata.find(path)
# for elem in self.metadata.iter(E_ODM.ITEM_DEF.value):
datatype = elem.get(A_ODM.DATATYPE.value)
codelist = None
for el in elem.iter(E_ODM.CODELIST_REF.value):
codelist = el.get(A_ODM.CODELIST_OID.value)
length = 1 if not A_ODM.LENGTH in elem else int(elem.get(A_ODM.LENGTH.value))
if A_ODM.SIGNIFICANT_DIGITS.value in elem.keys():
sd = elem.get(A_ODM.SIGNIFICANT_DIGITS.value)
else:
sd = 0
if A_ODM.DATETIME_FORMAT.value in elem.keys():
dt_format = elem.get(A_ODM.DATETIME_FORMAT.value)
for fmt in [('yyyy', '%Y'), ('MMM', '%b'), ('dd', '%d'), ('HH', '%H'), ('nn', '%M'), ('ss', '%S'),
('-', '')]:
dt_format = dt_format.replace(fmt[0], fmt[1])
if codelist is not None:
return self.scramble_codelist(codelist)
elif datatype == 'integer':
return self.scramble_int(length)
elif datatype == 'float':
return self.scramble_float(length, sd)
elif datatype in ['string', 'text']:
return self.scramble_string(length)
elif datatype in ['date', 'datetime']:
return self.scramble_date(value, dt_format)
elif datatype in ['time']:
return self.scramble_time(dt_format)
else:
return self.scramble_value(value)
else:
return self.scramble_value(value) | [
"def",
"scramble_itemdata",
"(",
"self",
",",
"oid",
",",
"value",
")",
":",
"if",
"self",
".",
"metadata",
"is",
"not",
"None",
":",
"path",
"=",
"\".//{0}[@{1}='{2}']\"",
".",
"format",
"(",
"E_ODM",
".",
"ITEM_DEF",
".",
"value",
",",
"A_ODM",
".",
... | If metadata provided, use it to scramble the value based on data type | [
"If",
"metadata",
"provided",
"use",
"it",
"to",
"scramble",
"the",
"value",
"based",
"on",
"data",
"type"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L147-L194 | train | 50,311 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.fill_empty | def fill_empty(self, fixed_values, input):
"""Fill in random values for all empty-valued ItemData elements in an ODM document"""
odm_elements = etree.fromstring(input)
for v in odm_elements.iter(E_ODM.ITEM_DATA.value):
if v.get(A_ODM.VALUE.value) == "":
oid = v.get(A_ODM.ITEM_OID.value)
if fixed_values is not None and oid in fixed_values:
d = fixed_values[oid]
else:
d = self.scramble_itemdata(v.get(A_ODM.ITEM_OID.value), v.get(A_ODM.VALUE.value))
v.set(A_ODM.VALUE.value, d)
else:
# Remove ItemData if it already has a value
v.getparent().remove(v)
# Remove empty ItemGroupData elements
for v in odm_elements.iter(E_ODM.ITEM_GROUP_DATA.value):
if len(v) == 0:
v.getparent().remove(v)
# Remove empty FormData elements
for v in odm_elements.iter(E_ODM.FORM_DATA.value):
if len(v) == 0:
v.getparent().remove(v)
# Remove empty StudyEventData elements
for v in odm_elements.iter(E_ODM.STUDY_EVENT_DATA.value):
if len(v) == 0:
v.getparent().remove(v)
return etree.tostring(odm_elements) | python | def fill_empty(self, fixed_values, input):
"""Fill in random values for all empty-valued ItemData elements in an ODM document"""
odm_elements = etree.fromstring(input)
for v in odm_elements.iter(E_ODM.ITEM_DATA.value):
if v.get(A_ODM.VALUE.value) == "":
oid = v.get(A_ODM.ITEM_OID.value)
if fixed_values is not None and oid in fixed_values:
d = fixed_values[oid]
else:
d = self.scramble_itemdata(v.get(A_ODM.ITEM_OID.value), v.get(A_ODM.VALUE.value))
v.set(A_ODM.VALUE.value, d)
else:
# Remove ItemData if it already has a value
v.getparent().remove(v)
# Remove empty ItemGroupData elements
for v in odm_elements.iter(E_ODM.ITEM_GROUP_DATA.value):
if len(v) == 0:
v.getparent().remove(v)
# Remove empty FormData elements
for v in odm_elements.iter(E_ODM.FORM_DATA.value):
if len(v) == 0:
v.getparent().remove(v)
# Remove empty StudyEventData elements
for v in odm_elements.iter(E_ODM.STUDY_EVENT_DATA.value):
if len(v) == 0:
v.getparent().remove(v)
return etree.tostring(odm_elements) | [
"def",
"fill_empty",
"(",
"self",
",",
"fixed_values",
",",
"input",
")",
":",
"odm_elements",
"=",
"etree",
".",
"fromstring",
"(",
"input",
")",
"for",
"v",
"in",
"odm_elements",
".",
"iter",
"(",
"E_ODM",
".",
"ITEM_DATA",
".",
"value",
")",
":",
"i... | Fill in random values for all empty-valued ItemData elements in an ODM document | [
"Fill",
"in",
"random",
"values",
"for",
"all",
"empty",
"-",
"valued",
"ItemData",
"elements",
"in",
"an",
"ODM",
"document"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L200-L233 | train | 50,312 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | make_int | def make_int(value, missing=-1):
"""Convert string value to long, '' to missing"""
if isinstance(value, six.string_types):
if not value.strip():
return missing
elif value is None:
return missing
return int(value) | python | def make_int(value, missing=-1):
"""Convert string value to long, '' to missing"""
if isinstance(value, six.string_types):
if not value.strip():
return missing
elif value is None:
return missing
return int(value) | [
"def",
"make_int",
"(",
"value",
",",
"missing",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"if",
"not",
"value",
".",
"strip",
"(",
")",
":",
"return",
"missing",
"elif",
"value",
"is",
"N... | Convert string value to long, '' to missing | [
"Convert",
"string",
"value",
"to",
"long",
"to",
"missing"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L38-L45 | train | 50,313 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | parse | def parse(data, eventer):
"""Parse the XML data, firing events from the eventer"""
parser = etree.XMLParser(target=ODMTargetParser(eventer))
return etree.XML(data, parser) | python | def parse(data, eventer):
"""Parse the XML data, firing events from the eventer"""
parser = etree.XMLParser(target=ODMTargetParser(eventer))
return etree.XML(data, parser) | [
"def",
"parse",
"(",
"data",
",",
"eventer",
")",
":",
"parser",
"=",
"etree",
".",
"XMLParser",
"(",
"target",
"=",
"ODMTargetParser",
"(",
"eventer",
")",
")",
"return",
"etree",
".",
"XML",
"(",
"data",
",",
"parser",
")"
] | Parse the XML data, firing events from the eventer | [
"Parse",
"the",
"XML",
"data",
"firing",
"events",
"from",
"the",
"eventer"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L284-L287 | train | 50,314 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | ODMTargetParser.emit | def emit(self):
"""We are finished processing one element. Emit it"""
self.count += 1
# event_name = 'on_{0}'.format(self.context.subcategory.lower())
event_name = self.context.subcategory
if hasattr(self.handler, event_name):
getattr(self.handler, event_name)(self.context)
elif hasattr(self.handler, 'default'):
self.handler.default(self.context) | python | def emit(self):
"""We are finished processing one element. Emit it"""
self.count += 1
# event_name = 'on_{0}'.format(self.context.subcategory.lower())
event_name = self.context.subcategory
if hasattr(self.handler, event_name):
getattr(self.handler, event_name)(self.context)
elif hasattr(self.handler, 'default'):
self.handler.default(self.context) | [
"def",
"emit",
"(",
"self",
")",
":",
"self",
".",
"count",
"+=",
"1",
"# event_name = 'on_{0}'.format(self.context.subcategory.lower())",
"event_name",
"=",
"self",
".",
"context",
".",
"subcategory",
"if",
"hasattr",
"(",
"self",
".",
"handler",
",",
"event_name... | We are finished processing one element. Emit it | [
"We",
"are",
"finished",
"processing",
"one",
"element",
".",
"Emit",
"it"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L139-L149 | train | 50,315 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | ODMTargetParser.get_parent_element | def get_parent_element(self):
"""Signatures and Audit elements share sub-elements, we need to know which to set attributes on"""
return {AUDIT_REF_STATE: self.context.audit_record,
SIGNATURE_REF_STATE: self.context.signature}[self.ref_state] | python | def get_parent_element(self):
"""Signatures and Audit elements share sub-elements, we need to know which to set attributes on"""
return {AUDIT_REF_STATE: self.context.audit_record,
SIGNATURE_REF_STATE: self.context.signature}[self.ref_state] | [
"def",
"get_parent_element",
"(",
"self",
")",
":",
"return",
"{",
"AUDIT_REF_STATE",
":",
"self",
".",
"context",
".",
"audit_record",
",",
"SIGNATURE_REF_STATE",
":",
"self",
".",
"context",
".",
"signature",
"}",
"[",
"self",
".",
"ref_state",
"]"
] | Signatures and Audit elements share sub-elements, we need to know which to set attributes on | [
"Signatures",
"and",
"Audit",
"elements",
"share",
"sub",
"-",
"elements",
"we",
"need",
"to",
"know",
"which",
"to",
"set",
"attributes",
"on"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L263-L266 | train | 50,316 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | ODMTargetParser.data | def data(self, data):
"""Called for text between tags"""
if self.state == STATE_SOURCE_ID:
self.context.audit_record.source_id = int(data) # Audit ids can be 64 bits
elif self.state == STATE_DATETIME:
dt = datetime.datetime.strptime(data, "%Y-%m-%dT%H:%M:%S")
self.get_parent_element().datetimestamp = dt
elif self.state == STATE_REASON_FOR_CHANGE:
self.context.audit_record.reason_for_change = data.strip() or None # Convert a result of '' to None.
self.state = STATE_NONE | python | def data(self, data):
"""Called for text between tags"""
if self.state == STATE_SOURCE_ID:
self.context.audit_record.source_id = int(data) # Audit ids can be 64 bits
elif self.state == STATE_DATETIME:
dt = datetime.datetime.strptime(data, "%Y-%m-%dT%H:%M:%S")
self.get_parent_element().datetimestamp = dt
elif self.state == STATE_REASON_FOR_CHANGE:
self.context.audit_record.reason_for_change = data.strip() or None # Convert a result of '' to None.
self.state = STATE_NONE | [
"def",
"data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"state",
"==",
"STATE_SOURCE_ID",
":",
"self",
".",
"context",
".",
"audit_record",
".",
"source_id",
"=",
"int",
"(",
"data",
")",
"# Audit ids can be 64 bits",
"elif",
"self",
".",
"... | Called for text between tags | [
"Called",
"for",
"text",
"between",
"tags"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L268-L277 | train | 50,317 |
timster/peewee-validates | peewee_validates.py | validate_one_of | def validate_one_of(values):
"""
Validate that a field is in one of the given values.
:param values: Iterable of valid values.
:raises: ``ValidationError('one_of')``
"""
def one_of_validator(field, data):
if field.value is None:
return
options = values
if callable(options):
options = options()
if field.value not in options:
raise ValidationError('one_of', choices=', '.join(map(str, options)))
return one_of_validator | python | def validate_one_of(values):
"""
Validate that a field is in one of the given values.
:param values: Iterable of valid values.
:raises: ``ValidationError('one_of')``
"""
def one_of_validator(field, data):
if field.value is None:
return
options = values
if callable(options):
options = options()
if field.value not in options:
raise ValidationError('one_of', choices=', '.join(map(str, options)))
return one_of_validator | [
"def",
"validate_one_of",
"(",
"values",
")",
":",
"def",
"one_of_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"field",
".",
"value",
"is",
"None",
":",
"return",
"options",
"=",
"values",
"if",
"callable",
"(",
"options",
")",
":",
"options",
... | Validate that a field is in one of the given values.
:param values: Iterable of valid values.
:raises: ``ValidationError('one_of')`` | [
"Validate",
"that",
"a",
"field",
"is",
"in",
"one",
"of",
"the",
"given",
"values",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L117-L132 | train | 50,318 |
timster/peewee-validates | peewee_validates.py | validate_none_of | def validate_none_of(values):
"""
Validate that a field is not in one of the given values.
:param values: Iterable of invalid values.
:raises: ``ValidationError('none_of')``
"""
def none_of_validator(field, data):
options = values
if callable(options):
options = options()
if field.value in options:
raise ValidationError('none_of', choices=str.join(', ', options))
return none_of_validator | python | def validate_none_of(values):
"""
Validate that a field is not in one of the given values.
:param values: Iterable of invalid values.
:raises: ``ValidationError('none_of')``
"""
def none_of_validator(field, data):
options = values
if callable(options):
options = options()
if field.value in options:
raise ValidationError('none_of', choices=str.join(', ', options))
return none_of_validator | [
"def",
"validate_none_of",
"(",
"values",
")",
":",
"def",
"none_of_validator",
"(",
"field",
",",
"data",
")",
":",
"options",
"=",
"values",
"if",
"callable",
"(",
"options",
")",
":",
"options",
"=",
"options",
"(",
")",
"if",
"field",
".",
"value",
... | Validate that a field is not in one of the given values.
:param values: Iterable of invalid values.
:raises: ``ValidationError('none_of')`` | [
"Validate",
"that",
"a",
"field",
"is",
"not",
"in",
"one",
"of",
"the",
"given",
"values",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L135-L148 | train | 50,319 |
timster/peewee-validates | peewee_validates.py | validate_equal | def validate_equal(value):
"""
Validate the field value is equal to the given value.
Should work with anything that supports '==' operator.
:param value: Value to compare.
:raises: ``ValidationError('equal')``
"""
def equal_validator(field, data):
if field.value is None:
return
if not (field.value == value):
raise ValidationError('equal', other=value)
return equal_validator | python | def validate_equal(value):
"""
Validate the field value is equal to the given value.
Should work with anything that supports '==' operator.
:param value: Value to compare.
:raises: ``ValidationError('equal')``
"""
def equal_validator(field, data):
if field.value is None:
return
if not (field.value == value):
raise ValidationError('equal', other=value)
return equal_validator | [
"def",
"validate_equal",
"(",
"value",
")",
":",
"def",
"equal_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"field",
".",
"value",
"is",
"None",
":",
"return",
"if",
"not",
"(",
"field",
".",
"value",
"==",
"value",
")",
":",
"raise",
"Vali... | Validate the field value is equal to the given value.
Should work with anything that supports '==' operator.
:param value: Value to compare.
:raises: ``ValidationError('equal')`` | [
"Validate",
"the",
"field",
"value",
"is",
"equal",
"to",
"the",
"given",
"value",
".",
"Should",
"work",
"with",
"anything",
"that",
"supports",
"==",
"operator",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L174-L187 | train | 50,320 |
timster/peewee-validates | peewee_validates.py | validate_matches | def validate_matches(other):
"""
Validate the field value is equal to another field in the data.
Should work with anything that supports '==' operator.
:param value: Field key to compare.
:raises: ``ValidationError('matches')``
"""
def matches_validator(field, data):
if field.value is None:
return
if not (field.value == data.get(other)):
raise ValidationError('matches', other=other)
return matches_validator | python | def validate_matches(other):
"""
Validate the field value is equal to another field in the data.
Should work with anything that supports '==' operator.
:param value: Field key to compare.
:raises: ``ValidationError('matches')``
"""
def matches_validator(field, data):
if field.value is None:
return
if not (field.value == data.get(other)):
raise ValidationError('matches', other=other)
return matches_validator | [
"def",
"validate_matches",
"(",
"other",
")",
":",
"def",
"matches_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"field",
".",
"value",
"is",
"None",
":",
"return",
"if",
"not",
"(",
"field",
".",
"value",
"==",
"data",
".",
"get",
"(",
"oth... | Validate the field value is equal to another field in the data.
Should work with anything that supports '==' operator.
:param value: Field key to compare.
:raises: ``ValidationError('matches')`` | [
"Validate",
"the",
"field",
"value",
"is",
"equal",
"to",
"another",
"field",
"in",
"the",
"data",
".",
"Should",
"work",
"with",
"anything",
"that",
"supports",
"==",
"operator",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L190-L203 | train | 50,321 |
timster/peewee-validates | peewee_validates.py | validate_regexp | def validate_regexp(pattern, flags=0):
"""
Validate the field matches the given regular expression.
Should work with anything that supports '==' operator.
:param pattern: Regular expresion to match. String or regular expression instance.
:param pattern: Flags for the regular expression.
:raises: ``ValidationError('equal')``
"""
regex = re.compile(pattern, flags) if isinstance(pattern, str) else pattern
def regexp_validator(field, data):
if field.value is None:
return
if regex.match(str(field.value)) is None:
raise ValidationError('regexp', pattern=pattern)
return regexp_validator | python | def validate_regexp(pattern, flags=0):
"""
Validate the field matches the given regular expression.
Should work with anything that supports '==' operator.
:param pattern: Regular expresion to match. String or regular expression instance.
:param pattern: Flags for the regular expression.
:raises: ``ValidationError('equal')``
"""
regex = re.compile(pattern, flags) if isinstance(pattern, str) else pattern
def regexp_validator(field, data):
if field.value is None:
return
if regex.match(str(field.value)) is None:
raise ValidationError('regexp', pattern=pattern)
return regexp_validator | [
"def",
"validate_regexp",
"(",
"pattern",
",",
"flags",
"=",
"0",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"pattern",
",",
"flags",
")",
"if",
"isinstance",
"(",
"pattern",
",",
"str",
")",
"else",
"pattern",
"def",
"regexp_validator",
"(",
"... | Validate the field matches the given regular expression.
Should work with anything that supports '==' operator.
:param pattern: Regular expresion to match. String or regular expression instance.
:param pattern: Flags for the regular expression.
:raises: ``ValidationError('equal')`` | [
"Validate",
"the",
"field",
"matches",
"the",
"given",
"regular",
"expression",
".",
"Should",
"work",
"with",
"anything",
"that",
"supports",
"==",
"operator",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L206-L222 | train | 50,322 |
timster/peewee-validates | peewee_validates.py | validate_email | def validate_email():
"""
Validate the field is a valid email address.
:raises: ``ValidationError('email')``
"""
user_regex = re.compile(
r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$"
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'
r'|\\[\001-\011\013\014\016-\177])*"$)', re.IGNORECASE | re.UNICODE)
domain_regex = re.compile(
r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}|[A-Z0-9-]{2,})$'
r'|^\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)'
r'(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE | re.UNICODE)
domain_whitelist = ('localhost',)
def email_validator(field, data):
if field.value is None:
return
value = str(field.value)
if '@' not in value:
raise ValidationError('email')
user_part, domain_part = value.rsplit('@', 1)
if not user_regex.match(user_part):
raise ValidationError('email')
if domain_part in domain_whitelist:
return
if not domain_regex.match(domain_part):
raise ValidationError('email')
return email_validator | python | def validate_email():
"""
Validate the field is a valid email address.
:raises: ``ValidationError('email')``
"""
user_regex = re.compile(
r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$"
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'
r'|\\[\001-\011\013\014\016-\177])*"$)', re.IGNORECASE | re.UNICODE)
domain_regex = re.compile(
r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}|[A-Z0-9-]{2,})$'
r'|^\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)'
r'(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE | re.UNICODE)
domain_whitelist = ('localhost',)
def email_validator(field, data):
if field.value is None:
return
value = str(field.value)
if '@' not in value:
raise ValidationError('email')
user_part, domain_part = value.rsplit('@', 1)
if not user_regex.match(user_part):
raise ValidationError('email')
if domain_part in domain_whitelist:
return
if not domain_regex.match(domain_part):
raise ValidationError('email')
return email_validator | [
"def",
"validate_email",
"(",
")",
":",
"user_regex",
"=",
"re",
".",
"compile",
"(",
"r\"(^[-!#$%&'*+/=?^`{}|~\\w]+(\\.[-!#$%&'*+/=?^`{}|~\\w]+)*$\"",
"r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]'",
"r'|\\\\[\\001-\\011\\013\\014\\016-\\177])*\"$)'",
",",
"re",
".",
"... | Validate the field is a valid email address.
:raises: ``ValidationError('email')`` | [
"Validate",
"the",
"field",
"is",
"a",
"valid",
"email",
"address",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L248-L287 | train | 50,323 |
timster/peewee-validates | peewee_validates.py | isiterable_notstring | def isiterable_notstring(value):
"""
Returns True if the value is iterable but not a string. Otherwise returns False.
:param value: Value to check.
"""
if isinstance(value, str):
return False
return isinstance(value, Iterable) or isgeneratorfunction(value) or isgenerator(value) | python | def isiterable_notstring(value):
"""
Returns True if the value is iterable but not a string. Otherwise returns False.
:param value: Value to check.
"""
if isinstance(value, str):
return False
return isinstance(value, Iterable) or isgeneratorfunction(value) or isgenerator(value) | [
"def",
"isiterable_notstring",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"False",
"return",
"isinstance",
"(",
"value",
",",
"Iterable",
")",
"or",
"isgeneratorfunction",
"(",
"value",
")",
"or",
"isgenerator",... | Returns True if the value is iterable but not a string. Otherwise returns False.
:param value: Value to check. | [
"Returns",
"True",
"if",
"the",
"value",
"is",
"iterable",
"but",
"not",
"a",
"string",
".",
"Otherwise",
"returns",
"False",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L337-L345 | train | 50,324 |
timster/peewee-validates | peewee_validates.py | Field.get_value | def get_value(self, name, data):
"""
Get the value of this field from the data.
If there is a problem with the data, raise ValidationError.
:param name: Name of this field (to retrieve from data).
:param data: Dictionary of data for all fields.
:raises: ValidationError
:return: The value of this field.
:rtype: any
"""
if name in data:
return data.get(name)
if self.default:
if callable(self.default):
return self.default()
return self.default
return None | python | def get_value(self, name, data):
"""
Get the value of this field from the data.
If there is a problem with the data, raise ValidationError.
:param name: Name of this field (to retrieve from data).
:param data: Dictionary of data for all fields.
:raises: ValidationError
:return: The value of this field.
:rtype: any
"""
if name in data:
return data.get(name)
if self.default:
if callable(self.default):
return self.default()
return self.default
return None | [
"def",
"get_value",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"if",
"name",
"in",
"data",
":",
"return",
"data",
".",
"get",
"(",
"name",
")",
"if",
"self",
".",
"default",
":",
"if",
"callable",
"(",
"self",
".",
"default",
")",
":",
"ret... | Get the value of this field from the data.
If there is a problem with the data, raise ValidationError.
:param name: Name of this field (to retrieve from data).
:param data: Dictionary of data for all fields.
:raises: ValidationError
:return: The value of this field.
:rtype: any | [
"Get",
"the",
"value",
"of",
"this",
"field",
"from",
"the",
"data",
".",
"If",
"there",
"is",
"a",
"problem",
"with",
"the",
"data",
"raise",
"ValidationError",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L379-L396 | train | 50,325 |
timster/peewee-validates | peewee_validates.py | Field.validate | def validate(self, name, data):
"""
Check to make sure ths data for this field is valid.
Usually runs all validators in self.validators list.
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError
"""
self.value = self.get_value(name, data)
if self.value is not None:
self.value = self.coerce(self.value)
for method in self.validators:
method(self, data) | python | def validate(self, name, data):
"""
Check to make sure ths data for this field is valid.
Usually runs all validators in self.validators list.
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError
"""
self.value = self.get_value(name, data)
if self.value is not None:
self.value = self.coerce(self.value)
for method in self.validators:
method(self, data) | [
"def",
"validate",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"self",
".",
"value",
"=",
"self",
".",
"get_value",
"(",
"name",
",",
"data",
")",
"if",
"self",
".",
"value",
"is",
"not",
"None",
":",
"self",
".",
"value",
"=",
"self",
".",
... | Check to make sure ths data for this field is valid.
Usually runs all validators in self.validators list.
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError | [
"Check",
"to",
"make",
"sure",
"ths",
"data",
"for",
"this",
"field",
"is",
"valid",
".",
"Usually",
"runs",
"all",
"validators",
"in",
"self",
".",
"validators",
"list",
".",
"If",
"there",
"is",
"a",
"problem",
"with",
"the",
"data",
"raise",
"Validati... | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L398-L412 | train | 50,326 |
timster/peewee-validates | peewee_validates.py | ModelChoiceField.validate | def validate(self, name, data):
"""
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError
"""
super().validate(name, data)
if self.value is not None:
try:
self.value = self.query.get(self.lookup_field == self.value)
except (AttributeError, ValueError, peewee.DoesNotExist):
raise ValidationError('related', field=self.lookup_field.name, values=self.value) | python | def validate(self, name, data):
"""
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError
"""
super().validate(name, data)
if self.value is not None:
try:
self.value = self.query.get(self.lookup_field == self.value)
except (AttributeError, ValueError, peewee.DoesNotExist):
raise ValidationError('related', field=self.lookup_field.name, values=self.value) | [
"def",
"validate",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"super",
"(",
")",
".",
"validate",
"(",
"name",
",",
"data",
")",
"if",
"self",
".",
"value",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"value",
"=",
"self",
".",
"qu... | If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError | [
"If",
"there",
"is",
"a",
"problem",
"with",
"the",
"data",
"raise",
"ValidationError",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L641-L654 | train | 50,327 |
timster/peewee-validates | peewee_validates.py | ManyModelChoiceField.coerce | def coerce(self, value):
"""Convert from whatever is given to a list of scalars for the lookup_field."""
if isinstance(value, dict):
value = [value]
if not isiterable_notstring(value):
value = [value]
return [coerce_single_instance(self.lookup_field, v) for v in value] | python | def coerce(self, value):
"""Convert from whatever is given to a list of scalars for the lookup_field."""
if isinstance(value, dict):
value = [value]
if not isiterable_notstring(value):
value = [value]
return [coerce_single_instance(self.lookup_field, v) for v in value] | [
"def",
"coerce",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value",
"=",
"[",
"value",
"]",
"if",
"not",
"isiterable_notstring",
"(",
"value",
")",
":",
"value",
"=",
"[",
"value",
"]",
"return",
... | Convert from whatever is given to a list of scalars for the lookup_field. | [
"Convert",
"from",
"whatever",
"is",
"given",
"to",
"a",
"list",
"of",
"scalars",
"for",
"the",
"lookup_field",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L672-L678 | train | 50,328 |
timster/peewee-validates | peewee_validates.py | Validator.initialize_fields | def initialize_fields(self):
"""
The dict self.base_fields is a model instance at this point.
Turn it into an instance attribute on this meta class.
Also intitialize any other special fields if needed in sub-classes.
:return: None
"""
for field in dir(self):
obj = getattr(self, field)
if isinstance(obj, Field):
self._meta.fields[field] = obj | python | def initialize_fields(self):
"""
The dict self.base_fields is a model instance at this point.
Turn it into an instance attribute on this meta class.
Also intitialize any other special fields if needed in sub-classes.
:return: None
"""
for field in dir(self):
obj = getattr(self, field)
if isinstance(obj, Field):
self._meta.fields[field] = obj | [
"def",
"initialize_fields",
"(",
"self",
")",
":",
"for",
"field",
"in",
"dir",
"(",
"self",
")",
":",
"obj",
"=",
"getattr",
"(",
"self",
",",
"field",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Field",
")",
":",
"self",
".",
"_meta",
".",
"fields... | The dict self.base_fields is a model instance at this point.
Turn it into an instance attribute on this meta class.
Also intitialize any other special fields if needed in sub-classes.
:return: None | [
"The",
"dict",
"self",
".",
"base_fields",
"is",
"a",
"model",
"instance",
"at",
"this",
"point",
".",
"Turn",
"it",
"into",
"an",
"instance",
"attribute",
"on",
"this",
"meta",
"class",
".",
"Also",
"intitialize",
"any",
"other",
"special",
"fields",
"if"... | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L742-L753 | train | 50,329 |
timster/peewee-validates | peewee_validates.py | ModelValidator.initialize_fields | def initialize_fields(self):
"""
Convert all model fields to validator fields.
Then call the parent so that overwrites can happen if necessary for manually defined fields.
:return: None
"""
# # Pull all the "normal" fields off the model instance meta.
for name, field in self.instance._meta.fields.items():
if getattr(field, 'primary_key', False):
continue
self._meta.fields[name] = self.convert_field(name, field)
# Many-to-many fields are not stored in the meta fields dict.
# Pull them directly off the class.
for name in dir(type(self.instance)):
field = getattr(type(self.instance), name, None)
if isinstance(field, ManyToManyField):
self._meta.fields[name] = self.convert_field(name, field)
super().initialize_fields() | python | def initialize_fields(self):
"""
Convert all model fields to validator fields.
Then call the parent so that overwrites can happen if necessary for manually defined fields.
:return: None
"""
# # Pull all the "normal" fields off the model instance meta.
for name, field in self.instance._meta.fields.items():
if getattr(field, 'primary_key', False):
continue
self._meta.fields[name] = self.convert_field(name, field)
# Many-to-many fields are not stored in the meta fields dict.
# Pull them directly off the class.
for name in dir(type(self.instance)):
field = getattr(type(self.instance), name, None)
if isinstance(field, ManyToManyField):
self._meta.fields[name] = self.convert_field(name, field)
super().initialize_fields() | [
"def",
"initialize_fields",
"(",
"self",
")",
":",
"# # Pull all the \"normal\" fields off the model instance meta.",
"for",
"name",
",",
"field",
"in",
"self",
".",
"instance",
".",
"_meta",
".",
"fields",
".",
"items",
"(",
")",
":",
"if",
"getattr",
"(",
"fie... | Convert all model fields to validator fields.
Then call the parent so that overwrites can happen if necessary for manually defined fields.
:return: None | [
"Convert",
"all",
"model",
"fields",
"to",
"validator",
"fields",
".",
"Then",
"call",
"the",
"parent",
"so",
"that",
"overwrites",
"can",
"happen",
"if",
"necessary",
"for",
"manually",
"defined",
"fields",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L864-L884 | train | 50,330 |
timster/peewee-validates | peewee_validates.py | ModelValidator.convert_field | def convert_field(self, name, field):
"""
Convert a single field from a Peewee model field to a validator field.
:param name: Name of the field as defined on this validator.
:param name: Peewee field instance.
:return: Validator field.
"""
if PEEWEE3:
field_type = field.field_type.lower()
else:
field_type = field.db_field
pwv_field = ModelValidator.FIELD_MAP.get(field_type, StringField)
print('pwv_field', field_type, pwv_field)
validators = []
required = not bool(getattr(field, 'null', True))
choices = getattr(field, 'choices', ())
default = getattr(field, 'default', None)
max_length = getattr(field, 'max_length', None)
unique = getattr(field, 'unique', False)
if required:
validators.append(validate_required())
if choices:
print('CHOICES', choices)
validators.append(validate_one_of([c[0] for c in choices]))
if max_length:
validators.append(validate_length(high=max_length))
if unique:
validators.append(validate_model_unique(field, self.instance.select(), self.pk_field, self.pk_value))
if isinstance(field, peewee.ForeignKeyField):
if PEEWEE3:
rel_field = field.rel_field
else:
rel_field = field.to_field
return ModelChoiceField(field.rel_model, rel_field, default=default, validators=validators)
if isinstance(field, ManyToManyField):
return ManyModelChoiceField(
field.rel_model, field.rel_model._meta.primary_key,
default=default, validators=validators)
return pwv_field(default=default, validators=validators) | python | def convert_field(self, name, field):
"""
Convert a single field from a Peewee model field to a validator field.
:param name: Name of the field as defined on this validator.
:param name: Peewee field instance.
:return: Validator field.
"""
if PEEWEE3:
field_type = field.field_type.lower()
else:
field_type = field.db_field
pwv_field = ModelValidator.FIELD_MAP.get(field_type, StringField)
print('pwv_field', field_type, pwv_field)
validators = []
required = not bool(getattr(field, 'null', True))
choices = getattr(field, 'choices', ())
default = getattr(field, 'default', None)
max_length = getattr(field, 'max_length', None)
unique = getattr(field, 'unique', False)
if required:
validators.append(validate_required())
if choices:
print('CHOICES', choices)
validators.append(validate_one_of([c[0] for c in choices]))
if max_length:
validators.append(validate_length(high=max_length))
if unique:
validators.append(validate_model_unique(field, self.instance.select(), self.pk_field, self.pk_value))
if isinstance(field, peewee.ForeignKeyField):
if PEEWEE3:
rel_field = field.rel_field
else:
rel_field = field.to_field
return ModelChoiceField(field.rel_model, rel_field, default=default, validators=validators)
if isinstance(field, ManyToManyField):
return ManyModelChoiceField(
field.rel_model, field.rel_model._meta.primary_key,
default=default, validators=validators)
return pwv_field(default=default, validators=validators) | [
"def",
"convert_field",
"(",
"self",
",",
"name",
",",
"field",
")",
":",
"if",
"PEEWEE3",
":",
"field_type",
"=",
"field",
".",
"field_type",
".",
"lower",
"(",
")",
"else",
":",
"field_type",
"=",
"field",
".",
"db_field",
"pwv_field",
"=",
"ModelValid... | Convert a single field from a Peewee model field to a validator field.
:param name: Name of the field as defined on this validator.
:param name: Peewee field instance.
:return: Validator field. | [
"Convert",
"a",
"single",
"field",
"from",
"a",
"Peewee",
"model",
"field",
"to",
"a",
"validator",
"field",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L886-L935 | train | 50,331 |
timster/peewee-validates | peewee_validates.py | ModelValidator.perform_index_validation | def perform_index_validation(self, data):
"""
Validate any unique indexes specified on the model.
This should happen after all the normal fields have been validated.
This can add error messages to multiple fields.
:return: None
"""
# Build a list of dict containing query values for each unique index.
index_data = []
for columns, unique in self.instance._meta.indexes:
if not unique:
continue
index_data.append({col: data.get(col, None) for col in columns})
# Then query for each unique index to see if the value is unique.
for index in index_data:
query = self.instance.filter(**index)
# If we have a primary key, need to exclude the current record from the check.
if self.pk_field and self.pk_value:
query = query.where(~(self.pk_field == self.pk_value))
if query.count():
err = ValidationError('index', fields=str.join(', ', index.keys()))
for col in index.keys():
self.add_error(col, err) | python | def perform_index_validation(self, data):
"""
Validate any unique indexes specified on the model.
This should happen after all the normal fields have been validated.
This can add error messages to multiple fields.
:return: None
"""
# Build a list of dict containing query values for each unique index.
index_data = []
for columns, unique in self.instance._meta.indexes:
if not unique:
continue
index_data.append({col: data.get(col, None) for col in columns})
# Then query for each unique index to see if the value is unique.
for index in index_data:
query = self.instance.filter(**index)
# If we have a primary key, need to exclude the current record from the check.
if self.pk_field and self.pk_value:
query = query.where(~(self.pk_field == self.pk_value))
if query.count():
err = ValidationError('index', fields=str.join(', ', index.keys()))
for col in index.keys():
self.add_error(col, err) | [
"def",
"perform_index_validation",
"(",
"self",
",",
"data",
")",
":",
"# Build a list of dict containing query values for each unique index.",
"index_data",
"=",
"[",
"]",
"for",
"columns",
",",
"unique",
"in",
"self",
".",
"instance",
".",
"_meta",
".",
"indexes",
... | Validate any unique indexes specified on the model.
This should happen after all the normal fields have been validated.
This can add error messages to multiple fields.
:return: None | [
"Validate",
"any",
"unique",
"indexes",
"specified",
"on",
"the",
"model",
".",
"This",
"should",
"happen",
"after",
"all",
"the",
"normal",
"fields",
"have",
"been",
"validated",
".",
"This",
"can",
"add",
"error",
"messages",
"to",
"multiple",
"fields",
".... | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L976-L1000 | train | 50,332 |
timster/peewee-validates | peewee_validates.py | ModelValidator.save | def save(self, force_insert=False):
"""
Save the model and any related many-to-many fields.
:param force_insert: Should the save force an insert?
:return: Number of rows impacted, or False.
"""
delayed = {}
for field, value in self.data.items():
model_field = getattr(type(self.instance), field, None)
# If this is a many-to-many field, we cannot save it to the instance until the instance
# is saved to the database. Collect these fields and delay the setting until after
# the model instance is saved.
if isinstance(model_field, ManyToManyField):
if value is not None:
delayed[field] = value
continue
setattr(self.instance, field, value)
rv = self.instance.save(force_insert=force_insert)
for field, value in delayed.items():
setattr(self.instance, field, value)
return rv | python | def save(self, force_insert=False):
"""
Save the model and any related many-to-many fields.
:param force_insert: Should the save force an insert?
:return: Number of rows impacted, or False.
"""
delayed = {}
for field, value in self.data.items():
model_field = getattr(type(self.instance), field, None)
# If this is a many-to-many field, we cannot save it to the instance until the instance
# is saved to the database. Collect these fields and delay the setting until after
# the model instance is saved.
if isinstance(model_field, ManyToManyField):
if value is not None:
delayed[field] = value
continue
setattr(self.instance, field, value)
rv = self.instance.save(force_insert=force_insert)
for field, value in delayed.items():
setattr(self.instance, field, value)
return rv | [
"def",
"save",
"(",
"self",
",",
"force_insert",
"=",
"False",
")",
":",
"delayed",
"=",
"{",
"}",
"for",
"field",
",",
"value",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"model_field",
"=",
"getattr",
"(",
"type",
"(",
"self",
".",
... | Save the model and any related many-to-many fields.
:param force_insert: Should the save force an insert?
:return: Number of rows impacted, or False. | [
"Save",
"the",
"model",
"and",
"any",
"related",
"many",
"-",
"to",
"-",
"many",
"fields",
"."
] | 417f0fafb87fe9209439d65bc279d86a3d9e8028 | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L1002-L1028 | train | 50,333 |
kpdyer/libfte | fte/bit_ops.py | long_to_bytes | def long_to_bytes(N, blocksize=1):
"""Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
such that the return values length is a multiple of ``blocksize``.
"""
bytestring = hex(N)
bytestring = bytestring[2:] if bytestring.startswith('0x') else bytestring
bytestring = bytestring[:-1] if bytestring.endswith('L') else bytestring
bytestring = '0' + bytestring if (len(bytestring) % 2) != 0 else bytestring
bytestring = binascii.unhexlify(bytestring)
if blocksize > 0 and len(bytestring) % blocksize != 0:
bytestring = '\x00' * \
(blocksize - (len(bytestring) % blocksize)) + bytestring
return bytestring | python | def long_to_bytes(N, blocksize=1):
"""Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
such that the return values length is a multiple of ``blocksize``.
"""
bytestring = hex(N)
bytestring = bytestring[2:] if bytestring.startswith('0x') else bytestring
bytestring = bytestring[:-1] if bytestring.endswith('L') else bytestring
bytestring = '0' + bytestring if (len(bytestring) % 2) != 0 else bytestring
bytestring = binascii.unhexlify(bytestring)
if blocksize > 0 and len(bytestring) % blocksize != 0:
bytestring = '\x00' * \
(blocksize - (len(bytestring) % blocksize)) + bytestring
return bytestring | [
"def",
"long_to_bytes",
"(",
"N",
",",
"blocksize",
"=",
"1",
")",
":",
"bytestring",
"=",
"hex",
"(",
"N",
")",
"bytestring",
"=",
"bytestring",
"[",
"2",
":",
"]",
"if",
"bytestring",
".",
"startswith",
"(",
"'0x'",
")",
"else",
"bytestring",
"bytest... | Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
such that the return values length is a multiple of ``blocksize``. | [
"Given",
"an",
"input",
"integer",
"N",
"long_to_bytes",
"returns",
"the",
"representation",
"of",
"N",
"in",
"bytes",
".",
"If",
"blocksize",
"is",
"greater",
"than",
"1",
"then",
"the",
"output",
"string",
"will",
"be",
"right",
"justified",
"and",
"then",... | 74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7 | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/bit_ops.py#L17-L33 | train | 50,334 |
kpdyer/libfte | fte/encrypter.py | Encrypter.getCiphertextLen | def getCiphertextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
"""
plaintext_length = self.getPlaintextLen(ciphertext)
ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION
return ciphertext_length | python | def getCiphertextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
"""
plaintext_length = self.getPlaintextLen(ciphertext)
ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION
return ciphertext_length | [
"def",
"getCiphertextLen",
"(",
"self",
",",
"ciphertext",
")",
":",
"plaintext_length",
"=",
"self",
".",
"getPlaintextLen",
"(",
"ciphertext",
")",
"ciphertext_length",
"=",
"plaintext_length",
"+",
"Encrypter",
".",
"_CTXT_EXPANSION",
"return",
"ciphertext_length"
... | Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion. | [
"Given",
"a",
"ciphertext",
"with",
"a",
"valid",
"header",
"returns",
"the",
"length",
"of",
"the",
"ciphertext",
"inclusive",
"of",
"ciphertext",
"expansion",
"."
] | 74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7 | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L173-L179 | train | 50,335 |
kpdyer/libfte | fte/encrypter.py | Encrypter.getPlaintextLen | def getPlaintextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload.
"""
completeCiphertextHeader = (len(ciphertext) >= 16)
if completeCiphertextHeader is False:
raise RecoverableDecryptionError('Incomplete ciphertext header.')
ciphertext_header = ciphertext[:16]
L = self._ecb_enc_K1.decrypt(ciphertext_header)
padding_expected = '\x00\x00\x00\x00'
padding_actual = L[-8:-4]
validPadding = (padding_actual == padding_expected)
if validPadding is False:
raise UnrecoverableDecryptionError(
'Invalid padding: ' + padding_actual)
message_length = fte.bit_ops.bytes_to_long(L[-8:])
msgLenNonNegative = (message_length >= 0)
if msgLenNonNegative is False:
raise UnrecoverableDecryptionError('Negative message length.')
return message_length | python | def getPlaintextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload.
"""
completeCiphertextHeader = (len(ciphertext) >= 16)
if completeCiphertextHeader is False:
raise RecoverableDecryptionError('Incomplete ciphertext header.')
ciphertext_header = ciphertext[:16]
L = self._ecb_enc_K1.decrypt(ciphertext_header)
padding_expected = '\x00\x00\x00\x00'
padding_actual = L[-8:-4]
validPadding = (padding_actual == padding_expected)
if validPadding is False:
raise UnrecoverableDecryptionError(
'Invalid padding: ' + padding_actual)
message_length = fte.bit_ops.bytes_to_long(L[-8:])
msgLenNonNegative = (message_length >= 0)
if msgLenNonNegative is False:
raise UnrecoverableDecryptionError('Negative message length.')
return message_length | [
"def",
"getPlaintextLen",
"(",
"self",
",",
"ciphertext",
")",
":",
"completeCiphertextHeader",
"=",
"(",
"len",
"(",
"ciphertext",
")",
">=",
"16",
")",
"if",
"completeCiphertextHeader",
"is",
"False",
":",
"raise",
"RecoverableDecryptionError",
"(",
"'Incomplete... | Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload. | [
"Given",
"a",
"ciphertext",
"with",
"a",
"valid",
"header",
"returns",
"the",
"length",
"of",
"the",
"plaintext",
"payload",
"."
] | 74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7 | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L181-L205 | train | 50,336 |
hammerlab/stancache | stancache/stancache.py | cached_stan_file | def cached_stan_file(model_name='anon_model', file=None, model_code=None,
cache_dir=None, fit_cachefile=None, cache_only=None, force=False,
include_modelfile=False, prefix_only=False,
**kwargs
):
''' Given inputs to cached_stan_fit, compute pickle file containing cached fit
'''
model_prefix, model_cachefile = cached_model_file(model_name=model_name, file=file, model_code=model_code,
cache_dir=cache_dir, fit_cachefile=fit_cachefile, include_prefix=True)
if not fit_cachefile:
fit_cachefile = '.'.join([model_prefix, 'stanfit', _make_digest(dict(**kwargs)), 'pkl'])
if include_modelfile:
return model_cachefile, fit_cachefile
if prefix_only:
fit_cachefile = re.sub(string=fit_cachefile, pattern='.pkl$', repl='')
return fit_cachefile | python | def cached_stan_file(model_name='anon_model', file=None, model_code=None,
cache_dir=None, fit_cachefile=None, cache_only=None, force=False,
include_modelfile=False, prefix_only=False,
**kwargs
):
''' Given inputs to cached_stan_fit, compute pickle file containing cached fit
'''
model_prefix, model_cachefile = cached_model_file(model_name=model_name, file=file, model_code=model_code,
cache_dir=cache_dir, fit_cachefile=fit_cachefile, include_prefix=True)
if not fit_cachefile:
fit_cachefile = '.'.join([model_prefix, 'stanfit', _make_digest(dict(**kwargs)), 'pkl'])
if include_modelfile:
return model_cachefile, fit_cachefile
if prefix_only:
fit_cachefile = re.sub(string=fit_cachefile, pattern='.pkl$', repl='')
return fit_cachefile | [
"def",
"cached_stan_file",
"(",
"model_name",
"=",
"'anon_model'",
",",
"file",
"=",
"None",
",",
"model_code",
"=",
"None",
",",
"cache_dir",
"=",
"None",
",",
"fit_cachefile",
"=",
"None",
",",
"cache_only",
"=",
"None",
",",
"force",
"=",
"False",
",",
... | Given inputs to cached_stan_fit, compute pickle file containing cached fit | [
"Given",
"inputs",
"to",
"cached_stan_fit",
"compute",
"pickle",
"file",
"containing",
"cached",
"fit"
] | 22f2548731d0960c14c0d41f4f64e418d3f22e4c | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/stancache.py#L170-L185 | train | 50,337 |
oscarlazoarjona/fast | fast/electric_field.py | MotField.plot | def plot(self, **kwds):
r"""The plotting function for MOT fields."""
plo = self.lx.plot(dist_to_center=3, **kwds)
plo += self.ly.plot(dist_to_center=3, **kwds)
plo += self.lz.plot(dist_to_center=3, **kwds)
plo += self.lx_r.plot(dist_to_center=3, **kwds)
plo += self.ly_r.plot(dist_to_center=3, **kwds)
plo += self.lz_r.plot(dist_to_center=3, **kwds)
return plo | python | def plot(self, **kwds):
r"""The plotting function for MOT fields."""
plo = self.lx.plot(dist_to_center=3, **kwds)
plo += self.ly.plot(dist_to_center=3, **kwds)
plo += self.lz.plot(dist_to_center=3, **kwds)
plo += self.lx_r.plot(dist_to_center=3, **kwds)
plo += self.ly_r.plot(dist_to_center=3, **kwds)
plo += self.lz_r.plot(dist_to_center=3, **kwds)
return plo | [
"def",
"plot",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"plo",
"=",
"self",
".",
"lx",
".",
"plot",
"(",
"dist_to_center",
"=",
"3",
",",
"*",
"*",
"kwds",
")",
"plo",
"+=",
"self",
".",
"ly",
".",
"plot",
"(",
"dist_to_center",
"=",
"3",
... | r"""The plotting function for MOT fields. | [
"r",
"The",
"plotting",
"function",
"for",
"MOT",
"fields",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L307-L315 | train | 50,338 |
oscarlazoarjona/fast | fast/misc.py | fprint | def fprint(expr, print_ascii=False):
r"""This function chooses whether to use ascii characters to represent
a symbolic expression in the notebook or to use sympy's pprint.
>>> from sympy import cos
>>> omega=Symbol("omega")
>>> fprint(cos(omega),print_ascii=True)
cos(omega)
"""
if print_ascii:
pprint(expr, use_unicode=False, num_columns=120)
else:
return expr | python | def fprint(expr, print_ascii=False):
r"""This function chooses whether to use ascii characters to represent
a symbolic expression in the notebook or to use sympy's pprint.
>>> from sympy import cos
>>> omega=Symbol("omega")
>>> fprint(cos(omega),print_ascii=True)
cos(omega)
"""
if print_ascii:
pprint(expr, use_unicode=False, num_columns=120)
else:
return expr | [
"def",
"fprint",
"(",
"expr",
",",
"print_ascii",
"=",
"False",
")",
":",
"if",
"print_ascii",
":",
"pprint",
"(",
"expr",
",",
"use_unicode",
"=",
"False",
",",
"num_columns",
"=",
"120",
")",
"else",
":",
"return",
"expr"
] | r"""This function chooses whether to use ascii characters to represent
a symbolic expression in the notebook or to use sympy's pprint.
>>> from sympy import cos
>>> omega=Symbol("omega")
>>> fprint(cos(omega),print_ascii=True)
cos(omega) | [
"r",
"This",
"function",
"chooses",
"whether",
"to",
"use",
"ascii",
"characters",
"to",
"represent",
"a",
"symbolic",
"expression",
"in",
"the",
"notebook",
"or",
"to",
"use",
"sympy",
"s",
"pprint",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L45-L59 | train | 50,339 |
oscarlazoarjona/fast | fast/misc.py | Mu | def Mu(i, j, s, N, excluded_mu=[]):
"""This function calculates the global index mu for the element i, j.
It returns the index for the real part if s=0 and the one for the
imaginary part if s=1.
"""
if i == j:
if s == -1:
if i == 1:
return 0
else:
mes = 'There is no population rhoii with i='+str(i)+'.'
raise ValueError(mes)
mu = i-1
elif i > j and s == 1:
mu = i - j + sum([N-k for k in range(1, j)])+N-1
elif i > j and s == -1:
mu = i - j + sum([N-k for k in range(1, j)])+N-1 + N*(N-1)/2
else:
mes = 'i='+str(i)+', j='+str(j)
mes += ' Equations for i<j are not calculated.'+str(s)
raise ValueError(mes)
if excluded_mu != []:
mu = mu-len([ii for ii in excluded_mu if ii < mu])
return mu | python | def Mu(i, j, s, N, excluded_mu=[]):
"""This function calculates the global index mu for the element i, j.
It returns the index for the real part if s=0 and the one for the
imaginary part if s=1.
"""
if i == j:
if s == -1:
if i == 1:
return 0
else:
mes = 'There is no population rhoii with i='+str(i)+'.'
raise ValueError(mes)
mu = i-1
elif i > j and s == 1:
mu = i - j + sum([N-k for k in range(1, j)])+N-1
elif i > j and s == -1:
mu = i - j + sum([N-k for k in range(1, j)])+N-1 + N*(N-1)/2
else:
mes = 'i='+str(i)+', j='+str(j)
mes += ' Equations for i<j are not calculated.'+str(s)
raise ValueError(mes)
if excluded_mu != []:
mu = mu-len([ii for ii in excluded_mu if ii < mu])
return mu | [
"def",
"Mu",
"(",
"i",
",",
"j",
",",
"s",
",",
"N",
",",
"excluded_mu",
"=",
"[",
"]",
")",
":",
"if",
"i",
"==",
"j",
":",
"if",
"s",
"==",
"-",
"1",
":",
"if",
"i",
"==",
"1",
":",
"return",
"0",
"else",
":",
"mes",
"=",
"'There is no ... | This function calculates the global index mu for the element i, j.
It returns the index for the real part if s=0 and the one for the
imaginary part if s=1. | [
"This",
"function",
"calculates",
"the",
"global",
"index",
"mu",
"for",
"the",
"element",
"i",
"j",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L71-L96 | train | 50,340 |
oscarlazoarjona/fast | fast/misc.py | IJ | def IJ(mu, N):
"""Return i, j, s for any given mu."""
if mu == 0: return 1, 1, 1
if mu not in range(0, N**2):
raise ValueError('mu has an invalid value mu='+str(mu)+'.')
if 1 <= mu <= N-1:
return mu+1, mu+1, 1
else:
m = N-1
M = N*(N-1)/2
for jj in range(1, N):
for ii in range(jj+1, N+1):
m += 1
if m == mu or m+M == mu:
if mu > N*(N+1)/2 - 1:
return ii, jj, -1
else:
return ii, jj, 1 | python | def IJ(mu, N):
"""Return i, j, s for any given mu."""
if mu == 0: return 1, 1, 1
if mu not in range(0, N**2):
raise ValueError('mu has an invalid value mu='+str(mu)+'.')
if 1 <= mu <= N-1:
return mu+1, mu+1, 1
else:
m = N-1
M = N*(N-1)/2
for jj in range(1, N):
for ii in range(jj+1, N+1):
m += 1
if m == mu or m+M == mu:
if mu > N*(N+1)/2 - 1:
return ii, jj, -1
else:
return ii, jj, 1 | [
"def",
"IJ",
"(",
"mu",
",",
"N",
")",
":",
"if",
"mu",
"==",
"0",
":",
"return",
"1",
",",
"1",
",",
"1",
"if",
"mu",
"not",
"in",
"range",
"(",
"0",
",",
"N",
"**",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'mu has an invalid value mu='",
"... | Return i, j, s for any given mu. | [
"Return",
"i",
"j",
"s",
"for",
"any",
"given",
"mu",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L99-L118 | train | 50,341 |
oscarlazoarjona/fast | fast/misc.py | calculate_iI_correspondence | def calculate_iI_correspondence(omega):
r"""Get the correspondance between degenerate and nondegenerate schemes."""
Ne = len(omega[0])
om = omega[0][0]
correspondence = []
I = 0
for i in range(Ne):
if omega[i][0] != om:
om = omega[i][0]
I += 1
correspondence += [(i+1, I+1)]
Nnd = I+1
def I_nd(i):
return correspondence[i-1][1]
def i_d(I):
for i in range(Ne):
if correspondence[i][1] == I:
return correspondence[i][0]
return i_d, I_nd, Nnd | python | def calculate_iI_correspondence(omega):
r"""Get the correspondance between degenerate and nondegenerate schemes."""
Ne = len(omega[0])
om = omega[0][0]
correspondence = []
I = 0
for i in range(Ne):
if omega[i][0] != om:
om = omega[i][0]
I += 1
correspondence += [(i+1, I+1)]
Nnd = I+1
def I_nd(i):
return correspondence[i-1][1]
def i_d(I):
for i in range(Ne):
if correspondence[i][1] == I:
return correspondence[i][0]
return i_d, I_nd, Nnd | [
"def",
"calculate_iI_correspondence",
"(",
"omega",
")",
":",
"Ne",
"=",
"len",
"(",
"omega",
"[",
"0",
"]",
")",
"om",
"=",
"omega",
"[",
"0",
"]",
"[",
"0",
"]",
"correspondence",
"=",
"[",
"]",
"I",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
... | r"""Get the correspondance between degenerate and nondegenerate schemes. | [
"r",
"Get",
"the",
"correspondance",
"between",
"degenerate",
"and",
"nondegenerate",
"schemes",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L278-L299 | train | 50,342 |
oscarlazoarjona/fast | fast/misc.py | part | def part(z, s):
r"""Get the real or imaginary part of a complex number."""
if sage_included:
if s == 1: return np.real(z)
elif s == -1: return np.imag(z)
elif s == 0:
return z
else:
if s == 1: return z.real
elif s == -1: return z.imag
elif s == 0: return z | python | def part(z, s):
r"""Get the real or imaginary part of a complex number."""
if sage_included:
if s == 1: return np.real(z)
elif s == -1: return np.imag(z)
elif s == 0:
return z
else:
if s == 1: return z.real
elif s == -1: return z.imag
elif s == 0: return z | [
"def",
"part",
"(",
"z",
",",
"s",
")",
":",
"if",
"sage_included",
":",
"if",
"s",
"==",
"1",
":",
"return",
"np",
".",
"real",
"(",
"z",
")",
"elif",
"s",
"==",
"-",
"1",
":",
"return",
"np",
".",
"imag",
"(",
"z",
")",
"elif",
"s",
"==",... | r"""Get the real or imaginary part of a complex number. | [
"r",
"Get",
"the",
"real",
"or",
"imaginary",
"part",
"of",
"a",
"complex",
"number",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L302-L312 | train | 50,343 |
oscarlazoarjona/fast | fast/misc.py | symbolic_part | def symbolic_part(z, s):
r"""Get the real or imaginary part of a complex symbol."""
if s == 1: return symre(z)
elif s == -1: return symim(z)
elif s == 0: return z | python | def symbolic_part(z, s):
r"""Get the real or imaginary part of a complex symbol."""
if s == 1: return symre(z)
elif s == -1: return symim(z)
elif s == 0: return z | [
"def",
"symbolic_part",
"(",
"z",
",",
"s",
")",
":",
"if",
"s",
"==",
"1",
":",
"return",
"symre",
"(",
"z",
")",
"elif",
"s",
"==",
"-",
"1",
":",
"return",
"symim",
"(",
"z",
")",
"elif",
"s",
"==",
"0",
":",
"return",
"z"
] | r"""Get the real or imaginary part of a complex symbol. | [
"r",
"Get",
"the",
"real",
"or",
"imaginary",
"part",
"of",
"a",
"complex",
"symbol",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L315-L319 | train | 50,344 |
oscarlazoarjona/fast | fast/misc.py | detuning_combinations | def detuning_combinations(lists):
r"""This function recieves a list of length Nl with the number of
transitions each laser induces. It returns the cartesian product of all
these posibilities as a list of all possible combinations.
"""
Nl = len(lists)
comb = [[i] for i in range(lists[0])]
for l in range(1, Nl):
combn = []
for c0 in comb:
for cl in range(lists[l]):
combn += [c0[:]+[cl]]
comb = combn[:]
return comb | python | def detuning_combinations(lists):
r"""This function recieves a list of length Nl with the number of
transitions each laser induces. It returns the cartesian product of all
these posibilities as a list of all possible combinations.
"""
Nl = len(lists)
comb = [[i] for i in range(lists[0])]
for l in range(1, Nl):
combn = []
for c0 in comb:
for cl in range(lists[l]):
combn += [c0[:]+[cl]]
comb = combn[:]
return comb | [
"def",
"detuning_combinations",
"(",
"lists",
")",
":",
"Nl",
"=",
"len",
"(",
"lists",
")",
"comb",
"=",
"[",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"lists",
"[",
"0",
"]",
")",
"]",
"for",
"l",
"in",
"range",
"(",
"1",
",",
"Nl",
")... | r"""This function recieves a list of length Nl with the number of
transitions each laser induces. It returns the cartesian product of all
these posibilities as a list of all possible combinations. | [
"r",
"This",
"function",
"recieves",
"a",
"list",
"of",
"length",
"Nl",
"with",
"the",
"number",
"of",
"transitions",
"each",
"laser",
"induces",
".",
"It",
"returns",
"the",
"cartesian",
"product",
"of",
"all",
"these",
"posibilities",
"as",
"a",
"list",
... | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L322-L335 | train | 50,345 |
oscarlazoarjona/fast | fast/misc.py | laser_detunings | def laser_detunings(Lij, Nl, i_d, I_nd, Nnd):
r"""This function returns the list of transitions i,j that each laser
produces as lists of length Ne, whose elements are all zero except for the
ith element =1 and the jth element = -1.
Also, it returns detuningsij, which contains the same information
but as pairs if ij. The indices in it start from 0.
"""
Ne = len(Lij)
detunings = [[] for i in range(Nl)]
detuningsij = [[] for i in range(Nl)]
detuning = [0 for i in range(Nnd)]
for i in range(1, Ne):
for j in range(i):
for l in Lij[i][j]:
det = detuning[:]
det[I_nd(i+1)-1] += 1; det[I_nd(j+1)-1] -= 1
if det not in detunings[l-1]:
detunings[l-1] += [det]
detuningsij[l-1] += [(I_nd(i+1)-1, I_nd(j+1)-1)]
return detunings, detuningsij | python | def laser_detunings(Lij, Nl, i_d, I_nd, Nnd):
r"""This function returns the list of transitions i,j that each laser
produces as lists of length Ne, whose elements are all zero except for the
ith element =1 and the jth element = -1.
Also, it returns detuningsij, which contains the same information
but as pairs if ij. The indices in it start from 0.
"""
Ne = len(Lij)
detunings = [[] for i in range(Nl)]
detuningsij = [[] for i in range(Nl)]
detuning = [0 for i in range(Nnd)]
for i in range(1, Ne):
for j in range(i):
for l in Lij[i][j]:
det = detuning[:]
det[I_nd(i+1)-1] += 1; det[I_nd(j+1)-1] -= 1
if det not in detunings[l-1]:
detunings[l-1] += [det]
detuningsij[l-1] += [(I_nd(i+1)-1, I_nd(j+1)-1)]
return detunings, detuningsij | [
"def",
"laser_detunings",
"(",
"Lij",
",",
"Nl",
",",
"i_d",
",",
"I_nd",
",",
"Nnd",
")",
":",
"Ne",
"=",
"len",
"(",
"Lij",
")",
"detunings",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"Nl",
")",
"]",
"detuningsij",
"=",
"[",
"[",
... | r"""This function returns the list of transitions i,j that each laser
produces as lists of length Ne, whose elements are all zero except for the
ith element =1 and the jth element = -1.
Also, it returns detuningsij, which contains the same information
but as pairs if ij. The indices in it start from 0. | [
"r",
"This",
"function",
"returns",
"the",
"list",
"of",
"transitions",
"i",
"j",
"that",
"each",
"laser",
"produces",
"as",
"lists",
"of",
"length",
"Ne",
"whose",
"elements",
"are",
"all",
"zero",
"except",
"for",
"the",
"ith",
"element",
"=",
"1",
"an... | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L338-L359 | train | 50,346 |
oscarlazoarjona/fast | fast/misc.py | find_omega_min | def find_omega_min(omega, Nl, detuningsij, i_d, I_nd):
r"""This function returns a list of length Nl containing the mininmal frequency
that each laser excites.
"""
omega_min = []
omega_min_indices = []
for l in range(Nl):
omegas = sorted([(omega[i_d(p[0]+1)-1][i_d(p[1]+1)-1], p)
for p in detuningsij[l]])
omega_min += [omegas[0][0]]
omega_min_indices += [omegas[0][1]]
return omega_min, omega_min_indices | python | def find_omega_min(omega, Nl, detuningsij, i_d, I_nd):
r"""This function returns a list of length Nl containing the mininmal frequency
that each laser excites.
"""
omega_min = []
omega_min_indices = []
for l in range(Nl):
omegas = sorted([(omega[i_d(p[0]+1)-1][i_d(p[1]+1)-1], p)
for p in detuningsij[l]])
omega_min += [omegas[0][0]]
omega_min_indices += [omegas[0][1]]
return omega_min, omega_min_indices | [
"def",
"find_omega_min",
"(",
"omega",
",",
"Nl",
",",
"detuningsij",
",",
"i_d",
",",
"I_nd",
")",
":",
"omega_min",
"=",
"[",
"]",
"omega_min_indices",
"=",
"[",
"]",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
":",
"omegas",
"=",
"sorted",
"(",
"... | r"""This function returns a list of length Nl containing the mininmal frequency
that each laser excites. | [
"r",
"This",
"function",
"returns",
"a",
"list",
"of",
"length",
"Nl",
"containing",
"the",
"mininmal",
"frequency",
"that",
"each",
"laser",
"excites",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L602-L613 | train | 50,347 |
oscarlazoarjona/fast | fast/misc.py | block_diagonal_matrix | def block_diagonal_matrix(matrices, type=None):
ur"""Build a block-diagonal matrix out of a given list of matrices.
The type of matrix is chosen according to the input matrices.
>>> import numpy as np
>>> import sympy as sy
>>> lis = [sy.ones(2), 2*sy.ones(3), 3*sy.ones(4)]
>>> sy.pprint(block_diagonal_matrix(lis))
⎡1 1 0 0 0 0 0 0 0⎤
⎢ ⎥
⎢1 1 0 0 0 0 0 0 0⎥
⎢ ⎥
⎢0 0 2 2 2 0 0 0 0⎥
⎢ ⎥
⎢0 0 2 2 2 0 0 0 0⎥
⎢ ⎥
⎢0 0 2 2 2 0 0 0 0⎥
⎢ ⎥
⎢0 0 0 0 0 3 3 3 3⎥
⎢ ⎥
⎢0 0 0 0 0 3 3 3 3⎥
⎢ ⎥
⎢0 0 0 0 0 3 3 3 3⎥
⎢ ⎥
⎣0 0 0 0 0 3 3 3 3⎦
>>> lis = [np.ones((2, 2)), 2*np.ones((3, 3)), 3*np.ones((4, 4))]
>>> print(block_diagonal_matrix(lis))
[[1. 1. 0. 0. 0. 0. 0. 0. 0.]
[1. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 2. 2. 2. 0. 0. 0. 0.]
[0. 0. 2. 2. 2. 0. 0. 0. 0.]
[0. 0. 2. 2. 2. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]]
"""
if type is None:
type = np.float64
sizes = [Ai.shape[0] for Ai in matrices]
size = sum(sizes)
symbolic = hasattr(matrices[0][0], "subs")
if symbolic:
A = symzeros(size, size)
else:
A = np.zeros((size, size), type)
ini = 0; fin = 0
for i, sizei in enumerate(sizes):
fin += sizei
A[ini: fin, ini: fin] = matrices[i]
ini += sizei
return A | python | def block_diagonal_matrix(matrices, type=None):
ur"""Build a block-diagonal matrix out of a given list of matrices.
The type of matrix is chosen according to the input matrices.
>>> import numpy as np
>>> import sympy as sy
>>> lis = [sy.ones(2), 2*sy.ones(3), 3*sy.ones(4)]
>>> sy.pprint(block_diagonal_matrix(lis))
⎡1 1 0 0 0 0 0 0 0⎤
⎢ ⎥
⎢1 1 0 0 0 0 0 0 0⎥
⎢ ⎥
⎢0 0 2 2 2 0 0 0 0⎥
⎢ ⎥
⎢0 0 2 2 2 0 0 0 0⎥
⎢ ⎥
⎢0 0 2 2 2 0 0 0 0⎥
⎢ ⎥
⎢0 0 0 0 0 3 3 3 3⎥
⎢ ⎥
⎢0 0 0 0 0 3 3 3 3⎥
⎢ ⎥
⎢0 0 0 0 0 3 3 3 3⎥
⎢ ⎥
⎣0 0 0 0 0 3 3 3 3⎦
>>> lis = [np.ones((2, 2)), 2*np.ones((3, 3)), 3*np.ones((4, 4))]
>>> print(block_diagonal_matrix(lis))
[[1. 1. 0. 0. 0. 0. 0. 0. 0.]
[1. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 2. 2. 2. 0. 0. 0. 0.]
[0. 0. 2. 2. 2. 0. 0. 0. 0.]
[0. 0. 2. 2. 2. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]]
"""
if type is None:
type = np.float64
sizes = [Ai.shape[0] for Ai in matrices]
size = sum(sizes)
symbolic = hasattr(matrices[0][0], "subs")
if symbolic:
A = symzeros(size, size)
else:
A = np.zeros((size, size), type)
ini = 0; fin = 0
for i, sizei in enumerate(sizes):
fin += sizei
A[ini: fin, ini: fin] = matrices[i]
ini += sizei
return A | [
"def",
"block_diagonal_matrix",
"(",
"matrices",
",",
"type",
"=",
"None",
")",
":",
"if",
"type",
"is",
"None",
":",
"type",
"=",
"np",
".",
"float64",
"sizes",
"=",
"[",
"Ai",
".",
"shape",
"[",
"0",
"]",
"for",
"Ai",
"in",
"matrices",
"]",
"size... | ur"""Build a block-diagonal matrix out of a given list of matrices.
The type of matrix is chosen according to the input matrices.
>>> import numpy as np
>>> import sympy as sy
>>> lis = [sy.ones(2), 2*sy.ones(3), 3*sy.ones(4)]
>>> sy.pprint(block_diagonal_matrix(lis))
⎡1 1 0 0 0 0 0 0 0⎤
⎢ ⎥
⎢1 1 0 0 0 0 0 0 0⎥
⎢ ⎥
⎢0 0 2 2 2 0 0 0 0⎥
⎢ ⎥
⎢0 0 2 2 2 0 0 0 0⎥
⎢ ⎥
⎢0 0 2 2 2 0 0 0 0⎥
⎢ ⎥
⎢0 0 0 0 0 3 3 3 3⎥
⎢ ⎥
⎢0 0 0 0 0 3 3 3 3⎥
⎢ ⎥
⎢0 0 0 0 0 3 3 3 3⎥
⎢ ⎥
⎣0 0 0 0 0 3 3 3 3⎦
>>> lis = [np.ones((2, 2)), 2*np.ones((3, 3)), 3*np.ones((4, 4))]
>>> print(block_diagonal_matrix(lis))
[[1. 1. 0. 0. 0. 0. 0. 0. 0.]
[1. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 2. 2. 2. 0. 0. 0. 0.]
[0. 0. 2. 2. 2. 0. 0. 0. 0.]
[0. 0. 2. 2. 2. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]
[0. 0. 0. 0. 0. 3. 3. 3. 3.]] | [
"ur",
"Build",
"a",
"block",
"-",
"diagonal",
"matrix",
"out",
"of",
"a",
"given",
"list",
"of",
"matrices",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L1088-L1143 | train | 50,348 |
abn/cafeteria | cafeteria/datastructs/dict.py | MergingDict.update | def update(self, other=None, **kwargs):
"""
A special update method to handle merging of dict objects. For all
other iterable objects, we use the parent class update method. For
other objects, we simply make use of the internal merging logic.
:param other: An iterable object.
:type other: dict or object
:param kwargs: key/value pairs to update.
:rtype: None
"""
if other is not None:
if isinstance(other, dict):
for key in other:
self[key] = other[key]
else:
# noinspection PyTypeChecker
super(MergingDict, self).update(other)
for key in kwargs:
self._merge(key, kwargs[key]) | python | def update(self, other=None, **kwargs):
"""
A special update method to handle merging of dict objects. For all
other iterable objects, we use the parent class update method. For
other objects, we simply make use of the internal merging logic.
:param other: An iterable object.
:type other: dict or object
:param kwargs: key/value pairs to update.
:rtype: None
"""
if other is not None:
if isinstance(other, dict):
for key in other:
self[key] = other[key]
else:
# noinspection PyTypeChecker
super(MergingDict, self).update(other)
for key in kwargs:
self._merge(key, kwargs[key]) | [
"def",
"update",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"other",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"other",
",",
"dict",
")",
":",
"for",
"key",
"in",
"other",
":",
"self",
"[",
"key",
... | A special update method to handle merging of dict objects. For all
other iterable objects, we use the parent class update method. For
other objects, we simply make use of the internal merging logic.
:param other: An iterable object.
:type other: dict or object
:param kwargs: key/value pairs to update.
:rtype: None | [
"A",
"special",
"update",
"method",
"to",
"handle",
"merging",
"of",
"dict",
"objects",
".",
"For",
"all",
"other",
"iterable",
"objects",
"we",
"use",
"the",
"parent",
"class",
"update",
"method",
".",
"For",
"other",
"objects",
"we",
"simply",
"make",
"u... | 0a2efb0529484d6da08568f4364daff77f734dfd | https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/datastructs/dict.py#L65-L85 | train | 50,349 |
tilde-lab/tilde | tilde/berlinium/categs.py | wrap_cell | def wrap_cell(entity, json_obj, mapping, table_view=False):
'''
Cell wrappers
for customizing the GUI data table
TODO : must coincide with hierarchy!
TODO : simplify this!
'''
html_class = '' # for GUI javascript
out = ''
#if 'cell_wrapper' in entity: # TODO : this bound type was defined by apps only
# out = entity['cell_wrapper'](json_obj)
#else:
if entity['multiple']:
out = ", ".join( map(lambda x: num2name(x, entity, mapping), json_obj.get(entity['source'], [])) )
elif entity['is_chem_formula']:
out = html_formula(json_obj[ entity['source'] ]) if entity['source'] in json_obj else '—'
elif entity['source'] == 'bandgap':
html_class = ' class=_g'
out = json_obj.get('bandgap')
if out is None: out = '—'
# dynamic determination below:
elif entity['source'] == 'energy':
html_class = ' class=_e'
out = "%6.5f" % json_obj['energy'] if json_obj['energy'] else '—'
elif entity['source'] == 'dims':
out = "%4.2f" % json_obj['dims'] if json_obj['periodicity'] in [2, 3] else '—'
else:
out = num2name(json_obj.get(entity['source']), entity, mapping) or '—'
if table_view:
return '<td rel=' + str(entity['cid']) + html_class + '>' + str(out) + '</td>'
elif html_class:
return '<span' + html_class + '>' + str(out) + '</span>'
return str(out) | python | def wrap_cell(entity, json_obj, mapping, table_view=False):
'''
Cell wrappers
for customizing the GUI data table
TODO : must coincide with hierarchy!
TODO : simplify this!
'''
html_class = '' # for GUI javascript
out = ''
#if 'cell_wrapper' in entity: # TODO : this bound type was defined by apps only
# out = entity['cell_wrapper'](json_obj)
#else:
if entity['multiple']:
out = ", ".join( map(lambda x: num2name(x, entity, mapping), json_obj.get(entity['source'], [])) )
elif entity['is_chem_formula']:
out = html_formula(json_obj[ entity['source'] ]) if entity['source'] in json_obj else '—'
elif entity['source'] == 'bandgap':
html_class = ' class=_g'
out = json_obj.get('bandgap')
if out is None: out = '—'
# dynamic determination below:
elif entity['source'] == 'energy':
html_class = ' class=_e'
out = "%6.5f" % json_obj['energy'] if json_obj['energy'] else '—'
elif entity['source'] == 'dims':
out = "%4.2f" % json_obj['dims'] if json_obj['periodicity'] in [2, 3] else '—'
else:
out = num2name(json_obj.get(entity['source']), entity, mapping) or '—'
if table_view:
return '<td rel=' + str(entity['cid']) + html_class + '>' + str(out) + '</td>'
elif html_class:
return '<span' + html_class + '>' + str(out) + '</span>'
return str(out) | [
"def",
"wrap_cell",
"(",
"entity",
",",
"json_obj",
",",
"mapping",
",",
"table_view",
"=",
"False",
")",
":",
"html_class",
"=",
"''",
"# for GUI javascript",
"out",
"=",
"''",
"#if 'cell_wrapper' in entity: # TODO : this bound type was defined by apps only",
"# out =... | Cell wrappers
for customizing the GUI data table
TODO : must coincide with hierarchy!
TODO : simplify this! | [
"Cell",
"wrappers",
"for",
"customizing",
"the",
"GUI",
"data",
"table"
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/categs.py#L4-L46 | train | 50,350 |
tilde-lab/tilde | utils/syshwinfo.py | meminfo | def meminfo():
"""Get the amount of memory and swap, Mebibytes"""
f = open("/proc/meminfo")
hwinfo = {}
for line in f.readlines():
meml = line.split()
if (meml[0] == "MemTotal:"):
mem = int(meml[1])
hwinfo["Mem_MiB"] = mem/1024
elif (meml[0] == "SwapTotal:"):
swap = int(meml[1])
hwinfo["Swap_MiB"] = swap/1024
f.close()
return hwinfo | python | def meminfo():
"""Get the amount of memory and swap, Mebibytes"""
f = open("/proc/meminfo")
hwinfo = {}
for line in f.readlines():
meml = line.split()
if (meml[0] == "MemTotal:"):
mem = int(meml[1])
hwinfo["Mem_MiB"] = mem/1024
elif (meml[0] == "SwapTotal:"):
swap = int(meml[1])
hwinfo["Swap_MiB"] = swap/1024
f.close()
return hwinfo | [
"def",
"meminfo",
"(",
")",
":",
"f",
"=",
"open",
"(",
"\"/proc/meminfo\"",
")",
"hwinfo",
"=",
"{",
"}",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"meml",
"=",
"line",
".",
"split",
"(",
")",
"if",
"(",
"meml",
"[",
"0",
"]",... | Get the amount of memory and swap, Mebibytes | [
"Get",
"the",
"amount",
"of",
"memory",
"and",
"swap",
"Mebibytes"
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L34-L47 | train | 50,351 |
tilde-lab/tilde | utils/syshwinfo.py | cpuinfo | def cpuinfo():
"""Get the cpu info"""
f = open("/proc/cpuinfo")
hwinfo = {}
for line in f.readlines():
cpul = line.split(":")
name = cpul[0].strip()
if (len(cpul) > 1):
val = cpul[1].strip()
if (name == "model name"):
hwinfo["CPU"] = val
elif (name == "cpu MHz"):
hwinfo["MHz"] = int(round(float(val)))
f.close()
return hwinfo | python | def cpuinfo():
"""Get the cpu info"""
f = open("/proc/cpuinfo")
hwinfo = {}
for line in f.readlines():
cpul = line.split(":")
name = cpul[0].strip()
if (len(cpul) > 1):
val = cpul[1].strip()
if (name == "model name"):
hwinfo["CPU"] = val
elif (name == "cpu MHz"):
hwinfo["MHz"] = int(round(float(val)))
f.close()
return hwinfo | [
"def",
"cpuinfo",
"(",
")",
":",
"f",
"=",
"open",
"(",
"\"/proc/cpuinfo\"",
")",
"hwinfo",
"=",
"{",
"}",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"cpul",
"=",
"line",
".",
"split",
"(",
"\":\"",
")",
"name",
"=",
"cpul",
"[",
... | Get the cpu info | [
"Get",
"the",
"cpu",
"info"
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L49-L63 | train | 50,352 |
tilde-lab/tilde | utils/syshwinfo.py | vgadata | def vgadata():
"""Get data about the graphics card."""
if os.path.isfile('/sbin/lspci'):
lspci = '/sbin/lspci'
else:
lspci = '/usr/bin/lspci'
f = os.popen (lspci + ' -m')
pdata = {}
for line in f.readlines():
p = line.split("\"")
name = p[1].strip()
if (name == "VGA compatible controller"):
pdata["Graphics"] = p[3] + " " + p[5]
f.close()
return pdata | python | def vgadata():
"""Get data about the graphics card."""
if os.path.isfile('/sbin/lspci'):
lspci = '/sbin/lspci'
else:
lspci = '/usr/bin/lspci'
f = os.popen (lspci + ' -m')
pdata = {}
for line in f.readlines():
p = line.split("\"")
name = p[1].strip()
if (name == "VGA compatible controller"):
pdata["Graphics"] = p[3] + " " + p[5]
f.close()
return pdata | [
"def",
"vgadata",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"'/sbin/lspci'",
")",
":",
"lspci",
"=",
"'/sbin/lspci'",
"else",
":",
"lspci",
"=",
"'/usr/bin/lspci'",
"f",
"=",
"os",
".",
"popen",
"(",
"lspci",
"+",
"' -m'",
")",
"pda... | Get data about the graphics card. | [
"Get",
"data",
"about",
"the",
"graphics",
"card",
"."
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L70-L84 | train | 50,353 |
tilde-lab/tilde | utils/syshwinfo.py | serial_number | def serial_number():
"""Get the serial number. Requires root access"""
sdata = {}
if os.getuid() == 0:
try:
sdata['Serial'] = open('/sys/class/dmi/id/product_serial') \
.read().strip()
except:
for line in os.popen('/usr/sbin/dmidecode -s system-serial-number'):
sdata['Serial'] = line.strip()
return sdata | python | def serial_number():
"""Get the serial number. Requires root access"""
sdata = {}
if os.getuid() == 0:
try:
sdata['Serial'] = open('/sys/class/dmi/id/product_serial') \
.read().strip()
except:
for line in os.popen('/usr/sbin/dmidecode -s system-serial-number'):
sdata['Serial'] = line.strip()
return sdata | [
"def",
"serial_number",
"(",
")",
":",
"sdata",
"=",
"{",
"}",
"if",
"os",
".",
"getuid",
"(",
")",
"==",
"0",
":",
"try",
":",
"sdata",
"[",
"'Serial'",
"]",
"=",
"open",
"(",
"'/sys/class/dmi/id/product_serial'",
")",
".",
"read",
"(",
")",
".",
... | Get the serial number. Requires root access | [
"Get",
"the",
"serial",
"number",
".",
"Requires",
"root",
"access"
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L86-L96 | train | 50,354 |
tilde-lab/tilde | utils/syshwinfo.py | system_model | def system_model():
"""Get manufacturer and model number.
On older Linux kernel versions without /sys/class/dmi/id this
requires root access.
"""
mdata = {}
man = None
pn = None
try:
# This might be
# sys_vendor, bios_vendor, board_vendor, or chassis_vendor
man = open('/sys/class/dmi/id/sys_vendor').read().strip()
except:
if os.getuid() == 0:
for line in os.popen('/usr/sbin/dmidecode -s system-manufacturer'):
man = line.strip()
try:
pn = open('/sys/class/dmi/id/product_name').read().strip()
except:
if os.getuid() == 0:
for line in os.popen('/usr/sbin/dmidecode -s system-product-name'):
pn = line.strip()
if man is not None:
mdata['System_manufacturer'] = man
if pn is not None:
mdata['System_product_name'] = pn
return mdata | python | def system_model():
"""Get manufacturer and model number.
On older Linux kernel versions without /sys/class/dmi/id this
requires root access.
"""
mdata = {}
man = None
pn = None
try:
# This might be
# sys_vendor, bios_vendor, board_vendor, or chassis_vendor
man = open('/sys/class/dmi/id/sys_vendor').read().strip()
except:
if os.getuid() == 0:
for line in os.popen('/usr/sbin/dmidecode -s system-manufacturer'):
man = line.strip()
try:
pn = open('/sys/class/dmi/id/product_name').read().strip()
except:
if os.getuid() == 0:
for line in os.popen('/usr/sbin/dmidecode -s system-product-name'):
pn = line.strip()
if man is not None:
mdata['System_manufacturer'] = man
if pn is not None:
mdata['System_product_name'] = pn
return mdata | [
"def",
"system_model",
"(",
")",
":",
"mdata",
"=",
"{",
"}",
"man",
"=",
"None",
"pn",
"=",
"None",
"try",
":",
"# This might be",
"# sys_vendor, bios_vendor, board_vendor, or chassis_vendor",
"man",
"=",
"open",
"(",
"'/sys/class/dmi/id/sys_vendor'",
")",
".",
"... | Get manufacturer and model number.
On older Linux kernel versions without /sys/class/dmi/id this
requires root access. | [
"Get",
"manufacturer",
"and",
"model",
"number",
"."
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L98-L125 | train | 50,355 |
tilde-lab/tilde | utils/syshwinfo.py | diskdata | def diskdata():
"""Get total disk size in GB."""
p = os.popen("/bin/df -l -P")
ddata = {}
tsize = 0
for line in p.readlines():
d = line.split()
if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]):
tsize = tsize + int(d[1])
ddata["Disk_GB"] = int(tsize)/1000000
p.close()
return ddata | python | def diskdata():
"""Get total disk size in GB."""
p = os.popen("/bin/df -l -P")
ddata = {}
tsize = 0
for line in p.readlines():
d = line.split()
if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]):
tsize = tsize + int(d[1])
ddata["Disk_GB"] = int(tsize)/1000000
p.close()
return ddata | [
"def",
"diskdata",
"(",
")",
":",
"p",
"=",
"os",
".",
"popen",
"(",
"\"/bin/df -l -P\"",
")",
"ddata",
"=",
"{",
"}",
"tsize",
"=",
"0",
"for",
"line",
"in",
"p",
".",
"readlines",
"(",
")",
":",
"d",
"=",
"line",
".",
"split",
"(",
")",
"if",... | Get total disk size in GB. | [
"Get",
"total",
"disk",
"size",
"in",
"GB",
"."
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L127-L138 | train | 50,356 |
tilde-lab/tilde | utils/syshwinfo.py | ip_address | def ip_address():
"""Get the IP address used for public connections."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 8.8.8.8 is the google public DNS
s.connect(("8.8.8.8", 53))
ip = s.getsockname()[0]
s.close()
return ip | python | def ip_address():
"""Get the IP address used for public connections."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 8.8.8.8 is the google public DNS
s.connect(("8.8.8.8", 53))
ip = s.getsockname()[0]
s.close()
return ip | [
"def",
"ip_address",
"(",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"# 8.8.8.8 is the google public DNS",
"s",
".",
"connect",
"(",
"(",
"\"8.8.8.8\"",
",",
"53",
")",
")",
"ip",
"=... | Get the IP address used for public connections. | [
"Get",
"the",
"IP",
"address",
"used",
"for",
"public",
"connections",
"."
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L155-L162 | train | 50,357 |
tilde-lab/tilde | utils/syshwinfo.py | mac_address | def mac_address(ip):
"""Get the MAC address"""
mac = ''
for line in os.popen('/sbin/ifconfig'):
s = line.split()
if len(s) > 3:
if s[3] == 'HWaddr':
mac = s[4]
elif s[2] == ip:
break
return {'MAC': mac} | python | def mac_address(ip):
"""Get the MAC address"""
mac = ''
for line in os.popen('/sbin/ifconfig'):
s = line.split()
if len(s) > 3:
if s[3] == 'HWaddr':
mac = s[4]
elif s[2] == ip:
break
return {'MAC': mac} | [
"def",
"mac_address",
"(",
"ip",
")",
":",
"mac",
"=",
"''",
"for",
"line",
"in",
"os",
".",
"popen",
"(",
"'/sbin/ifconfig'",
")",
":",
"s",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"s",
")",
">",
"3",
":",
"if",
"s",
"[",
"3",... | Get the MAC address | [
"Get",
"the",
"MAC",
"address"
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L164-L174 | train | 50,358 |
tilde-lab/tilde | utils/syshwinfo.py | getallhwinfo | def getallhwinfo():
"""Get all the hw info."""
hwinfo = meminfo()
hwinfo.update(cpuinfo())
hwinfo.update(uname())
hwinfo.update(vgadata())
hwinfo.update(distro())
hwinfo.update(diskdata())
hwinfo.update(hostname())
hwinfo.update(serial_number())
ip = ip_address()
hwinfo.update(mac_address(ip))
hwinfo.update({'IP': ip})
hwinfo.update(system_model())
return hwinfo | python | def getallhwinfo():
"""Get all the hw info."""
hwinfo = meminfo()
hwinfo.update(cpuinfo())
hwinfo.update(uname())
hwinfo.update(vgadata())
hwinfo.update(distro())
hwinfo.update(diskdata())
hwinfo.update(hostname())
hwinfo.update(serial_number())
ip = ip_address()
hwinfo.update(mac_address(ip))
hwinfo.update({'IP': ip})
hwinfo.update(system_model())
return hwinfo | [
"def",
"getallhwinfo",
"(",
")",
":",
"hwinfo",
"=",
"meminfo",
"(",
")",
"hwinfo",
".",
"update",
"(",
"cpuinfo",
"(",
")",
")",
"hwinfo",
".",
"update",
"(",
"uname",
"(",
")",
")",
"hwinfo",
".",
"update",
"(",
"vgadata",
"(",
")",
")",
"hwinfo"... | Get all the hw info. | [
"Get",
"all",
"the",
"hw",
"info",
"."
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L176-L190 | train | 50,359 |
tilde-lab/tilde | utils/syshwinfo.py | printheader | def printheader(h=None):
"""Print the header for the CSV table."""
writer = csv.writer(sys.stdout)
writer.writerow(header_fields(h)) | python | def printheader(h=None):
"""Print the header for the CSV table."""
writer = csv.writer(sys.stdout)
writer.writerow(header_fields(h)) | [
"def",
"printheader",
"(",
"h",
"=",
"None",
")",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"sys",
".",
"stdout",
")",
"writer",
".",
"writerow",
"(",
"header_fields",
"(",
"h",
")",
")"
] | Print the header for the CSV table. | [
"Print",
"the",
"header",
"for",
"the",
"CSV",
"table",
"."
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L200-L203 | train | 50,360 |
tilde-lab/tilde | utils/syshwinfo.py | agent | def agent(server="http://localhost:8000"):
"""Run in agent mode.
This gathers data, and sends it to a server given by the server argument.
"""
import xmlrpc.client
sp = xmlrpc.client.ServerProxy(server)
hw = getallhwinfo()
fields = header_fields()
for f in fields:
if not f in hw:
hw[f] = ''
try:
sp.puthwinfo(xmlrpc.client.dumps((hw,)))
except xmlrpc.client.Error as v:
print("ERROR occured: ", v) | python | def agent(server="http://localhost:8000"):
"""Run in agent mode.
This gathers data, and sends it to a server given by the server argument.
"""
import xmlrpc.client
sp = xmlrpc.client.ServerProxy(server)
hw = getallhwinfo()
fields = header_fields()
for f in fields:
if not f in hw:
hw[f] = ''
try:
sp.puthwinfo(xmlrpc.client.dumps((hw,)))
except xmlrpc.client.Error as v:
print("ERROR occured: ", v) | [
"def",
"agent",
"(",
"server",
"=",
"\"http://localhost:8000\"",
")",
":",
"import",
"xmlrpc",
".",
"client",
"sp",
"=",
"xmlrpc",
".",
"client",
".",
"ServerProxy",
"(",
"server",
")",
"hw",
"=",
"getallhwinfo",
"(",
")",
"fields",
"=",
"header_fields",
"... | Run in agent mode.
This gathers data, and sends it to a server given by the server argument. | [
"Run",
"in",
"agent",
"mode",
"."
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L213-L229 | train | 50,361 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | calculate_omega_matrix | def calculate_omega_matrix(states, Omega=1):
"""Calculate the matrix of transition frequencies.
This function recieves a list of states and returns the corresponding
omega_ij matrix, rescaled to units of Omega. These are understood to be
absolute frequencies (as opposed angular frequencies).
"""
N = len(states)
omega = [[2*Pi*(states[i].nu-states[j].nu)/Omega
for j in range(N)] for i in range(N)]
return omega | python | def calculate_omega_matrix(states, Omega=1):
"""Calculate the matrix of transition frequencies.
This function recieves a list of states and returns the corresponding
omega_ij matrix, rescaled to units of Omega. These are understood to be
absolute frequencies (as opposed angular frequencies).
"""
N = len(states)
omega = [[2*Pi*(states[i].nu-states[j].nu)/Omega
for j in range(N)] for i in range(N)]
return omega | [
"def",
"calculate_omega_matrix",
"(",
"states",
",",
"Omega",
"=",
"1",
")",
":",
"N",
"=",
"len",
"(",
"states",
")",
"omega",
"=",
"[",
"[",
"2",
"*",
"Pi",
"*",
"(",
"states",
"[",
"i",
"]",
".",
"nu",
"-",
"states",
"[",
"j",
"]",
".",
"n... | Calculate the matrix of transition frequencies.
This function recieves a list of states and returns the corresponding
omega_ij matrix, rescaled to units of Omega. These are understood to be
absolute frequencies (as opposed angular frequencies). | [
"Calculate",
"the",
"matrix",
"of",
"transition",
"frequencies",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1279-L1290 | train | 50,362 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | calculate_gamma_matrix | def calculate_gamma_matrix(magnetic_states, Omega=1):
r"""Calculate the matrix of decay between states.
This function calculates the matrix $\gamma_{ij}$ of decay rates between
states |i> and |j> (in the units specified by the Omega argument).
>>> g=State("Rb",87,5,0,1/Integer(2))
>>> e=State("Rb",87,5,1,3/Integer(2))
>>> magnetic_states=make_list_of_states([g,e],"magnetic")
To return the rates in rad/s:
>>> print calculate_gamma_matrix(magnetic_states)
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12702506.296014734, -15878132.870018415, -15878132.870018415, -0.0, -19053759.4440221, -9526879.72201105, -3175626.5740036834, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12702506.296014734, -15878132.870018415, -0.0, -15878132.870018415, -0.0, -9526879.72201105, -12702506.296014734, -9526879.72201105, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12702506.296014734, -0.0, -15878132.870018415, -15878132.870018415, -0.0, -0.0, -3175626.5740036834, -9526879.72201105, -19053759.4440221, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -3810751.8888044204, -0.0, -0.0, -12702506.296014734, -6351253.148007367, -0.0, -0.0, -0.0, -38107518.8880442, -12702506.296014734, -2540501.2592029474, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -1905375.9444022102, -1905375.9444022102, -0.0, -6351253.148007367, -3175626.5740036834, -9526879.72201105, -0.0, -0.0, -0.0, -25405012.592029467, -20324010.07362358, -7621503.77760884, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -635125.3148007367, -2540501.259202947, -635125.3148007367, -0.0, -9526879.72201105, -0.0, -9526879.72201105, -0.0, -0.0, -0.0, -15243007.55521768, -22864511.33282652, -15243007.55521768, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -1905375.9444022102, -1905375.9444022102, -0.0, -0.0, -9526879.72201105, -3175626.5740036834, -6351253.148007367, -0.0, -0.0, -0.0, -7621503.77760884, -20324010.07362358, -25405012.592029467, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -3810751.8888044204, -0.0, -0.0, -0.0, -6351253.148007367, -12702506.296014734, -0.0, -0.0, -0.0, -0.0, -2540501.2592029474, -12702506.296014734, -38107518.8880442], [12702506.296014734, 12702506.296014734, 12702506.296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15878132.870018415, 15878132.870018415, 0.0, 3810751.8888044204, 1905375.9444022102, 635125.3148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15878132.870018415, 0.0, 15878132.870018415, 0.0, 1905375.9444022102, 2540501.259202947, 1905375.9444022102, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 15878132.870018415, 15878132.870018415, 0.0, 0.0, 635125.3148007367, 1905375.9444022102, 3810751.8888044204, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [19053759.4440221, 0.0, 0.0, 12702506.296014734, 6351253.148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [9526879.72201105, 9526879.72201105, 0.0, 6351253.148007367, 3175626.5740036834, 9526879.72201105, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [3175626.5740036834, 12702506.296014734, 3175626.5740036834, 0.0, 9526879.72201105, 0.0, 9526879.72201105, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 9526879.72201105, 9526879.72201105, 0.0, 0.0, 9526879.72201105, 3175626.5740036834, 6351253.148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 19053759.4440221, 0.0, 0.0, 0.0, 6351253.148007367, 12702506.296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 38107518.8880442, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 12702506.296014734, 25405012.592029467, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 2540501.2592029474, 20324010.07362358, 15243007.55521768, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 7621503.77760884, 22864511.33282652, 7621503.77760884, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 15243007.55521768, 20324010.07362358, 2540501.2592029474, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 25405012.592029467, 12702506.296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 38107518.8880442, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
To return the rates in 10^6 rad /s:
>>> gamma = calculate_gamma_matrix(magnetic_states,Omega=1e6)
>>> gamma
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12.702506296014734, -15.878132870018417, -15.878132870018417, -0.0, -19.053759444022102, -9.526879722011051, -3.1756265740036835, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12.702506296014734, -15.878132870018417, -0.0, -15.878132870018417, -0.0, -9.526879722011051, -12.702506296014734, -9.526879722011051, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12.702506296014734, -0.0, -15.878132870018417, -15.878132870018417, -0.0, -0.0, -3.1756265740036835, -9.526879722011051, -19.053759444022102, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -3.8107518888044205, -0.0, -0.0, -12.702506296014734, -6.351253148007367, -0.0, -0.0, -0.0, -38.107518888044204, -12.702506296014734, -2.5405012592029474, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -1.9053759444022103, -1.9053759444022103, -0.0, -6.351253148007367, -3.1756265740036835, -9.526879722011051, -0.0, -0.0, -0.0, -25.40501259202947, -20.32401007362358, -7.62150377760884, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.6351253148007368, -2.540501259202947, -0.6351253148007368, -0.0, -9.526879722011051, -0.0, -9.526879722011051, -0.0, -0.0, -0.0, -15.24300755521768, -22.86451133282652, -15.24300755521768, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -1.9053759444022103, -1.9053759444022103, -0.0, -0.0, -9.526879722011051, -3.1756265740036835, -6.351253148007367, -0.0, -0.0, -0.0, -7.62150377760884, -20.32401007362358, -25.40501259202947, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -3.8107518888044205, -0.0, -0.0, -0.0, -6.351253148007367, -12.702506296014734, -0.0, -0.0, -0.0, -0.0, -2.5405012592029474, -12.702506296014734, -38.107518888044204], [12.702506296014734, 12.702506296014734, 12.702506296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15.878132870018417, 15.878132870018417, 0.0, 3.8107518888044205, 1.9053759444022103, 0.6351253148007368, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15.878132870018417, 0.0, 15.878132870018417, 0.0, 1.9053759444022103, 2.540501259202947, 1.9053759444022103, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 15.878132870018417, 15.878132870018417, 0.0, 0.0, 0.6351253148007368, 1.9053759444022103, 3.8107518888044205, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [19.053759444022102, 0.0, 0.0, 12.702506296014734, 6.351253148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [9.526879722011051, 9.526879722011051, 0.0, 6.351253148007367, 3.1756265740036835, 9.526879722011051, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [3.1756265740036835, 12.702506296014734, 3.1756265740036835, 0.0, 9.526879722011051, 0.0, 9.526879722011051, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 9.526879722011051, 9.526879722011051, 0.0, 0.0, 9.526879722011051, 3.1756265740036835, 6.351253148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 19.053759444022102, 0.0, 0.0, 0.0, 6.351253148007367, 12.702506296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 38.107518888044204, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 12.702506296014734, 25.40501259202947, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 2.5405012592029474, 20.32401007362358, 15.24300755521768, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 7.62150377760884, 22.86451133282652, 7.62150377760884, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 15.24300755521768, 20.32401007362358, 2.5405012592029474, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 25.40501259202947, 12.702506296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 38.107518888044204, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
Let us test if all D2 lines decay at the expected rate (6.065 MHz):
>>> Gamma =[ sum([ gamma[i][j] for j in range(i)])/2/pi for i in range(len(magnetic_states))][8:]
>>> for Gammai in Gamma: print Gammai
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
"""
Ne = len(magnetic_states)
II = magnetic_states[0].i
gamma = [[0.0 for j in range(Ne)] for i in range(Ne)]
for i in range(Ne):
for j in range(i):
ei = magnetic_states[i]
ej = magnetic_states[j]
einsteinAij = Transition(ei, ej).einsteinA
if einsteinAij != 0:
ji = ei.j; jj = ej.j
fi = ei.f; fj = ej.f
mi = ei.m; mj = ej.m
gammaij = (2.0*ji+1)
gammaij *= (2.0*fi+1)
gammaij *= (2.0*fj+1)
gammaij *= float(wigner_6j(ji, fi, II, fj, jj, 1)**2)
gammaij *= sum([float(wigner_3j(fj, 1, fi, -mj, q, mi)**2)
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gammaij = float(gammaij)
gamma[i][j] = gammaij
gamma[j][i] = -gammaij
return gamma | python | def calculate_gamma_matrix(magnetic_states, Omega=1):
r"""Calculate the matrix of decay between states.
This function calculates the matrix $\gamma_{ij}$ of decay rates between
states |i> and |j> (in the units specified by the Omega argument).
>>> g=State("Rb",87,5,0,1/Integer(2))
>>> e=State("Rb",87,5,1,3/Integer(2))
>>> magnetic_states=make_list_of_states([g,e],"magnetic")
To return the rates in rad/s:
>>> print calculate_gamma_matrix(magnetic_states)
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12702506.296014734, -15878132.870018415, -15878132.870018415, -0.0, -19053759.4440221, -9526879.72201105, -3175626.5740036834, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12702506.296014734, -15878132.870018415, -0.0, -15878132.870018415, -0.0, -9526879.72201105, -12702506.296014734, -9526879.72201105, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12702506.296014734, -0.0, -15878132.870018415, -15878132.870018415, -0.0, -0.0, -3175626.5740036834, -9526879.72201105, -19053759.4440221, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -3810751.8888044204, -0.0, -0.0, -12702506.296014734, -6351253.148007367, -0.0, -0.0, -0.0, -38107518.8880442, -12702506.296014734, -2540501.2592029474, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -1905375.9444022102, -1905375.9444022102, -0.0, -6351253.148007367, -3175626.5740036834, -9526879.72201105, -0.0, -0.0, -0.0, -25405012.592029467, -20324010.07362358, -7621503.77760884, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -635125.3148007367, -2540501.259202947, -635125.3148007367, -0.0, -9526879.72201105, -0.0, -9526879.72201105, -0.0, -0.0, -0.0, -15243007.55521768, -22864511.33282652, -15243007.55521768, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -1905375.9444022102, -1905375.9444022102, -0.0, -0.0, -9526879.72201105, -3175626.5740036834, -6351253.148007367, -0.0, -0.0, -0.0, -7621503.77760884, -20324010.07362358, -25405012.592029467, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -3810751.8888044204, -0.0, -0.0, -0.0, -6351253.148007367, -12702506.296014734, -0.0, -0.0, -0.0, -0.0, -2540501.2592029474, -12702506.296014734, -38107518.8880442], [12702506.296014734, 12702506.296014734, 12702506.296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15878132.870018415, 15878132.870018415, 0.0, 3810751.8888044204, 1905375.9444022102, 635125.3148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15878132.870018415, 0.0, 15878132.870018415, 0.0, 1905375.9444022102, 2540501.259202947, 1905375.9444022102, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 15878132.870018415, 15878132.870018415, 0.0, 0.0, 635125.3148007367, 1905375.9444022102, 3810751.8888044204, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [19053759.4440221, 0.0, 0.0, 12702506.296014734, 6351253.148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [9526879.72201105, 9526879.72201105, 0.0, 6351253.148007367, 3175626.5740036834, 9526879.72201105, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [3175626.5740036834, 12702506.296014734, 3175626.5740036834, 0.0, 9526879.72201105, 0.0, 9526879.72201105, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 9526879.72201105, 9526879.72201105, 0.0, 0.0, 9526879.72201105, 3175626.5740036834, 6351253.148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 19053759.4440221, 0.0, 0.0, 0.0, 6351253.148007367, 12702506.296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 38107518.8880442, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 12702506.296014734, 25405012.592029467, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 2540501.2592029474, 20324010.07362358, 15243007.55521768, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 7621503.77760884, 22864511.33282652, 7621503.77760884, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 15243007.55521768, 20324010.07362358, 2540501.2592029474, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 25405012.592029467, 12702506.296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 38107518.8880442, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
To return the rates in 10^6 rad /s:
>>> gamma = calculate_gamma_matrix(magnetic_states,Omega=1e6)
>>> gamma
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12.702506296014734, -15.878132870018417, -15.878132870018417, -0.0, -19.053759444022102, -9.526879722011051, -3.1756265740036835, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12.702506296014734, -15.878132870018417, -0.0, -15.878132870018417, -0.0, -9.526879722011051, -12.702506296014734, -9.526879722011051, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12.702506296014734, -0.0, -15.878132870018417, -15.878132870018417, -0.0, -0.0, -3.1756265740036835, -9.526879722011051, -19.053759444022102, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -3.8107518888044205, -0.0, -0.0, -12.702506296014734, -6.351253148007367, -0.0, -0.0, -0.0, -38.107518888044204, -12.702506296014734, -2.5405012592029474, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -1.9053759444022103, -1.9053759444022103, -0.0, -6.351253148007367, -3.1756265740036835, -9.526879722011051, -0.0, -0.0, -0.0, -25.40501259202947, -20.32401007362358, -7.62150377760884, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.6351253148007368, -2.540501259202947, -0.6351253148007368, -0.0, -9.526879722011051, -0.0, -9.526879722011051, -0.0, -0.0, -0.0, -15.24300755521768, -22.86451133282652, -15.24300755521768, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -1.9053759444022103, -1.9053759444022103, -0.0, -0.0, -9.526879722011051, -3.1756265740036835, -6.351253148007367, -0.0, -0.0, -0.0, -7.62150377760884, -20.32401007362358, -25.40501259202947, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -3.8107518888044205, -0.0, -0.0, -0.0, -6.351253148007367, -12.702506296014734, -0.0, -0.0, -0.0, -0.0, -2.5405012592029474, -12.702506296014734, -38.107518888044204], [12.702506296014734, 12.702506296014734, 12.702506296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15.878132870018417, 15.878132870018417, 0.0, 3.8107518888044205, 1.9053759444022103, 0.6351253148007368, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15.878132870018417, 0.0, 15.878132870018417, 0.0, 1.9053759444022103, 2.540501259202947, 1.9053759444022103, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 15.878132870018417, 15.878132870018417, 0.0, 0.0, 0.6351253148007368, 1.9053759444022103, 3.8107518888044205, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [19.053759444022102, 0.0, 0.0, 12.702506296014734, 6.351253148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [9.526879722011051, 9.526879722011051, 0.0, 6.351253148007367, 3.1756265740036835, 9.526879722011051, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [3.1756265740036835, 12.702506296014734, 3.1756265740036835, 0.0, 9.526879722011051, 0.0, 9.526879722011051, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 9.526879722011051, 9.526879722011051, 0.0, 0.0, 9.526879722011051, 3.1756265740036835, 6.351253148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 19.053759444022102, 0.0, 0.0, 0.0, 6.351253148007367, 12.702506296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 38.107518888044204, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 12.702506296014734, 25.40501259202947, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 2.5405012592029474, 20.32401007362358, 15.24300755521768, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 7.62150377760884, 22.86451133282652, 7.62150377760884, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 15.24300755521768, 20.32401007362358, 2.5405012592029474, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 25.40501259202947, 12.702506296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 38.107518888044204, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
Let us test if all D2 lines decay at the expected rate (6.065 MHz):
>>> Gamma =[ sum([ gamma[i][j] for j in range(i)])/2/pi for i in range(len(magnetic_states))][8:]
>>> for Gammai in Gamma: print Gammai
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
"""
Ne = len(magnetic_states)
II = magnetic_states[0].i
gamma = [[0.0 for j in range(Ne)] for i in range(Ne)]
for i in range(Ne):
for j in range(i):
ei = magnetic_states[i]
ej = magnetic_states[j]
einsteinAij = Transition(ei, ej).einsteinA
if einsteinAij != 0:
ji = ei.j; jj = ej.j
fi = ei.f; fj = ej.f
mi = ei.m; mj = ej.m
gammaij = (2.0*ji+1)
gammaij *= (2.0*fi+1)
gammaij *= (2.0*fj+1)
gammaij *= float(wigner_6j(ji, fi, II, fj, jj, 1)**2)
gammaij *= sum([float(wigner_3j(fj, 1, fi, -mj, q, mi)**2)
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gammaij = float(gammaij)
gamma[i][j] = gammaij
gamma[j][i] = -gammaij
return gamma | [
"def",
"calculate_gamma_matrix",
"(",
"magnetic_states",
",",
"Omega",
"=",
"1",
")",
":",
"Ne",
"=",
"len",
"(",
"magnetic_states",
")",
"II",
"=",
"magnetic_states",
"[",
"0",
"]",
".",
"i",
"gamma",
"=",
"[",
"[",
"0.0",
"for",
"j",
"in",
"range",
... | r"""Calculate the matrix of decay between states.
This function calculates the matrix $\gamma_{ij}$ of decay rates between
states |i> and |j> (in the units specified by the Omega argument).
>>> g=State("Rb",87,5,0,1/Integer(2))
>>> e=State("Rb",87,5,1,3/Integer(2))
>>> magnetic_states=make_list_of_states([g,e],"magnetic")
To return the rates in rad/s:
>>> print calculate_gamma_matrix(magnetic_states)
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12702506.296014734, -15878132.870018415, -15878132.870018415, -0.0, -19053759.4440221, -9526879.72201105, -3175626.5740036834, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12702506.296014734, -15878132.870018415, -0.0, -15878132.870018415, -0.0, -9526879.72201105, -12702506.296014734, -9526879.72201105, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12702506.296014734, -0.0, -15878132.870018415, -15878132.870018415, -0.0, -0.0, -3175626.5740036834, -9526879.72201105, -19053759.4440221, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -3810751.8888044204, -0.0, -0.0, -12702506.296014734, -6351253.148007367, -0.0, -0.0, -0.0, -38107518.8880442, -12702506.296014734, -2540501.2592029474, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -1905375.9444022102, -1905375.9444022102, -0.0, -6351253.148007367, -3175626.5740036834, -9526879.72201105, -0.0, -0.0, -0.0, -25405012.592029467, -20324010.07362358, -7621503.77760884, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -635125.3148007367, -2540501.259202947, -635125.3148007367, -0.0, -9526879.72201105, -0.0, -9526879.72201105, -0.0, -0.0, -0.0, -15243007.55521768, -22864511.33282652, -15243007.55521768, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -1905375.9444022102, -1905375.9444022102, -0.0, -0.0, -9526879.72201105, -3175626.5740036834, -6351253.148007367, -0.0, -0.0, -0.0, -7621503.77760884, -20324010.07362358, -25405012.592029467, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -3810751.8888044204, -0.0, -0.0, -0.0, -6351253.148007367, -12702506.296014734, -0.0, -0.0, -0.0, -0.0, -2540501.2592029474, -12702506.296014734, -38107518.8880442], [12702506.296014734, 12702506.296014734, 12702506.296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15878132.870018415, 15878132.870018415, 0.0, 3810751.8888044204, 1905375.9444022102, 635125.3148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15878132.870018415, 0.0, 15878132.870018415, 0.0, 1905375.9444022102, 2540501.259202947, 1905375.9444022102, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 15878132.870018415, 15878132.870018415, 0.0, 0.0, 635125.3148007367, 1905375.9444022102, 3810751.8888044204, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [19053759.4440221, 0.0, 0.0, 12702506.296014734, 6351253.148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [9526879.72201105, 9526879.72201105, 0.0, 6351253.148007367, 3175626.5740036834, 9526879.72201105, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [3175626.5740036834, 12702506.296014734, 3175626.5740036834, 0.0, 9526879.72201105, 0.0, 9526879.72201105, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 9526879.72201105, 9526879.72201105, 0.0, 0.0, 9526879.72201105, 3175626.5740036834, 6351253.148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 19053759.4440221, 0.0, 0.0, 0.0, 6351253.148007367, 12702506.296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 38107518.8880442, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 12702506.296014734, 25405012.592029467, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 2540501.2592029474, 20324010.07362358, 15243007.55521768, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 7621503.77760884, 22864511.33282652, 7621503.77760884, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 15243007.55521768, 20324010.07362358, 2540501.2592029474, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 25405012.592029467, 12702506.296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 38107518.8880442, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
To return the rates in 10^6 rad /s:
>>> gamma = calculate_gamma_matrix(magnetic_states,Omega=1e6)
>>> gamma
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12.702506296014734, -15.878132870018417, -15.878132870018417, -0.0, -19.053759444022102, -9.526879722011051, -3.1756265740036835, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12.702506296014734, -15.878132870018417, -0.0, -15.878132870018417, -0.0, -9.526879722011051, -12.702506296014734, -9.526879722011051, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -12.702506296014734, -0.0, -15.878132870018417, -15.878132870018417, -0.0, -0.0, -3.1756265740036835, -9.526879722011051, -19.053759444022102, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -3.8107518888044205, -0.0, -0.0, -12.702506296014734, -6.351253148007367, -0.0, -0.0, -0.0, -38.107518888044204, -12.702506296014734, -2.5405012592029474, -0.0, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -1.9053759444022103, -1.9053759444022103, -0.0, -6.351253148007367, -3.1756265740036835, -9.526879722011051, -0.0, -0.0, -0.0, -25.40501259202947, -20.32401007362358, -7.62150377760884, -0.0, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.6351253148007368, -2.540501259202947, -0.6351253148007368, -0.0, -9.526879722011051, -0.0, -9.526879722011051, -0.0, -0.0, -0.0, -15.24300755521768, -22.86451133282652, -15.24300755521768, -0.0, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -1.9053759444022103, -1.9053759444022103, -0.0, -0.0, -9.526879722011051, -3.1756265740036835, -6.351253148007367, -0.0, -0.0, -0.0, -7.62150377760884, -20.32401007362358, -25.40501259202947, -0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -3.8107518888044205, -0.0, -0.0, -0.0, -6.351253148007367, -12.702506296014734, -0.0, -0.0, -0.0, -0.0, -2.5405012592029474, -12.702506296014734, -38.107518888044204], [12.702506296014734, 12.702506296014734, 12.702506296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15.878132870018417, 15.878132870018417, 0.0, 3.8107518888044205, 1.9053759444022103, 0.6351253148007368, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [15.878132870018417, 0.0, 15.878132870018417, 0.0, 1.9053759444022103, 2.540501259202947, 1.9053759444022103, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 15.878132870018417, 15.878132870018417, 0.0, 0.0, 0.6351253148007368, 1.9053759444022103, 3.8107518888044205, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [19.053759444022102, 0.0, 0.0, 12.702506296014734, 6.351253148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [9.526879722011051, 9.526879722011051, 0.0, 6.351253148007367, 3.1756265740036835, 9.526879722011051, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [3.1756265740036835, 12.702506296014734, 3.1756265740036835, 0.0, 9.526879722011051, 0.0, 9.526879722011051, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 9.526879722011051, 9.526879722011051, 0.0, 0.0, 9.526879722011051, 3.1756265740036835, 6.351253148007367, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 19.053759444022102, 0.0, 0.0, 0.0, 6.351253148007367, 12.702506296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 38.107518888044204, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 12.702506296014734, 25.40501259202947, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 2.5405012592029474, 20.32401007362358, 15.24300755521768, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 7.62150377760884, 22.86451133282652, 7.62150377760884, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 15.24300755521768, 20.32401007362358, 2.5405012592029474, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 25.40501259202947, 12.702506296014734, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 38.107518888044204, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
Let us test if all D2 lines decay at the expected rate (6.065 MHz):
>>> Gamma =[ sum([ gamma[i][j] for j in range(i)])/2/pi for i in range(len(magnetic_states))][8:]
>>> for Gammai in Gamma: print Gammai
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065 | [
"r",
"Calculate",
"the",
"matrix",
"of",
"decay",
"between",
"states",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1316-L1386 | train | 50,363 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | calculate_boundaries | def calculate_boundaries(fine_states, full_magnetic_states):
r"""Calculate the boundary indices within a list of magnetic states.
This function calculates the boundary indices of each fine state
and each hyperfine state within a list of magnetic states. The output
is a list of tuples (a,b) with a the starting index of a state and
b it's ending index.
>>> g=State("Rb", 87, 5, 0, 1/Integer(2))
>>> full_magnetic_states=make_list_of_states([g],"magnetic")
>>> calculate_boundaries([g], full_magnetic_states)
([(0, 8)], [(0, 3), (3, 8)])
"""
N_magnetic = len(full_magnetic_states)
# We calculate the boundaries of the various detail levels
# First we will make a list of indices of that will tell where each fine
# level begins and ends.
fq = full_magnetic_states[0].quantum_numbers[:4]
index_list_fine = []; start_fine = 0
# And another list of indices that will tell where each hyperfine level
# begins and ends.
hq = full_magnetic_states[0].quantum_numbers[:5]
index_list_hyperfine = []; start_hyperfine = 0
for i in range(N_magnetic):
magnetic = full_magnetic_states[i]
if magnetic.quantum_numbers[:4] != fq:
index_list_fine += [(start_fine, i)]
start_fine = i
fq = magnetic.quantum_numbers[:4]
if magnetic.quantum_numbers[:5] != hq:
index_list_hyperfine += [(start_hyperfine, i)]
start_hyperfine = i
hq = magnetic.quantum_numbers[:5]
if i == N_magnetic-1:
index_list_fine += [(start_fine, i+1)]
index_list_hyperfine += [(start_hyperfine, i+1)]
return index_list_fine, index_list_hyperfine | python | def calculate_boundaries(fine_states, full_magnetic_states):
r"""Calculate the boundary indices within a list of magnetic states.
This function calculates the boundary indices of each fine state
and each hyperfine state within a list of magnetic states. The output
is a list of tuples (a,b) with a the starting index of a state and
b it's ending index.
>>> g=State("Rb", 87, 5, 0, 1/Integer(2))
>>> full_magnetic_states=make_list_of_states([g],"magnetic")
>>> calculate_boundaries([g], full_magnetic_states)
([(0, 8)], [(0, 3), (3, 8)])
"""
N_magnetic = len(full_magnetic_states)
# We calculate the boundaries of the various detail levels
# First we will make a list of indices of that will tell where each fine
# level begins and ends.
fq = full_magnetic_states[0].quantum_numbers[:4]
index_list_fine = []; start_fine = 0
# And another list of indices that will tell where each hyperfine level
# begins and ends.
hq = full_magnetic_states[0].quantum_numbers[:5]
index_list_hyperfine = []; start_hyperfine = 0
for i in range(N_magnetic):
magnetic = full_magnetic_states[i]
if magnetic.quantum_numbers[:4] != fq:
index_list_fine += [(start_fine, i)]
start_fine = i
fq = magnetic.quantum_numbers[:4]
if magnetic.quantum_numbers[:5] != hq:
index_list_hyperfine += [(start_hyperfine, i)]
start_hyperfine = i
hq = magnetic.quantum_numbers[:5]
if i == N_magnetic-1:
index_list_fine += [(start_fine, i+1)]
index_list_hyperfine += [(start_hyperfine, i+1)]
return index_list_fine, index_list_hyperfine | [
"def",
"calculate_boundaries",
"(",
"fine_states",
",",
"full_magnetic_states",
")",
":",
"N_magnetic",
"=",
"len",
"(",
"full_magnetic_states",
")",
"# We calculate the boundaries of the various detail levels",
"# First we will make a list of indices of that will tell where each fine"... | r"""Calculate the boundary indices within a list of magnetic states.
This function calculates the boundary indices of each fine state
and each hyperfine state within a list of magnetic states. The output
is a list of tuples (a,b) with a the starting index of a state and
b it's ending index.
>>> g=State("Rb", 87, 5, 0, 1/Integer(2))
>>> full_magnetic_states=make_list_of_states([g],"magnetic")
>>> calculate_boundaries([g], full_magnetic_states)
([(0, 8)], [(0, 3), (3, 8)]) | [
"r",
"Calculate",
"the",
"boundary",
"indices",
"within",
"a",
"list",
"of",
"magnetic",
"states",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1526-L1567 | train | 50,364 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | exclude_states | def exclude_states(omega, gamma, r, Lij, states, excluded_states):
"""Exclude states from matrices.
This function takes the matrices and excludes the states listed in
excluded_states.
"""
Ne = len(omega)
excluded_indices = [i for i in range(Ne) if states[i] in excluded_states]
omega_new = []; gamma_new = []; r_new = [[], [], []]; Lij_new = []
for i in range(Ne):
row_om = []; row_ga = []; row_L = []
for j in range(Ne):
if j not in excluded_indices:
row_om += [omega[i][j]]
row_ga += [gamma[i][j]]
row_L += [Lij[i][j]]
if i not in excluded_indices:
omega_new += [row_om]
gamma_new += [row_ga]
Lij_new += [row_L]
for p in range(3):
for i in range(Ne):
row_r = []
for j in range(Ne):
if j not in excluded_indices:
row_r += [r[p][i][j]]
if i not in excluded_indices:
r_new[p] += [row_r]
states_new = [states[i] for i in range(Ne) if i not in excluded_indices]
return omega_new, gamma_new, r_new, Lij_new, states_new | python | def exclude_states(omega, gamma, r, Lij, states, excluded_states):
"""Exclude states from matrices.
This function takes the matrices and excludes the states listed in
excluded_states.
"""
Ne = len(omega)
excluded_indices = [i for i in range(Ne) if states[i] in excluded_states]
omega_new = []; gamma_new = []; r_new = [[], [], []]; Lij_new = []
for i in range(Ne):
row_om = []; row_ga = []; row_L = []
for j in range(Ne):
if j not in excluded_indices:
row_om += [omega[i][j]]
row_ga += [gamma[i][j]]
row_L += [Lij[i][j]]
if i not in excluded_indices:
omega_new += [row_om]
gamma_new += [row_ga]
Lij_new += [row_L]
for p in range(3):
for i in range(Ne):
row_r = []
for j in range(Ne):
if j not in excluded_indices:
row_r += [r[p][i][j]]
if i not in excluded_indices:
r_new[p] += [row_r]
states_new = [states[i] for i in range(Ne) if i not in excluded_indices]
return omega_new, gamma_new, r_new, Lij_new, states_new | [
"def",
"exclude_states",
"(",
"omega",
",",
"gamma",
",",
"r",
",",
"Lij",
",",
"states",
",",
"excluded_states",
")",
":",
"Ne",
"=",
"len",
"(",
"omega",
")",
"excluded_indices",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"if",
"st... | Exclude states from matrices.
This function takes the matrices and excludes the states listed in
excluded_states. | [
"Exclude",
"states",
"from",
"matrices",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1604-L1637 | train | 50,365 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | vapour_pressure | def vapour_pressure(Temperature, element):
r"""Return the vapour pressure of rubidium or cesium in Pascals.
This function receives as input the temperature in Kelvins and the
name of the element.
>>> print vapour_pressure(25.0 + 273.15,"Rb")
5.31769896107e-05
>>> print vapour_pressure(39.3 + 273.15,"Rb")
0.000244249795696
>>> print vapour_pressure(90.0 + 273.15,"Rb")
0.0155963687128
>>> print vapour_pressure(25.0 + 273.15,"Cs")
0.000201461144963
>>> print vapour_pressure(28.5 + 273.15,"Cs")
0.000297898928349
>>> print vapour_pressure(90.0 + 273.15,"Cs")
0.0421014384667
The element must be in the database.
>>> print vapour_pressure(90.0 + 273.15,"Ca")
Traceback (most recent call last):
...
ValueError: Ca is not an element in the database for this function.
References:
[1] Daniel A. Steck, "Cesium D Line Data," available online at
http://steck.us/alkalidata (revision 2.1.4, 23 December 2010).
[2] Daniel A. Steck, "Rubidium 85 D Line Data," available online at
http://steck.us/alkalidata (revision 2.1.5, 19 September 2012).
[3] Daniel A. Steck, "Rubidium 87 D Line Data," available online at
http://steck.us/alkalidata (revision 2.1.5, 19 September 2012).
"""
if element == "Rb":
Tmelt = 39.30+273.15 # K.
if Temperature < Tmelt:
P = 10**(2.881+4.857-4215.0/Temperature) # Torr.
else:
P = 10**(2.881+4.312-4040.0/Temperature) # Torr.
elif element == "Cs":
Tmelt = 28.5 + 273.15 # K.
if Temperature < Tmelt:
P = 10**(2.881+4.711-3999.0/Temperature) # Torr.
else:
P = 10**(2.881+4.165-3830.0/Temperature) # Torr.
else:
s = str(element)
s += " is not an element in the database for this function."
raise ValueError(s)
P = P * 101325.0/760.0 # Pascals.
return P | python | def vapour_pressure(Temperature, element):
r"""Return the vapour pressure of rubidium or cesium in Pascals.
This function receives as input the temperature in Kelvins and the
name of the element.
>>> print vapour_pressure(25.0 + 273.15,"Rb")
5.31769896107e-05
>>> print vapour_pressure(39.3 + 273.15,"Rb")
0.000244249795696
>>> print vapour_pressure(90.0 + 273.15,"Rb")
0.0155963687128
>>> print vapour_pressure(25.0 + 273.15,"Cs")
0.000201461144963
>>> print vapour_pressure(28.5 + 273.15,"Cs")
0.000297898928349
>>> print vapour_pressure(90.0 + 273.15,"Cs")
0.0421014384667
The element must be in the database.
>>> print vapour_pressure(90.0 + 273.15,"Ca")
Traceback (most recent call last):
...
ValueError: Ca is not an element in the database for this function.
References:
[1] Daniel A. Steck, "Cesium D Line Data," available online at
http://steck.us/alkalidata (revision 2.1.4, 23 December 2010).
[2] Daniel A. Steck, "Rubidium 85 D Line Data," available online at
http://steck.us/alkalidata (revision 2.1.5, 19 September 2012).
[3] Daniel A. Steck, "Rubidium 87 D Line Data," available online at
http://steck.us/alkalidata (revision 2.1.5, 19 September 2012).
"""
if element == "Rb":
Tmelt = 39.30+273.15 # K.
if Temperature < Tmelt:
P = 10**(2.881+4.857-4215.0/Temperature) # Torr.
else:
P = 10**(2.881+4.312-4040.0/Temperature) # Torr.
elif element == "Cs":
Tmelt = 28.5 + 273.15 # K.
if Temperature < Tmelt:
P = 10**(2.881+4.711-3999.0/Temperature) # Torr.
else:
P = 10**(2.881+4.165-3830.0/Temperature) # Torr.
else:
s = str(element)
s += " is not an element in the database for this function."
raise ValueError(s)
P = P * 101325.0/760.0 # Pascals.
return P | [
"def",
"vapour_pressure",
"(",
"Temperature",
",",
"element",
")",
":",
"if",
"element",
"==",
"\"Rb\"",
":",
"Tmelt",
"=",
"39.30",
"+",
"273.15",
"# K.",
"if",
"Temperature",
"<",
"Tmelt",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.857",
"-",
... | r"""Return the vapour pressure of rubidium or cesium in Pascals.
This function receives as input the temperature in Kelvins and the
name of the element.
>>> print vapour_pressure(25.0 + 273.15,"Rb")
5.31769896107e-05
>>> print vapour_pressure(39.3 + 273.15,"Rb")
0.000244249795696
>>> print vapour_pressure(90.0 + 273.15,"Rb")
0.0155963687128
>>> print vapour_pressure(25.0 + 273.15,"Cs")
0.000201461144963
>>> print vapour_pressure(28.5 + 273.15,"Cs")
0.000297898928349
>>> print vapour_pressure(90.0 + 273.15,"Cs")
0.0421014384667
The element must be in the database.
>>> print vapour_pressure(90.0 + 273.15,"Ca")
Traceback (most recent call last):
...
ValueError: Ca is not an element in the database for this function.
References:
[1] Daniel A. Steck, "Cesium D Line Data," available online at
http://steck.us/alkalidata (revision 2.1.4, 23 December 2010).
[2] Daniel A. Steck, "Rubidium 85 D Line Data," available online at
http://steck.us/alkalidata (revision 2.1.5, 19 September 2012).
[3] Daniel A. Steck, "Rubidium 87 D Line Data," available online at
http://steck.us/alkalidata (revision 2.1.5, 19 September 2012). | [
"r",
"Return",
"the",
"vapour",
"pressure",
"of",
"rubidium",
"or",
"cesium",
"in",
"Pascals",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1904-L1956 | train | 50,366 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | Atom.states | def states(self,
Nmax=50, omega_min=None, omega_max=None, return_missing=False):
r"""Find all states of available in an atom.
This function returns all available states up to the fine structure
(ordered by energy) such that the principal quantum number is N<=Nmax.
Nmax is 50 by default.
>>> atom=Atom("Rb",85)
>>> states=atom.states()
>>> print states
[85Rb 5S_1/2, 85Rb 5P_1/2, 85Rb 5P_3/2, 85Rb 4D_5/2, 85Rb 4D_3/2, 85Rb 6S_1/2, 85Rb 6P_1/2, 85Rb 6P_3/2, 85Rb 5D_3/2, 85Rb 5D_5/2, 85Rb 7S_1/2, 85Rb 7P_1/2, 85Rb 7P_3/2, 85Rb 6D_3/2, 85Rb 7D_3/2, 85Rb 14S_1/2, 85Rb 15S_1/2, 85Rb 16S_1/2, 85Rb 17S_1/2, 85Rb 18S_1/2, 85Rb 19S_1/2, 85Rb 20S_1/2, 85Rb 21S_1/2, 85Rb 22S_1/2, 85Rb 23S_1/2, 85Rb 24S_1/2, 85Rb 25S_1/2, 85Rb 26S_1/2, 85Rb 27S_1/2, 85Rb 28S_1/2, 85Rb 29S_1/2, 85Rb 30S_1/2, 85Rb 31S_1/2, 85Rb 32S_1/2, 85Rb 33S_1/2, 85Rb 34S_1/2, 85Rb 35S_1/2, 85Rb 36S_1/2, 85Rb 37S_1/2, 85Rb 38S_1/2, 85Rb 39S_1/2, 85Rb 40S_1/2, 85Rb 41S_1/2, 85Rb 42S_1/2, 85Rb 43S_1/2, 85Rb 44S_1/2, 85Rb 45S_1/2, 85Rb 46S_1/2, 85Rb 47S_1/2, 85Rb 48S_1/2, 85Rb 49S_1/2, 85Rb 50S_1/2]
If an omega_max is provided any state with an energy higher than
hbar*omega will not be returned. If an omega_min is provided any state
with an energy lower than hbar*omega will not be returned.
>>> atom.states(omega_min=1.00845e15*2*pi, omega_max=1.0086e+15*2*pi)
[85Rb 49S_1/2, 85Rb 50S_1/2]
If return_missing=True then the function will return a 2-tuple composed
by a list of the states available, and a list of the valid states not
available.
>>> available,not_available=atom.states(Nmax=5,return_missing=True)
>>> print available
[85Rb 5S_1/2, 85Rb 5P_1/2, 85Rb 5P_3/2, 85Rb 4D_5/2, 85Rb 4D_3/2, 85Rb 5D_3/2, 85Rb 5D_5/2]
>>> print not_available
[('Rb', 85, 1, 0, 1/2), ('Rb', 85, 2, 0, 1/2), ('Rb', 85, 2, 1, 1/2), ('Rb', 85, 2, 1, 3/2), ('Rb', 85, 3, 0, 1/2), ('Rb', 85, 3, 1, 1/2), ('Rb', 85, 3, 1, 3/2), ('Rb', 85, 3, 2, 3/2), ('Rb', 85, 3, 2, 5/2), ('Rb', 85, 4, 0, 1/2), ('Rb', 85, 4, 1, 1/2), ('Rb', 85, 4, 1, 3/2), ('Rb', 85, 4, 3, 5/2), ('Rb', 85, 4, 3, 7/2), ('Rb', 85, 5, 3, 5/2), ('Rb', 85, 5, 3, 7/2), ('Rb', 85, 5, 4, 7/2), ('Rb', 85, 5, 4, 9/2)]
"""
# We generate all possible quantum numbers for N<=Nmax.
S = 1/Integer(2) # The spin of the electron.
available = []
not_available = []
for N in range(1, Nmax+1):
for L in range(N):
Jmin = abs(L-S)
Jmax = L+S
Jpos = [Jmin+i for i in range(Jmax-Jmin+1)]
for J in Jpos:
try:
state = State(self.element, self.isotope, N, L, J)
available += [state]
except:
not_available += [(self.element, self.isotope,
N, L, J)]
if omega_min is not None:
available = [s for s in available if s.omega >= omega_min]
if omega_max is not None:
available = [s for s in available if s.omega <= omega_max]
# We sort the states by energy.
available = [(s.omega, s) for s in available]
available = sorted(available)
available = [s[1] for s in available]
if return_missing:
return available, not_available
else:
return available | python | def states(self,
Nmax=50, omega_min=None, omega_max=None, return_missing=False):
r"""Find all states of available in an atom.
This function returns all available states up to the fine structure
(ordered by energy) such that the principal quantum number is N<=Nmax.
Nmax is 50 by default.
>>> atom=Atom("Rb",85)
>>> states=atom.states()
>>> print states
[85Rb 5S_1/2, 85Rb 5P_1/2, 85Rb 5P_3/2, 85Rb 4D_5/2, 85Rb 4D_3/2, 85Rb 6S_1/2, 85Rb 6P_1/2, 85Rb 6P_3/2, 85Rb 5D_3/2, 85Rb 5D_5/2, 85Rb 7S_1/2, 85Rb 7P_1/2, 85Rb 7P_3/2, 85Rb 6D_3/2, 85Rb 7D_3/2, 85Rb 14S_1/2, 85Rb 15S_1/2, 85Rb 16S_1/2, 85Rb 17S_1/2, 85Rb 18S_1/2, 85Rb 19S_1/2, 85Rb 20S_1/2, 85Rb 21S_1/2, 85Rb 22S_1/2, 85Rb 23S_1/2, 85Rb 24S_1/2, 85Rb 25S_1/2, 85Rb 26S_1/2, 85Rb 27S_1/2, 85Rb 28S_1/2, 85Rb 29S_1/2, 85Rb 30S_1/2, 85Rb 31S_1/2, 85Rb 32S_1/2, 85Rb 33S_1/2, 85Rb 34S_1/2, 85Rb 35S_1/2, 85Rb 36S_1/2, 85Rb 37S_1/2, 85Rb 38S_1/2, 85Rb 39S_1/2, 85Rb 40S_1/2, 85Rb 41S_1/2, 85Rb 42S_1/2, 85Rb 43S_1/2, 85Rb 44S_1/2, 85Rb 45S_1/2, 85Rb 46S_1/2, 85Rb 47S_1/2, 85Rb 48S_1/2, 85Rb 49S_1/2, 85Rb 50S_1/2]
If an omega_max is provided any state with an energy higher than
hbar*omega will not be returned. If an omega_min is provided any state
with an energy lower than hbar*omega will not be returned.
>>> atom.states(omega_min=1.00845e15*2*pi, omega_max=1.0086e+15*2*pi)
[85Rb 49S_1/2, 85Rb 50S_1/2]
If return_missing=True then the function will return a 2-tuple composed
by a list of the states available, and a list of the valid states not
available.
>>> available,not_available=atom.states(Nmax=5,return_missing=True)
>>> print available
[85Rb 5S_1/2, 85Rb 5P_1/2, 85Rb 5P_3/2, 85Rb 4D_5/2, 85Rb 4D_3/2, 85Rb 5D_3/2, 85Rb 5D_5/2]
>>> print not_available
[('Rb', 85, 1, 0, 1/2), ('Rb', 85, 2, 0, 1/2), ('Rb', 85, 2, 1, 1/2), ('Rb', 85, 2, 1, 3/2), ('Rb', 85, 3, 0, 1/2), ('Rb', 85, 3, 1, 1/2), ('Rb', 85, 3, 1, 3/2), ('Rb', 85, 3, 2, 3/2), ('Rb', 85, 3, 2, 5/2), ('Rb', 85, 4, 0, 1/2), ('Rb', 85, 4, 1, 1/2), ('Rb', 85, 4, 1, 3/2), ('Rb', 85, 4, 3, 5/2), ('Rb', 85, 4, 3, 7/2), ('Rb', 85, 5, 3, 5/2), ('Rb', 85, 5, 3, 7/2), ('Rb', 85, 5, 4, 7/2), ('Rb', 85, 5, 4, 9/2)]
"""
# We generate all possible quantum numbers for N<=Nmax.
S = 1/Integer(2) # The spin of the electron.
available = []
not_available = []
for N in range(1, Nmax+1):
for L in range(N):
Jmin = abs(L-S)
Jmax = L+S
Jpos = [Jmin+i for i in range(Jmax-Jmin+1)]
for J in Jpos:
try:
state = State(self.element, self.isotope, N, L, J)
available += [state]
except:
not_available += [(self.element, self.isotope,
N, L, J)]
if omega_min is not None:
available = [s for s in available if s.omega >= omega_min]
if omega_max is not None:
available = [s for s in available if s.omega <= omega_max]
# We sort the states by energy.
available = [(s.omega, s) for s in available]
available = sorted(available)
available = [s[1] for s in available]
if return_missing:
return available, not_available
else:
return available | [
"def",
"states",
"(",
"self",
",",
"Nmax",
"=",
"50",
",",
"omega_min",
"=",
"None",
",",
"omega_max",
"=",
"None",
",",
"return_missing",
"=",
"False",
")",
":",
"# We generate all possible quantum numbers for N<=Nmax.",
"S",
"=",
"1",
"/",
"Integer",
"(",
... | r"""Find all states of available in an atom.
This function returns all available states up to the fine structure
(ordered by energy) such that the principal quantum number is N<=Nmax.
Nmax is 50 by default.
>>> atom=Atom("Rb",85)
>>> states=atom.states()
>>> print states
[85Rb 5S_1/2, 85Rb 5P_1/2, 85Rb 5P_3/2, 85Rb 4D_5/2, 85Rb 4D_3/2, 85Rb 6S_1/2, 85Rb 6P_1/2, 85Rb 6P_3/2, 85Rb 5D_3/2, 85Rb 5D_5/2, 85Rb 7S_1/2, 85Rb 7P_1/2, 85Rb 7P_3/2, 85Rb 6D_3/2, 85Rb 7D_3/2, 85Rb 14S_1/2, 85Rb 15S_1/2, 85Rb 16S_1/2, 85Rb 17S_1/2, 85Rb 18S_1/2, 85Rb 19S_1/2, 85Rb 20S_1/2, 85Rb 21S_1/2, 85Rb 22S_1/2, 85Rb 23S_1/2, 85Rb 24S_1/2, 85Rb 25S_1/2, 85Rb 26S_1/2, 85Rb 27S_1/2, 85Rb 28S_1/2, 85Rb 29S_1/2, 85Rb 30S_1/2, 85Rb 31S_1/2, 85Rb 32S_1/2, 85Rb 33S_1/2, 85Rb 34S_1/2, 85Rb 35S_1/2, 85Rb 36S_1/2, 85Rb 37S_1/2, 85Rb 38S_1/2, 85Rb 39S_1/2, 85Rb 40S_1/2, 85Rb 41S_1/2, 85Rb 42S_1/2, 85Rb 43S_1/2, 85Rb 44S_1/2, 85Rb 45S_1/2, 85Rb 46S_1/2, 85Rb 47S_1/2, 85Rb 48S_1/2, 85Rb 49S_1/2, 85Rb 50S_1/2]
If an omega_max is provided any state with an energy higher than
hbar*omega will not be returned. If an omega_min is provided any state
with an energy lower than hbar*omega will not be returned.
>>> atom.states(omega_min=1.00845e15*2*pi, omega_max=1.0086e+15*2*pi)
[85Rb 49S_1/2, 85Rb 50S_1/2]
If return_missing=True then the function will return a 2-tuple composed
by a list of the states available, and a list of the valid states not
available.
>>> available,not_available=atom.states(Nmax=5,return_missing=True)
>>> print available
[85Rb 5S_1/2, 85Rb 5P_1/2, 85Rb 5P_3/2, 85Rb 4D_5/2, 85Rb 4D_3/2, 85Rb 5D_3/2, 85Rb 5D_5/2]
>>> print not_available
[('Rb', 85, 1, 0, 1/2), ('Rb', 85, 2, 0, 1/2), ('Rb', 85, 2, 1, 1/2), ('Rb', 85, 2, 1, 3/2), ('Rb', 85, 3, 0, 1/2), ('Rb', 85, 3, 1, 1/2), ('Rb', 85, 3, 1, 3/2), ('Rb', 85, 3, 2, 3/2), ('Rb', 85, 3, 2, 5/2), ('Rb', 85, 4, 0, 1/2), ('Rb', 85, 4, 1, 1/2), ('Rb', 85, 4, 1, 3/2), ('Rb', 85, 4, 3, 5/2), ('Rb', 85, 4, 3, 7/2), ('Rb', 85, 5, 3, 5/2), ('Rb', 85, 5, 3, 7/2), ('Rb', 85, 5, 4, 7/2), ('Rb', 85, 5, 4, 9/2)] | [
"r",
"Find",
"all",
"states",
"of",
"available",
"in",
"an",
"atom",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L229-L292 | train | 50,367 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | Atom.find_decays | def find_decays(self, fine_state):
r"""Find all possible decays from a given fine state.
This function finds all the states to which a given fine structure
state can decay (through electric dipole selection rules).
>>> atom=Atom("Cs",133)
>>> e=State("Cs",133,6,"P",3/Integer(2))
>>> atom.find_decays(e)
[133Cs 6P_3/2, 133Cs 6S_1/2]
>>> s=State("Cs",133,6,"D",5/Integer(2))
>>> atom.find_decays(s)
[133Cs 6D_5/2, 133Cs 6P_3/2, 133Cs 7P_3/2, 133Cs 6S_1/2, 133Cs 5D_3/2, 133Cs 5D_5/2, 133Cs 7S_1/2, 133Cs 6P_1/2]
"""
def decays_from(fine_state, transitions):
states_below = []
for t in transitions:
if t.e2 == fine_state:
states_below += [t.e1]
return states_below
def iterate(states, transitions):
new_and_old_states = states[:]
for state in states:
new_states = decays_from(state, transitions)
for new_state in new_states:
if new_state not in new_and_old_states:
new_and_old_states += [new_state]
if states == new_and_old_states:
return states
else:
return iterate(new_and_old_states, transitions)
transitions = self.transitions()
states = iterate([fine_state], transitions)
return states | python | def find_decays(self, fine_state):
r"""Find all possible decays from a given fine state.
This function finds all the states to which a given fine structure
state can decay (through electric dipole selection rules).
>>> atom=Atom("Cs",133)
>>> e=State("Cs",133,6,"P",3/Integer(2))
>>> atom.find_decays(e)
[133Cs 6P_3/2, 133Cs 6S_1/2]
>>> s=State("Cs",133,6,"D",5/Integer(2))
>>> atom.find_decays(s)
[133Cs 6D_5/2, 133Cs 6P_3/2, 133Cs 7P_3/2, 133Cs 6S_1/2, 133Cs 5D_3/2, 133Cs 5D_5/2, 133Cs 7S_1/2, 133Cs 6P_1/2]
"""
def decays_from(fine_state, transitions):
states_below = []
for t in transitions:
if t.e2 == fine_state:
states_below += [t.e1]
return states_below
def iterate(states, transitions):
new_and_old_states = states[:]
for state in states:
new_states = decays_from(state, transitions)
for new_state in new_states:
if new_state not in new_and_old_states:
new_and_old_states += [new_state]
if states == new_and_old_states:
return states
else:
return iterate(new_and_old_states, transitions)
transitions = self.transitions()
states = iterate([fine_state], transitions)
return states | [
"def",
"find_decays",
"(",
"self",
",",
"fine_state",
")",
":",
"def",
"decays_from",
"(",
"fine_state",
",",
"transitions",
")",
":",
"states_below",
"=",
"[",
"]",
"for",
"t",
"in",
"transitions",
":",
"if",
"t",
".",
"e2",
"==",
"fine_state",
":",
"... | r"""Find all possible decays from a given fine state.
This function finds all the states to which a given fine structure
state can decay (through electric dipole selection rules).
>>> atom=Atom("Cs",133)
>>> e=State("Cs",133,6,"P",3/Integer(2))
>>> atom.find_decays(e)
[133Cs 6P_3/2, 133Cs 6S_1/2]
>>> s=State("Cs",133,6,"D",5/Integer(2))
>>> atom.find_decays(s)
[133Cs 6D_5/2, 133Cs 6P_3/2, 133Cs 7P_3/2, 133Cs 6S_1/2, 133Cs 5D_3/2, 133Cs 5D_5/2, 133Cs 7S_1/2, 133Cs 6P_1/2] | [
"r",
"Find",
"all",
"possible",
"decays",
"from",
"a",
"given",
"fine",
"state",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L342-L381 | train | 50,368 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | State._latex_ | def _latex_(self):
r"""The LaTeX routine for states.
>>> State("Rb",85,5,0,1/Integer(2))._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}'
>>> State("Rb",85,5,0,1/Integer(2),2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2}'
>>> State("Rb",85,5,0,1/Integer(2),2,2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2,2}'
"""
if self.l == 0: l = 'S'
elif self.l == 1: l = 'P'
elif self.l == 2: l = 'D'
elif self.l == 3: l = 'F'
else: l = str(self.l)
if self.f is None:
s = '^{'+str(self.isotope)+'}\\mathrm{'+self.element+'}\\ '
s += str(self.n)+l+'_{'+str(self.j)+'}'
else:
s = '^{'+str(self.isotope)+'}\\mathrm{'+self.element+'}\\ '
s += str(self.n)+l+'_{'+str(self.j)+'}^{'+str(self.f)+'}'
if self.m is not None:
s = s[:-1] + ','+str(self.m)+'}'
return s | python | def _latex_(self):
r"""The LaTeX routine for states.
>>> State("Rb",85,5,0,1/Integer(2))._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}'
>>> State("Rb",85,5,0,1/Integer(2),2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2}'
>>> State("Rb",85,5,0,1/Integer(2),2,2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2,2}'
"""
if self.l == 0: l = 'S'
elif self.l == 1: l = 'P'
elif self.l == 2: l = 'D'
elif self.l == 3: l = 'F'
else: l = str(self.l)
if self.f is None:
s = '^{'+str(self.isotope)+'}\\mathrm{'+self.element+'}\\ '
s += str(self.n)+l+'_{'+str(self.j)+'}'
else:
s = '^{'+str(self.isotope)+'}\\mathrm{'+self.element+'}\\ '
s += str(self.n)+l+'_{'+str(self.j)+'}^{'+str(self.f)+'}'
if self.m is not None:
s = s[:-1] + ','+str(self.m)+'}'
return s | [
"def",
"_latex_",
"(",
"self",
")",
":",
"if",
"self",
".",
"l",
"==",
"0",
":",
"l",
"=",
"'S'",
"elif",
"self",
".",
"l",
"==",
"1",
":",
"l",
"=",
"'P'",
"elif",
"self",
".",
"l",
"==",
"2",
":",
"l",
"=",
"'D'",
"elif",
"self",
".",
"... | r"""The LaTeX routine for states.
>>> State("Rb",85,5,0,1/Integer(2))._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}'
>>> State("Rb",85,5,0,1/Integer(2),2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2}'
>>> State("Rb",85,5,0,1/Integer(2),2,2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2,2}' | [
"r",
"The",
"LaTeX",
"routine",
"for",
"states",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L926-L955 | train | 50,369 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | Transition._latex_ | def _latex_(self):
r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^{3}'
"""
if self.allowed:
return self.e1._latex_()+'\\ \\rightarrow \\ '+self.e2._latex_()
elif not self.allowed:
return self.e1._latex_()+'\\ \\nrightarrow \\ '+self.e2._latex_()
else:
return self.e1._latex_()+'\\ \\rightarrow^? \\ '+self.e2._latex_()
return self.e1._latex_()+'\\ \\nleftrightarrow \\ '+self.e2._latex_() | python | def _latex_(self):
r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^{3}'
"""
if self.allowed:
return self.e1._latex_()+'\\ \\rightarrow \\ '+self.e2._latex_()
elif not self.allowed:
return self.e1._latex_()+'\\ \\nrightarrow \\ '+self.e2._latex_()
else:
return self.e1._latex_()+'\\ \\rightarrow^? \\ '+self.e2._latex_()
return self.e1._latex_()+'\\ \\nleftrightarrow \\ '+self.e2._latex_() | [
"def",
"_latex_",
"(",
"self",
")",
":",
"if",
"self",
".",
"allowed",
":",
"return",
"self",
".",
"e1",
".",
"_latex_",
"(",
")",
"+",
"'\\\\ \\\\rightarrow \\\\ '",
"+",
"self",
".",
"e2",
".",
"_latex_",
"(",
")",
"elif",
"not",
"self",
".",
"allo... | r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^{3}' | [
"r",
"The",
"representation",
"routine",
"for",
"transitions",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1163-L1179 | train | 50,370 |
tilde-lab/tilde | tilde/berlinium/cubicspline.py | uFuncConverter | def uFuncConverter(variableIndex):
'''A decorator to convert python functions to numpy universal functions
A standard function of 1 variable is extended by a decorator to handle
all values in a list, tuple or numpy array
:param variableIndex: Specifies index for args to use as variable.
This way the function can be used in classes as well as functions
:type variableIndex: An positive integer
**How to use:**
In the example below uFuncConverter is used on the first parameter x:
>>> @uFuncConverter(0)
... def test(x, y = 2):
... return x+y
...
>>> x0 = 4
>>> x1 = (1, 2, 3)
>>> x2 = [2, 3, 4]
>>> x3 = asarray(x1) + 2
>>> print test(x0)
6
>>> print test(x1)
[3 4 5]
>>> print test(x2)
[4 5 6]
>>> print test(x3)
[5 6 7]
'''
def wrap(func):
'''Function to wrap around methods and functions
'''
def npWrapFunc(*args):
'''Function specifying what the wrapping should do
'''
if len(args) >= variableIndex:
before = list(args[:variableIndex])
arguments = args[variableIndex]
after = list(args[variableIndex + 1:])
if isinstance(arguments, (int, float, Decimal)):
if variableIndex:
return func(*args)
else:
return func(args[0])
elif isinstance(arguments, (list, tuple, ndarray)):
if variableIndex:
return asarray([func(*(before + [x] + after)) for x in arguments])
else:
return asarray([func(x) for x in arguments])
raise Exception('Error! Arguments (%s) not of proper format' % str(arguments))
return npWrapFunc
return wrap | python | def uFuncConverter(variableIndex):
'''A decorator to convert python functions to numpy universal functions
A standard function of 1 variable is extended by a decorator to handle
all values in a list, tuple or numpy array
:param variableIndex: Specifies index for args to use as variable.
This way the function can be used in classes as well as functions
:type variableIndex: An positive integer
**How to use:**
In the example below uFuncConverter is used on the first parameter x:
>>> @uFuncConverter(0)
... def test(x, y = 2):
... return x+y
...
>>> x0 = 4
>>> x1 = (1, 2, 3)
>>> x2 = [2, 3, 4]
>>> x3 = asarray(x1) + 2
>>> print test(x0)
6
>>> print test(x1)
[3 4 5]
>>> print test(x2)
[4 5 6]
>>> print test(x3)
[5 6 7]
'''
def wrap(func):
'''Function to wrap around methods and functions
'''
def npWrapFunc(*args):
'''Function specifying what the wrapping should do
'''
if len(args) >= variableIndex:
before = list(args[:variableIndex])
arguments = args[variableIndex]
after = list(args[variableIndex + 1:])
if isinstance(arguments, (int, float, Decimal)):
if variableIndex:
return func(*args)
else:
return func(args[0])
elif isinstance(arguments, (list, tuple, ndarray)):
if variableIndex:
return asarray([func(*(before + [x] + after)) for x in arguments])
else:
return asarray([func(x) for x in arguments])
raise Exception('Error! Arguments (%s) not of proper format' % str(arguments))
return npWrapFunc
return wrap | [
"def",
"uFuncConverter",
"(",
"variableIndex",
")",
":",
"def",
"wrap",
"(",
"func",
")",
":",
"'''Function to wrap around methods and functions\n '''",
"def",
"npWrapFunc",
"(",
"*",
"args",
")",
":",
"'''Function specifying what the wrapping should do\n ''... | A decorator to convert python functions to numpy universal functions
A standard function of 1 variable is extended by a decorator to handle
all values in a list, tuple or numpy array
:param variableIndex: Specifies index for args to use as variable.
This way the function can be used in classes as well as functions
:type variableIndex: An positive integer
**How to use:**
In the example below uFuncConverter is used on the first parameter x:
>>> @uFuncConverter(0)
... def test(x, y = 2):
... return x+y
...
>>> x0 = 4
>>> x1 = (1, 2, 3)
>>> x2 = [2, 3, 4]
>>> x3 = asarray(x1) + 2
>>> print test(x0)
6
>>> print test(x1)
[3 4 5]
>>> print test(x2)
[4 5 6]
>>> print test(x3)
[5 6 7] | [
"A",
"decorator",
"to",
"convert",
"python",
"functions",
"to",
"numpy",
"universal",
"functions"
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/cubicspline.py#L23-L77 | train | 50,371 |
oscarlazoarjona/fast | fast/atomic_structure.py | unperturbed_hamiltonian | def unperturbed_hamiltonian(states):
r"""Return the unperturbed atomic hamiltonian for given states.
We calcualte the atomic hamiltonian in the basis of the ground states of \
rubidium 87 (in GHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([g], "magnetic")
>>> print(np.diag(unperturbed_hamiltonian(magnetic_states))/hbar/2/pi*1e-9)
[-4.2717+0.j -4.2717+0.j -4.2717+0.j 2.563 +0.j 2.563 +0.j 2.563 +0.j
2.563 +0.j 2.563 +0.j]
"""
Ne = len(states)
H0 = np.zeros((Ne, Ne), complex)
for i in range(Ne):
H0[i, i] = hbar*states[i].omega
return H0 | python | def unperturbed_hamiltonian(states):
r"""Return the unperturbed atomic hamiltonian for given states.
We calcualte the atomic hamiltonian in the basis of the ground states of \
rubidium 87 (in GHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([g], "magnetic")
>>> print(np.diag(unperturbed_hamiltonian(magnetic_states))/hbar/2/pi*1e-9)
[-4.2717+0.j -4.2717+0.j -4.2717+0.j 2.563 +0.j 2.563 +0.j 2.563 +0.j
2.563 +0.j 2.563 +0.j]
"""
Ne = len(states)
H0 = np.zeros((Ne, Ne), complex)
for i in range(Ne):
H0[i, i] = hbar*states[i].omega
return H0 | [
"def",
"unperturbed_hamiltonian",
"(",
"states",
")",
":",
"Ne",
"=",
"len",
"(",
"states",
")",
"H0",
"=",
"np",
".",
"zeros",
"(",
"(",
"Ne",
",",
"Ne",
")",
",",
"complex",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"H0",
"[",
"i",... | r"""Return the unperturbed atomic hamiltonian for given states.
We calcualte the atomic hamiltonian in the basis of the ground states of \
rubidium 87 (in GHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([g], "magnetic")
>>> print(np.diag(unperturbed_hamiltonian(magnetic_states))/hbar/2/pi*1e-9)
[-4.2717+0.j -4.2717+0.j -4.2717+0.j 2.563 +0.j 2.563 +0.j 2.563 +0.j
2.563 +0.j 2.563 +0.j] | [
"r",
"Return",
"the",
"unperturbed",
"atomic",
"hamiltonian",
"for",
"given",
"states",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1433-L1449 | train | 50,372 |
oscarlazoarjona/fast | fast/atomic_structure.py | calculate_gamma_matrix | def calculate_gamma_matrix(magnetic_states, Omega=1, einsteinA=None,
numeric=True):
ur"""Calculate the matrix of decay between states.
This function calculates the matrix :math:`\gamma_{ij}` of decay rates
between states :math:`|i\rangle` and :math:`|j\rangle` (in the units
specified by the Omega argument).
>>> import numpy as np
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> magnetic_states = make_list_of_states([g, e], "magnetic")
To return the rates in 10^6 rad /s:
>>> gamma = np.array(calculate_gamma_matrix(magnetic_states, Omega=1e6))
The :math:`5P_{3/2}, 5S_{1/2}` block of this matrix is
>>> print(gamma[8:, :8]/2/np.pi)
[[2.0217 2.0217 2.0217 0. 0. 0. 0. 0. ]
[2.5271 2.5271 0. 0.6065 0.3033 0.1011 0. 0. ]
[2.5271 0. 2.5271 0. 0.3033 0.4043 0.3033 0. ]
[0. 2.5271 2.5271 0. 0. 0.1011 0.3033 0.6065]
[3.0325 0. 0. 2.0217 1.0108 0. 0. 0. ]
[1.5163 1.5163 0. 1.0108 0.5054 1.5163 0. 0. ]
[0.5054 2.0217 0.5054 0. 1.5163 0. 1.5163 0. ]
[0. 1.5163 1.5163 0. 0. 1.5163 0.5054 1.0108]
[0. 0. 3.0325 0. 0. 0. 1.0108 2.0217]
[0. 0. 0. 6.065 0. 0. 0. 0. ]
[0. 0. 0. 2.0217 4.0433 0. 0. 0. ]
[0. 0. 0. 0.4043 3.2347 2.426 0. 0. ]
[0. 0. 0. 0. 1.213 3.639 1.213 0. ]
[0. 0. 0. 0. 0. 2.426 3.2347 0.4043]
[0. 0. 0. 0. 0. 0. 4.0433 2.0217]
[0. 0. 0. 0. 0. 0. 0. 6.065 ]]
Let us test if all D2 lines decay at the expected rate (6.065 MHz):
>>> Gamma = [sum([gamma[i][j] for j in range(i)])/2/pi
... for i in range(len(magnetic_states))][8:]
>>> for Gammai in Gamma: print("{:2.3f}".format(Gammai))
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
Let us do this symbolically
>>> from sympy import Matrix, pprint, symbols
>>> Gamma = symbols("Gamma", positive=True)
>>> einsteinA = Matrix([[0, -Gamma], [Gamma, 0]])
>>> gamma = calculate_gamma_matrix(magnetic_states, einsteinA=einsteinA,
... numeric=False)
>>> pprint(Matrix(gamma)[8:, :8])
⎡ Γ Γ Γ ⎤
⎢ ─ ─ ─ 0 0 0 0 0 ⎥
⎢ 3 3 3 ⎥
⎢ ⎥
⎢5⋅Γ 5⋅Γ Γ Γ Γ ⎥
⎢─── ─── 0 ── ── ── 0 0 ⎥
⎢ 12 12 10 20 60 ⎥
⎢ ⎥
⎢5⋅Γ 5⋅Γ Γ Γ Γ ⎥
⎢─── 0 ─── 0 ── ── ── 0 ⎥
⎢ 12 12 20 15 20 ⎥
⎢ ⎥
⎢ 5⋅Γ 5⋅Γ Γ Γ Γ ⎥
⎢ 0 ─── ─── 0 0 ── ── ──⎥
⎢ 12 12 60 20 10⎥
⎢ ⎥
⎢ Γ Γ Γ ⎥
⎢ ─ 0 0 ─ ─ 0 0 0 ⎥
⎢ 2 3 6 ⎥
⎢ ⎥
⎢ Γ Γ Γ Γ Γ ⎥
⎢ ─ ─ 0 ─ ── ─ 0 0 ⎥
⎢ 4 4 6 12 4 ⎥
⎢ ⎥
⎢Γ Γ Γ Γ Γ ⎥
⎢── ─ ── 0 ─ 0 ─ 0 ⎥
⎢12 3 12 4 4 ⎥
⎢ ⎥
⎢ Γ Γ Γ Γ Γ ⎥
⎢ 0 ─ ─ 0 0 ─ ── ─ ⎥
⎢ 4 4 4 12 6 ⎥
⎢ ⎥
⎢ Γ Γ Γ ⎥
⎢ 0 0 ─ 0 0 0 ─ ─ ⎥
⎢ 2 6 3 ⎥
⎢ ⎥
⎢ 0 0 0 Γ 0 0 0 0 ⎥
⎢ ⎥
⎢ Γ 2⋅Γ ⎥
⎢ 0 0 0 ─ ─── 0 0 0 ⎥
⎢ 3 3 ⎥
⎢ ⎥
⎢ Γ 8⋅Γ 2⋅Γ ⎥
⎢ 0 0 0 ── ─── ─── 0 0 ⎥
⎢ 15 15 5 ⎥
⎢ ⎥
⎢ Γ 3⋅Γ Γ ⎥
⎢ 0 0 0 0 ─ ─── ─ 0 ⎥
⎢ 5 5 5 ⎥
⎢ ⎥
⎢ 2⋅Γ 8⋅Γ Γ ⎥
⎢ 0 0 0 0 0 ─── ─── ──⎥
⎢ 5 15 15⎥
⎢ ⎥
⎢ 2⋅Γ Γ ⎥
⎢ 0 0 0 0 0 0 ─── ─ ⎥
⎢ 3 3 ⎥
⎢ ⎥
⎣ 0 0 0 0 0 0 0 Γ ⎦
>>> Gamma =Matrix([sum([gamma[i][j] for j in range(i)])
... for i in range(len(magnetic_states))][8:])
>>> pprint(Gamma)
⎡Γ⎤
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎣Γ⎦
"""
Ne = len(magnetic_states)
fine_states = []
fine_map = {}
ii = 0
for ei in magnetic_states:
fine = State(ei.element, ei.isotope, ei.n, ei.l, ei.j)
if fine not in fine_states:
fine_states += [fine]
ii += 1
fine_map.update({ei: ii-1})
II = magnetic_states[0].i
gamma = [[0.0 for j in range(Ne)] for i in range(Ne)]
for i in range(Ne):
for j in range(i):
ei = magnetic_states[i]
ej = magnetic_states[j]
if einsteinA is not None:
iii = fine_map[ei]
jjj = fine_map[ej]
einsteinAij = einsteinA[iii, jjj]
else:
einsteinAij = Transition(ei, ej).einsteinA
if einsteinAij != 0:
ji = ei.j; jj = ej.j
fi = ei.f; fj = ej.f
mi = ei.m; mj = ej.m
gammaij = (2*ji+1)
gammaij *= (2*fi+1)
gammaij *= (2*fj+1)
if numeric:
gammaij *= float(wigner_6j(ji, fi, II, fj, jj, 1)**2)
gammaij *= sum([float(wigner_3j(fj, 1, fi, -mj, q, mi)**2)
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gammaij = float(gammaij)
else:
gammaij *= wigner_6j(ji, fi, II, fj, jj, 1)**2
gammaij *= sum([wigner_3j(fj, 1, fi, -mj, q, mi)**2
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gamma[i][j] = gammaij
gamma[j][i] = -gammaij
return gamma | python | def calculate_gamma_matrix(magnetic_states, Omega=1, einsteinA=None,
numeric=True):
ur"""Calculate the matrix of decay between states.
This function calculates the matrix :math:`\gamma_{ij}` of decay rates
between states :math:`|i\rangle` and :math:`|j\rangle` (in the units
specified by the Omega argument).
>>> import numpy as np
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> magnetic_states = make_list_of_states([g, e], "magnetic")
To return the rates in 10^6 rad /s:
>>> gamma = np.array(calculate_gamma_matrix(magnetic_states, Omega=1e6))
The :math:`5P_{3/2}, 5S_{1/2}` block of this matrix is
>>> print(gamma[8:, :8]/2/np.pi)
[[2.0217 2.0217 2.0217 0. 0. 0. 0. 0. ]
[2.5271 2.5271 0. 0.6065 0.3033 0.1011 0. 0. ]
[2.5271 0. 2.5271 0. 0.3033 0.4043 0.3033 0. ]
[0. 2.5271 2.5271 0. 0. 0.1011 0.3033 0.6065]
[3.0325 0. 0. 2.0217 1.0108 0. 0. 0. ]
[1.5163 1.5163 0. 1.0108 0.5054 1.5163 0. 0. ]
[0.5054 2.0217 0.5054 0. 1.5163 0. 1.5163 0. ]
[0. 1.5163 1.5163 0. 0. 1.5163 0.5054 1.0108]
[0. 0. 3.0325 0. 0. 0. 1.0108 2.0217]
[0. 0. 0. 6.065 0. 0. 0. 0. ]
[0. 0. 0. 2.0217 4.0433 0. 0. 0. ]
[0. 0. 0. 0.4043 3.2347 2.426 0. 0. ]
[0. 0. 0. 0. 1.213 3.639 1.213 0. ]
[0. 0. 0. 0. 0. 2.426 3.2347 0.4043]
[0. 0. 0. 0. 0. 0. 4.0433 2.0217]
[0. 0. 0. 0. 0. 0. 0. 6.065 ]]
Let us test if all D2 lines decay at the expected rate (6.065 MHz):
>>> Gamma = [sum([gamma[i][j] for j in range(i)])/2/pi
... for i in range(len(magnetic_states))][8:]
>>> for Gammai in Gamma: print("{:2.3f}".format(Gammai))
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
Let us do this symbolically
>>> from sympy import Matrix, pprint, symbols
>>> Gamma = symbols("Gamma", positive=True)
>>> einsteinA = Matrix([[0, -Gamma], [Gamma, 0]])
>>> gamma = calculate_gamma_matrix(magnetic_states, einsteinA=einsteinA,
... numeric=False)
>>> pprint(Matrix(gamma)[8:, :8])
⎡ Γ Γ Γ ⎤
⎢ ─ ─ ─ 0 0 0 0 0 ⎥
⎢ 3 3 3 ⎥
⎢ ⎥
⎢5⋅Γ 5⋅Γ Γ Γ Γ ⎥
⎢─── ─── 0 ── ── ── 0 0 ⎥
⎢ 12 12 10 20 60 ⎥
⎢ ⎥
⎢5⋅Γ 5⋅Γ Γ Γ Γ ⎥
⎢─── 0 ─── 0 ── ── ── 0 ⎥
⎢ 12 12 20 15 20 ⎥
⎢ ⎥
⎢ 5⋅Γ 5⋅Γ Γ Γ Γ ⎥
⎢ 0 ─── ─── 0 0 ── ── ──⎥
⎢ 12 12 60 20 10⎥
⎢ ⎥
⎢ Γ Γ Γ ⎥
⎢ ─ 0 0 ─ ─ 0 0 0 ⎥
⎢ 2 3 6 ⎥
⎢ ⎥
⎢ Γ Γ Γ Γ Γ ⎥
⎢ ─ ─ 0 ─ ── ─ 0 0 ⎥
⎢ 4 4 6 12 4 ⎥
⎢ ⎥
⎢Γ Γ Γ Γ Γ ⎥
⎢── ─ ── 0 ─ 0 ─ 0 ⎥
⎢12 3 12 4 4 ⎥
⎢ ⎥
⎢ Γ Γ Γ Γ Γ ⎥
⎢ 0 ─ ─ 0 0 ─ ── ─ ⎥
⎢ 4 4 4 12 6 ⎥
⎢ ⎥
⎢ Γ Γ Γ ⎥
⎢ 0 0 ─ 0 0 0 ─ ─ ⎥
⎢ 2 6 3 ⎥
⎢ ⎥
⎢ 0 0 0 Γ 0 0 0 0 ⎥
⎢ ⎥
⎢ Γ 2⋅Γ ⎥
⎢ 0 0 0 ─ ─── 0 0 0 ⎥
⎢ 3 3 ⎥
⎢ ⎥
⎢ Γ 8⋅Γ 2⋅Γ ⎥
⎢ 0 0 0 ── ─── ─── 0 0 ⎥
⎢ 15 15 5 ⎥
⎢ ⎥
⎢ Γ 3⋅Γ Γ ⎥
⎢ 0 0 0 0 ─ ─── ─ 0 ⎥
⎢ 5 5 5 ⎥
⎢ ⎥
⎢ 2⋅Γ 8⋅Γ Γ ⎥
⎢ 0 0 0 0 0 ─── ─── ──⎥
⎢ 5 15 15⎥
⎢ ⎥
⎢ 2⋅Γ Γ ⎥
⎢ 0 0 0 0 0 0 ─── ─ ⎥
⎢ 3 3 ⎥
⎢ ⎥
⎣ 0 0 0 0 0 0 0 Γ ⎦
>>> Gamma =Matrix([sum([gamma[i][j] for j in range(i)])
... for i in range(len(magnetic_states))][8:])
>>> pprint(Gamma)
⎡Γ⎤
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎣Γ⎦
"""
Ne = len(magnetic_states)
fine_states = []
fine_map = {}
ii = 0
for ei in magnetic_states:
fine = State(ei.element, ei.isotope, ei.n, ei.l, ei.j)
if fine not in fine_states:
fine_states += [fine]
ii += 1
fine_map.update({ei: ii-1})
II = magnetic_states[0].i
gamma = [[0.0 for j in range(Ne)] for i in range(Ne)]
for i in range(Ne):
for j in range(i):
ei = magnetic_states[i]
ej = magnetic_states[j]
if einsteinA is not None:
iii = fine_map[ei]
jjj = fine_map[ej]
einsteinAij = einsteinA[iii, jjj]
else:
einsteinAij = Transition(ei, ej).einsteinA
if einsteinAij != 0:
ji = ei.j; jj = ej.j
fi = ei.f; fj = ej.f
mi = ei.m; mj = ej.m
gammaij = (2*ji+1)
gammaij *= (2*fi+1)
gammaij *= (2*fj+1)
if numeric:
gammaij *= float(wigner_6j(ji, fi, II, fj, jj, 1)**2)
gammaij *= sum([float(wigner_3j(fj, 1, fi, -mj, q, mi)**2)
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gammaij = float(gammaij)
else:
gammaij *= wigner_6j(ji, fi, II, fj, jj, 1)**2
gammaij *= sum([wigner_3j(fj, 1, fi, -mj, q, mi)**2
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gamma[i][j] = gammaij
gamma[j][i] = -gammaij
return gamma | [
"def",
"calculate_gamma_matrix",
"(",
"magnetic_states",
",",
"Omega",
"=",
"1",
",",
"einsteinA",
"=",
"None",
",",
"numeric",
"=",
"True",
")",
":",
"Ne",
"=",
"len",
"(",
"magnetic_states",
")",
"fine_states",
"=",
"[",
"]",
"fine_map",
"=",
"{",
"}",... | ur"""Calculate the matrix of decay between states.
This function calculates the matrix :math:`\gamma_{ij}` of decay rates
between states :math:`|i\rangle` and :math:`|j\rangle` (in the units
specified by the Omega argument).
>>> import numpy as np
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> magnetic_states = make_list_of_states([g, e], "magnetic")
To return the rates in 10^6 rad /s:
>>> gamma = np.array(calculate_gamma_matrix(magnetic_states, Omega=1e6))
The :math:`5P_{3/2}, 5S_{1/2}` block of this matrix is
>>> print(gamma[8:, :8]/2/np.pi)
[[2.0217 2.0217 2.0217 0. 0. 0. 0. 0. ]
[2.5271 2.5271 0. 0.6065 0.3033 0.1011 0. 0. ]
[2.5271 0. 2.5271 0. 0.3033 0.4043 0.3033 0. ]
[0. 2.5271 2.5271 0. 0. 0.1011 0.3033 0.6065]
[3.0325 0. 0. 2.0217 1.0108 0. 0. 0. ]
[1.5163 1.5163 0. 1.0108 0.5054 1.5163 0. 0. ]
[0.5054 2.0217 0.5054 0. 1.5163 0. 1.5163 0. ]
[0. 1.5163 1.5163 0. 0. 1.5163 0.5054 1.0108]
[0. 0. 3.0325 0. 0. 0. 1.0108 2.0217]
[0. 0. 0. 6.065 0. 0. 0. 0. ]
[0. 0. 0. 2.0217 4.0433 0. 0. 0. ]
[0. 0. 0. 0.4043 3.2347 2.426 0. 0. ]
[0. 0. 0. 0. 1.213 3.639 1.213 0. ]
[0. 0. 0. 0. 0. 2.426 3.2347 0.4043]
[0. 0. 0. 0. 0. 0. 4.0433 2.0217]
[0. 0. 0. 0. 0. 0. 0. 6.065 ]]
Let us test if all D2 lines decay at the expected rate (6.065 MHz):
>>> Gamma = [sum([gamma[i][j] for j in range(i)])/2/pi
... for i in range(len(magnetic_states))][8:]
>>> for Gammai in Gamma: print("{:2.3f}".format(Gammai))
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
Let us do this symbolically
>>> from sympy import Matrix, pprint, symbols
>>> Gamma = symbols("Gamma", positive=True)
>>> einsteinA = Matrix([[0, -Gamma], [Gamma, 0]])
>>> gamma = calculate_gamma_matrix(magnetic_states, einsteinA=einsteinA,
... numeric=False)
>>> pprint(Matrix(gamma)[8:, :8])
⎡ Γ Γ Γ ⎤
⎢ ─ ─ ─ 0 0 0 0 0 ⎥
⎢ 3 3 3 ⎥
⎢ ⎥
⎢5⋅Γ 5⋅Γ Γ Γ Γ ⎥
⎢─── ─── 0 ── ── ── 0 0 ⎥
⎢ 12 12 10 20 60 ⎥
⎢ ⎥
⎢5⋅Γ 5⋅Γ Γ Γ Γ ⎥
⎢─── 0 ─── 0 ── ── ── 0 ⎥
⎢ 12 12 20 15 20 ⎥
⎢ ⎥
⎢ 5⋅Γ 5⋅Γ Γ Γ Γ ⎥
⎢ 0 ─── ─── 0 0 ── ── ──⎥
⎢ 12 12 60 20 10⎥
⎢ ⎥
⎢ Γ Γ Γ ⎥
⎢ ─ 0 0 ─ ─ 0 0 0 ⎥
⎢ 2 3 6 ⎥
⎢ ⎥
⎢ Γ Γ Γ Γ Γ ⎥
⎢ ─ ─ 0 ─ ── ─ 0 0 ⎥
⎢ 4 4 6 12 4 ⎥
⎢ ⎥
⎢Γ Γ Γ Γ Γ ⎥
⎢── ─ ── 0 ─ 0 ─ 0 ⎥
⎢12 3 12 4 4 ⎥
⎢ ⎥
⎢ Γ Γ Γ Γ Γ ⎥
⎢ 0 ─ ─ 0 0 ─ ── ─ ⎥
⎢ 4 4 4 12 6 ⎥
⎢ ⎥
⎢ Γ Γ Γ ⎥
⎢ 0 0 ─ 0 0 0 ─ ─ ⎥
⎢ 2 6 3 ⎥
⎢ ⎥
⎢ 0 0 0 Γ 0 0 0 0 ⎥
⎢ ⎥
⎢ Γ 2⋅Γ ⎥
⎢ 0 0 0 ─ ─── 0 0 0 ⎥
⎢ 3 3 ⎥
⎢ ⎥
⎢ Γ 8⋅Γ 2⋅Γ ⎥
⎢ 0 0 0 ── ─── ─── 0 0 ⎥
⎢ 15 15 5 ⎥
⎢ ⎥
⎢ Γ 3⋅Γ Γ ⎥
⎢ 0 0 0 0 ─ ─── ─ 0 ⎥
⎢ 5 5 5 ⎥
⎢ ⎥
⎢ 2⋅Γ 8⋅Γ Γ ⎥
⎢ 0 0 0 0 0 ─── ─── ──⎥
⎢ 5 15 15⎥
⎢ ⎥
⎢ 2⋅Γ Γ ⎥
⎢ 0 0 0 0 0 0 ─── ─ ⎥
⎢ 3 3 ⎥
⎢ ⎥
⎣ 0 0 0 0 0 0 0 Γ ⎦
>>> Gamma =Matrix([sum([gamma[i][j] for j in range(i)])
... for i in range(len(magnetic_states))][8:])
>>> pprint(Gamma)
⎡Γ⎤
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎢Γ⎥
⎢ ⎥
⎣Γ⎦ | [
"ur",
"Calculate",
"the",
"matrix",
"of",
"decay",
"between",
"states",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1489-L1709 | train | 50,373 |
oscarlazoarjona/fast | fast/atomic_structure.py | reduced_matrix_element | def reduced_matrix_element(fine_statei, fine_statej, convention=1):
r"""Return the reduced matrix element of the position operator in Bohr\
radii.
We have two available conventions for this
1.- [Racah]_ and [Edmonds74]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah}
2.- [Brink_Satchler]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \sqrt{2J_i+1} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
These two definitions of the reduced matrix element are related by
.. math::
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah} = \sqrt{2J_i+1} \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
With the Racah element being symetric under argument exchange apart from a\
sign:
.. math::
\langle \gamma_j, J_j|| (\hat{T}^k)^\dagger|| \gamma_i, J_i\rangle \
_\mathrm{Racah} = (-1)^{J_j-J_i}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Racah}
And the Brink element being asymetric under argument exchange:
.. math::
\langle \gamma_j, J_j|| \hat{T}^k|| \gamma_i, J_i\rangle \
_\mathrm{Brink} = (-1)^{J_j-J_i}\
\frac{\sqrt{2J_i +1}}{\sqrt{2J_j +1}}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
References:
.. [Brink_Satchler] Brink, D. M. and G. R. Satchler: 1994. "Angular\
Momentum". Oxford: Oxford University Press, 3rd edn., 182 pages.
.. [Racah] Racah, G.: 1942. "Theory of complex spectra II". Phys. Rev., \
62 438-462.
.. [Edmonds74] A. R. Edmonds. Angular momentum in quantum mechanics.
Investigations in physics, 4.; Investigations in physics, no. 4.
Princeton, N.J., Princeton University Press, 1957..
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> print(reduced_matrix_element(g, e))
5.97785756147
>>> print(reduced_matrix_element(e, g))
-5.97785756146761
>>> print(reduced_matrix_element(g, e, convention=2))
4.22698361868
>>> print(reduced_matrix_element(e, g, convention=2))
-2.11349180934051
"""
if fine_statei == fine_statej:
return 0.0
t = Transition(fine_statei, fine_statej)
einsteinAij = t.einsteinA
omega0 = t.omega
Ji = fine_statei.j; Jj = fine_statej.j
factor = sqrt(3*Pi*hbar*c**3*epsilon0)/e
if omega0 < 0:
rij = factor*sqrt((2*Jj+1)*einsteinAij/omega0**3)/a0
else:
rij = reduced_matrix_element(fine_statej, fine_statei,
convention=convention)
rij *= (-1)**(Jj-Ji)
# We return the Brink matrix element.
if convention == 2:
if omega0 < 0:
rij = rij / sqrt(2*Ji+1)
else:
rij = rij / sqrt(2*Ji+1)
return rij | python | def reduced_matrix_element(fine_statei, fine_statej, convention=1):
r"""Return the reduced matrix element of the position operator in Bohr\
radii.
We have two available conventions for this
1.- [Racah]_ and [Edmonds74]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah}
2.- [Brink_Satchler]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \sqrt{2J_i+1} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
These two definitions of the reduced matrix element are related by
.. math::
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah} = \sqrt{2J_i+1} \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
With the Racah element being symetric under argument exchange apart from a\
sign:
.. math::
\langle \gamma_j, J_j|| (\hat{T}^k)^\dagger|| \gamma_i, J_i\rangle \
_\mathrm{Racah} = (-1)^{J_j-J_i}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Racah}
And the Brink element being asymetric under argument exchange:
.. math::
\langle \gamma_j, J_j|| \hat{T}^k|| \gamma_i, J_i\rangle \
_\mathrm{Brink} = (-1)^{J_j-J_i}\
\frac{\sqrt{2J_i +1}}{\sqrt{2J_j +1}}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
References:
.. [Brink_Satchler] Brink, D. M. and G. R. Satchler: 1994. "Angular\
Momentum". Oxford: Oxford University Press, 3rd edn., 182 pages.
.. [Racah] Racah, G.: 1942. "Theory of complex spectra II". Phys. Rev., \
62 438-462.
.. [Edmonds74] A. R. Edmonds. Angular momentum in quantum mechanics.
Investigations in physics, 4.; Investigations in physics, no. 4.
Princeton, N.J., Princeton University Press, 1957..
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> print(reduced_matrix_element(g, e))
5.97785756147
>>> print(reduced_matrix_element(e, g))
-5.97785756146761
>>> print(reduced_matrix_element(g, e, convention=2))
4.22698361868
>>> print(reduced_matrix_element(e, g, convention=2))
-2.11349180934051
"""
if fine_statei == fine_statej:
return 0.0
t = Transition(fine_statei, fine_statej)
einsteinAij = t.einsteinA
omega0 = t.omega
Ji = fine_statei.j; Jj = fine_statej.j
factor = sqrt(3*Pi*hbar*c**3*epsilon0)/e
if omega0 < 0:
rij = factor*sqrt((2*Jj+1)*einsteinAij/omega0**3)/a0
else:
rij = reduced_matrix_element(fine_statej, fine_statei,
convention=convention)
rij *= (-1)**(Jj-Ji)
# We return the Brink matrix element.
if convention == 2:
if omega0 < 0:
rij = rij / sqrt(2*Ji+1)
else:
rij = rij / sqrt(2*Ji+1)
return rij | [
"def",
"reduced_matrix_element",
"(",
"fine_statei",
",",
"fine_statej",
",",
"convention",
"=",
"1",
")",
":",
"if",
"fine_statei",
"==",
"fine_statej",
":",
"return",
"0.0",
"t",
"=",
"Transition",
"(",
"fine_statei",
",",
"fine_statej",
")",
"einsteinAij",
... | r"""Return the reduced matrix element of the position operator in Bohr\
radii.
We have two available conventions for this
1.- [Racah]_ and [Edmonds74]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah}
2.- [Brink_Satchler]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \sqrt{2J_i+1} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
These two definitions of the reduced matrix element are related by
.. math::
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah} = \sqrt{2J_i+1} \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
With the Racah element being symetric under argument exchange apart from a\
sign:
.. math::
\langle \gamma_j, J_j|| (\hat{T}^k)^\dagger|| \gamma_i, J_i\rangle \
_\mathrm{Racah} = (-1)^{J_j-J_i}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Racah}
And the Brink element being asymetric under argument exchange:
.. math::
\langle \gamma_j, J_j|| \hat{T}^k|| \gamma_i, J_i\rangle \
_\mathrm{Brink} = (-1)^{J_j-J_i}\
\frac{\sqrt{2J_i +1}}{\sqrt{2J_j +1}}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
References:
.. [Brink_Satchler] Brink, D. M. and G. R. Satchler: 1994. "Angular\
Momentum". Oxford: Oxford University Press, 3rd edn., 182 pages.
.. [Racah] Racah, G.: 1942. "Theory of complex spectra II". Phys. Rev., \
62 438-462.
.. [Edmonds74] A. R. Edmonds. Angular momentum in quantum mechanics.
Investigations in physics, 4.; Investigations in physics, no. 4.
Princeton, N.J., Princeton University Press, 1957..
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> print(reduced_matrix_element(g, e))
5.97785756147
>>> print(reduced_matrix_element(e, g))
-5.97785756146761
>>> print(reduced_matrix_element(g, e, convention=2))
4.22698361868
>>> print(reduced_matrix_element(e, g, convention=2))
-2.11349180934051 | [
"r",
"Return",
"the",
"reduced",
"matrix",
"element",
"of",
"the",
"position",
"operator",
"in",
"Bohr",
"\\",
"radii",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1712-L1810 | train | 50,374 |
oscarlazoarjona/fast | fast/atomic_structure.py | calculate_reduced_matrix_elements | def calculate_reduced_matrix_elements(fine_states, convention=1):
r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduced matrix elements found in [SteckRb87]_ for the \
D1 and D2 lines in rubidium.
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e1 = State("Rb", 87, 5, 1, 1/Integer(2))
>>> e2 = State("Rb", 87,5 , 1, 3/Integer(2))
>>> red = calculate_reduced_matrix_elements([g, e1, e2], convention=2)
>>> print(red[0][1])
2.99207750426
>>> print(red[0][2])
4.22698361868
"""
reduced_matrix_elements = [[reduced_matrix_element(ei, ej,
convention=convention)
for ej in fine_states]
for ei in fine_states]
return reduced_matrix_elements | python | def calculate_reduced_matrix_elements(fine_states, convention=1):
r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduced matrix elements found in [SteckRb87]_ for the \
D1 and D2 lines in rubidium.
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e1 = State("Rb", 87, 5, 1, 1/Integer(2))
>>> e2 = State("Rb", 87,5 , 1, 3/Integer(2))
>>> red = calculate_reduced_matrix_elements([g, e1, e2], convention=2)
>>> print(red[0][1])
2.99207750426
>>> print(red[0][2])
4.22698361868
"""
reduced_matrix_elements = [[reduced_matrix_element(ei, ej,
convention=convention)
for ej in fine_states]
for ei in fine_states]
return reduced_matrix_elements | [
"def",
"calculate_reduced_matrix_elements",
"(",
"fine_states",
",",
"convention",
"=",
"1",
")",
":",
"reduced_matrix_elements",
"=",
"[",
"[",
"reduced_matrix_element",
"(",
"ei",
",",
"ej",
",",
"convention",
"=",
"convention",
")",
"for",
"ej",
"in",
"fine_s... | r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduced matrix elements found in [SteckRb87]_ for the \
D1 and D2 lines in rubidium.
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e1 = State("Rb", 87, 5, 1, 1/Integer(2))
>>> e2 = State("Rb", 87,5 , 1, 3/Integer(2))
>>> red = calculate_reduced_matrix_elements([g, e1, e2], convention=2)
>>> print(red[0][1])
2.99207750426
>>> print(red[0][2])
4.22698361868 | [
"r",
"Calculate",
"the",
"reduced",
"matrix",
"elements",
"for",
"a",
"list",
"of",
"fine",
"states",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1813-L1841 | train | 50,375 |
oscarlazoarjona/fast | fast/atomic_structure.py | calculate_matrices | def calculate_matrices(states, Omega=1):
r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail.
"""
# We check that all states belong to the same element and the same isotope.
iso = states[0].isotope
element = states[0].element
for state in states[1:]:
if state.element != element:
raise ValueError('All states must belong to the same element.')
if state.isotope != iso:
raise ValueError('All states must belong to the same isotope.')
# We find the fine states involved in the problem.
fine_states = find_fine_states(states)
# We find the full magnetic states. The matrices will be first calculated
# for the complete problem and later reduced to include only the states of
# interest.
full_magnetic_states = make_list_of_states(fine_states, 'magnetic',
verbose=0)
# We calculate the indices corresponding to each sub matrix of fine and
# hyperfine levels.
# We calculate the frequency differences between states.
omega_full = calculate_omega_matrix(full_magnetic_states, Omega)
# We calculate the matrix gamma.
gamma_full = calculate_gamma_matrix(full_magnetic_states, Omega)
# We calculate the reduced matrix elements
reduced_matrix_elements = calculate_reduced_matrix_elements(fine_states)
# We calculate the matrices r_-1, r_0, r_1
r_full = calculate_r_matrices(fine_states, reduced_matrix_elements)
# Reduction to be implemented
omega = omega_full
r = r_full
gamma = gamma_full
return omega, gamma, r | python | def calculate_matrices(states, Omega=1):
r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail.
"""
# We check that all states belong to the same element and the same isotope.
iso = states[0].isotope
element = states[0].element
for state in states[1:]:
if state.element != element:
raise ValueError('All states must belong to the same element.')
if state.isotope != iso:
raise ValueError('All states must belong to the same isotope.')
# We find the fine states involved in the problem.
fine_states = find_fine_states(states)
# We find the full magnetic states. The matrices will be first calculated
# for the complete problem and later reduced to include only the states of
# interest.
full_magnetic_states = make_list_of_states(fine_states, 'magnetic',
verbose=0)
# We calculate the indices corresponding to each sub matrix of fine and
# hyperfine levels.
# We calculate the frequency differences between states.
omega_full = calculate_omega_matrix(full_magnetic_states, Omega)
# We calculate the matrix gamma.
gamma_full = calculate_gamma_matrix(full_magnetic_states, Omega)
# We calculate the reduced matrix elements
reduced_matrix_elements = calculate_reduced_matrix_elements(fine_states)
# We calculate the matrices r_-1, r_0, r_1
r_full = calculate_r_matrices(fine_states, reduced_matrix_elements)
# Reduction to be implemented
omega = omega_full
r = r_full
gamma = gamma_full
return omega, gamma, r | [
"def",
"calculate_matrices",
"(",
"states",
",",
"Omega",
"=",
"1",
")",
":",
"# We check that all states belong to the same element and the same isotope.",
"iso",
"=",
"states",
"[",
"0",
"]",
".",
"isotope",
"element",
"=",
"states",
"[",
"0",
"]",
".",
"element... | r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail. | [
"r",
"Calculate",
"the",
"matrices",
"omega_ij",
"gamma_ij",
"r_pij",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L2130-L2173 | train | 50,376 |
oscarlazoarjona/fast | fast/atomic_structure.py | thermal_state | def thermal_state(omega_level, T, return_diagonal=False):
r"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations.
>>> ground = State("Rb", 85, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([ground], "magnetic")
>>> omega_level = [ei.omega for ei in magnetic_states]
>>> T = 273.15 + 20
>>> print(thermal_state(omega_level, T, return_diagonal=True))
[0.0834 0.0834 0.0834 0.0834 0.0834 0.0833 0.0833 0.0833 0.0833 0.0833
0.0833 0.0833]
"""
Ne = len(omega_level)
E = np.array([hbar*omega_level[i] for i in range(Ne)])
p = np.exp(-E/k_B/T)
p = p/sum(p)
if not return_diagonal:
return np.diag(p)
return p | python | def thermal_state(omega_level, T, return_diagonal=False):
r"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations.
>>> ground = State("Rb", 85, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([ground], "magnetic")
>>> omega_level = [ei.omega for ei in magnetic_states]
>>> T = 273.15 + 20
>>> print(thermal_state(omega_level, T, return_diagonal=True))
[0.0834 0.0834 0.0834 0.0834 0.0834 0.0833 0.0833 0.0833 0.0833 0.0833
0.0833 0.0833]
"""
Ne = len(omega_level)
E = np.array([hbar*omega_level[i] for i in range(Ne)])
p = np.exp(-E/k_B/T)
p = p/sum(p)
if not return_diagonal:
return np.diag(p)
return p | [
"def",
"thermal_state",
"(",
"omega_level",
",",
"T",
",",
"return_diagonal",
"=",
"False",
")",
":",
"Ne",
"=",
"len",
"(",
"omega_level",
")",
"E",
"=",
"np",
".",
"array",
"(",
"[",
"hbar",
"*",
"omega_level",
"[",
"i",
"]",
"for",
"i",
"in",
"r... | r"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations.
>>> ground = State("Rb", 85, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([ground], "magnetic")
>>> omega_level = [ei.omega for ei in magnetic_states]
>>> T = 273.15 + 20
>>> print(thermal_state(omega_level, T, return_diagonal=True))
[0.0834 0.0834 0.0834 0.0834 0.0834 0.0833 0.0833 0.0833 0.0833 0.0833
0.0833 0.0833] | [
"r",
"Return",
"a",
"thermal",
"state",
"for",
"a",
"given",
"set",
"of",
"levels",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L2660-L2685 | train | 50,377 |
oscarlazoarjona/fast | fast/atomic_structure.py | Atom.transitions | def transitions(self, omega_min=None, omega_max=None):
r"""Find all allowed transitions.
This function finds all allowed transitions (by electric-dipole
selection rules) in the atom.
>>> atom=Atom("Rb",85)
>>> transitions=atom.transitions()
>>> print(len(transitions))
270
Arguments omega_min and omega_max can be used to make filter out the
results.
>>> from scipy.constants import c
>>> wavelength_min=770e-9
>>> wavelength_max=790e-9
>>> omega_min=2*pi*c/wavelength_max
>>> omega_max=2*pi*c/wavelength_min
>>> easy_transitions=atom.transitions(omega_min=omega_min,
... omega_max=omega_max)
>>> for ti in easy_transitions:
... print("{} {}".format(abs(ti.wavelength)*1e9, ti))
780.241476935 85Rb 5S_1/2 -----> 85Rb 5P_3/2
776.157015322 85Rb 5P_3/2 -----> 85Rb 5D_3/2
775.978619616 85Rb 5P_3/2 -----> 85Rb 5D_5/2
"""
states = self.states()
transitions = states
transitions = []
for i in range(len(states)):
si = states[i]
for j in range(i):
sj = states[j]
t = Transition(sj, si)
if t.allowed:
transitions += [t]
if omega_min is not None:
transitions = [ti for ti in transitions
if abs(ti.omega) >= omega_min]
if omega_max is not None:
transitions = [ti for ti in transitions
if abs(ti.omega) <= omega_max]
return transitions | python | def transitions(self, omega_min=None, omega_max=None):
r"""Find all allowed transitions.
This function finds all allowed transitions (by electric-dipole
selection rules) in the atom.
>>> atom=Atom("Rb",85)
>>> transitions=atom.transitions()
>>> print(len(transitions))
270
Arguments omega_min and omega_max can be used to make filter out the
results.
>>> from scipy.constants import c
>>> wavelength_min=770e-9
>>> wavelength_max=790e-9
>>> omega_min=2*pi*c/wavelength_max
>>> omega_max=2*pi*c/wavelength_min
>>> easy_transitions=atom.transitions(omega_min=omega_min,
... omega_max=omega_max)
>>> for ti in easy_transitions:
... print("{} {}".format(abs(ti.wavelength)*1e9, ti))
780.241476935 85Rb 5S_1/2 -----> 85Rb 5P_3/2
776.157015322 85Rb 5P_3/2 -----> 85Rb 5D_3/2
775.978619616 85Rb 5P_3/2 -----> 85Rb 5D_5/2
"""
states = self.states()
transitions = states
transitions = []
for i in range(len(states)):
si = states[i]
for j in range(i):
sj = states[j]
t = Transition(sj, si)
if t.allowed:
transitions += [t]
if omega_min is not None:
transitions = [ti for ti in transitions
if abs(ti.omega) >= omega_min]
if omega_max is not None:
transitions = [ti for ti in transitions
if abs(ti.omega) <= omega_max]
return transitions | [
"def",
"transitions",
"(",
"self",
",",
"omega_min",
"=",
"None",
",",
"omega_max",
"=",
"None",
")",
":",
"states",
"=",
"self",
".",
"states",
"(",
")",
"transitions",
"=",
"states",
"transitions",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"le... | r"""Find all allowed transitions.
This function finds all allowed transitions (by electric-dipole
selection rules) in the atom.
>>> atom=Atom("Rb",85)
>>> transitions=atom.transitions()
>>> print(len(transitions))
270
Arguments omega_min and omega_max can be used to make filter out the
results.
>>> from scipy.constants import c
>>> wavelength_min=770e-9
>>> wavelength_max=790e-9
>>> omega_min=2*pi*c/wavelength_max
>>> omega_max=2*pi*c/wavelength_min
>>> easy_transitions=atom.transitions(omega_min=omega_min,
... omega_max=omega_max)
>>> for ti in easy_transitions:
... print("{} {}".format(abs(ti.wavelength)*1e9, ti))
780.241476935 85Rb 5S_1/2 -----> 85Rb 5P_3/2
776.157015322 85Rb 5P_3/2 -----> 85Rb 5D_3/2
775.978619616 85Rb 5P_3/2 -----> 85Rb 5D_5/2 | [
"r",
"Find",
"all",
"allowed",
"transitions",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L348-L395 | train | 50,378 |
oscarlazoarjona/fast | fast/inhomo.py | Inhomogeneity.average | def average(self, rho):
r"""Return the average density matrix of an inhomogeneous ensemble."""
def marginal(f, rho):
remaining = len(f.shape)
if remaining == 0:
return rho
rho = sum([f[i]*rho[i] for i in range(rho.shape[0])])
f = np.sum(f, 0)
return marginal(f, rho)
return marginal(self.distribution, rho) | python | def average(self, rho):
r"""Return the average density matrix of an inhomogeneous ensemble."""
def marginal(f, rho):
remaining = len(f.shape)
if remaining == 0:
return rho
rho = sum([f[i]*rho[i] for i in range(rho.shape[0])])
f = np.sum(f, 0)
return marginal(f, rho)
return marginal(self.distribution, rho) | [
"def",
"average",
"(",
"self",
",",
"rho",
")",
":",
"def",
"marginal",
"(",
"f",
",",
"rho",
")",
":",
"remaining",
"=",
"len",
"(",
"f",
".",
"shape",
")",
"if",
"remaining",
"==",
"0",
":",
"return",
"rho",
"rho",
"=",
"sum",
"(",
"[",
"f",
... | r"""Return the average density matrix of an inhomogeneous ensemble. | [
"r",
"Return",
"the",
"average",
"density",
"matrix",
"of",
"an",
"inhomogeneous",
"ensemble",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/inhomo.py#L104-L114 | train | 50,379 |
oscarlazoarjona/fast | fast/inhomo.py | DopplerBroadening.reset | def reset(self, T):
r"""Recalculate the doppler broadening for a given temperature."""
self.__init__(self.shape, self.stds, T,
self.mass, self.detuning_knob, self.k,
self.omega_level, self.xi, self.theta, self.unfolding,
self.axes,
self.matrix_form) | python | def reset(self, T):
r"""Recalculate the doppler broadening for a given temperature."""
self.__init__(self.shape, self.stds, T,
self.mass, self.detuning_knob, self.k,
self.omega_level, self.xi, self.theta, self.unfolding,
self.axes,
self.matrix_form) | [
"def",
"reset",
"(",
"self",
",",
"T",
")",
":",
"self",
".",
"__init__",
"(",
"self",
".",
"shape",
",",
"self",
".",
"stds",
",",
"T",
",",
"self",
".",
"mass",
",",
"self",
".",
"detuning_knob",
",",
"self",
".",
"k",
",",
"self",
".",
"omeg... | r"""Recalculate the doppler broadening for a given temperature. | [
"r",
"Recalculate",
"the",
"doppler",
"broadening",
"for",
"a",
"given",
"temperature",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/inhomo.py#L232-L238 | train | 50,380 |
oscarlazoarjona/fast | fast/angular_momentum.py | perm_j | def perm_j(j1, j2):
r"""Calculate the allowed total angular momenta.
>>> from sympy import Integer
>>> L = 1
>>> S = 1/Integer(2)
>>> perm_j(L, S)
[1/2, 3/2]
"""
jmin = abs(j1-j2)
jmax = j1+j2
return [jmin + i for i in range(jmax-jmin+1)] | python | def perm_j(j1, j2):
r"""Calculate the allowed total angular momenta.
>>> from sympy import Integer
>>> L = 1
>>> S = 1/Integer(2)
>>> perm_j(L, S)
[1/2, 3/2]
"""
jmin = abs(j1-j2)
jmax = j1+j2
return [jmin + i for i in range(jmax-jmin+1)] | [
"def",
"perm_j",
"(",
"j1",
",",
"j2",
")",
":",
"jmin",
"=",
"abs",
"(",
"j1",
"-",
"j2",
")",
"jmax",
"=",
"j1",
"+",
"j2",
"return",
"[",
"jmin",
"+",
"i",
"for",
"i",
"in",
"range",
"(",
"jmax",
"-",
"jmin",
"+",
"1",
")",
"]"
] | r"""Calculate the allowed total angular momenta.
>>> from sympy import Integer
>>> L = 1
>>> S = 1/Integer(2)
>>> perm_j(L, S)
[1/2, 3/2] | [
"r",
"Calculate",
"the",
"allowed",
"total",
"angular",
"momenta",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L31-L43 | train | 50,381 |
oscarlazoarjona/fast | fast/angular_momentum.py | wigner_d_small | def wigner_d_small(J, beta):
u"""Return the small Wigner d matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.15.
Some examples form [Edmonds74]_:
>>> from sympy import Integer, symbols, pi
>>> half = 1/Integer(2)
>>> beta = symbols("beta", real=True)
>>> wigner_d_small(half, beta)
Matrix([
[ cos(beta/2), sin(beta/2)],
[-sin(beta/2), cos(beta/2)]])
>>> from sympy import pprint
>>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
⎡ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎤
⎢ cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟ sin ⎜─⎟ ⎥
⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎥
⎢ ⎥
⎢ ⎛β⎞ ⎛β⎞ 2⎛β⎞ 2⎛β⎞ ⎛β⎞ ⎛β⎞⎥
⎢-√2⋅sin⎜─⎟⋅cos⎜─⎟ - sin ⎜─⎟ + cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟⎥
⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠⎥
⎢ ⎥
⎢ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎥
⎢ sin ⎜─⎟ -√2⋅sin⎜─⎟⋅cos⎜─⎟ cos ⎜─⎟ ⎥
⎣ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎦
From table 4 in [Edmonds74]_
>>> wigner_d_small(half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/2, sqrt(2)/2],
[-sqrt(2)/2, sqrt(2)/2]])
>>> wigner_d_small(2*half, beta).subs({beta:pi/2})
Matrix([
[ 1/2, sqrt(2)/2, 1/2],
[-sqrt(2)/2, 0, sqrt(2)/2],
[ 1/2, -sqrt(2)/2, 1/2]])
>>> wigner_d_small(3*half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/4, sqrt(6)/4, sqrt(6)/4, sqrt(2)/4],
[-sqrt(6)/4, -sqrt(2)/4, sqrt(2)/4, sqrt(6)/4],
[ sqrt(6)/4, -sqrt(2)/4, -sqrt(2)/4, sqrt(6)/4],
[-sqrt(2)/4, sqrt(6)/4, -sqrt(6)/4, sqrt(2)/4]])
>>> wigner_d_small(4*half, beta).subs({beta:pi/2})
Matrix([
[ 1/4, 1/2, sqrt(6)/4, 1/2, 1/4],
[ -1/2, -1/2, 0, 1/2, 1/2],
[sqrt(6)/4, 0, -1/2, 0, sqrt(6)/4],
[ -1/2, 1/2, 0, -1/2, 1/2],
[ 1/4, -1/2, sqrt(6)/4, -1/2, 1/4]])
"""
def prod(x):
p = 1
for i, xi in enumerate(x): p = p*xi
return p
M = [J-i for i in range(2*J+1)]
d = []
for Mi in M:
row = []
for Mj in M:
# We get the maximum and minimum value of sigma.
sigmamax = max([-Mi-Mj, J-Mj])
sigmamin = min([0, J-Mi])
dij = sqrt(factorial(J+Mi)*factorial(J-Mi) /
factorial(J+Mj)/factorial(J-Mj))
terms = [[(-1)**(J-Mi-s),
binomial(J+Mj, J-Mi-s),
binomial(J-Mj, s),
cos(beta/2)**(2*s+Mi+Mj),
sin(beta/2)**(2*J-2*s-Mj-Mi)]
for s in range(sigmamin, sigmamax+1)]
terms = [prod(term) if 0 not in term else 0 for term in terms]
dij = dij*sum(terms)
row += [dij]
d += [row]
return Matrix(d) | python | def wigner_d_small(J, beta):
u"""Return the small Wigner d matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.15.
Some examples form [Edmonds74]_:
>>> from sympy import Integer, symbols, pi
>>> half = 1/Integer(2)
>>> beta = symbols("beta", real=True)
>>> wigner_d_small(half, beta)
Matrix([
[ cos(beta/2), sin(beta/2)],
[-sin(beta/2), cos(beta/2)]])
>>> from sympy import pprint
>>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
⎡ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎤
⎢ cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟ sin ⎜─⎟ ⎥
⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎥
⎢ ⎥
⎢ ⎛β⎞ ⎛β⎞ 2⎛β⎞ 2⎛β⎞ ⎛β⎞ ⎛β⎞⎥
⎢-√2⋅sin⎜─⎟⋅cos⎜─⎟ - sin ⎜─⎟ + cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟⎥
⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠⎥
⎢ ⎥
⎢ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎥
⎢ sin ⎜─⎟ -√2⋅sin⎜─⎟⋅cos⎜─⎟ cos ⎜─⎟ ⎥
⎣ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎦
From table 4 in [Edmonds74]_
>>> wigner_d_small(half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/2, sqrt(2)/2],
[-sqrt(2)/2, sqrt(2)/2]])
>>> wigner_d_small(2*half, beta).subs({beta:pi/2})
Matrix([
[ 1/2, sqrt(2)/2, 1/2],
[-sqrt(2)/2, 0, sqrt(2)/2],
[ 1/2, -sqrt(2)/2, 1/2]])
>>> wigner_d_small(3*half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/4, sqrt(6)/4, sqrt(6)/4, sqrt(2)/4],
[-sqrt(6)/4, -sqrt(2)/4, sqrt(2)/4, sqrt(6)/4],
[ sqrt(6)/4, -sqrt(2)/4, -sqrt(2)/4, sqrt(6)/4],
[-sqrt(2)/4, sqrt(6)/4, -sqrt(6)/4, sqrt(2)/4]])
>>> wigner_d_small(4*half, beta).subs({beta:pi/2})
Matrix([
[ 1/4, 1/2, sqrt(6)/4, 1/2, 1/4],
[ -1/2, -1/2, 0, 1/2, 1/2],
[sqrt(6)/4, 0, -1/2, 0, sqrt(6)/4],
[ -1/2, 1/2, 0, -1/2, 1/2],
[ 1/4, -1/2, sqrt(6)/4, -1/2, 1/4]])
"""
def prod(x):
p = 1
for i, xi in enumerate(x): p = p*xi
return p
M = [J-i for i in range(2*J+1)]
d = []
for Mi in M:
row = []
for Mj in M:
# We get the maximum and minimum value of sigma.
sigmamax = max([-Mi-Mj, J-Mj])
sigmamin = min([0, J-Mi])
dij = sqrt(factorial(J+Mi)*factorial(J-Mi) /
factorial(J+Mj)/factorial(J-Mj))
terms = [[(-1)**(J-Mi-s),
binomial(J+Mj, J-Mi-s),
binomial(J-Mj, s),
cos(beta/2)**(2*s+Mi+Mj),
sin(beta/2)**(2*J-2*s-Mj-Mi)]
for s in range(sigmamin, sigmamax+1)]
terms = [prod(term) if 0 not in term else 0 for term in terms]
dij = dij*sum(terms)
row += [dij]
d += [row]
return Matrix(d) | [
"def",
"wigner_d_small",
"(",
"J",
",",
"beta",
")",
":",
"def",
"prod",
"(",
"x",
")",
":",
"p",
"=",
"1",
"for",
"i",
",",
"xi",
"in",
"enumerate",
"(",
"x",
")",
":",
"p",
"=",
"p",
"*",
"xi",
"return",
"p",
"M",
"=",
"[",
"J",
"-",
"i... | u"""Return the small Wigner d matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.15.
Some examples form [Edmonds74]_:
>>> from sympy import Integer, symbols, pi
>>> half = 1/Integer(2)
>>> beta = symbols("beta", real=True)
>>> wigner_d_small(half, beta)
Matrix([
[ cos(beta/2), sin(beta/2)],
[-sin(beta/2), cos(beta/2)]])
>>> from sympy import pprint
>>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
⎡ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎤
⎢ cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟ sin ⎜─⎟ ⎥
⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎥
⎢ ⎥
⎢ ⎛β⎞ ⎛β⎞ 2⎛β⎞ 2⎛β⎞ ⎛β⎞ ⎛β⎞⎥
⎢-√2⋅sin⎜─⎟⋅cos⎜─⎟ - sin ⎜─⎟ + cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟⎥
⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠⎥
⎢ ⎥
⎢ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎥
⎢ sin ⎜─⎟ -√2⋅sin⎜─⎟⋅cos⎜─⎟ cos ⎜─⎟ ⎥
⎣ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎦
From table 4 in [Edmonds74]_
>>> wigner_d_small(half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/2, sqrt(2)/2],
[-sqrt(2)/2, sqrt(2)/2]])
>>> wigner_d_small(2*half, beta).subs({beta:pi/2})
Matrix([
[ 1/2, sqrt(2)/2, 1/2],
[-sqrt(2)/2, 0, sqrt(2)/2],
[ 1/2, -sqrt(2)/2, 1/2]])
>>> wigner_d_small(3*half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/4, sqrt(6)/4, sqrt(6)/4, sqrt(2)/4],
[-sqrt(6)/4, -sqrt(2)/4, sqrt(2)/4, sqrt(6)/4],
[ sqrt(6)/4, -sqrt(2)/4, -sqrt(2)/4, sqrt(6)/4],
[-sqrt(2)/4, sqrt(6)/4, -sqrt(6)/4, sqrt(2)/4]])
>>> wigner_d_small(4*half, beta).subs({beta:pi/2})
Matrix([
[ 1/4, 1/2, sqrt(6)/4, 1/2, 1/4],
[ -1/2, -1/2, 0, 1/2, 1/2],
[sqrt(6)/4, 0, -1/2, 0, sqrt(6)/4],
[ -1/2, 1/2, 0, -1/2, 1/2],
[ 1/4, -1/2, sqrt(6)/4, -1/2, 1/4]]) | [
"u",
"Return",
"the",
"small",
"Wigner",
"d",
"matrix",
"for",
"angular",
"momentum",
"J",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L419-L507 | train | 50,382 |
oscarlazoarjona/fast | fast/angular_momentum.py | wigner_d | def wigner_d(J, alpha, beta, gamma):
u"""Return the Wigner D matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.12.
The simplest possible example:
>>> from sympy import Integer, symbols, pprint
>>> half = 1/Integer(2)
>>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
>>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
⎡ ⅈ⋅α ⅈ⋅γ ⅈ⋅α -ⅈ⋅γ ⎤
⎢ ─── ─── ─── ───── ⎥
⎢ 2 2 ⎛β⎞ 2 2 ⎛β⎞ ⎥
⎢ ℯ ⋅ℯ ⋅cos⎜─⎟ ℯ ⋅ℯ ⋅sin⎜─⎟ ⎥
⎢ ⎝2⎠ ⎝2⎠ ⎥
⎢ ⎥
⎢ -ⅈ⋅α ⅈ⋅γ -ⅈ⋅α -ⅈ⋅γ ⎥
⎢ ───── ─── ───── ───── ⎥
⎢ 2 2 ⎛β⎞ 2 2 ⎛β⎞⎥
⎢-ℯ ⋅ℯ ⋅sin⎜─⎟ ℯ ⋅ℯ ⋅cos⎜─⎟⎥
⎣ ⎝2⎠ ⎝2⎠⎦
"""
d = wigner_d_small(J, beta)
M = [J-i for i in range(2*J+1)]
D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma)
for j, Mj in enumerate(M)] for i, Mi in enumerate(M)]
return Matrix(D) | python | def wigner_d(J, alpha, beta, gamma):
u"""Return the Wigner D matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.12.
The simplest possible example:
>>> from sympy import Integer, symbols, pprint
>>> half = 1/Integer(2)
>>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
>>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
⎡ ⅈ⋅α ⅈ⋅γ ⅈ⋅α -ⅈ⋅γ ⎤
⎢ ─── ─── ─── ───── ⎥
⎢ 2 2 ⎛β⎞ 2 2 ⎛β⎞ ⎥
⎢ ℯ ⋅ℯ ⋅cos⎜─⎟ ℯ ⋅ℯ ⋅sin⎜─⎟ ⎥
⎢ ⎝2⎠ ⎝2⎠ ⎥
⎢ ⎥
⎢ -ⅈ⋅α ⅈ⋅γ -ⅈ⋅α -ⅈ⋅γ ⎥
⎢ ───── ─── ───── ───── ⎥
⎢ 2 2 ⎛β⎞ 2 2 ⎛β⎞⎥
⎢-ℯ ⋅ℯ ⋅sin⎜─⎟ ℯ ⋅ℯ ⋅cos⎜─⎟⎥
⎣ ⎝2⎠ ⎝2⎠⎦
"""
d = wigner_d_small(J, beta)
M = [J-i for i in range(2*J+1)]
D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma)
for j, Mj in enumerate(M)] for i, Mi in enumerate(M)]
return Matrix(D) | [
"def",
"wigner_d",
"(",
"J",
",",
"alpha",
",",
"beta",
",",
"gamma",
")",
":",
"d",
"=",
"wigner_d_small",
"(",
"J",
",",
"beta",
")",
"M",
"=",
"[",
"J",
"-",
"i",
"for",
"i",
"in",
"range",
"(",
"2",
"*",
"J",
"+",
"1",
")",
"]",
"D",
... | u"""Return the Wigner D matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.12.
The simplest possible example:
>>> from sympy import Integer, symbols, pprint
>>> half = 1/Integer(2)
>>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
>>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
⎡ ⅈ⋅α ⅈ⋅γ ⅈ⋅α -ⅈ⋅γ ⎤
⎢ ─── ─── ─── ───── ⎥
⎢ 2 2 ⎛β⎞ 2 2 ⎛β⎞ ⎥
⎢ ℯ ⋅ℯ ⋅cos⎜─⎟ ℯ ⋅ℯ ⋅sin⎜─⎟ ⎥
⎢ ⎝2⎠ ⎝2⎠ ⎥
⎢ ⎥
⎢ -ⅈ⋅α ⅈ⋅γ -ⅈ⋅α -ⅈ⋅γ ⎥
⎢ ───── ─── ───── ───── ⎥
⎢ 2 2 ⎛β⎞ 2 2 ⎛β⎞⎥
⎢-ℯ ⋅ℯ ⋅sin⎜─⎟ ℯ ⋅ℯ ⋅cos⎜─⎟⎥
⎣ ⎝2⎠ ⎝2⎠⎦ | [
"u",
"Return",
"the",
"Wigner",
"D",
"matrix",
"for",
"angular",
"momentum",
"J",
"."
] | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L510-L538 | train | 50,383 |
oscarlazoarjona/fast | fast/angular_momentum.py | density_matrix_rotation | def density_matrix_rotation(J_values, alpha, beta, gamma):
r"""Return a block-wise diagonal Wigner D matrix for that rotates
a density matrix of an ensemble of particles in definite total
angular momentum states given by J_values.
>>> from sympy import Integer, pi
>>> half = 1/Integer(2)
>>> J_values = [2*half, 0]
>>> density_matrix_rotation(J_values, 0, pi/2, 0)
Matrix([
[ 1/2, sqrt(2)/2, 1/2, 0],
[-sqrt(2)/2, 0, sqrt(2)/2, 0],
[ 1/2, -sqrt(2)/2, 1/2, 0],
[ 0, 0, 0, 1]])
"""
size = sum([2*J+1 for J in J_values])
D = zeros(size, size)
ind0 = 0
for J in J_values:
DJ = wigner_d(J, alpha, beta, gamma)
sizeJ = 2*J+1
indf = ind0 + sizeJ
D[ind0: indf, ind0: indf] = DJ
ind0 += sizeJ
return D | python | def density_matrix_rotation(J_values, alpha, beta, gamma):
r"""Return a block-wise diagonal Wigner D matrix for that rotates
a density matrix of an ensemble of particles in definite total
angular momentum states given by J_values.
>>> from sympy import Integer, pi
>>> half = 1/Integer(2)
>>> J_values = [2*half, 0]
>>> density_matrix_rotation(J_values, 0, pi/2, 0)
Matrix([
[ 1/2, sqrt(2)/2, 1/2, 0],
[-sqrt(2)/2, 0, sqrt(2)/2, 0],
[ 1/2, -sqrt(2)/2, 1/2, 0],
[ 0, 0, 0, 1]])
"""
size = sum([2*J+1 for J in J_values])
D = zeros(size, size)
ind0 = 0
for J in J_values:
DJ = wigner_d(J, alpha, beta, gamma)
sizeJ = 2*J+1
indf = ind0 + sizeJ
D[ind0: indf, ind0: indf] = DJ
ind0 += sizeJ
return D | [
"def",
"density_matrix_rotation",
"(",
"J_values",
",",
"alpha",
",",
"beta",
",",
"gamma",
")",
":",
"size",
"=",
"sum",
"(",
"[",
"2",
"*",
"J",
"+",
"1",
"for",
"J",
"in",
"J_values",
"]",
")",
"D",
"=",
"zeros",
"(",
"size",
",",
"size",
")",... | r"""Return a block-wise diagonal Wigner D matrix for that rotates
a density matrix of an ensemble of particles in definite total
angular momentum states given by J_values.
>>> from sympy import Integer, pi
>>> half = 1/Integer(2)
>>> J_values = [2*half, 0]
>>> density_matrix_rotation(J_values, 0, pi/2, 0)
Matrix([
[ 1/2, sqrt(2)/2, 1/2, 0],
[-sqrt(2)/2, 0, sqrt(2)/2, 0],
[ 1/2, -sqrt(2)/2, 1/2, 0],
[ 0, 0, 0, 1]]) | [
"r",
"Return",
"a",
"block",
"-",
"wise",
"diagonal",
"Wigner",
"D",
"matrix",
"for",
"that",
"rotates",
"a",
"density",
"matrix",
"of",
"an",
"ensemble",
"of",
"particles",
"in",
"definite",
"total",
"angular",
"momentum",
"states",
"given",
"by",
"J_values... | 3e5400672af2a7b7cc616e7f4aa10d7672720222 | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L541-L567 | train | 50,384 |
alexwlchan/specktre | src/specktre/tilings.py | generate_unit_squares | def generate_unit_squares(image_width, image_height):
"""Generate coordinates for a tiling of unit squares."""
# Iterate over the required rows and cells. The for loops (x, y)
# give the coordinates of the top left-hand corner of each square:
#
# (x, y) +-----+ (x + 1, y)
# | |
# | |
# | |
# (x, y + 1) +-----+ (x + 1, y + 1)
#
for x in range(image_width):
for y in range(image_height):
yield [(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)] | python | def generate_unit_squares(image_width, image_height):
"""Generate coordinates for a tiling of unit squares."""
# Iterate over the required rows and cells. The for loops (x, y)
# give the coordinates of the top left-hand corner of each square:
#
# (x, y) +-----+ (x + 1, y)
# | |
# | |
# | |
# (x, y + 1) +-----+ (x + 1, y + 1)
#
for x in range(image_width):
for y in range(image_height):
yield [(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)] | [
"def",
"generate_unit_squares",
"(",
"image_width",
",",
"image_height",
")",
":",
"# Iterate over the required rows and cells. The for loops (x, y)",
"# give the coordinates of the top left-hand corner of each square:",
"#",
"# (x, y) +-----+ (x + 1, y)",
"# | |",
"#... | Generate coordinates for a tiling of unit squares. | [
"Generate",
"coordinates",
"for",
"a",
"tiling",
"of",
"unit",
"squares",
"."
] | dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc | https://github.com/alexwlchan/specktre/blob/dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc/src/specktre/tilings.py#L23-L36 | train | 50,385 |
alexwlchan/specktre | src/specktre/tilings.py | generate_unit_triangles | def generate_unit_triangles(image_width, image_height):
"""Generate coordinates for a tiling of unit triangles."""
# Our triangles lie with one side parallel to the x-axis. Let s be
# the length of one side, and h the height of the triangle.
#
# The for loops (x, y) gives the coordinates of the top left-hand corner
# of a pair of triangles:
#
# (x, y) +-----+ (x + 1, y)
# \ / \
# \ / \
# (x + 1/2, y + h) +-----+ (x + 3/2, y + h)
#
# where h = sin(60°) is the height of an equilateral triangle with
# side length 1.
#
# On odd-numbered rows, we translate by (s/2, 0) to make the triangles
# line up with the even-numbered rows.
#
# To avoid blank spaces on the edge of the canvas, the first pair of
# triangles on each row starts at (-1, 0) -- one width before the edge
# of the canvas.
h = math.sin(math.pi / 3)
for x in range(-1, image_width):
for y in range(int(image_height / h)):
# Add a horizontal offset on odd numbered rows
x_ = x if (y % 2 == 0) else x + 0.5
yield [(x_, y * h), (x_ + 1, y * h), (x_ + 0.5, (y + 1) * h)]
yield [(x_ + 1, y * h), (x_ + 1.5, (y + 1) * h),
(x_ + 0.5, (y + 1) * h)] | python | def generate_unit_triangles(image_width, image_height):
"""Generate coordinates for a tiling of unit triangles."""
# Our triangles lie with one side parallel to the x-axis. Let s be
# the length of one side, and h the height of the triangle.
#
# The for loops (x, y) gives the coordinates of the top left-hand corner
# of a pair of triangles:
#
# (x, y) +-----+ (x + 1, y)
# \ / \
# \ / \
# (x + 1/2, y + h) +-----+ (x + 3/2, y + h)
#
# where h = sin(60°) is the height of an equilateral triangle with
# side length 1.
#
# On odd-numbered rows, we translate by (s/2, 0) to make the triangles
# line up with the even-numbered rows.
#
# To avoid blank spaces on the edge of the canvas, the first pair of
# triangles on each row starts at (-1, 0) -- one width before the edge
# of the canvas.
h = math.sin(math.pi / 3)
for x in range(-1, image_width):
for y in range(int(image_height / h)):
# Add a horizontal offset on odd numbered rows
x_ = x if (y % 2 == 0) else x + 0.5
yield [(x_, y * h), (x_ + 1, y * h), (x_ + 0.5, (y + 1) * h)]
yield [(x_ + 1, y * h), (x_ + 1.5, (y + 1) * h),
(x_ + 0.5, (y + 1) * h)] | [
"def",
"generate_unit_triangles",
"(",
"image_width",
",",
"image_height",
")",
":",
"# Our triangles lie with one side parallel to the x-axis. Let s be",
"# the length of one side, and h the height of the triangle.",
"#",
"# The for loops (x, y) gives the coordinates of the top left-hand cor... | Generate coordinates for a tiling of unit triangles. | [
"Generate",
"coordinates",
"for",
"a",
"tiling",
"of",
"unit",
"triangles",
"."
] | dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc | https://github.com/alexwlchan/specktre/blob/dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc/src/specktre/tilings.py#L44-L76 | train | 50,386 |
hammerlab/stancache | stancache/config.py | restore_default_settings | def restore_default_settings():
""" Restore settings to default values.
"""
global __DEFAULTS
__DEFAULTS.CACHE_DIR = defaults.CACHE_DIR
__DEFAULTS.SET_SEED = defaults.SET_SEED
__DEFAULTS.SEED = defaults.SEED
logging.info('Settings reverted to their default values.') | python | def restore_default_settings():
""" Restore settings to default values.
"""
global __DEFAULTS
__DEFAULTS.CACHE_DIR = defaults.CACHE_DIR
__DEFAULTS.SET_SEED = defaults.SET_SEED
__DEFAULTS.SEED = defaults.SEED
logging.info('Settings reverted to their default values.') | [
"def",
"restore_default_settings",
"(",
")",
":",
"global",
"__DEFAULTS",
"__DEFAULTS",
".",
"CACHE_DIR",
"=",
"defaults",
".",
"CACHE_DIR",
"__DEFAULTS",
".",
"SET_SEED",
"=",
"defaults",
".",
"SET_SEED",
"__DEFAULTS",
".",
"SEED",
"=",
"defaults",
".",
"SEED",... | Restore settings to default values. | [
"Restore",
"settings",
"to",
"default",
"values",
"."
] | 22f2548731d0960c14c0d41f4f64e418d3f22e4c | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/config.py#L19-L26 | train | 50,387 |
hammerlab/stancache | stancache/config.py | load_config | def load_config(config_file='~/.stancache.ini'):
""" Load config file into default settings
"""
if not os.path.exists(config_file):
logging.warning('Config file does not exist: {}. Using default settings.'.format(config_file))
return
## get user-level config in *.ini format
config = configparser.ConfigParser()
config.read(config_file)
if not config.has_section('main'):
raise ValueError('Config file {} has no section "main"'.format(config_file))
for (key, val) in config.items('main'):
_set_value(key.upper(), val)
return | python | def load_config(config_file='~/.stancache.ini'):
""" Load config file into default settings
"""
if not os.path.exists(config_file):
logging.warning('Config file does not exist: {}. Using default settings.'.format(config_file))
return
## get user-level config in *.ini format
config = configparser.ConfigParser()
config.read(config_file)
if not config.has_section('main'):
raise ValueError('Config file {} has no section "main"'.format(config_file))
for (key, val) in config.items('main'):
_set_value(key.upper(), val)
return | [
"def",
"load_config",
"(",
"config_file",
"=",
"'~/.stancache.ini'",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_file",
")",
":",
"logging",
".",
"warning",
"(",
"'Config file does not exist: {}. Using default settings.'",
".",
"format",
... | Load config file into default settings | [
"Load",
"config",
"file",
"into",
"default",
"settings"
] | 22f2548731d0960c14c0d41f4f64e418d3f22e4c | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/config.py#L29-L42 | train | 50,388 |
deployed/django-emailtemplates | emailtemplates/shortcuts.py | send_email | def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs):
"""
Shortcut function for EmailFromTemplate class
@return: None
"""
eft = EmailFromTemplate(name=name)
eft.subject = subject
eft.context = ctx_dict
eft.get_object()
eft.render_message()
eft.send_email(send_to=send_to, **kwargs) | python | def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs):
"""
Shortcut function for EmailFromTemplate class
@return: None
"""
eft = EmailFromTemplate(name=name)
eft.subject = subject
eft.context = ctx_dict
eft.get_object()
eft.render_message()
eft.send_email(send_to=send_to, **kwargs) | [
"def",
"send_email",
"(",
"name",
",",
"ctx_dict",
",",
"send_to",
"=",
"None",
",",
"subject",
"=",
"u'Subject'",
",",
"*",
"*",
"kwargs",
")",
":",
"eft",
"=",
"EmailFromTemplate",
"(",
"name",
"=",
"name",
")",
"eft",
".",
"subject",
"=",
"subject",... | Shortcut function for EmailFromTemplate class
@return: None | [
"Shortcut",
"function",
"for",
"EmailFromTemplate",
"class"
] | 0e95139989dbcf7e624153ddcd7b5b66b48eb6eb | https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/shortcuts.py#L5-L17 | train | 50,389 |
daddyd/dewiki | dewiki/parser.py | Parser.__parse | def __parse(self, string=''):
'''
Parse a string to remove and replace all wiki markup tags
'''
self.string = string
self.string = self.wiki_re.sub('', self.string)
# search for lists
self.listmatch = re.search('^(\*+)', self.string)
if self.listmatch:
self.string = self.__list(self.listmatch) + re.sub('^(\*+)', \
'', self.string)
return self.string | python | def __parse(self, string=''):
'''
Parse a string to remove and replace all wiki markup tags
'''
self.string = string
self.string = self.wiki_re.sub('', self.string)
# search for lists
self.listmatch = re.search('^(\*+)', self.string)
if self.listmatch:
self.string = self.__list(self.listmatch) + re.sub('^(\*+)', \
'', self.string)
return self.string | [
"def",
"__parse",
"(",
"self",
",",
"string",
"=",
"''",
")",
":",
"self",
".",
"string",
"=",
"string",
"self",
".",
"string",
"=",
"self",
".",
"wiki_re",
".",
"sub",
"(",
"''",
",",
"self",
".",
"string",
")",
"# search for lists",
"self",
".",
... | Parse a string to remove and replace all wiki markup tags | [
"Parse",
"a",
"string",
"to",
"remove",
"and",
"replace",
"all",
"wiki",
"markup",
"tags"
] | 84214bb9537326e036fa65e70d7a9ce7c6659c26 | https://github.com/daddyd/dewiki/blob/84214bb9537326e036fa65e70d7a9ce7c6659c26/dewiki/parser.py#L32-L43 | train | 50,390 |
daddyd/dewiki | dewiki/parser.py | Parser.parse_string | def parse_string(self, string=''):
'''
Parse a string object to de-wikified text
'''
self.strings = string.splitlines(1)
self.strings = [self.__parse(line) for line in self.strings]
return ''.join(self.strings) | python | def parse_string(self, string=''):
'''
Parse a string object to de-wikified text
'''
self.strings = string.splitlines(1)
self.strings = [self.__parse(line) for line in self.strings]
return ''.join(self.strings) | [
"def",
"parse_string",
"(",
"self",
",",
"string",
"=",
"''",
")",
":",
"self",
".",
"strings",
"=",
"string",
".",
"splitlines",
"(",
"1",
")",
"self",
".",
"strings",
"=",
"[",
"self",
".",
"__parse",
"(",
"line",
")",
"for",
"line",
"in",
"self"... | Parse a string object to de-wikified text | [
"Parse",
"a",
"string",
"object",
"to",
"de",
"-",
"wikified",
"text"
] | 84214bb9537326e036fa65e70d7a9ce7c6659c26 | https://github.com/daddyd/dewiki/blob/84214bb9537326e036fa65e70d7a9ce7c6659c26/dewiki/parser.py#L45-L51 | train | 50,391 |
tilde-lab/tilde | tilde/core/symmetry.py | SymmetryFinder.refine_cell | def refine_cell(self, tilde_obj):
'''
NB only used for perovskite_tilting app
'''
try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
except Exception as ex:
self.error = 'Symmetry finder error: %s' % ex
else:
self.refinedcell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions, pbc=tilde_obj['structures'][-1].get_pbc())
self.refinedcell.periodicity = sum(self.refinedcell.get_pbc())
self.refinedcell.dims = abs(det(tilde_obj['structures'][-1].cell)) | python | def refine_cell(self, tilde_obj):
'''
NB only used for perovskite_tilting app
'''
try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
except Exception as ex:
self.error = 'Symmetry finder error: %s' % ex
else:
self.refinedcell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions, pbc=tilde_obj['structures'][-1].get_pbc())
self.refinedcell.periodicity = sum(self.refinedcell.get_pbc())
self.refinedcell.dims = abs(det(tilde_obj['structures'][-1].cell)) | [
"def",
"refine_cell",
"(",
"self",
",",
"tilde_obj",
")",
":",
"try",
":",
"lattice",
",",
"positions",
",",
"numbers",
"=",
"spg",
".",
"refine_cell",
"(",
"tilde_obj",
"[",
"'structures'",
"]",
"[",
"-",
"1",
"]",
",",
"symprec",
"=",
"self",
".",
... | NB only used for perovskite_tilting app | [
"NB",
"only",
"used",
"for",
"perovskite_tilting",
"app"
] | 59841578b3503075aa85c76f9ae647b3ff92b0a3 | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/symmetry.py#L36-L46 | train | 50,392 |
myth/pepper8 | pepper8/parser.py | Parser.parse | def parse(self):
"""
Reads all lines from the current data source and yields each FileResult objects
"""
if self.data is None:
raise ValueError('No input data provided, unable to parse')
for line in self.data:
parts = line.strip().split()
try:
path = parts[0]
code = parts[1]
path, line, char = path.split(':')[:3]
if not re.match(POSITION, line):
continue
if not re.match(POSITION, char):
continue
if not re.match(ERROR_CODE, code):
continue
if not re.match(FILEPATH, path):
continue
# For parts mismatch
except IndexError:
continue
# For unpack mismatch
except ValueError:
continue
yield path, code, line, char, ' '.join(parts[2:]) | python | def parse(self):
"""
Reads all lines from the current data source and yields each FileResult objects
"""
if self.data is None:
raise ValueError('No input data provided, unable to parse')
for line in self.data:
parts = line.strip().split()
try:
path = parts[0]
code = parts[1]
path, line, char = path.split(':')[:3]
if not re.match(POSITION, line):
continue
if not re.match(POSITION, char):
continue
if not re.match(ERROR_CODE, code):
continue
if not re.match(FILEPATH, path):
continue
# For parts mismatch
except IndexError:
continue
# For unpack mismatch
except ValueError:
continue
yield path, code, line, char, ' '.join(parts[2:]) | [
"def",
"parse",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No input data provided, unable to parse'",
")",
"for",
"line",
"in",
"self",
".",
"data",
":",
"parts",
"=",
"line",
".",
"strip",
"(",
")"... | Reads all lines from the current data source and yields each FileResult objects | [
"Reads",
"all",
"lines",
"from",
"the",
"current",
"data",
"source",
"and",
"yields",
"each",
"FileResult",
"objects"
] | 98ffed4089241d8d3c1048995bc6777a2f3abdda | https://github.com/myth/pepper8/blob/98ffed4089241d8d3c1048995bc6777a2f3abdda/pepper8/parser.py#L26-L57 | train | 50,393 |
rshipp/python-dshield | dshield.py | _get | def _get(function, return_format=None):
"""Get and return data from the API.
:returns: A str, list, or dict, depending on the input values and API data.
"""
if return_format:
return requests.get(''.join([__BASE_URL, function, return_format])).text
return requests.get(''.join([__BASE_URL, function, JSON])).json() | python | def _get(function, return_format=None):
"""Get and return data from the API.
:returns: A str, list, or dict, depending on the input values and API data.
"""
if return_format:
return requests.get(''.join([__BASE_URL, function, return_format])).text
return requests.get(''.join([__BASE_URL, function, JSON])).json() | [
"def",
"_get",
"(",
"function",
",",
"return_format",
"=",
"None",
")",
":",
"if",
"return_format",
":",
"return",
"requests",
".",
"get",
"(",
"''",
".",
"join",
"(",
"[",
"__BASE_URL",
",",
"function",
",",
"return_format",
"]",
")",
")",
".",
"text"... | Get and return data from the API.
:returns: A str, list, or dict, depending on the input values and API data. | [
"Get",
"and",
"return",
"data",
"from",
"the",
"API",
"."
] | 1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0 | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L20-L27 | train | 50,394 |
rshipp/python-dshield | dshield.py | backscatter | def backscatter(date=None, rows=None, return_format=None):
"""Returns possible backscatter data.
This report only includes "syn ack" data and is summarized by source port.
:param date: optional string (in Y-M-D format) or datetime.date() object
:param rows: optional number of rows returned (default 1000)
:returns: list -- backscatter data.
"""
uri = 'backscatter'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
if rows:
uri = '/'.join([uri, str(rows)])
return _get(uri, return_format) | python | def backscatter(date=None, rows=None, return_format=None):
"""Returns possible backscatter data.
This report only includes "syn ack" data and is summarized by source port.
:param date: optional string (in Y-M-D format) or datetime.date() object
:param rows: optional number of rows returned (default 1000)
:returns: list -- backscatter data.
"""
uri = 'backscatter'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
if rows:
uri = '/'.join([uri, str(rows)])
return _get(uri, return_format) | [
"def",
"backscatter",
"(",
"date",
"=",
"None",
",",
"rows",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'backscatter'",
"if",
"date",
":",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
".",
... | Returns possible backscatter data.
This report only includes "syn ack" data and is summarized by source port.
:param date: optional string (in Y-M-D format) or datetime.date() object
:param rows: optional number of rows returned (default 1000)
:returns: list -- backscatter data. | [
"Returns",
"possible",
"backscatter",
"data",
"."
] | 1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0 | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L30-L47 | train | 50,395 |
rshipp/python-dshield | dshield.py | port | def port(port_number, return_format=None):
"""Summary information about a particular port.
In the returned data:
Records: Total number of records for a given date.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a string or integer port number
"""
response = _get('port/{number}'.format(number=port_number), return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | python | def port(port_number, return_format=None):
"""Summary information about a particular port.
In the returned data:
Records: Total number of records for a given date.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a string or integer port number
"""
response = _get('port/{number}'.format(number=port_number), return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | [
"def",
"port",
"(",
"port_number",
",",
"return_format",
"=",
"None",
")",
":",
"response",
"=",
"_get",
"(",
"'port/{number}'",
".",
"format",
"(",
"number",
"=",
"port_number",
")",
",",
"return_format",
")",
"if",
"'bad port number'",
"in",
"str",
"(",
... | Summary information about a particular port.
In the returned data:
Records: Total number of records for a given date.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a string or integer port number | [
"Summary",
"information",
"about",
"a",
"particular",
"port",
"."
] | 1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0 | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L76-L91 | train | 50,396 |
rshipp/python-dshield | dshield.py | portdate | def portdate(port_number, date=None, return_format=None):
"""Information about a particular port at a particular date.
If the date is ommited, today's date is used.
:param port_number: a string or integer port number
:param date: an optional string in 'Y-M-D' format or datetime.date() object
"""
uri = 'portdate/{number}'.format(number=port_number)
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
response = _get(uri, return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | python | def portdate(port_number, date=None, return_format=None):
"""Information about a particular port at a particular date.
If the date is ommited, today's date is used.
:param port_number: a string or integer port number
:param date: an optional string in 'Y-M-D' format or datetime.date() object
"""
uri = 'portdate/{number}'.format(number=port_number)
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
response = _get(uri, return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | [
"def",
"portdate",
"(",
"port_number",
",",
"date",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'portdate/{number}'",
".",
"format",
"(",
"number",
"=",
"port_number",
")",
"if",
"date",
":",
"try",
":",
"uri",
"=",
"'/'",
".... | Information about a particular port at a particular date.
If the date is ommited, today's date is used.
:param port_number: a string or integer port number
:param date: an optional string in 'Y-M-D' format or datetime.date() object | [
"Information",
"about",
"a",
"particular",
"port",
"at",
"a",
"particular",
"date",
"."
] | 1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0 | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L93-L111 | train | 50,397 |
rshipp/python-dshield | dshield.py | topports | def topports(sort_by='records', limit=10, date=None, return_format=None):
"""Information about top ports for a particular date with return limit.
:param sort_by: one of 'records', 'targets', 'sources'
:param limit: number of records to be returned
:param date: an optional string in 'Y-M-D' format or datetime.date() object
"""
uri = '/'.join(['topports', sort_by, str(limit)])
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | python | def topports(sort_by='records', limit=10, date=None, return_format=None):
"""Information about top ports for a particular date with return limit.
:param sort_by: one of 'records', 'targets', 'sources'
:param limit: number of records to be returned
:param date: an optional string in 'Y-M-D' format or datetime.date() object
"""
uri = '/'.join(['topports', sort_by, str(limit)])
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | [
"def",
"topports",
"(",
"sort_by",
"=",
"'records'",
",",
"limit",
"=",
"10",
",",
"date",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"'topports'",
",",
"sort_by",
",",
"str",
"(",
"limit",
"... | Information about top ports for a particular date with return limit.
:param sort_by: one of 'records', 'targets', 'sources'
:param limit: number of records to be returned
:param date: an optional string in 'Y-M-D' format or datetime.date() object | [
"Information",
"about",
"top",
"ports",
"for",
"a",
"particular",
"date",
"with",
"return",
"limit",
"."
] | 1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0 | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L113-L126 | train | 50,398 |
rshipp/python-dshield | dshield.py | porthistory | def porthistory(port_number, start_date=None, end_date=None, return_format=None):
"""Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a valid port number (required)
:param start_date: string or datetime.date(), default is 30 days ago
:param end_date: string or datetime.date(), default is today
"""
uri = 'porthistory/{port}'.format(port=port_number)
if not start_date:
# default 30 days ago
start_date = datetime.datetime.now() - datetime.timedelta(days=30)
try:
uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, start_date])
if end_date:
try:
uri = '/'.join([uri, end_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, end_date])
response = _get(uri, return_format)
if 'bad port number' in str(response):
raise Error('Bad port, {port}'.format(port=port_number))
else:
return response | python | def porthistory(port_number, start_date=None, end_date=None, return_format=None):
"""Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a valid port number (required)
:param start_date: string or datetime.date(), default is 30 days ago
:param end_date: string or datetime.date(), default is today
"""
uri = 'porthistory/{port}'.format(port=port_number)
if not start_date:
# default 30 days ago
start_date = datetime.datetime.now() - datetime.timedelta(days=30)
try:
uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, start_date])
if end_date:
try:
uri = '/'.join([uri, end_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, end_date])
response = _get(uri, return_format)
if 'bad port number' in str(response):
raise Error('Bad port, {port}'.format(port=port_number))
else:
return response | [
"def",
"porthistory",
"(",
"port_number",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'porthistory/{port}'",
".",
"format",
"(",
"port",
"=",
"port_number",
")",
"if",
"not",
"star... | Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a valid port number (required)
:param start_date: string or datetime.date(), default is 30 days ago
:param end_date: string or datetime.date(), default is today | [
"Returns",
"port",
"data",
"for",
"a",
"range",
"of",
"dates",
"."
] | 1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0 | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L159-L191 | train | 50,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.