repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
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", "(", "0", ",", "length", ")", "]", ")" ]
Return random string
[ "Return", "random", "string" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L102-L104
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", "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", "\"\"" ]
Duck-type value and scramble appropriately
[ "Duck", "-", "type", "value", "and", "scramble", "appropriately" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L106-L124
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", ")", "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", ")" ]
Return random element from code list
[ "Return", "random", "element", "from", "code", "list" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L134-L145
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", ".", "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", ")" ]
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" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L147-L194
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", ")", ":", "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", ")" ]
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" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L200-L233
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", "None", ":", "return", "missing", "return", "int", "(", "value", ")" ]
Convert string value to long, '' to missing
[ "Convert", "string", "value", "to", "long", "to", "missing" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L38-L45
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" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L284-L287
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", ")", ":", "getattr", "(", "self", ".", "handler", ",", "event_name", ")", "(", "self", ".", "context", ")", "elif", "hasattr", "(", "self", ".", "handler", ",", "'default'", ")", ":", "self", ".", "handler", ".", "default", "(", "self", ".", "context", ")" ]
We are finished processing one element. Emit it
[ "We", "are", "finished", "processing", "one", "element", ".", "Emit", "it" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L139-L149
mdsol/rwslib
rwslib/extras/audit_event/parser.py
ODMTargetParser.start
def start(self, tag, attrib): """On start of element tag""" if tag == E_CLINICAL_DATA: self.ref_state = AUDIT_REF_STATE self.context = Context(attrib[A_STUDY_OID], attrib[A_AUDIT_SUBCATEGORY_NAME], int(attrib[A_METADATA_VERSION_OID])) elif tag == E_SUBJECT_DATA: self.context.subject = Subject( attrib.get(A_SUBJECT_KEY), attrib.get(A_SUBJECT_NAME), attrib.get(A_SUBJECT_STATUS), attrib.get(A_TRANSACTION_TYPE, DEFAULT_TRANSACTION_TYPE), ) elif tag == E_USER_REF: # Set the Signature or audit-record value depending on state self.get_parent_element().user_oid = attrib.get(A_USER_OID) elif tag == E_SOURCE_ID: self.state = STATE_SOURCE_ID elif tag == E_DATE_TIME_STAMP_: self.state = STATE_DATETIME elif tag == E_REASON_FOR_CHANGE: self.state = STATE_REASON_FOR_CHANGE elif tag == E_LOCATION_REF: # Set the Signature or audit-record value depending on state self.get_parent_element().location_oid = attrib.get(A_LOCATION_OID) elif tag == E_STUDY_EVENT_DATA: self.context.event = Event( attrib.get(A_STUDYEVENT_OID), attrib.get(A_STUDYEVENT_REPEAT_KEY), attrib.get(A_TRANSACTION_TYPE), attrib.get(A_INSTANCE_NAME), attrib.get(A_INSTANCE_OVERDUE), make_int(attrib.get(A_INSTANCE_ID), -1) ) elif tag == E_FORM_DATA: self.context.form = Form( attrib.get(A_FORM_OID), int(attrib.get(A_FORM_REPEAT_KEY, 0)), attrib.get(A_TRANSACTION_TYPE), attrib.get(A_DATAPAGE_NAME), make_int(attrib.get(A_DATAPAGE_ID, -1)), ) elif tag == E_ITEM_GROUP_DATA: self.context.itemgroup = ItemGroup( attrib.get(A_ITEMGROUP_OID), int(attrib.get(A_ITEMGROUP_REPEAT_KEY, 0)), attrib.get(A_TRANSACTION_TYPE), make_int(attrib.get(A_RECORD_ID, -1)), ) elif tag == E_ITEM_DATA: self.context.item = Item( attrib.get(A_ITEM_OID), attrib.get(A_VALUE), yes_no_none(attrib.get(A_FREEZE)), yes_no_none(attrib.get(A_VERIFY)), yes_no_none(attrib.get(A_LOCK)), attrib.get(A_TRANSACTION_TYPE) ) elif tag == E_QUERY: self.context.query = Query( make_int(attrib.get(A_QUERY_REPEAT_KEY, -1)), attrib.get(A_STATUS), attrib.get(A_RESPONSE), attrib.get(A_RECIPIENT), attrib.get(A_VALUE) # Optional, depends on status ) elif tag == E_PROTOCOL_DEVIATION: self.context.protocol_deviation = ProtocolDeviation( make_int(attrib.get(A_PROTCOL_DEVIATION_REPEAT_KEY, -1)), attrib.get(A_CODE), attrib.get(A_CLASS), attrib.get(A_STATUS), attrib.get(A_VALUE), attrib.get(A_TRANSACTION_TYPE) ) elif tag == E_REVIEW: self.context.review = Review( attrib.get(A_GROUP_NAME), yes_no_none(attrib.get(A_REVIEWED)), ) elif tag == E_COMMENT: self.context.comment = Comment( attrib.get(A_COMMENT_REPEAT_KEY), attrib.get(A_VALUE), attrib.get(A_TRANSACTION_TYPE) ) elif tag == E_SIGNATURE: self.ref_state = SIGNATURE_REF_STATE elif tag == E_SIGNATURE_REF: self.context.signature.oid = attrib.get(A_SIGNATURE_OID)
python
def start(self, tag, attrib): """On start of element tag""" if tag == E_CLINICAL_DATA: self.ref_state = AUDIT_REF_STATE self.context = Context(attrib[A_STUDY_OID], attrib[A_AUDIT_SUBCATEGORY_NAME], int(attrib[A_METADATA_VERSION_OID])) elif tag == E_SUBJECT_DATA: self.context.subject = Subject( attrib.get(A_SUBJECT_KEY), attrib.get(A_SUBJECT_NAME), attrib.get(A_SUBJECT_STATUS), attrib.get(A_TRANSACTION_TYPE, DEFAULT_TRANSACTION_TYPE), ) elif tag == E_USER_REF: # Set the Signature or audit-record value depending on state self.get_parent_element().user_oid = attrib.get(A_USER_OID) elif tag == E_SOURCE_ID: self.state = STATE_SOURCE_ID elif tag == E_DATE_TIME_STAMP_: self.state = STATE_DATETIME elif tag == E_REASON_FOR_CHANGE: self.state = STATE_REASON_FOR_CHANGE elif tag == E_LOCATION_REF: # Set the Signature or audit-record value depending on state self.get_parent_element().location_oid = attrib.get(A_LOCATION_OID) elif tag == E_STUDY_EVENT_DATA: self.context.event = Event( attrib.get(A_STUDYEVENT_OID), attrib.get(A_STUDYEVENT_REPEAT_KEY), attrib.get(A_TRANSACTION_TYPE), attrib.get(A_INSTANCE_NAME), attrib.get(A_INSTANCE_OVERDUE), make_int(attrib.get(A_INSTANCE_ID), -1) ) elif tag == E_FORM_DATA: self.context.form = Form( attrib.get(A_FORM_OID), int(attrib.get(A_FORM_REPEAT_KEY, 0)), attrib.get(A_TRANSACTION_TYPE), attrib.get(A_DATAPAGE_NAME), make_int(attrib.get(A_DATAPAGE_ID, -1)), ) elif tag == E_ITEM_GROUP_DATA: self.context.itemgroup = ItemGroup( attrib.get(A_ITEMGROUP_OID), int(attrib.get(A_ITEMGROUP_REPEAT_KEY, 0)), attrib.get(A_TRANSACTION_TYPE), make_int(attrib.get(A_RECORD_ID, -1)), ) elif tag == E_ITEM_DATA: self.context.item = Item( attrib.get(A_ITEM_OID), attrib.get(A_VALUE), yes_no_none(attrib.get(A_FREEZE)), yes_no_none(attrib.get(A_VERIFY)), yes_no_none(attrib.get(A_LOCK)), attrib.get(A_TRANSACTION_TYPE) ) elif tag == E_QUERY: self.context.query = Query( make_int(attrib.get(A_QUERY_REPEAT_KEY, -1)), attrib.get(A_STATUS), attrib.get(A_RESPONSE), attrib.get(A_RECIPIENT), attrib.get(A_VALUE) # Optional, depends on status ) elif tag == E_PROTOCOL_DEVIATION: self.context.protocol_deviation = ProtocolDeviation( make_int(attrib.get(A_PROTCOL_DEVIATION_REPEAT_KEY, -1)), attrib.get(A_CODE), attrib.get(A_CLASS), attrib.get(A_STATUS), attrib.get(A_VALUE), attrib.get(A_TRANSACTION_TYPE) ) elif tag == E_REVIEW: self.context.review = Review( attrib.get(A_GROUP_NAME), yes_no_none(attrib.get(A_REVIEWED)), ) elif tag == E_COMMENT: self.context.comment = Comment( attrib.get(A_COMMENT_REPEAT_KEY), attrib.get(A_VALUE), attrib.get(A_TRANSACTION_TYPE) ) elif tag == E_SIGNATURE: self.ref_state = SIGNATURE_REF_STATE elif tag == E_SIGNATURE_REF: self.context.signature.oid = attrib.get(A_SIGNATURE_OID)
[ "def", "start", "(", "self", ",", "tag", ",", "attrib", ")", ":", "if", "tag", "==", "E_CLINICAL_DATA", ":", "self", ".", "ref_state", "=", "AUDIT_REF_STATE", "self", ".", "context", "=", "Context", "(", "attrib", "[", "A_STUDY_OID", "]", ",", "attrib", "[", "A_AUDIT_SUBCATEGORY_NAME", "]", ",", "int", "(", "attrib", "[", "A_METADATA_VERSION_OID", "]", ")", ")", "elif", "tag", "==", "E_SUBJECT_DATA", ":", "self", ".", "context", ".", "subject", "=", "Subject", "(", "attrib", ".", "get", "(", "A_SUBJECT_KEY", ")", ",", "attrib", ".", "get", "(", "A_SUBJECT_NAME", ")", ",", "attrib", ".", "get", "(", "A_SUBJECT_STATUS", ")", ",", "attrib", ".", "get", "(", "A_TRANSACTION_TYPE", ",", "DEFAULT_TRANSACTION_TYPE", ")", ",", ")", "elif", "tag", "==", "E_USER_REF", ":", "# Set the Signature or audit-record value depending on state", "self", ".", "get_parent_element", "(", ")", ".", "user_oid", "=", "attrib", ".", "get", "(", "A_USER_OID", ")", "elif", "tag", "==", "E_SOURCE_ID", ":", "self", ".", "state", "=", "STATE_SOURCE_ID", "elif", "tag", "==", "E_DATE_TIME_STAMP_", ":", "self", ".", "state", "=", "STATE_DATETIME", "elif", "tag", "==", "E_REASON_FOR_CHANGE", ":", "self", ".", "state", "=", "STATE_REASON_FOR_CHANGE", "elif", "tag", "==", "E_LOCATION_REF", ":", "# Set the Signature or audit-record value depending on state", "self", ".", "get_parent_element", "(", ")", ".", "location_oid", "=", "attrib", ".", "get", "(", "A_LOCATION_OID", ")", "elif", "tag", "==", "E_STUDY_EVENT_DATA", ":", "self", ".", "context", ".", "event", "=", "Event", "(", "attrib", ".", "get", "(", "A_STUDYEVENT_OID", ")", ",", "attrib", ".", "get", "(", "A_STUDYEVENT_REPEAT_KEY", ")", ",", "attrib", ".", "get", "(", "A_TRANSACTION_TYPE", ")", ",", "attrib", ".", "get", "(", "A_INSTANCE_NAME", ")", ",", "attrib", ".", "get", "(", "A_INSTANCE_OVERDUE", ")", ",", "make_int", "(", "attrib", ".", "get", "(", "A_INSTANCE_ID", ")", ",", "-", "1", ")", ")", "elif", "tag", "==", "E_FORM_DATA", ":", "self", ".", "context", ".", "form", "=", "Form", "(", "attrib", ".", "get", "(", "A_FORM_OID", ")", ",", "int", "(", "attrib", ".", "get", "(", "A_FORM_REPEAT_KEY", ",", "0", ")", ")", ",", "attrib", ".", "get", "(", "A_TRANSACTION_TYPE", ")", ",", "attrib", ".", "get", "(", "A_DATAPAGE_NAME", ")", ",", "make_int", "(", "attrib", ".", "get", "(", "A_DATAPAGE_ID", ",", "-", "1", ")", ")", ",", ")", "elif", "tag", "==", "E_ITEM_GROUP_DATA", ":", "self", ".", "context", ".", "itemgroup", "=", "ItemGroup", "(", "attrib", ".", "get", "(", "A_ITEMGROUP_OID", ")", ",", "int", "(", "attrib", ".", "get", "(", "A_ITEMGROUP_REPEAT_KEY", ",", "0", ")", ")", ",", "attrib", ".", "get", "(", "A_TRANSACTION_TYPE", ")", ",", "make_int", "(", "attrib", ".", "get", "(", "A_RECORD_ID", ",", "-", "1", ")", ")", ",", ")", "elif", "tag", "==", "E_ITEM_DATA", ":", "self", ".", "context", ".", "item", "=", "Item", "(", "attrib", ".", "get", "(", "A_ITEM_OID", ")", ",", "attrib", ".", "get", "(", "A_VALUE", ")", ",", "yes_no_none", "(", "attrib", ".", "get", "(", "A_FREEZE", ")", ")", ",", "yes_no_none", "(", "attrib", ".", "get", "(", "A_VERIFY", ")", ")", ",", "yes_no_none", "(", "attrib", ".", "get", "(", "A_LOCK", ")", ")", ",", "attrib", ".", "get", "(", "A_TRANSACTION_TYPE", ")", ")", "elif", "tag", "==", "E_QUERY", ":", "self", ".", "context", ".", "query", "=", "Query", "(", "make_int", "(", "attrib", ".", "get", "(", "A_QUERY_REPEAT_KEY", ",", "-", "1", ")", ")", ",", "attrib", ".", "get", "(", "A_STATUS", ")", ",", "attrib", ".", "get", "(", "A_RESPONSE", ")", ",", "attrib", ".", "get", "(", "A_RECIPIENT", ")", ",", "attrib", ".", "get", "(", "A_VALUE", ")", "# Optional, depends on status", ")", "elif", "tag", "==", "E_PROTOCOL_DEVIATION", ":", "self", ".", "context", ".", "protocol_deviation", "=", "ProtocolDeviation", "(", "make_int", "(", "attrib", ".", "get", "(", "A_PROTCOL_DEVIATION_REPEAT_KEY", ",", "-", "1", ")", ")", ",", "attrib", ".", "get", "(", "A_CODE", ")", ",", "attrib", ".", "get", "(", "A_CLASS", ")", ",", "attrib", ".", "get", "(", "A_STATUS", ")", ",", "attrib", ".", "get", "(", "A_VALUE", ")", ",", "attrib", ".", "get", "(", "A_TRANSACTION_TYPE", ")", ")", "elif", "tag", "==", "E_REVIEW", ":", "self", ".", "context", ".", "review", "=", "Review", "(", "attrib", ".", "get", "(", "A_GROUP_NAME", ")", ",", "yes_no_none", "(", "attrib", ".", "get", "(", "A_REVIEWED", ")", ")", ",", ")", "elif", "tag", "==", "E_COMMENT", ":", "self", ".", "context", ".", "comment", "=", "Comment", "(", "attrib", ".", "get", "(", "A_COMMENT_REPEAT_KEY", ")", ",", "attrib", ".", "get", "(", "A_VALUE", ")", ",", "attrib", ".", "get", "(", "A_TRANSACTION_TYPE", ")", ")", "elif", "tag", "==", "E_SIGNATURE", ":", "self", ".", "ref_state", "=", "SIGNATURE_REF_STATE", "elif", "tag", "==", "E_SIGNATURE_REF", ":", "self", ".", "context", ".", "signature", ".", "oid", "=", "attrib", ".", "get", "(", "A_SIGNATURE_OID", ")" ]
On start of element tag
[ "On", "start", "of", "element", "tag" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L151-L255
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" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L263-L266
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", ".", "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" ]
Called for text between tags
[ "Called", "for", "text", "between", "tags" ]
train
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L268-L277
timster/peewee-validates
peewee_validates.py
validate_not_empty
def validate_not_empty(): """ Validate that a field is not empty (blank string). :raises: ``ValidationError('empty')`` """ def empty_validator(field, data): if isinstance(field.value, str) and not field.value.strip(): raise ValidationError('empty') return empty_validator
python
def validate_not_empty(): """ Validate that a field is not empty (blank string). :raises: ``ValidationError('empty')`` """ def empty_validator(field, data): if isinstance(field.value, str) and not field.value.strip(): raise ValidationError('empty') return empty_validator
[ "def", "validate_not_empty", "(", ")", ":", "def", "empty_validator", "(", "field", ",", "data", ")", ":", "if", "isinstance", "(", "field", ".", "value", ",", "str", ")", "and", "not", "field", ".", "value", ".", "strip", "(", ")", ":", "raise", "ValidationError", "(", "'empty'", ")", "return", "empty_validator" ]
Validate that a field is not empty (blank string). :raises: ``ValidationError('empty')``
[ "Validate", "that", "a", "field", "is", "not", "empty", "(", "blank", "string", ")", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L78-L87
timster/peewee-validates
peewee_validates.py
validate_length
def validate_length(low=None, high=None, equal=None): """ Validate the length of a field with either low, high, or equal. Should work with anything that supports len(). :param low: Smallest length required. :param high: Longest length required. :param equal: Exact length required. :raises: ``ValidationError('length_low')`` :raises: ``ValidationError('length_high')`` :raises: ``ValidationError('length_between')`` :raises: ``ValidationError('length_equal')`` """ def length_validator(field, data): if field.value is None: return if equal is not None and len(field.value) != equal: raise ValidationError('length_equal', equal=equal) if low is not None and len(field.value) < low: key = 'length_low' if high is None else 'length_between' raise ValidationError(key, low=low, high=high) if high is not None and len(field.value) > high: key = 'length_high' if low is None else 'length_between' raise ValidationError(key, low=low, high=high) return length_validator
python
def validate_length(low=None, high=None, equal=None): """ Validate the length of a field with either low, high, or equal. Should work with anything that supports len(). :param low: Smallest length required. :param high: Longest length required. :param equal: Exact length required. :raises: ``ValidationError('length_low')`` :raises: ``ValidationError('length_high')`` :raises: ``ValidationError('length_between')`` :raises: ``ValidationError('length_equal')`` """ def length_validator(field, data): if field.value is None: return if equal is not None and len(field.value) != equal: raise ValidationError('length_equal', equal=equal) if low is not None and len(field.value) < low: key = 'length_low' if high is None else 'length_between' raise ValidationError(key, low=low, high=high) if high is not None and len(field.value) > high: key = 'length_high' if low is None else 'length_between' raise ValidationError(key, low=low, high=high) return length_validator
[ "def", "validate_length", "(", "low", "=", "None", ",", "high", "=", "None", ",", "equal", "=", "None", ")", ":", "def", "length_validator", "(", "field", ",", "data", ")", ":", "if", "field", ".", "value", "is", "None", ":", "return", "if", "equal", "is", "not", "None", "and", "len", "(", "field", ".", "value", ")", "!=", "equal", ":", "raise", "ValidationError", "(", "'length_equal'", ",", "equal", "=", "equal", ")", "if", "low", "is", "not", "None", "and", "len", "(", "field", ".", "value", ")", "<", "low", ":", "key", "=", "'length_low'", "if", "high", "is", "None", "else", "'length_between'", "raise", "ValidationError", "(", "key", ",", "low", "=", "low", ",", "high", "=", "high", ")", "if", "high", "is", "not", "None", "and", "len", "(", "field", ".", "value", ")", ">", "high", ":", "key", "=", "'length_high'", "if", "low", "is", "None", "else", "'length_between'", "raise", "ValidationError", "(", "key", ",", "low", "=", "low", ",", "high", "=", "high", ")", "return", "length_validator" ]
Validate the length of a field with either low, high, or equal. Should work with anything that supports len(). :param low: Smallest length required. :param high: Longest length required. :param equal: Exact length required. :raises: ``ValidationError('length_low')`` :raises: ``ValidationError('length_high')`` :raises: ``ValidationError('length_between')`` :raises: ``ValidationError('length_equal')``
[ "Validate", "the", "length", "of", "a", "field", "with", "either", "low", "high", "or", "equal", ".", "Should", "work", "with", "anything", "that", "supports", "len", "()", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L90-L114
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", "=", "options", "(", ")", "if", "field", ".", "value", "not", "in", "options", ":", "raise", "ValidationError", "(", "'one_of'", ",", "choices", "=", "', '", ".", "join", "(", "map", "(", "str", ",", "options", ")", ")", ")", "return", "one_of_validator" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L117-L132
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", "in", "options", ":", "raise", "ValidationError", "(", "'none_of'", ",", "choices", "=", "str", ".", "join", "(", "', '", ",", "options", ")", ")", "return", "none_of_validator" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L135-L148
timster/peewee-validates
peewee_validates.py
validate_range
def validate_range(low=None, high=None): """ Validate the range of a field with either low, high, or equal. Should work with anything that supports '>' and '<' operators. :param low: Smallest value required. :param high: Longest value required. :raises: ``ValidationError('range_low')`` :raises: ``ValidationError('range_high')`` :raises: ``ValidationError('range_between')`` """ def range_validator(field, data): if field.value is None: return if low is not None and field.value < low: key = 'range_low' if high is None else 'range_between' raise ValidationError(key, low=low, high=high) if high is not None and field.value > high: key = 'range_high' if high is None else 'range_between' raise ValidationError(key, low=low, high=high) return range_validator
python
def validate_range(low=None, high=None): """ Validate the range of a field with either low, high, or equal. Should work with anything that supports '>' and '<' operators. :param low: Smallest value required. :param high: Longest value required. :raises: ``ValidationError('range_low')`` :raises: ``ValidationError('range_high')`` :raises: ``ValidationError('range_between')`` """ def range_validator(field, data): if field.value is None: return if low is not None and field.value < low: key = 'range_low' if high is None else 'range_between' raise ValidationError(key, low=low, high=high) if high is not None and field.value > high: key = 'range_high' if high is None else 'range_between' raise ValidationError(key, low=low, high=high) return range_validator
[ "def", "validate_range", "(", "low", "=", "None", ",", "high", "=", "None", ")", ":", "def", "range_validator", "(", "field", ",", "data", ")", ":", "if", "field", ".", "value", "is", "None", ":", "return", "if", "low", "is", "not", "None", "and", "field", ".", "value", "<", "low", ":", "key", "=", "'range_low'", "if", "high", "is", "None", "else", "'range_between'", "raise", "ValidationError", "(", "key", ",", "low", "=", "low", ",", "high", "=", "high", ")", "if", "high", "is", "not", "None", "and", "field", ".", "value", ">", "high", ":", "key", "=", "'range_high'", "if", "high", "is", "None", "else", "'range_between'", "raise", "ValidationError", "(", "key", ",", "low", "=", "low", ",", "high", "=", "high", ")", "return", "range_validator" ]
Validate the range of a field with either low, high, or equal. Should work with anything that supports '>' and '<' operators. :param low: Smallest value required. :param high: Longest value required. :raises: ``ValidationError('range_low')`` :raises: ``ValidationError('range_high')`` :raises: ``ValidationError('range_between')``
[ "Validate", "the", "range", "of", "a", "field", "with", "either", "low", "high", "or", "equal", ".", "Should", "work", "with", "anything", "that", "supports", ">", "and", "<", "operators", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L151-L171
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", "ValidationError", "(", "'equal'", ",", "other", "=", "value", ")", "return", "equal_validator" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L174-L187
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", "(", "other", ")", ")", ":", "raise", "ValidationError", "(", "'matches'", ",", "other", "=", "other", ")", "return", "matches_validator" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L190-L203
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", "(", "field", ",", "data", ")", ":", "if", "field", ".", "value", "is", "None", ":", "return", "if", "regex", ".", "match", "(", "str", "(", "field", ".", "value", ")", ")", "is", "None", ":", "raise", "ValidationError", "(", "'regexp'", ",", "pattern", "=", "pattern", ")", "return", "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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L206-L222
timster/peewee-validates
peewee_validates.py
validate_function
def validate_function(method, **kwargs): """ Validate the field matches the result of calling the given method. Example:: def myfunc(value, name): return value == name validator = validate_function(myfunc, name='tim') Essentially creates a validator that only accepts the name 'tim'. :param method: Method to call. :param kwargs: Additional keyword arguments passed to the method. :raises: ``ValidationError('function')`` """ def function_validator(field, data): if field.value is None: return if not method(field.value, **kwargs): raise ValidationError('function', function=method.__name__) return function_validator
python
def validate_function(method, **kwargs): """ Validate the field matches the result of calling the given method. Example:: def myfunc(value, name): return value == name validator = validate_function(myfunc, name='tim') Essentially creates a validator that only accepts the name 'tim'. :param method: Method to call. :param kwargs: Additional keyword arguments passed to the method. :raises: ``ValidationError('function')`` """ def function_validator(field, data): if field.value is None: return if not method(field.value, **kwargs): raise ValidationError('function', function=method.__name__) return function_validator
[ "def", "validate_function", "(", "method", ",", "*", "*", "kwargs", ")", ":", "def", "function_validator", "(", "field", ",", "data", ")", ":", "if", "field", ".", "value", "is", "None", ":", "return", "if", "not", "method", "(", "field", ".", "value", ",", "*", "*", "kwargs", ")", ":", "raise", "ValidationError", "(", "'function'", ",", "function", "=", "method", ".", "__name__", ")", "return", "function_validator" ]
Validate the field matches the result of calling the given method. Example:: def myfunc(value, name): return value == name validator = validate_function(myfunc, name='tim') Essentially creates a validator that only accepts the name 'tim'. :param method: Method to call. :param kwargs: Additional keyword arguments passed to the method. :raises: ``ValidationError('function')``
[ "Validate", "the", "field", "matches", "the", "result", "of", "calling", "the", "given", "method", ".", "Example", "::" ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L225-L245
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", ".", "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" ]
Validate the field is a valid email address. :raises: ``ValidationError('email')``
[ "Validate", "the", "field", "is", "a", "valid", "email", "address", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L248-L287
timster/peewee-validates
peewee_validates.py
validate_model_unique
def validate_model_unique(lookup_field, queryset, pk_field=None, pk_value=None): """ Validate the field is a unique, given a queryset and lookup_field. Example:: validator = validate_model_unique(User.email, User.select()) Creates a validator that can validate the uniqueness of an email address. :param lookup_field: Peewee model field that should be used for checking existing values. :param queryset: Queryset to use for lookup. :param pk_field: Field instance to use when excluding existing instance. :param pk_value: Field value to use when excluding existing instance. :raises: ``ValidationError('unique')`` """ def unique_validator(field, data): # If we have a PK, ignore it because it represents the current record. query = queryset.where(lookup_field == field.value) if pk_field and pk_value: query = query.where(~(pk_field == pk_value)) if query.count(): raise ValidationError('unique') return unique_validator
python
def validate_model_unique(lookup_field, queryset, pk_field=None, pk_value=None): """ Validate the field is a unique, given a queryset and lookup_field. Example:: validator = validate_model_unique(User.email, User.select()) Creates a validator that can validate the uniqueness of an email address. :param lookup_field: Peewee model field that should be used for checking existing values. :param queryset: Queryset to use for lookup. :param pk_field: Field instance to use when excluding existing instance. :param pk_value: Field value to use when excluding existing instance. :raises: ``ValidationError('unique')`` """ def unique_validator(field, data): # If we have a PK, ignore it because it represents the current record. query = queryset.where(lookup_field == field.value) if pk_field and pk_value: query = query.where(~(pk_field == pk_value)) if query.count(): raise ValidationError('unique') return unique_validator
[ "def", "validate_model_unique", "(", "lookup_field", ",", "queryset", ",", "pk_field", "=", "None", ",", "pk_value", "=", "None", ")", ":", "def", "unique_validator", "(", "field", ",", "data", ")", ":", "# If we have a PK, ignore it because it represents the current record.", "query", "=", "queryset", ".", "where", "(", "lookup_field", "==", "field", ".", "value", ")", "if", "pk_field", "and", "pk_value", ":", "query", "=", "query", ".", "where", "(", "~", "(", "pk_field", "==", "pk_value", ")", ")", "if", "query", ".", "count", "(", ")", ":", "raise", "ValidationError", "(", "'unique'", ")", "return", "unique_validator" ]
Validate the field is a unique, given a queryset and lookup_field. Example:: validator = validate_model_unique(User.email, User.select()) Creates a validator that can validate the uniqueness of an email address. :param lookup_field: Peewee model field that should be used for checking existing values. :param queryset: Queryset to use for lookup. :param pk_field: Field instance to use when excluding existing instance. :param pk_value: Field value to use when excluding existing instance. :raises: ``ValidationError('unique')``
[ "Validate", "the", "field", "is", "a", "unique", "given", "a", "queryset", "and", "lookup_field", ".", "Example", "::" ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L290-L311
timster/peewee-validates
peewee_validates.py
coerce_single_instance
def coerce_single_instance(lookup_field, value): """ Convert from whatever value is given to a scalar value for lookup_field. If value is a dict, then lookup_field.name is used to get the value from the dict. Example: lookup_field.name = 'id' value = {'id': 123, 'name': 'tim'} returns = 123 If value is a model, then lookup_field.name is extracted from the model. Example: lookup_field.name = 'id' value = <User id=123 name='tim'> returns = 123 Otherwise the value is returned as-is. :param lookup_field: Peewee model field used for getting name from value. :param value: Some kind of value (usually a dict, Model instance, or scalar). """ if isinstance(value, dict): return value.get(lookup_field.name) if isinstance(value, peewee.Model): return getattr(value, lookup_field.name) return value
python
def coerce_single_instance(lookup_field, value): """ Convert from whatever value is given to a scalar value for lookup_field. If value is a dict, then lookup_field.name is used to get the value from the dict. Example: lookup_field.name = 'id' value = {'id': 123, 'name': 'tim'} returns = 123 If value is a model, then lookup_field.name is extracted from the model. Example: lookup_field.name = 'id' value = <User id=123 name='tim'> returns = 123 Otherwise the value is returned as-is. :param lookup_field: Peewee model field used for getting name from value. :param value: Some kind of value (usually a dict, Model instance, or scalar). """ if isinstance(value, dict): return value.get(lookup_field.name) if isinstance(value, peewee.Model): return getattr(value, lookup_field.name) return value
[ "def", "coerce_single_instance", "(", "lookup_field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "value", ".", "get", "(", "lookup_field", ".", "name", ")", "if", "isinstance", "(", "value", ",", "peewee", ".", "Model", ")", ":", "return", "getattr", "(", "value", ",", "lookup_field", ".", "name", ")", "return", "value" ]
Convert from whatever value is given to a scalar value for lookup_field. If value is a dict, then lookup_field.name is used to get the value from the dict. Example: lookup_field.name = 'id' value = {'id': 123, 'name': 'tim'} returns = 123 If value is a model, then lookup_field.name is extracted from the model. Example: lookup_field.name = 'id' value = <User id=123 name='tim'> returns = 123 Otherwise the value is returned as-is. :param lookup_field: Peewee model field used for getting name from value. :param value: Some kind of value (usually a dict, Model instance, or scalar).
[ "Convert", "from", "whatever", "value", "is", "given", "to", "a", "scalar", "value", "for", "lookup_field", ".", "If", "value", "is", "a", "dict", "then", "lookup_field", ".", "name", "is", "used", "to", "get", "the", "value", "from", "the", "dict", ".", "Example", ":", "lookup_field", ".", "name", "=", "id", "value", "=", "{", "id", ":", "123", "name", ":", "tim", "}", "returns", "=", "123", "If", "value", "is", "a", "model", "then", "lookup_field", ".", "name", "is", "extracted", "from", "the", "model", ".", "Example", ":", "lookup_field", ".", "name", "=", "id", "value", "=", "<User", "id", "=", "123", "name", "=", "tim", ">", "returns", "=", "123", "Otherwise", "the", "value", "is", "returned", "as", "-", "is", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L314-L334
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", "(", "value", ")" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L337-L345
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", ")", ":", "return", "self", ".", "default", "(", ")", "return", "self", ".", "default", "return", "None" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L379-L396
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", ".", "coerce", "(", "self", ".", "value", ")", "for", "method", "in", "self", ".", "validators", ":", "method", "(", "self", ",", "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
[ "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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L398-L412
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", ".", "query", ".", "get", "(", "self", ".", "lookup_field", "==", "self", ".", "value", ")", "except", "(", "AttributeError", ",", "ValueError", ",", "peewee", ".", "DoesNotExist", ")", ":", "raise", "ValidationError", "(", "'related'", ",", "field", "=", "self", ".", "lookup_field", ".", "name", ",", "values", "=", "self", ".", "value", ")" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L641-L654
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", "[", "coerce_single_instance", "(", "self", ".", "lookup_field", ",", "v", ")", "for", "v", "in", "value", "]" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L672-L678
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", "[", "field", "]", "=", "obj" ]
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", "needed", "in", "sub", "-", "classes", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L742-L753
timster/peewee-validates
peewee_validates.py
Validator.validate
def validate(self, data=None, only=None, exclude=None): """ Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. This is usually the method you want to call after creating the validator instance. :param data: Dictionary of data to validate. :param only: List or tuple of fields to validate. :param exclude: List or tuple of fields to exclude from validation. :return: True if validation was successful. Otherwise False. """ only = only or [] exclude = exclude or [] data = data or {} self.errors = {} self.data = {} # Validate individual fields. for name, field in self._meta.fields.items(): if name in exclude or (only and name not in only): continue try: field.validate(name, data) except ValidationError as err: self.add_error(name, err) continue self.data[name] = field.value # Clean individual fields. if not self.errors: self.clean_fields(self.data) # Then finally clean the whole data dict. if not self.errors: try: self.data = self.clean(self.data) except ValidationError as err: self.add_error('__base__', err) return (not self.errors)
python
def validate(self, data=None, only=None, exclude=None): """ Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. This is usually the method you want to call after creating the validator instance. :param data: Dictionary of data to validate. :param only: List or tuple of fields to validate. :param exclude: List or tuple of fields to exclude from validation. :return: True if validation was successful. Otherwise False. """ only = only or [] exclude = exclude or [] data = data or {} self.errors = {} self.data = {} # Validate individual fields. for name, field in self._meta.fields.items(): if name in exclude or (only and name not in only): continue try: field.validate(name, data) except ValidationError as err: self.add_error(name, err) continue self.data[name] = field.value # Clean individual fields. if not self.errors: self.clean_fields(self.data) # Then finally clean the whole data dict. if not self.errors: try: self.data = self.clean(self.data) except ValidationError as err: self.add_error('__base__', err) return (not self.errors)
[ "def", "validate", "(", "self", ",", "data", "=", "None", ",", "only", "=", "None", ",", "exclude", "=", "None", ")", ":", "only", "=", "only", "or", "[", "]", "exclude", "=", "exclude", "or", "[", "]", "data", "=", "data", "or", "{", "}", "self", ".", "errors", "=", "{", "}", "self", ".", "data", "=", "{", "}", "# Validate individual fields.", "for", "name", ",", "field", "in", "self", ".", "_meta", ".", "fields", ".", "items", "(", ")", ":", "if", "name", "in", "exclude", "or", "(", "only", "and", "name", "not", "in", "only", ")", ":", "continue", "try", ":", "field", ".", "validate", "(", "name", ",", "data", ")", "except", "ValidationError", "as", "err", ":", "self", ".", "add_error", "(", "name", ",", "err", ")", "continue", "self", ".", "data", "[", "name", "]", "=", "field", ".", "value", "# Clean individual fields.", "if", "not", "self", ".", "errors", ":", "self", ".", "clean_fields", "(", "self", ".", "data", ")", "# Then finally clean the whole data dict.", "if", "not", "self", ".", "errors", ":", "try", ":", "self", ".", "data", "=", "self", ".", "clean", "(", "self", ".", "data", ")", "except", "ValidationError", "as", "err", ":", "self", ".", "add_error", "(", "'__base__'", ",", "err", ")", "return", "(", "not", "self", ".", "errors", ")" ]
Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. This is usually the method you want to call after creating the validator instance. :param data: Dictionary of data to validate. :param only: List or tuple of fields to validate. :param exclude: List or tuple of fields to exclude from validation. :return: True if validation was successful. Otherwise False.
[ "Validate", "the", "data", "for", "all", "fields", "and", "return", "whether", "the", "validation", "was", "successful", ".", "This", "method", "also", "retains", "the", "validated", "data", "in", "self", ".", "data", "so", "that", "it", "can", "be", "accessed", "later", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L755-L795
timster/peewee-validates
peewee_validates.py
Validator.clean_fields
def clean_fields(self, data): """ For each field, check to see if there is a clean_<name> method. If so, run that method and set the returned value on the self.data dict. This happens after all validations so that each field can act on the cleaned data of other fields if needed. :param data: Dictionary of data to clean. :return: None """ for name, value in data.items(): try: method = getattr(self, 'clean_{}'.format(name), None) if method: self.data[name] = method(value) except ValidationError as err: self.add_error(name, err) continue
python
def clean_fields(self, data): """ For each field, check to see if there is a clean_<name> method. If so, run that method and set the returned value on the self.data dict. This happens after all validations so that each field can act on the cleaned data of other fields if needed. :param data: Dictionary of data to clean. :return: None """ for name, value in data.items(): try: method = getattr(self, 'clean_{}'.format(name), None) if method: self.data[name] = method(value) except ValidationError as err: self.add_error(name, err) continue
[ "def", "clean_fields", "(", "self", ",", "data", ")", ":", "for", "name", ",", "value", "in", "data", ".", "items", "(", ")", ":", "try", ":", "method", "=", "getattr", "(", "self", ",", "'clean_{}'", ".", "format", "(", "name", ")", ",", "None", ")", "if", "method", ":", "self", ".", "data", "[", "name", "]", "=", "method", "(", "value", ")", "except", "ValidationError", "as", "err", ":", "self", ".", "add_error", "(", "name", ",", "err", ")", "continue" ]
For each field, check to see if there is a clean_<name> method. If so, run that method and set the returned value on the self.data dict. This happens after all validations so that each field can act on the cleaned data of other fields if needed. :param data: Dictionary of data to clean. :return: None
[ "For", "each", "field", "check", "to", "see", "if", "there", "is", "a", "clean_<name", ">", "method", ".", "If", "so", "run", "that", "method", "and", "set", "the", "returned", "value", "on", "the", "self", ".", "data", "dict", ".", "This", "happens", "after", "all", "validations", "so", "that", "each", "field", "can", "act", "on", "the", "cleaned", "data", "of", "other", "fields", "if", "needed", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L797-L814
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", "(", "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", "(", ")" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L864-L884
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", "=", "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", ")" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L886-L935
timster/peewee-validates
peewee_validates.py
ModelValidator.validate
def validate(self, data=None, only=None, exclude=None): """ Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. If data for a field is not provided in ``data`` then this validator will check against the provided model instance. This is usually the method you want to call after creating the validator instance. :param data: Dictionary of data to validate. :param only: List or tuple of fields to validate. :param exclude: List or tuple of fields to exclude from validation. :return: True if validation is successful, otherwise False. """ data = data or {} only = only or self._meta.only exclude = exclude or self._meta.exclude for name, field in self.instance._meta.fields.items(): if name in exclude or (only and name not in only): continue try: data.setdefault(name, getattr(self.instance, name, None)) except (peewee.DoesNotExist): if PEEWEE3: instance_data = self.instance.__data__ else: instance_data = self.instance._data data.setdefault(name, instance_data.get(name, None)) # This will set self.data which we should use from now on. super().validate(data=data, only=only, exclude=exclude) if not self.errors: self.perform_index_validation(self.data) return (not self.errors)
python
def validate(self, data=None, only=None, exclude=None): """ Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. If data for a field is not provided in ``data`` then this validator will check against the provided model instance. This is usually the method you want to call after creating the validator instance. :param data: Dictionary of data to validate. :param only: List or tuple of fields to validate. :param exclude: List or tuple of fields to exclude from validation. :return: True if validation is successful, otherwise False. """ data = data or {} only = only or self._meta.only exclude = exclude or self._meta.exclude for name, field in self.instance._meta.fields.items(): if name in exclude or (only and name not in only): continue try: data.setdefault(name, getattr(self.instance, name, None)) except (peewee.DoesNotExist): if PEEWEE3: instance_data = self.instance.__data__ else: instance_data = self.instance._data data.setdefault(name, instance_data.get(name, None)) # This will set self.data which we should use from now on. super().validate(data=data, only=only, exclude=exclude) if not self.errors: self.perform_index_validation(self.data) return (not self.errors)
[ "def", "validate", "(", "self", ",", "data", "=", "None", ",", "only", "=", "None", ",", "exclude", "=", "None", ")", ":", "data", "=", "data", "or", "{", "}", "only", "=", "only", "or", "self", ".", "_meta", ".", "only", "exclude", "=", "exclude", "or", "self", ".", "_meta", ".", "exclude", "for", "name", ",", "field", "in", "self", ".", "instance", ".", "_meta", ".", "fields", ".", "items", "(", ")", ":", "if", "name", "in", "exclude", "or", "(", "only", "and", "name", "not", "in", "only", ")", ":", "continue", "try", ":", "data", ".", "setdefault", "(", "name", ",", "getattr", "(", "self", ".", "instance", ",", "name", ",", "None", ")", ")", "except", "(", "peewee", ".", "DoesNotExist", ")", ":", "if", "PEEWEE3", ":", "instance_data", "=", "self", ".", "instance", ".", "__data__", "else", ":", "instance_data", "=", "self", ".", "instance", ".", "_data", "data", ".", "setdefault", "(", "name", ",", "instance_data", ".", "get", "(", "name", ",", "None", ")", ")", "# This will set self.data which we should use from now on.", "super", "(", ")", ".", "validate", "(", "data", "=", "data", ",", "only", "=", "only", ",", "exclude", "=", "exclude", ")", "if", "not", "self", ".", "errors", ":", "self", ".", "perform_index_validation", "(", "self", ".", "data", ")", "return", "(", "not", "self", ".", "errors", ")" ]
Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. If data for a field is not provided in ``data`` then this validator will check against the provided model instance. This is usually the method you want to call after creating the validator instance. :param data: Dictionary of data to validate. :param only: List or tuple of fields to validate. :param exclude: List or tuple of fields to exclude from validation. :return: True if validation is successful, otherwise False.
[ "Validate", "the", "data", "for", "all", "fields", "and", "return", "whether", "the", "validation", "was", "successful", ".", "This", "method", "also", "retains", "the", "validated", "data", "in", "self", ".", "data", "so", "that", "it", "can", "be", "accessed", "later", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L937-L974
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", ":", "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", ")" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L976-L1000
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", ".", "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" ]
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", "." ]
train
https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L1002-L1028
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", "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" ]
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", "padded", "with", "zero", "-", "bytes", "such", "that", "the", "return", "values", "length", "is", "a", "multiple", "of", "blocksize", "." ]
train
https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/bit_ops.py#L17-L33
kpdyer/libfte
fte/encrypter.py
Encrypter.encrypt
def encrypt(self, plaintext, iv_bytes=None): """Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``. Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``. The input ``plaintext`` can be ``''``. Raises ``PlaintextTypeError`` if input plaintext is not a string. """ if not isinstance(plaintext, str): raise PlaintextTypeError("Input plaintext is not of type string") if iv_bytes is None: iv_bytes = fte.bit_ops.random_bytes(Encrypter._IV_LENGTH) iv1_bytes = '\x01' + iv_bytes iv2_bytes = '\x02' + iv_bytes W1 = iv1_bytes W1 += fte.bit_ops.long_to_bytes( len(plaintext), Encrypter._MSG_COUNTER_LENGTH) W1 = self._ecb_enc_K1.encrypt(W1) counter_length_in_bits = AES.block_size * 8 counter_val = fte.bit_ops.bytes_to_long(iv2_bytes) counter = Counter.new( counter_length_in_bits, initial_value=counter_val) ctr_enc = AES.new(key=self.K1, mode=AES.MODE_CTR, IV='\x00' * 8 + iv2_bytes, counter=counter) W2 = ctr_enc.encrypt(plaintext) mac = HMAC.new(self.K2, W1 + W2, SHA512) T = mac.digest() T = T[:Encrypter._MAC_LENGTH] ciphertext = W1 + W2 + T return ciphertext
python
def encrypt(self, plaintext, iv_bytes=None): """Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``. Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``. The input ``plaintext`` can be ``''``. Raises ``PlaintextTypeError`` if input plaintext is not a string. """ if not isinstance(plaintext, str): raise PlaintextTypeError("Input plaintext is not of type string") if iv_bytes is None: iv_bytes = fte.bit_ops.random_bytes(Encrypter._IV_LENGTH) iv1_bytes = '\x01' + iv_bytes iv2_bytes = '\x02' + iv_bytes W1 = iv1_bytes W1 += fte.bit_ops.long_to_bytes( len(plaintext), Encrypter._MSG_COUNTER_LENGTH) W1 = self._ecb_enc_K1.encrypt(W1) counter_length_in_bits = AES.block_size * 8 counter_val = fte.bit_ops.bytes_to_long(iv2_bytes) counter = Counter.new( counter_length_in_bits, initial_value=counter_val) ctr_enc = AES.new(key=self.K1, mode=AES.MODE_CTR, IV='\x00' * 8 + iv2_bytes, counter=counter) W2 = ctr_enc.encrypt(plaintext) mac = HMAC.new(self.K2, W1 + W2, SHA512) T = mac.digest() T = T[:Encrypter._MAC_LENGTH] ciphertext = W1 + W2 + T return ciphertext
[ "def", "encrypt", "(", "self", ",", "plaintext", ",", "iv_bytes", "=", "None", ")", ":", "if", "not", "isinstance", "(", "plaintext", ",", "str", ")", ":", "raise", "PlaintextTypeError", "(", "\"Input plaintext is not of type string\"", ")", "if", "iv_bytes", "is", "None", ":", "iv_bytes", "=", "fte", ".", "bit_ops", ".", "random_bytes", "(", "Encrypter", ".", "_IV_LENGTH", ")", "iv1_bytes", "=", "'\\x01'", "+", "iv_bytes", "iv2_bytes", "=", "'\\x02'", "+", "iv_bytes", "W1", "=", "iv1_bytes", "W1", "+=", "fte", ".", "bit_ops", ".", "long_to_bytes", "(", "len", "(", "plaintext", ")", ",", "Encrypter", ".", "_MSG_COUNTER_LENGTH", ")", "W1", "=", "self", ".", "_ecb_enc_K1", ".", "encrypt", "(", "W1", ")", "counter_length_in_bits", "=", "AES", ".", "block_size", "*", "8", "counter_val", "=", "fte", ".", "bit_ops", ".", "bytes_to_long", "(", "iv2_bytes", ")", "counter", "=", "Counter", ".", "new", "(", "counter_length_in_bits", ",", "initial_value", "=", "counter_val", ")", "ctr_enc", "=", "AES", ".", "new", "(", "key", "=", "self", ".", "K1", ",", "mode", "=", "AES", ".", "MODE_CTR", ",", "IV", "=", "'\\x00'", "*", "8", "+", "iv2_bytes", ",", "counter", "=", "counter", ")", "W2", "=", "ctr_enc", ".", "encrypt", "(", "plaintext", ")", "mac", "=", "HMAC", ".", "new", "(", "self", ".", "K2", ",", "W1", "+", "W2", ",", "SHA512", ")", "T", "=", "mac", ".", "digest", "(", ")", "T", "=", "T", "[", ":", "Encrypter", ".", "_MAC_LENGTH", "]", "ciphertext", "=", "W1", "+", "W2", "+", "T", "return", "ciphertext" ]
Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``. Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``. The input ``plaintext`` can be ``''``. Raises ``PlaintextTypeError`` if input plaintext is not a string.
[ "Given", "plaintext", "returns", "a", "ciphertext", "encrypted", "with", "an", "authenticated", "-", "encryption", "scheme", "using", "the", "keys", "specified", "in", "__init__", ".", "Ciphertext", "expansion", "is", "deterministic", "the", "output", "ciphertext", "is", "always", "42", "bytes", "longer", "than", "the", "input", "plaintext", ".", "The", "input", "plaintext", "can", "be", "." ]
train
https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L84-L122
kpdyer/libfte
fte/encrypter.py
Encrypter.decrypt
def decrypt(self, ciphertext): """Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``. Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string. Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative message length greater than the ciphertext length. Raises ``UnrecoverableDecryptionError`` if invalid padding is detected, or the the MAC is invalid. """ if not isinstance(ciphertext, str): raise CiphertextTypeError("Input ciphertext is not of type string") plaintext_length = self.getPlaintextLen(ciphertext) ciphertext_length = self.getCiphertextLen(ciphertext) ciphertext_complete = (len(ciphertext) >= ciphertext_length) if ciphertext_complete is False: raise RecoverableDecryptionError('Incomplete ciphertext: ('+str(len(ciphertext))+' of '+str(ciphertext_length)+').') ciphertext = ciphertext[:ciphertext_length] W1_start = 0 W1_end = AES.block_size W1 = ciphertext[W1_start:W1_end] W2_start = AES.block_size W2_end = AES.block_size + plaintext_length W2 = ciphertext[W2_start:W2_end] T_start = AES.block_size + plaintext_length T_end = AES.block_size + plaintext_length + Encrypter._MAC_LENGTH T_expected = ciphertext[T_start:T_end] mac = HMAC.new(self.K2, W1 + W2, SHA512) T_actual = mac.digest()[:Encrypter._MAC_LENGTH] if T_expected != T_actual: raise UnrecoverableDecryptionError('Failed to verify MAC.') iv2_bytes = '\x02' + self._ecb_enc_K1.decrypt(W1)[1:8] counter_val = fte.bit_ops.bytes_to_long(iv2_bytes) counter_length_in_bits = AES.block_size * 8 counter = Counter.new( counter_length_in_bits, initial_value=counter_val) ctr_enc = AES.new(key=self.K1, mode=AES.MODE_CTR, IV='\x00' * 8 + iv2_bytes, counter=counter) plaintext = ctr_enc.decrypt(W2) return plaintext
python
def decrypt(self, ciphertext): """Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``. Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string. Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative message length greater than the ciphertext length. Raises ``UnrecoverableDecryptionError`` if invalid padding is detected, or the the MAC is invalid. """ if not isinstance(ciphertext, str): raise CiphertextTypeError("Input ciphertext is not of type string") plaintext_length = self.getPlaintextLen(ciphertext) ciphertext_length = self.getCiphertextLen(ciphertext) ciphertext_complete = (len(ciphertext) >= ciphertext_length) if ciphertext_complete is False: raise RecoverableDecryptionError('Incomplete ciphertext: ('+str(len(ciphertext))+' of '+str(ciphertext_length)+').') ciphertext = ciphertext[:ciphertext_length] W1_start = 0 W1_end = AES.block_size W1 = ciphertext[W1_start:W1_end] W2_start = AES.block_size W2_end = AES.block_size + plaintext_length W2 = ciphertext[W2_start:W2_end] T_start = AES.block_size + plaintext_length T_end = AES.block_size + plaintext_length + Encrypter._MAC_LENGTH T_expected = ciphertext[T_start:T_end] mac = HMAC.new(self.K2, W1 + W2, SHA512) T_actual = mac.digest()[:Encrypter._MAC_LENGTH] if T_expected != T_actual: raise UnrecoverableDecryptionError('Failed to verify MAC.') iv2_bytes = '\x02' + self._ecb_enc_K1.decrypt(W1)[1:8] counter_val = fte.bit_ops.bytes_to_long(iv2_bytes) counter_length_in_bits = AES.block_size * 8 counter = Counter.new( counter_length_in_bits, initial_value=counter_val) ctr_enc = AES.new(key=self.K1, mode=AES.MODE_CTR, IV='\x00' * 8 + iv2_bytes, counter=counter) plaintext = ctr_enc.decrypt(W2) return plaintext
[ "def", "decrypt", "(", "self", ",", "ciphertext", ")", ":", "if", "not", "isinstance", "(", "ciphertext", ",", "str", ")", ":", "raise", "CiphertextTypeError", "(", "\"Input ciphertext is not of type string\"", ")", "plaintext_length", "=", "self", ".", "getPlaintextLen", "(", "ciphertext", ")", "ciphertext_length", "=", "self", ".", "getCiphertextLen", "(", "ciphertext", ")", "ciphertext_complete", "=", "(", "len", "(", "ciphertext", ")", ">=", "ciphertext_length", ")", "if", "ciphertext_complete", "is", "False", ":", "raise", "RecoverableDecryptionError", "(", "'Incomplete ciphertext: ('", "+", "str", "(", "len", "(", "ciphertext", ")", ")", "+", "' of '", "+", "str", "(", "ciphertext_length", ")", "+", "').'", ")", "ciphertext", "=", "ciphertext", "[", ":", "ciphertext_length", "]", "W1_start", "=", "0", "W1_end", "=", "AES", ".", "block_size", "W1", "=", "ciphertext", "[", "W1_start", ":", "W1_end", "]", "W2_start", "=", "AES", ".", "block_size", "W2_end", "=", "AES", ".", "block_size", "+", "plaintext_length", "W2", "=", "ciphertext", "[", "W2_start", ":", "W2_end", "]", "T_start", "=", "AES", ".", "block_size", "+", "plaintext_length", "T_end", "=", "AES", ".", "block_size", "+", "plaintext_length", "+", "Encrypter", ".", "_MAC_LENGTH", "T_expected", "=", "ciphertext", "[", "T_start", ":", "T_end", "]", "mac", "=", "HMAC", ".", "new", "(", "self", ".", "K2", ",", "W1", "+", "W2", ",", "SHA512", ")", "T_actual", "=", "mac", ".", "digest", "(", ")", "[", ":", "Encrypter", ".", "_MAC_LENGTH", "]", "if", "T_expected", "!=", "T_actual", ":", "raise", "UnrecoverableDecryptionError", "(", "'Failed to verify MAC.'", ")", "iv2_bytes", "=", "'\\x02'", "+", "self", ".", "_ecb_enc_K1", ".", "decrypt", "(", "W1", ")", "[", "1", ":", "8", "]", "counter_val", "=", "fte", ".", "bit_ops", ".", "bytes_to_long", "(", "iv2_bytes", ")", "counter_length_in_bits", "=", "AES", ".", "block_size", "*", "8", "counter", "=", "Counter", ".", "new", "(", "counter_length_in_bits", ",", "initial_value", "=", "counter_val", ")", "ctr_enc", "=", "AES", ".", "new", "(", "key", "=", "self", ".", "K1", ",", "mode", "=", "AES", ".", "MODE_CTR", ",", "IV", "=", "'\\x00'", "*", "8", "+", "iv2_bytes", ",", "counter", "=", "counter", ")", "plaintext", "=", "ctr_enc", ".", "decrypt", "(", "W2", ")", "return", "plaintext" ]
Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``. Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string. Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative message length greater than the ciphertext length. Raises ``UnrecoverableDecryptionError`` if invalid padding is detected, or the the MAC is invalid.
[ "Given", "ciphertext", "returns", "a", "plaintext", "decrypted", "using", "the", "keys", "specified", "in", "__init__", "." ]
train
https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L124-L171
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", "." ]
train
https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L173-L179
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 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" ]
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", "." ]
train
https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L181-L205
hammerlab/stancache
stancache/stancache.py
_make_digest
def _make_digest(k, **kwargs): """ Creates a digest suitable for use within an :class:`phyles.FSCache` object from the key object `k`. >>> adict = {'a' : {'b':1}, 'f': []} >>> make_digest(adict) 'a2VKynHgDrUIm17r6BQ5QcA5XVmqpNBmiKbZ9kTu0A' """ result = list() result_dict = _make_digest_dict(k, **kwargs) if result_dict is None: return 'default' else: for (key, h) in sorted(result_dict.items()): result.append('{}_{}'.format(key, h)) return '.'.join(result)
python
def _make_digest(k, **kwargs): """ Creates a digest suitable for use within an :class:`phyles.FSCache` object from the key object `k`. >>> adict = {'a' : {'b':1}, 'f': []} >>> make_digest(adict) 'a2VKynHgDrUIm17r6BQ5QcA5XVmqpNBmiKbZ9kTu0A' """ result = list() result_dict = _make_digest_dict(k, **kwargs) if result_dict is None: return 'default' else: for (key, h) in sorted(result_dict.items()): result.append('{}_{}'.format(key, h)) return '.'.join(result)
[ "def", "_make_digest", "(", "k", ",", "*", "*", "kwargs", ")", ":", "result", "=", "list", "(", ")", "result_dict", "=", "_make_digest_dict", "(", "k", ",", "*", "*", "kwargs", ")", "if", "result_dict", "is", "None", ":", "return", "'default'", "else", ":", "for", "(", "key", ",", "h", ")", "in", "sorted", "(", "result_dict", ".", "items", "(", ")", ")", ":", "result", ".", "append", "(", "'{}_{}'", ".", "format", "(", "key", ",", "h", ")", ")", "return", "'.'", ".", "join", "(", "result", ")" ]
Creates a digest suitable for use within an :class:`phyles.FSCache` object from the key object `k`. >>> adict = {'a' : {'b':1}, 'f': []} >>> make_digest(adict) 'a2VKynHgDrUIm17r6BQ5QcA5XVmqpNBmiKbZ9kTu0A'
[ "Creates", "a", "digest", "suitable", "for", "use", "within", "an", ":", "class", ":", "phyles", ".", "FSCache", "object", "from", "the", "key", "object", "k", "." ]
train
https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/stancache.py#L106-L122
hammerlab/stancache
stancache/stancache.py
cached_model_file
def cached_model_file(model_name='anon_model', file=None, model_code=None, cache_dir=None, fit_cachefile=None, include_prefix=False): ''' Given model name & stan model code/file, compute path to cached stan fit if include_prefix, returns (model_prefix, model_cachefile) ''' cache_dir = _get_cache_dir(cache_dir) model_name = _sanitize_model_name(model_name) ## compute model prefix if file: model_code = _read_file(file) if model_code: model_prefix = '.'.join([model_name, _make_digest(dict(model_code=model_code, pystan=pystan.__version__, cython=Cython.__version__))]) else: ## handle case where no model code given if file is not None: logger.info('Note - no model code detected from given file: {}'.format(file)) else: logger.info('Note - no model code detected (neither file nor model_code given)') ## parse model_prefix from fit_cachefile if given if fit_cachefile: # if necessary, impute cache_dir from filepath if fit_cachefile != os.path.basename(fit_cachefile): cache_dir, fit_cachefile = os.path.split(os.path.abspath(fit_cachefile)) # if fit_cachefile given, parse to get fit_model_prefix fit_model_prefix = re.sub(string=os.path.basename(fit_cachefile), pattern='(.*).stanfit.*', repl='\\1') if model_code: if fit_model_prefix != model_prefix: logger.warning('Computed model prefix does not match that used to estimate model. Using prefix matching fit_cachefile') model_prefix = fit_model_prefix # compute path to model cachefile model_cachefile = '.'.join([model_prefix, 'stanmodel', 'pkl']) if include_prefix: return model_prefix, model_cachefile return model_cachefile
python
def cached_model_file(model_name='anon_model', file=None, model_code=None, cache_dir=None, fit_cachefile=None, include_prefix=False): ''' Given model name & stan model code/file, compute path to cached stan fit if include_prefix, returns (model_prefix, model_cachefile) ''' cache_dir = _get_cache_dir(cache_dir) model_name = _sanitize_model_name(model_name) ## compute model prefix if file: model_code = _read_file(file) if model_code: model_prefix = '.'.join([model_name, _make_digest(dict(model_code=model_code, pystan=pystan.__version__, cython=Cython.__version__))]) else: ## handle case where no model code given if file is not None: logger.info('Note - no model code detected from given file: {}'.format(file)) else: logger.info('Note - no model code detected (neither file nor model_code given)') ## parse model_prefix from fit_cachefile if given if fit_cachefile: # if necessary, impute cache_dir from filepath if fit_cachefile != os.path.basename(fit_cachefile): cache_dir, fit_cachefile = os.path.split(os.path.abspath(fit_cachefile)) # if fit_cachefile given, parse to get fit_model_prefix fit_model_prefix = re.sub(string=os.path.basename(fit_cachefile), pattern='(.*).stanfit.*', repl='\\1') if model_code: if fit_model_prefix != model_prefix: logger.warning('Computed model prefix does not match that used to estimate model. Using prefix matching fit_cachefile') model_prefix = fit_model_prefix # compute path to model cachefile model_cachefile = '.'.join([model_prefix, 'stanmodel', 'pkl']) if include_prefix: return model_prefix, model_cachefile return model_cachefile
[ "def", "cached_model_file", "(", "model_name", "=", "'anon_model'", ",", "file", "=", "None", ",", "model_code", "=", "None", ",", "cache_dir", "=", "None", ",", "fit_cachefile", "=", "None", ",", "include_prefix", "=", "False", ")", ":", "cache_dir", "=", "_get_cache_dir", "(", "cache_dir", ")", "model_name", "=", "_sanitize_model_name", "(", "model_name", ")", "## compute model prefix", "if", "file", ":", "model_code", "=", "_read_file", "(", "file", ")", "if", "model_code", ":", "model_prefix", "=", "'.'", ".", "join", "(", "[", "model_name", ",", "_make_digest", "(", "dict", "(", "model_code", "=", "model_code", ",", "pystan", "=", "pystan", ".", "__version__", ",", "cython", "=", "Cython", ".", "__version__", ")", ")", "]", ")", "else", ":", "## handle case where no model code given", "if", "file", "is", "not", "None", ":", "logger", ".", "info", "(", "'Note - no model code detected from given file: {}'", ".", "format", "(", "file", ")", ")", "else", ":", "logger", ".", "info", "(", "'Note - no model code detected (neither file nor model_code given)'", ")", "## parse model_prefix from fit_cachefile if given", "if", "fit_cachefile", ":", "# if necessary, impute cache_dir from filepath", "if", "fit_cachefile", "!=", "os", ".", "path", ".", "basename", "(", "fit_cachefile", ")", ":", "cache_dir", ",", "fit_cachefile", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "abspath", "(", "fit_cachefile", ")", ")", "# if fit_cachefile given, parse to get fit_model_prefix", "fit_model_prefix", "=", "re", ".", "sub", "(", "string", "=", "os", ".", "path", ".", "basename", "(", "fit_cachefile", ")", ",", "pattern", "=", "'(.*).stanfit.*'", ",", "repl", "=", "'\\\\1'", ")", "if", "model_code", ":", "if", "fit_model_prefix", "!=", "model_prefix", ":", "logger", ".", "warning", "(", "'Computed model prefix does not match that used to estimate model. Using prefix matching fit_cachefile'", ")", "model_prefix", "=", "fit_model_prefix", "# compute path to model cachefile", "model_cachefile", "=", "'.'", ".", "join", "(", "[", "model_prefix", ",", "'stanmodel'", ",", "'pkl'", "]", ")", "if", "include_prefix", ":", "return", "model_prefix", ",", "model_cachefile", "return", "model_cachefile" ]
Given model name & stan model code/file, compute path to cached stan fit if include_prefix, returns (model_prefix, model_cachefile)
[ "Given", "model", "name", "&", "stan", "model", "code", "/", "file", "compute", "path", "to", "cached", "stan", "fit", "if", "include_prefix", "returns", "(", "model_prefix", "model_cachefile", ")" ]
train
https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/stancache.py#L132-L167
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", ",", "include_modelfile", "=", "False", ",", "prefix_only", "=", "False", ",", "*", "*", "kwargs", ")", ":", "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" ]
Given inputs to cached_stan_fit, compute pickle file containing cached fit
[ "Given", "inputs", "to", "cached_stan_fit", "compute", "pickle", "file", "containing", "cached", "fit" ]
train
https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/stancache.py#L170-L185
hammerlab/stancache
stancache/stancache.py
_cached_stan_fit
def _cached_stan_fit(model_name='anon_model', file=None, model_code=None, force=False, cache_dir=None, cache_only=None, fit_cachefile=None, **kwargs): ''' Cache fit stan model, by storing pickled objects in filesystem per following warning: 07: UserWarning: Pickling fit objects is an experimental feature! The relevant StanModel instance must be pickled along with this fit object. When unpickling the StanModel must be unpickled first. pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) ''' if fit_cachefile and cache_only is None: cache_only = True model_cachefile, fit_cachefile = cached_stan_file(model_name=model_name, file=file, model_code=model_code, cache_dir=cache_dir, fit_cachefile=fit_cachefile, include_modelfile=True, **kwargs) cache_dir = _get_cache_dir(cache_dir) model_name = _sanitize_model_name(model_name) model_code = _get_model_code(model_code=model_code, file=file) logger.info('Step 1: Get compiled model code, possibly from cache') stan_model = cached(func=pystan.StanModel, cache_filename=model_cachefile, model_code=model_code, cache_dir=cache_dir, model_name=model_name, cache_only=cache_only, force=force) ## either pull fitted model from cache, or fit model logger.info('Step 2: Get posterior draws from model, possibly from cache') fit = cached(func=stan_model.sampling, cache_filename=fit_cachefile, cache_dir=cache_dir, force=force, cache_only=cache_only, **kwargs) return fit
python
def _cached_stan_fit(model_name='anon_model', file=None, model_code=None, force=False, cache_dir=None, cache_only=None, fit_cachefile=None, **kwargs): ''' Cache fit stan model, by storing pickled objects in filesystem per following warning: 07: UserWarning: Pickling fit objects is an experimental feature! The relevant StanModel instance must be pickled along with this fit object. When unpickling the StanModel must be unpickled first. pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) ''' if fit_cachefile and cache_only is None: cache_only = True model_cachefile, fit_cachefile = cached_stan_file(model_name=model_name, file=file, model_code=model_code, cache_dir=cache_dir, fit_cachefile=fit_cachefile, include_modelfile=True, **kwargs) cache_dir = _get_cache_dir(cache_dir) model_name = _sanitize_model_name(model_name) model_code = _get_model_code(model_code=model_code, file=file) logger.info('Step 1: Get compiled model code, possibly from cache') stan_model = cached(func=pystan.StanModel, cache_filename=model_cachefile, model_code=model_code, cache_dir=cache_dir, model_name=model_name, cache_only=cache_only, force=force) ## either pull fitted model from cache, or fit model logger.info('Step 2: Get posterior draws from model, possibly from cache') fit = cached(func=stan_model.sampling, cache_filename=fit_cachefile, cache_dir=cache_dir, force=force, cache_only=cache_only, **kwargs) return fit
[ "def", "_cached_stan_fit", "(", "model_name", "=", "'anon_model'", ",", "file", "=", "None", ",", "model_code", "=", "None", ",", "force", "=", "False", ",", "cache_dir", "=", "None", ",", "cache_only", "=", "None", ",", "fit_cachefile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "fit_cachefile", "and", "cache_only", "is", "None", ":", "cache_only", "=", "True", "model_cachefile", ",", "fit_cachefile", "=", "cached_stan_file", "(", "model_name", "=", "model_name", ",", "file", "=", "file", ",", "model_code", "=", "model_code", ",", "cache_dir", "=", "cache_dir", ",", "fit_cachefile", "=", "fit_cachefile", ",", "include_modelfile", "=", "True", ",", "*", "*", "kwargs", ")", "cache_dir", "=", "_get_cache_dir", "(", "cache_dir", ")", "model_name", "=", "_sanitize_model_name", "(", "model_name", ")", "model_code", "=", "_get_model_code", "(", "model_code", "=", "model_code", ",", "file", "=", "file", ")", "logger", ".", "info", "(", "'Step 1: Get compiled model code, possibly from cache'", ")", "stan_model", "=", "cached", "(", "func", "=", "pystan", ".", "StanModel", ",", "cache_filename", "=", "model_cachefile", ",", "model_code", "=", "model_code", ",", "cache_dir", "=", "cache_dir", ",", "model_name", "=", "model_name", ",", "cache_only", "=", "cache_only", ",", "force", "=", "force", ")", "## either pull fitted model from cache, or fit model", "logger", ".", "info", "(", "'Step 2: Get posterior draws from model, possibly from cache'", ")", "fit", "=", "cached", "(", "func", "=", "stan_model", ".", "sampling", ",", "cache_filename", "=", "fit_cachefile", ",", "cache_dir", "=", "cache_dir", ",", "force", "=", "force", ",", "cache_only", "=", "cache_only", ",", "*", "*", "kwargs", ")", "return", "fit" ]
Cache fit stan model, by storing pickled objects in filesystem per following warning: 07: UserWarning: Pickling fit objects is an experimental feature! The relevant StanModel instance must be pickled along with this fit object. When unpickling the StanModel must be unpickled first. pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
[ "Cache", "fit", "stan", "model", "by", "storing", "pickled", "objects", "in", "filesystem", "per", "following", "warning", ":", "07", ":", "UserWarning", ":", "Pickling", "fit", "objects", "is", "an", "experimental", "feature!", "The", "relevant", "StanModel", "instance", "must", "be", "pickled", "along", "with", "this", "fit", "object", ".", "When", "unpickling", "the", "StanModel", "must", "be", "unpickled", "first", ".", "pickle", ".", "dump", "(", "obj", "f", "pickle", ".", "HIGHEST_PROTOCOL", ")" ]
train
https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/stancache.py#L204-L240
oscarlazoarjona/fast
build/lib/fast/graphic.py
fit_lorentizan
def fit_lorentizan(curve,p0=None,N_points=1000): '''Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess. It returns a curve with N_points.''' def lorentzian(x,x0,A,gamma): return A*gamma**2/((x-x0)**2+gamma**2) N=len(curve) x=[curve[i][0] for i in range(N)] y=[curve[i][1] for i in range(N)] from scipy.optimize import curve_fit popt,pcov = curve_fit(lorentzian,x,y,p0=p0) x0=popt[0]; A=popt[1]; gamma=popt[2] a=x[0]; b=x[-1] x_step=(b-a)/(N_points-1) x_fit=[a+i*x_step for i in range(N_points)] fited_curve=[(xi,lorentzian(xi,x0,A,gamma)) for xi in x_fit] return fited_curve,A,x0,gamma
python
def fit_lorentizan(curve,p0=None,N_points=1000): '''Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess. It returns a curve with N_points.''' def lorentzian(x,x0,A,gamma): return A*gamma**2/((x-x0)**2+gamma**2) N=len(curve) x=[curve[i][0] for i in range(N)] y=[curve[i][1] for i in range(N)] from scipy.optimize import curve_fit popt,pcov = curve_fit(lorentzian,x,y,p0=p0) x0=popt[0]; A=popt[1]; gamma=popt[2] a=x[0]; b=x[-1] x_step=(b-a)/(N_points-1) x_fit=[a+i*x_step for i in range(N_points)] fited_curve=[(xi,lorentzian(xi,x0,A,gamma)) for xi in x_fit] return fited_curve,A,x0,gamma
[ "def", "fit_lorentizan", "(", "curve", ",", "p0", "=", "None", ",", "N_points", "=", "1000", ")", ":", "def", "lorentzian", "(", "x", ",", "x0", ",", "A", ",", "gamma", ")", ":", "return", "A", "*", "gamma", "**", "2", "/", "(", "(", "x", "-", "x0", ")", "**", "2", "+", "gamma", "**", "2", ")", "N", "=", "len", "(", "curve", ")", "x", "=", "[", "curve", "[", "i", "]", "[", "0", "]", "for", "i", "in", "range", "(", "N", ")", "]", "y", "=", "[", "curve", "[", "i", "]", "[", "1", "]", "for", "i", "in", "range", "(", "N", ")", "]", "from", "scipy", ".", "optimize", "import", "curve_fit", "popt", ",", "pcov", "=", "curve_fit", "(", "lorentzian", ",", "x", ",", "y", ",", "p0", "=", "p0", ")", "x0", "=", "popt", "[", "0", "]", "A", "=", "popt", "[", "1", "]", "gamma", "=", "popt", "[", "2", "]", "a", "=", "x", "[", "0", "]", "b", "=", "x", "[", "-", "1", "]", "x_step", "=", "(", "b", "-", "a", ")", "/", "(", "N_points", "-", "1", ")", "x_fit", "=", "[", "a", "+", "i", "*", "x_step", "for", "i", "in", "range", "(", "N_points", ")", "]", "fited_curve", "=", "[", "(", "xi", ",", "lorentzian", "(", "xi", ",", "x0", ",", "A", ",", "gamma", ")", ")", "for", "xi", "in", "x_fit", "]", "return", "fited_curve", ",", "A", ",", "x0", ",", "gamma" ]
Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess. It returns a curve with N_points.
[ "Fits", "a", "lorentzian", "curve", "using", "p0", "=", "[", "x0", "A", "gamma", "]", "as", "an", "initial", "guess", ".", "It", "returns", "a", "curve", "with", "N_points", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/graphic.py#L406-L422
oscarlazoarjona/fast
fast/electric_field.py
electric_field_amplitude_gaussian
def electric_field_amplitude_gaussian(P, sigmax, sigmay=None, Omega=1.0e6, units="ad-hoc"): """Return the amplitude of the electric field for a Gaussian beam. This the amplitude at the center of a laser beam of power P (in Watts) and\ a Gaussian intensity distribution of standard deviations sigmax, sigmay\ (in meters). The value of E0 is given in rescaled units according to the\ frequency scale Omega (in Hertz) understood as absolute frequency\ (as opposed to angular frequency). >>> print(electric_field_amplitude_gaussian(0.001, 0.001)) 19.6861467587 """ e0 = hbar*Omega/(e*a0) # This is the electric field scale. if sigmay is None: sigmay = sigmax E0 = sqrt((c*mu0*P)/(2*Pi))/sqrt(sigmax*sigmay) if units == "ad-hoc": E0 = E0/e0 return E0
python
def electric_field_amplitude_gaussian(P, sigmax, sigmay=None, Omega=1.0e6, units="ad-hoc"): """Return the amplitude of the electric field for a Gaussian beam. This the amplitude at the center of a laser beam of power P (in Watts) and\ a Gaussian intensity distribution of standard deviations sigmax, sigmay\ (in meters). The value of E0 is given in rescaled units according to the\ frequency scale Omega (in Hertz) understood as absolute frequency\ (as opposed to angular frequency). >>> print(electric_field_amplitude_gaussian(0.001, 0.001)) 19.6861467587 """ e0 = hbar*Omega/(e*a0) # This is the electric field scale. if sigmay is None: sigmay = sigmax E0 = sqrt((c*mu0*P)/(2*Pi))/sqrt(sigmax*sigmay) if units == "ad-hoc": E0 = E0/e0 return E0
[ "def", "electric_field_amplitude_gaussian", "(", "P", ",", "sigmax", ",", "sigmay", "=", "None", ",", "Omega", "=", "1.0e6", ",", "units", "=", "\"ad-hoc\"", ")", ":", "e0", "=", "hbar", "*", "Omega", "/", "(", "e", "*", "a0", ")", "# This is the electric field scale.\r", "if", "sigmay", "is", "None", ":", "sigmay", "=", "sigmax", "E0", "=", "sqrt", "(", "(", "c", "*", "mu0", "*", "P", ")", "/", "(", "2", "*", "Pi", ")", ")", "/", "sqrt", "(", "sigmax", "*", "sigmay", ")", "if", "units", "==", "\"ad-hoc\"", ":", "E0", "=", "E0", "/", "e0", "return", "E0" ]
Return the amplitude of the electric field for a Gaussian beam. This the amplitude at the center of a laser beam of power P (in Watts) and\ a Gaussian intensity distribution of standard deviations sigmax, sigmay\ (in meters). The value of E0 is given in rescaled units according to the\ frequency scale Omega (in Hertz) understood as absolute frequency\ (as opposed to angular frequency). >>> print(electric_field_amplitude_gaussian(0.001, 0.001)) 19.6861467587
[ "Return", "the", "amplitude", "of", "the", "electric", "field", "for", "a", "Gaussian", "beam", ".", "This", "the", "amplitude", "at", "the", "center", "of", "a", "laser", "beam", "of", "power", "P", "(", "in", "Watts", ")", "and", "\\", "a", "Gaussian", "intensity", "distribution", "of", "standard", "deviations", "sigmax", "sigmay", "\\", "(", "in", "meters", ")", ".", "The", "value", "of", "E0", "is", "given", "in", "rescaled", "units", "according", "to", "the", "\\", "frequency", "scale", "Omega", "(", "in", "Hertz", ")", "understood", "as", "absolute", "frequency", "\\", "(", "as", "opposed", "to", "angular", "frequency", ")", ".", ">>>", "print", "(", "electric_field_amplitude_gaussian", "(", "0", ".", "001", "0", ".", "001", "))", "19", ".", "6861467587" ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L318-L338
oscarlazoarjona/fast
fast/electric_field.py
electric_field_amplitude_top
def electric_field_amplitude_top(P, a, Omega=1e6, units="ad-hoc"): """Return the amplitude of the electric field for a top hat beam. This is the amplitude of a laser beam of power P (in Watts) and a top-hat\ intensity distribution of radius a (in meters). The value of E0 is given in\ rescaled units according to the frequency scale Omega (in Hertz)\ understood as absolute frequency (as opposed to angular frequency). >>> print(electric_field_amplitude_top(0.001, 0.001)) 27.8404157371 """ e0 = hbar*Omega/(e*a0) # This is the electric field scale. E0 = sqrt((c*mu0*P)/(Pi*a**2)) if units == "ad-hoc": E0 = E0/e0 return E0
python
def electric_field_amplitude_top(P, a, Omega=1e6, units="ad-hoc"): """Return the amplitude of the electric field for a top hat beam. This is the amplitude of a laser beam of power P (in Watts) and a top-hat\ intensity distribution of radius a (in meters). The value of E0 is given in\ rescaled units according to the frequency scale Omega (in Hertz)\ understood as absolute frequency (as opposed to angular frequency). >>> print(electric_field_amplitude_top(0.001, 0.001)) 27.8404157371 """ e0 = hbar*Omega/(e*a0) # This is the electric field scale. E0 = sqrt((c*mu0*P)/(Pi*a**2)) if units == "ad-hoc": E0 = E0/e0 return E0
[ "def", "electric_field_amplitude_top", "(", "P", ",", "a", ",", "Omega", "=", "1e6", ",", "units", "=", "\"ad-hoc\"", ")", ":", "e0", "=", "hbar", "*", "Omega", "/", "(", "e", "*", "a0", ")", "# This is the electric field scale.\r", "E0", "=", "sqrt", "(", "(", "c", "*", "mu0", "*", "P", ")", "/", "(", "Pi", "*", "a", "**", "2", ")", ")", "if", "units", "==", "\"ad-hoc\"", ":", "E0", "=", "E0", "/", "e0", "return", "E0" ]
Return the amplitude of the electric field for a top hat beam. This is the amplitude of a laser beam of power P (in Watts) and a top-hat\ intensity distribution of radius a (in meters). The value of E0 is given in\ rescaled units according to the frequency scale Omega (in Hertz)\ understood as absolute frequency (as opposed to angular frequency). >>> print(electric_field_amplitude_top(0.001, 0.001)) 27.8404157371
[ "Return", "the", "amplitude", "of", "the", "electric", "field", "for", "a", "top", "hat", "beam", ".", "This", "is", "the", "amplitude", "of", "a", "laser", "beam", "of", "power", "P", "(", "in", "Watts", ")", "and", "a", "top", "-", "hat", "\\", "intensity", "distribution", "of", "radius", "a", "(", "in", "meters", ")", ".", "The", "value", "of", "E0", "is", "given", "in", "\\", "rescaled", "units", "according", "to", "the", "frequency", "scale", "Omega", "(", "in", "Hertz", ")", "\\", "understood", "as", "absolute", "frequency", "(", "as", "opposed", "to", "angular", "frequency", ")", ".", ">>>", "print", "(", "electric_field_amplitude_top", "(", "0", ".", "001", "0", ".", "001", "))", "27", ".", "8404157371" ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L341-L357
oscarlazoarjona/fast
fast/electric_field.py
electric_field_amplitude_intensity
def electric_field_amplitude_intensity(s0, Isat=16.6889462814, Omega=1e6, units="ad-hoc"): """Return the amplitude of the electric field for saturation parameter. This is at a given saturation parameter s0=I/Isat, where I0 is by default \ Isat=16.6889462814 m/m^2 is the saturation intensity of the D2 line of \ rubidium for circularly polarized light. Optionally, a frequency scale \ `Omega` can be provided. >>> print(electric_field_amplitude_intensity(1.0, units="ad-hoc")) 9.0152984553 >>> print(electric_field_amplitude_intensity(1.0, Omega=1.0, units="SI")) 112.135917207 >>> print(electric_field_amplitude_intensity(1.0, units="SI")) 0.000112135917207 """ E0_sat = sqrt(2*mu0*c*Isat)/Omega if units == "ad-hoc": e0 = hbar/(e*a0) # This is the electric field scale. E0_sat = E0_sat/e0 return E0_sat*sqrt(s0)
python
def electric_field_amplitude_intensity(s0, Isat=16.6889462814, Omega=1e6, units="ad-hoc"): """Return the amplitude of the electric field for saturation parameter. This is at a given saturation parameter s0=I/Isat, where I0 is by default \ Isat=16.6889462814 m/m^2 is the saturation intensity of the D2 line of \ rubidium for circularly polarized light. Optionally, a frequency scale \ `Omega` can be provided. >>> print(electric_field_amplitude_intensity(1.0, units="ad-hoc")) 9.0152984553 >>> print(electric_field_amplitude_intensity(1.0, Omega=1.0, units="SI")) 112.135917207 >>> print(electric_field_amplitude_intensity(1.0, units="SI")) 0.000112135917207 """ E0_sat = sqrt(2*mu0*c*Isat)/Omega if units == "ad-hoc": e0 = hbar/(e*a0) # This is the electric field scale. E0_sat = E0_sat/e0 return E0_sat*sqrt(s0)
[ "def", "electric_field_amplitude_intensity", "(", "s0", ",", "Isat", "=", "16.6889462814", ",", "Omega", "=", "1e6", ",", "units", "=", "\"ad-hoc\"", ")", ":", "E0_sat", "=", "sqrt", "(", "2", "*", "mu0", "*", "c", "*", "Isat", ")", "/", "Omega", "if", "units", "==", "\"ad-hoc\"", ":", "e0", "=", "hbar", "/", "(", "e", "*", "a0", ")", "# This is the electric field scale.\r", "E0_sat", "=", "E0_sat", "/", "e0", "return", "E0_sat", "*", "sqrt", "(", "s0", ")" ]
Return the amplitude of the electric field for saturation parameter. This is at a given saturation parameter s0=I/Isat, where I0 is by default \ Isat=16.6889462814 m/m^2 is the saturation intensity of the D2 line of \ rubidium for circularly polarized light. Optionally, a frequency scale \ `Omega` can be provided. >>> print(electric_field_amplitude_intensity(1.0, units="ad-hoc")) 9.0152984553 >>> print(electric_field_amplitude_intensity(1.0, Omega=1.0, units="SI")) 112.135917207 >>> print(electric_field_amplitude_intensity(1.0, units="SI")) 0.000112135917207
[ "Return", "the", "amplitude", "of", "the", "electric", "field", "for", "saturation", "parameter", ".", "This", "is", "at", "a", "given", "saturation", "parameter", "s0", "=", "I", "/", "Isat", "where", "I0", "is", "by", "default", "\\", "Isat", "=", "16", ".", "6889462814", "m", "/", "m^2", "is", "the", "saturation", "intensity", "of", "the", "D2", "line", "of", "\\", "rubidium", "for", "circularly", "polarized", "light", ".", "Optionally", "a", "frequency", "scale", "\\", "Omega", "can", "be", "provided", ".", ">>>", "print", "(", "electric_field_amplitude_intensity", "(", "1", ".", "0", "units", "=", "ad", "-", "hoc", "))", "9", ".", "0152984553", ">>>", "print", "(", "electric_field_amplitude_intensity", "(", "1", ".", "0", "Omega", "=", "1", ".", "0", "units", "=", "SI", "))", "112", ".", "135917207", ">>>", "print", "(", "electric_field_amplitude_intensity", "(", "1", ".", "0", "units", "=", "SI", "))", "0", ".", "000112135917207" ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L360-L383
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", ",", "*", "*", "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" ]
r"""The plotting function for MOT fields.
[ "r", "The", "plotting", "function", "for", "MOT", "fields", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L307-L315
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L45-L59
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 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" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L71-L96
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='", "+", "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" ]
Return i, j, s for any given mu.
[ "Return", "i", "j", "s", "for", "any", "given", "mu", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L99-L118
oscarlazoarjona/fast
fast/misc.py
read_result
def read_result(path, name, i=None, j=None, s=0, N=None, excluded_mu=[], use_netcdf=True, clone=None): r"""This function reads the results stored in path under file name.dat returning them as a list of N^2 lists of the form [frequency, rho22, rho33, ... rho_N,N-1]. Alternatively it can return only two lists [frequency, rho_i,j,s] where s must be 1 for the real part and -1 for the imaginary part. """ if clone is not None: clone = '_'+str(clone) else: clone = '' if use_netcdf: ncfile = Dataset(path+name+clone+'.nc', 'r') matrix = ncfile.variables['matrix'][:] vector = ncfile.variables['vector'][:] Nrho, n_points = len(matrix), len(matrix[0]) ncfile.close() if i is not None: mu = Mu(i, j, s, N, excluded_mu) if sage_included: return [(vector[k], matrix[mu-1][k]) for k in range(n_points)] else: return vector, matrix[mu-1] else: return [vector] + [matrix[k] for k in range(Nrho)] # ln=[for i in range(m)] else: r = file(path+name+clone+'.dat', 'r') l = r.readlines() r.close() try: ln = [[float(num) for num in li.split()] for li in l] except: print(num) print([l[0]]) print([l[-2]]) print([l[-1]]) raise ValueError if i is not None: mu = Mu(i, j, s, N, excluded_mu) if sage_included: return [(li[0], li[mu]) for li in ln] else: x = [li[0] for li in ln] y = [li[mu] for li in ln] return x, y else: dat = [[ln[ii][0] for ii in range(len(ln))]] dat += [[ln[ii][mu+1] for ii in range(len(ln))] for mu in range(N**2-1)] return dat
python
def read_result(path, name, i=None, j=None, s=0, N=None, excluded_mu=[], use_netcdf=True, clone=None): r"""This function reads the results stored in path under file name.dat returning them as a list of N^2 lists of the form [frequency, rho22, rho33, ... rho_N,N-1]. Alternatively it can return only two lists [frequency, rho_i,j,s] where s must be 1 for the real part and -1 for the imaginary part. """ if clone is not None: clone = '_'+str(clone) else: clone = '' if use_netcdf: ncfile = Dataset(path+name+clone+'.nc', 'r') matrix = ncfile.variables['matrix'][:] vector = ncfile.variables['vector'][:] Nrho, n_points = len(matrix), len(matrix[0]) ncfile.close() if i is not None: mu = Mu(i, j, s, N, excluded_mu) if sage_included: return [(vector[k], matrix[mu-1][k]) for k in range(n_points)] else: return vector, matrix[mu-1] else: return [vector] + [matrix[k] for k in range(Nrho)] # ln=[for i in range(m)] else: r = file(path+name+clone+'.dat', 'r') l = r.readlines() r.close() try: ln = [[float(num) for num in li.split()] for li in l] except: print(num) print([l[0]]) print([l[-2]]) print([l[-1]]) raise ValueError if i is not None: mu = Mu(i, j, s, N, excluded_mu) if sage_included: return [(li[0], li[mu]) for li in ln] else: x = [li[0] for li in ln] y = [li[mu] for li in ln] return x, y else: dat = [[ln[ii][0] for ii in range(len(ln))]] dat += [[ln[ii][mu+1] for ii in range(len(ln))] for mu in range(N**2-1)] return dat
[ "def", "read_result", "(", "path", ",", "name", ",", "i", "=", "None", ",", "j", "=", "None", ",", "s", "=", "0", ",", "N", "=", "None", ",", "excluded_mu", "=", "[", "]", ",", "use_netcdf", "=", "True", ",", "clone", "=", "None", ")", ":", "if", "clone", "is", "not", "None", ":", "clone", "=", "'_'", "+", "str", "(", "clone", ")", "else", ":", "clone", "=", "''", "if", "use_netcdf", ":", "ncfile", "=", "Dataset", "(", "path", "+", "name", "+", "clone", "+", "'.nc'", ",", "'r'", ")", "matrix", "=", "ncfile", ".", "variables", "[", "'matrix'", "]", "[", ":", "]", "vector", "=", "ncfile", ".", "variables", "[", "'vector'", "]", "[", ":", "]", "Nrho", ",", "n_points", "=", "len", "(", "matrix", ")", ",", "len", "(", "matrix", "[", "0", "]", ")", "ncfile", ".", "close", "(", ")", "if", "i", "is", "not", "None", ":", "mu", "=", "Mu", "(", "i", ",", "j", ",", "s", ",", "N", ",", "excluded_mu", ")", "if", "sage_included", ":", "return", "[", "(", "vector", "[", "k", "]", ",", "matrix", "[", "mu", "-", "1", "]", "[", "k", "]", ")", "for", "k", "in", "range", "(", "n_points", ")", "]", "else", ":", "return", "vector", ",", "matrix", "[", "mu", "-", "1", "]", "else", ":", "return", "[", "vector", "]", "+", "[", "matrix", "[", "k", "]", "for", "k", "in", "range", "(", "Nrho", ")", "]", "# ln=[for i in range(m)]", "else", ":", "r", "=", "file", "(", "path", "+", "name", "+", "clone", "+", "'.dat'", ",", "'r'", ")", "l", "=", "r", ".", "readlines", "(", ")", "r", ".", "close", "(", ")", "try", ":", "ln", "=", "[", "[", "float", "(", "num", ")", "for", "num", "in", "li", ".", "split", "(", ")", "]", "for", "li", "in", "l", "]", "except", ":", "print", "(", "num", ")", "print", "(", "[", "l", "[", "0", "]", "]", ")", "print", "(", "[", "l", "[", "-", "2", "]", "]", ")", "print", "(", "[", "l", "[", "-", "1", "]", "]", ")", "raise", "ValueError", "if", "i", "is", "not", "None", ":", "mu", "=", "Mu", "(", "i", ",", "j", ",", "s", ",", "N", ",", "excluded_mu", ")", "if", "sage_included", ":", "return", "[", "(", "li", "[", "0", "]", ",", "li", "[", "mu", "]", ")", "for", "li", "in", "ln", "]", "else", ":", "x", "=", "[", "li", "[", "0", "]", "for", "li", "in", "ln", "]", "y", "=", "[", "li", "[", "mu", "]", "for", "li", "in", "ln", "]", "return", "x", ",", "y", "else", ":", "dat", "=", "[", "[", "ln", "[", "ii", "]", "[", "0", "]", "for", "ii", "in", "range", "(", "len", "(", "ln", ")", ")", "]", "]", "dat", "+=", "[", "[", "ln", "[", "ii", "]", "[", "mu", "+", "1", "]", "for", "ii", "in", "range", "(", "len", "(", "ln", ")", ")", "]", "for", "mu", "in", "range", "(", "N", "**", "2", "-", "1", ")", "]", "return", "dat" ]
r"""This function reads the results stored in path under file name.dat returning them as a list of N^2 lists of the form [frequency, rho22, rho33, ... rho_N,N-1]. Alternatively it can return only two lists [frequency, rho_i,j,s] where s must be 1 for the real part and -1 for the imaginary part.
[ "r", "This", "function", "reads", "the", "results", "stored", "in", "path", "under", "file", "name", ".", "dat", "returning", "them", "as", "a", "list", "of", "N^2", "lists", "of", "the", "form", "[", "frequency", "rho22", "rho33", "...", "rho_N", "N", "-", "1", "]", ".", "Alternatively", "it", "can", "return", "only", "two", "lists", "[", "frequency", "rho_i", "j", "s", "]", "where", "s", "must", "be", "1", "for", "the", "real", "part", "and", "-", "1", "for", "the", "imaginary", "part", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L121-L176
oscarlazoarjona/fast
fast/misc.py
find_phase_transformation
def find_phase_transformation(Ne, Nl, r, Lij, verbose=0, return_equations=False, **kwds): """This function returns a phase transformation specified as a list of lenght Ne whose elements correspond to each theta_i. Each element is a list of length Nl which specifies the coefficients multiplying each optical frequency omega^l. So for instance [[1,1],[1,0],[0,0]] means theta_1=omega^1+omega^2 theta_2=omega^1 theta_3=0. """ # We first define the needed variables _omega_laser = [Symbol('omega_laser'+str(l+1)) for l in range(Nl)] _theta = [Symbol('theta'+str(i+1)) for i in range(Ne)] # We find all the equations that the specified problem has to fulfil. eqs = [] for i in range(Ne): for j in range(i+1, Ne): if type(r[0]) == list: if (r[0][i][j] != 0) or (r[1][i][j] != 0) or (r[2][i][j] != 0): for l in range(Nl): if l+1 in Lij[i][j]: eqs += [_omega_laser[l] + _theta[j] - _theta[i]] else: if (r[0][i, j] != 0) or (r[1][i, j] != 0) or (r[2][i, j] != 0): for l in range(Nl): if l+1 in Lij[i][j]: eqs += [_omega_laser[l] + _theta[j] - _theta[i]] if return_equations: return eqs sol = solve(eqs, _theta, dict=True)[0] for i in range(Ne): if _theta[i] not in sol.keys(): sol.update({_theta[i]: _theta[i]}) sol_simple = {_theta[i]: sol[_theta[i]]-sol[_theta[-1]] for i in range(Ne)} sol = [] for i in range(Ne): soli = [] for l in range(Nl): soli += [diff(sol_simple[_theta[i]], _omega_laser[l])] sol += [soli] return sol
python
def find_phase_transformation(Ne, Nl, r, Lij, verbose=0, return_equations=False, **kwds): """This function returns a phase transformation specified as a list of lenght Ne whose elements correspond to each theta_i. Each element is a list of length Nl which specifies the coefficients multiplying each optical frequency omega^l. So for instance [[1,1],[1,0],[0,0]] means theta_1=omega^1+omega^2 theta_2=omega^1 theta_3=0. """ # We first define the needed variables _omega_laser = [Symbol('omega_laser'+str(l+1)) for l in range(Nl)] _theta = [Symbol('theta'+str(i+1)) for i in range(Ne)] # We find all the equations that the specified problem has to fulfil. eqs = [] for i in range(Ne): for j in range(i+1, Ne): if type(r[0]) == list: if (r[0][i][j] != 0) or (r[1][i][j] != 0) or (r[2][i][j] != 0): for l in range(Nl): if l+1 in Lij[i][j]: eqs += [_omega_laser[l] + _theta[j] - _theta[i]] else: if (r[0][i, j] != 0) or (r[1][i, j] != 0) or (r[2][i, j] != 0): for l in range(Nl): if l+1 in Lij[i][j]: eqs += [_omega_laser[l] + _theta[j] - _theta[i]] if return_equations: return eqs sol = solve(eqs, _theta, dict=True)[0] for i in range(Ne): if _theta[i] not in sol.keys(): sol.update({_theta[i]: _theta[i]}) sol_simple = {_theta[i]: sol[_theta[i]]-sol[_theta[-1]] for i in range(Ne)} sol = [] for i in range(Ne): soli = [] for l in range(Nl): soli += [diff(sol_simple[_theta[i]], _omega_laser[l])] sol += [soli] return sol
[ "def", "find_phase_transformation", "(", "Ne", ",", "Nl", ",", "r", ",", "Lij", ",", "verbose", "=", "0", ",", "return_equations", "=", "False", ",", "*", "*", "kwds", ")", ":", "# We first define the needed variables", "_omega_laser", "=", "[", "Symbol", "(", "'omega_laser'", "+", "str", "(", "l", "+", "1", ")", ")", "for", "l", "in", "range", "(", "Nl", ")", "]", "_theta", "=", "[", "Symbol", "(", "'theta'", "+", "str", "(", "i", "+", "1", ")", ")", "for", "i", "in", "range", "(", "Ne", ")", "]", "# We find all the equations that the specified problem has to fulfil.", "eqs", "=", "[", "]", "for", "i", "in", "range", "(", "Ne", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "Ne", ")", ":", "if", "type", "(", "r", "[", "0", "]", ")", "==", "list", ":", "if", "(", "r", "[", "0", "]", "[", "i", "]", "[", "j", "]", "!=", "0", ")", "or", "(", "r", "[", "1", "]", "[", "i", "]", "[", "j", "]", "!=", "0", ")", "or", "(", "r", "[", "2", "]", "[", "i", "]", "[", "j", "]", "!=", "0", ")", ":", "for", "l", "in", "range", "(", "Nl", ")", ":", "if", "l", "+", "1", "in", "Lij", "[", "i", "]", "[", "j", "]", ":", "eqs", "+=", "[", "_omega_laser", "[", "l", "]", "+", "_theta", "[", "j", "]", "-", "_theta", "[", "i", "]", "]", "else", ":", "if", "(", "r", "[", "0", "]", "[", "i", ",", "j", "]", "!=", "0", ")", "or", "(", "r", "[", "1", "]", "[", "i", ",", "j", "]", "!=", "0", ")", "or", "(", "r", "[", "2", "]", "[", "i", ",", "j", "]", "!=", "0", ")", ":", "for", "l", "in", "range", "(", "Nl", ")", ":", "if", "l", "+", "1", "in", "Lij", "[", "i", "]", "[", "j", "]", ":", "eqs", "+=", "[", "_omega_laser", "[", "l", "]", "+", "_theta", "[", "j", "]", "-", "_theta", "[", "i", "]", "]", "if", "return_equations", ":", "return", "eqs", "sol", "=", "solve", "(", "eqs", ",", "_theta", ",", "dict", "=", "True", ")", "[", "0", "]", "for", "i", "in", "range", "(", "Ne", ")", ":", "if", "_theta", "[", "i", "]", "not", "in", "sol", ".", "keys", "(", ")", ":", "sol", ".", "update", "(", "{", "_theta", "[", "i", "]", ":", "_theta", "[", "i", "]", "}", ")", "sol_simple", "=", "{", "_theta", "[", "i", "]", ":", "sol", "[", "_theta", "[", "i", "]", "]", "-", "sol", "[", "_theta", "[", "-", "1", "]", "]", "for", "i", "in", "range", "(", "Ne", ")", "}", "sol", "=", "[", "]", "for", "i", "in", "range", "(", "Ne", ")", ":", "soli", "=", "[", "]", "for", "l", "in", "range", "(", "Nl", ")", ":", "soli", "+=", "[", "diff", "(", "sol_simple", "[", "_theta", "[", "i", "]", "]", ",", "_omega_laser", "[", "l", "]", ")", "]", "sol", "+=", "[", "soli", "]", "return", "sol" ]
This function returns a phase transformation specified as a list of lenght Ne whose elements correspond to each theta_i. Each element is a list of length Nl which specifies the coefficients multiplying each optical frequency omega^l. So for instance [[1,1],[1,0],[0,0]] means theta_1=omega^1+omega^2 theta_2=omega^1 theta_3=0.
[ "This", "function", "returns", "a", "phase", "transformation", "specified", "as", "a", "list", "of", "lenght", "Ne", "whose", "elements", "correspond", "to", "each", "theta_i", ".", "Each", "element", "is", "a", "list", "of", "length", "Nl", "which", "specifies", "the", "coefficients", "multiplying", "each", "optical", "frequency", "omega^l", ".", "So", "for", "instance", "[[", "1", "1", "]", "[", "1", "0", "]", "[", "0", "0", "]]", "means" ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L228-L275
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", "(", "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" ]
r"""Get the correspondance between degenerate and nondegenerate schemes.
[ "r", "Get", "the", "correspondance", "between", "degenerate", "and", "nondegenerate", "schemes", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L278-L299
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", "==", "0", ":", "return", "z", "else", ":", "if", "s", "==", "1", ":", "return", "z", ".", "real", "elif", "s", "==", "-", "1", ":", "return", "z", ".", "imag", "elif", "s", "==", "0", ":", "return", "z" ]
r"""Get the real or imaginary part of a complex number.
[ "r", "Get", "the", "real", "or", "imaginary", "part", "of", "a", "complex", "number", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L302-L312
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L315-L319
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", ")", ":", "combn", "=", "[", "]", "for", "c0", "in", "comb", ":", "for", "cl", "in", "range", "(", "lists", "[", "l", "]", ")", ":", "combn", "+=", "[", "c0", "[", ":", "]", "+", "[", "cl", "]", "]", "comb", "=", "combn", "[", ":", "]", "return", "comb" ]
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", "of", "all", "possible", "combinations", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L322-L335
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", "=", "[", "[", "]", "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" ]
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", "and", "the", "jth", "element", "=", "-", "1", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L338-L359
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", "(", "[", "(", "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" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L602-L613
oscarlazoarjona/fast
fast/misc.py
write_equations_code
def write_equations_code(path, name, laser, omega, gamma, r, Lij, states=None, excluded_mu=[], verbose=1): r"""Write code for the equations.""" Ne = len(omega[0]) Nl = len(laser) N_excluded_mu = len(excluded_mu) if states is None: states = range(1, Ne+1) omega_rescaled = omega[:] # We determine whether it is possible to eliminate explicit time-dependance theta = find_phase_transformation(Ne, Nl, r, Lij) # We construct the correspondence i <-> I between degenerate and # non-degenerate indices. i_d, I_nd, Nnd = calculate_iI_correspondence(omega) # We find the non-degenerate detunings detunings, detuningsij = laser_detunings(Lij, Nl, i_d, I_nd, Nnd) aux = find_omega_min(omega_rescaled, Nl, detuningsij, i_d, I_nd) omega_min, omega_min_indices = aux detuning_indices = [len(detunings[i]) for i in range(Nl)] Nd = sum([len(detunings[l]) for l in range(Nl)]) combinations = detuning_combinations(detuning_indices) ########################################################################## # We add the code to caculate the detunings for each laser. code0 = '' code0 += ' !We calculate the detunings.\n' # We find the minimal frequency corresponding to each laser. code0 += ' !The list of detunings has the following meaning:\n' conta = 0 for ll in range(Nl): for kk in range(len(detuningsij[ll])): conta += 1 ii, jj = detuningsij[ll][kk] if states is None: code0 += ' !detuning('+str(conta)+')= delta^'+str(ll+1)+'_' code0 += str(i_d(ii+1))+','+str(i_d(jj+1))+'\n' else: state_i = str(states[i_d(ii+1)-1])[5:] state_j = str(states[i_d(jj+1)-1])[5:] code0 += ' !detuning('+str(conta)+')= delta^'+str(ll+1)+'_' code0 += state_i+','+state_j+'\n' det_index = 1 for l in range(Nl): # omega0 = omega_min[l] i_min, j_min = omega_min_indices[l] for ii, jj in detuningsij[l]: code0 += ' detuning('+str(det_index)+')=' # code0+=format_double(omega0-omega_rescaled[ii][jj])+'+(detuning_knob('+str(l+1)+'))\n' code0 += 'detuning_knob('+str(l+1)+') ' code0 += '-('+format_double( omega_rescaled[i_d(ii+1)-1][i_d(i_min+1)-1])+')' code0 += '-('+format_double( omega_rescaled[i_d(j_min+1)-1][i_d(jj+1)-1])+')\n' det_index += 1 code0 += '\n' ########################################################################### # We add here the code for the equations ########################################################################### code = '' ########################################################################### # We need to check that the resulting matrix A doesn't have any # row or column made of zeroes. If there is such a row or column # it means that for that particular i(mu),j(mu) or i(nu),j(nu) # neither the hamiltonian part of the correspondin equation nor the # phase transformation part nor the decay part were nonzero # (at least for the given light polarizations). # In this cases it is necessary to re-calculate all of the problem # without the corresponding mu components of A. # Also the right hand side will be checked for non zero elements. # Now we start the check for these exceptions. row_check = [False for mu in range(Ne**2-1-N_excluded_mu)] col_check = [False for nu in range(Ne**2-1-N_excluded_mu)] rhs_check = [False for nu in range(Ne**2-1-N_excluded_mu)] ########################################################################## # We give the code to calculate the independent vector. code += ' !We calculate the independent vector.\n' for i in range(2, Ne+1-N_excluded_mu): for s in [1, -1]: nu = Mu(i, 1, s, Ne, excluded_mu) rhs_check[nu-1] = True for l in Lij[i-1][0]: dp = dot_product(laser[l-1], 1, r, i, 1) dp = s*part(dp, -s) if dp != 0: code += ' B('+str(nu)+',1)=B('+str(nu)+',1) +E0('+str(l) code += ')*('+format_double(dp)+')\n' code += '\n' code += ' B=B/2.0d0\n\n' # +str(1/sqrt(2.0))+'d0\n\n' ########################################################################### # We give the code to calculate the equations for populations. code += ' !We calculate the equations for populations.\n' for i in range(2, Ne+1): mu = Mu(i, i, 1, Ne, excluded_mu) for k in range(1, Ne+1): if k < i: for l in Lij[k-1][i-1]: dp1 = dot_product(laser[l-1], -1, r, k, i) dp2 = dot_product(laser[l-1], 1, r, i, k) real_coef = part(dp1-dp2, -1) imag_coef = part(dp1+dp2, 1) if real_coef != 0: nu = Mu(i, k, 1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '+E0('+str(l)+')*('+format_double(real_coef) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True if imag_coef != 0: nu = Mu(i, k, -1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '+E0('+str(l)+')*('+format_double(imag_coef) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True if k > i: for l in Lij[k-1][i-1]: dp1 = dot_product(laser[l-1], -1, r, i, k) dp2 = dot_product(laser[l-1], 1, r, k, i) real_coef = -part(dp1-dp2, -1) imag_coef = -part(dp1+dp2, 1) if real_coef != 0: nu = Mu(k, i, 1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '+E0('+str(l)+')*('+format_double(real_coef) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True if imag_coef != 0: nu = Mu(k, i, -1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '+E0('+str(l)+')*('+format_double(imag_coef) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True code += '\n' ########################################################################### # We give the code to calculate the equations for coherences # given in equations with label "stationary-coherences" code += ' !The code to calculate the equations for coherences.\n' for i in range(2, Ne+1): for j in range(1, i): for s in [1, -1]: mu = Mu(i, j, s, Ne, excluded_mu) for k in range(1, Ne+1): for l in Lij[k-1][j-1]: if k < i: if k < j: dp = s*dot_product(laser[l-1], -1, r, k, j) dp1 = part(dp, -s) dp2 = part(s*dp, +s) nu = Mu(i, k, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True col_check[nu-1] = True nu = Mu(i, k, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp2)+')\n' row_check[mu-1] = True col_check[nu-1] = True elif k > j: dp = s*dot_product(laser[l-1], +1, r, k, j) dp1 = part(dp, -s) dp2 = part(s*dp, s) nu = Mu(i, k, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True col_check[nu-1] = True nu = Mu(i, k, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp2)+')\n' row_check[mu-1] = True col_check[nu-1] = True elif k > i: dp = s*dot_product(laser[l-1], 1, r, k, j) dp1 = part(dp, -s) dp2 = part(-s*dp, s) nu = Mu(k, i, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True; col_check[nu-1] = True nu = Mu(k, i, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*('+format_double(dp2) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True for l in Lij[i-1][k-1]: if k > j: if k > i: dp = -s*dot_product(laser[l-1], -1, r, i, k) dp1 = part(dp, -s) dp2 = part(s*dp, s) nu = Mu(k, j, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True col_check[nu-1] = True nu = Mu(k, j, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp2)+')\n' row_check[mu-1] = True col_check[nu-1] = True elif k < i: dp = -s*dot_product(laser[l-1], 1, r, i, k) dp1 = part(dp, -s) dp2 = part(s*dp, s) nu = Mu(k, j, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True col_check[nu-1] = True nu = Mu(k, j, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp2)+')\n' row_check[mu-1] = True col_check[nu-1] = True elif k < j: dp = -s*dot_product(laser[l-1], 1, r, i, k) dp1 = part(dp, -s) dp2 = part(-s*dp, s) nu = Mu(j, k, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True; col_check[nu-1] = True nu = Mu(j, k, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*('+format_double(dp2) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True for l in Lij[i-1][j-1]: dp = s*part(dot_product(laser[l-1], 1, r, i, j), -s) nu = Mu(i, i, 1, Ne, excluded_mu) if dp != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*('+format_double(dp)+')\n' row_check[mu-1] = True; col_check[nu-1] = True nu = Mu(j, j, 1, Ne, excluded_mu) if nu == 0: for n in range(1, Ne): code += ' A('+str(mu)+','+str(n)+')=A(' code += str(mu)+','+str(n)+')' code += '+E0('+str(l)+')*('+format_double(dp) code += ')\n' row_check[mu-1] = True; col_check[n-1] = True else: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*('+format_double(-dp) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True code += '\n' code += ' A=A/2.0d0\n\n' # +str(1/sqrt(2.0))+'d0\n\n' ########################################################################### # We add the terms associated with the phase transformation. code += ' !We calculate the terms associated with the phase ' code += 'transformation.\n' # for i in range(2,10): for i in range(2, Ne+1): for j in range(1, i): extra = Theta(i, j, theta, omega_rescaled, omega_min, detunings, detuningsij, combinations, detuning_indices, Lij, i_d, I_nd, Nnd, verbose=verbose, states=states) if extra != '': for s in [1, -1]: mu = Mu(i, j, s, Ne, excluded_mu) nu = Mu(i, j, -s, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' if s == 1: code += '-('+str(extra)+')\n' elif s == -1: code += '+('+str(extra)+')\n' row_check[mu-1] = True; col_check[nu-1] = True code += '\n' ########################################################################### # We add the terms associated with spontaneous decay. code += ' !We calculate the terms associated with spontaneous decay.\n' # First for populations. for i in range(2, Ne+1): mu = Mu(i, i, 1, Ne, excluded_mu) for k in range(1, Ne+1): gams = 0 if k < i: gams += gamma[i-1][k-1] elif k > i: nu = Mu(k, k, 1, Ne, excluded_mu) ga = gamma[i-1][k-1] if ga != 0: code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '-('+format_double(ga)+')\n' row_check[mu-1] = True; col_check[nu-1] = True if gams != 0: code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True # And now for coherences for i in range(1, Ne+1): for j in range(1, i): gams = gamma[i-1][j-1]/2 if gams != 0: for a in range(i+1, Ne+1): mu = Mu(a, i, 1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True mu = Mu(a, i, -1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True for b in range(1, i): mu = Mu(i, b, 1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True mu = Mu(i, b, -1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True code += '\n' code = code0+code Nd = sum([len(detunings[l]) for l in range(Nl)]) res = [code, Nd, row_check, col_check, rhs_check, Ne, N_excluded_mu, states, omega_min, detuningsij, omega_rescaled] return res
python
def write_equations_code(path, name, laser, omega, gamma, r, Lij, states=None, excluded_mu=[], verbose=1): r"""Write code for the equations.""" Ne = len(omega[0]) Nl = len(laser) N_excluded_mu = len(excluded_mu) if states is None: states = range(1, Ne+1) omega_rescaled = omega[:] # We determine whether it is possible to eliminate explicit time-dependance theta = find_phase_transformation(Ne, Nl, r, Lij) # We construct the correspondence i <-> I between degenerate and # non-degenerate indices. i_d, I_nd, Nnd = calculate_iI_correspondence(omega) # We find the non-degenerate detunings detunings, detuningsij = laser_detunings(Lij, Nl, i_d, I_nd, Nnd) aux = find_omega_min(omega_rescaled, Nl, detuningsij, i_d, I_nd) omega_min, omega_min_indices = aux detuning_indices = [len(detunings[i]) for i in range(Nl)] Nd = sum([len(detunings[l]) for l in range(Nl)]) combinations = detuning_combinations(detuning_indices) ########################################################################## # We add the code to caculate the detunings for each laser. code0 = '' code0 += ' !We calculate the detunings.\n' # We find the minimal frequency corresponding to each laser. code0 += ' !The list of detunings has the following meaning:\n' conta = 0 for ll in range(Nl): for kk in range(len(detuningsij[ll])): conta += 1 ii, jj = detuningsij[ll][kk] if states is None: code0 += ' !detuning('+str(conta)+')= delta^'+str(ll+1)+'_' code0 += str(i_d(ii+1))+','+str(i_d(jj+1))+'\n' else: state_i = str(states[i_d(ii+1)-1])[5:] state_j = str(states[i_d(jj+1)-1])[5:] code0 += ' !detuning('+str(conta)+')= delta^'+str(ll+1)+'_' code0 += state_i+','+state_j+'\n' det_index = 1 for l in range(Nl): # omega0 = omega_min[l] i_min, j_min = omega_min_indices[l] for ii, jj in detuningsij[l]: code0 += ' detuning('+str(det_index)+')=' # code0+=format_double(omega0-omega_rescaled[ii][jj])+'+(detuning_knob('+str(l+1)+'))\n' code0 += 'detuning_knob('+str(l+1)+') ' code0 += '-('+format_double( omega_rescaled[i_d(ii+1)-1][i_d(i_min+1)-1])+')' code0 += '-('+format_double( omega_rescaled[i_d(j_min+1)-1][i_d(jj+1)-1])+')\n' det_index += 1 code0 += '\n' ########################################################################### # We add here the code for the equations ########################################################################### code = '' ########################################################################### # We need to check that the resulting matrix A doesn't have any # row or column made of zeroes. If there is such a row or column # it means that for that particular i(mu),j(mu) or i(nu),j(nu) # neither the hamiltonian part of the correspondin equation nor the # phase transformation part nor the decay part were nonzero # (at least for the given light polarizations). # In this cases it is necessary to re-calculate all of the problem # without the corresponding mu components of A. # Also the right hand side will be checked for non zero elements. # Now we start the check for these exceptions. row_check = [False for mu in range(Ne**2-1-N_excluded_mu)] col_check = [False for nu in range(Ne**2-1-N_excluded_mu)] rhs_check = [False for nu in range(Ne**2-1-N_excluded_mu)] ########################################################################## # We give the code to calculate the independent vector. code += ' !We calculate the independent vector.\n' for i in range(2, Ne+1-N_excluded_mu): for s in [1, -1]: nu = Mu(i, 1, s, Ne, excluded_mu) rhs_check[nu-1] = True for l in Lij[i-1][0]: dp = dot_product(laser[l-1], 1, r, i, 1) dp = s*part(dp, -s) if dp != 0: code += ' B('+str(nu)+',1)=B('+str(nu)+',1) +E0('+str(l) code += ')*('+format_double(dp)+')\n' code += '\n' code += ' B=B/2.0d0\n\n' # +str(1/sqrt(2.0))+'d0\n\n' ########################################################################### # We give the code to calculate the equations for populations. code += ' !We calculate the equations for populations.\n' for i in range(2, Ne+1): mu = Mu(i, i, 1, Ne, excluded_mu) for k in range(1, Ne+1): if k < i: for l in Lij[k-1][i-1]: dp1 = dot_product(laser[l-1], -1, r, k, i) dp2 = dot_product(laser[l-1], 1, r, i, k) real_coef = part(dp1-dp2, -1) imag_coef = part(dp1+dp2, 1) if real_coef != 0: nu = Mu(i, k, 1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '+E0('+str(l)+')*('+format_double(real_coef) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True if imag_coef != 0: nu = Mu(i, k, -1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '+E0('+str(l)+')*('+format_double(imag_coef) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True if k > i: for l in Lij[k-1][i-1]: dp1 = dot_product(laser[l-1], -1, r, i, k) dp2 = dot_product(laser[l-1], 1, r, k, i) real_coef = -part(dp1-dp2, -1) imag_coef = -part(dp1+dp2, 1) if real_coef != 0: nu = Mu(k, i, 1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '+E0('+str(l)+')*('+format_double(real_coef) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True if imag_coef != 0: nu = Mu(k, i, -1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '+E0('+str(l)+')*('+format_double(imag_coef) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True code += '\n' ########################################################################### # We give the code to calculate the equations for coherences # given in equations with label "stationary-coherences" code += ' !The code to calculate the equations for coherences.\n' for i in range(2, Ne+1): for j in range(1, i): for s in [1, -1]: mu = Mu(i, j, s, Ne, excluded_mu) for k in range(1, Ne+1): for l in Lij[k-1][j-1]: if k < i: if k < j: dp = s*dot_product(laser[l-1], -1, r, k, j) dp1 = part(dp, -s) dp2 = part(s*dp, +s) nu = Mu(i, k, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True col_check[nu-1] = True nu = Mu(i, k, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp2)+')\n' row_check[mu-1] = True col_check[nu-1] = True elif k > j: dp = s*dot_product(laser[l-1], +1, r, k, j) dp1 = part(dp, -s) dp2 = part(s*dp, s) nu = Mu(i, k, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True col_check[nu-1] = True nu = Mu(i, k, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp2)+')\n' row_check[mu-1] = True col_check[nu-1] = True elif k > i: dp = s*dot_product(laser[l-1], 1, r, k, j) dp1 = part(dp, -s) dp2 = part(-s*dp, s) nu = Mu(k, i, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True; col_check[nu-1] = True nu = Mu(k, i, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*('+format_double(dp2) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True for l in Lij[i-1][k-1]: if k > j: if k > i: dp = -s*dot_product(laser[l-1], -1, r, i, k) dp1 = part(dp, -s) dp2 = part(s*dp, s) nu = Mu(k, j, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True col_check[nu-1] = True nu = Mu(k, j, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp2)+')\n' row_check[mu-1] = True col_check[nu-1] = True elif k < i: dp = -s*dot_product(laser[l-1], 1, r, i, k) dp1 = part(dp, -s) dp2 = part(s*dp, s) nu = Mu(k, j, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True col_check[nu-1] = True nu = Mu(k, j, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu) code += ')=A('+str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp2)+')\n' row_check[mu-1] = True col_check[nu-1] = True elif k < j: dp = -s*dot_product(laser[l-1], 1, r, i, k) dp1 = part(dp, -s) dp2 = part(-s*dp, s) nu = Mu(j, k, 1, Ne, excluded_mu) if dp1 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*(' code += format_double(dp1)+')\n' row_check[mu-1] = True; col_check[nu-1] = True nu = Mu(j, k, -1, Ne, excluded_mu) if dp2 != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*('+format_double(dp2) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True for l in Lij[i-1][j-1]: dp = s*part(dot_product(laser[l-1], 1, r, i, j), -s) nu = Mu(i, i, 1, Ne, excluded_mu) if dp != 0: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*('+format_double(dp)+')\n' row_check[mu-1] = True; col_check[nu-1] = True nu = Mu(j, j, 1, Ne, excluded_mu) if nu == 0: for n in range(1, Ne): code += ' A('+str(mu)+','+str(n)+')=A(' code += str(mu)+','+str(n)+')' code += '+E0('+str(l)+')*('+format_double(dp) code += ')\n' row_check[mu-1] = True; col_check[n-1] = True else: code += ' A('+str(mu)+','+str(nu)+')=A(' code += str(mu)+','+str(nu)+')' code += '+E0('+str(l)+')*('+format_double(-dp) code += ')\n' row_check[mu-1] = True; col_check[nu-1] = True code += '\n' code += ' A=A/2.0d0\n\n' # +str(1/sqrt(2.0))+'d0\n\n' ########################################################################### # We add the terms associated with the phase transformation. code += ' !We calculate the terms associated with the phase ' code += 'transformation.\n' # for i in range(2,10): for i in range(2, Ne+1): for j in range(1, i): extra = Theta(i, j, theta, omega_rescaled, omega_min, detunings, detuningsij, combinations, detuning_indices, Lij, i_d, I_nd, Nnd, verbose=verbose, states=states) if extra != '': for s in [1, -1]: mu = Mu(i, j, s, Ne, excluded_mu) nu = Mu(i, j, -s, Ne, excluded_mu) code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' if s == 1: code += '-('+str(extra)+')\n' elif s == -1: code += '+('+str(extra)+')\n' row_check[mu-1] = True; col_check[nu-1] = True code += '\n' ########################################################################### # We add the terms associated with spontaneous decay. code += ' !We calculate the terms associated with spontaneous decay.\n' # First for populations. for i in range(2, Ne+1): mu = Mu(i, i, 1, Ne, excluded_mu) for k in range(1, Ne+1): gams = 0 if k < i: gams += gamma[i-1][k-1] elif k > i: nu = Mu(k, k, 1, Ne, excluded_mu) ga = gamma[i-1][k-1] if ga != 0: code += ' A('+str(mu)+','+str(nu)+')=A('+str(mu)+',' code += str(nu)+')' code += '-('+format_double(ga)+')\n' row_check[mu-1] = True; col_check[nu-1] = True if gams != 0: code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True # And now for coherences for i in range(1, Ne+1): for j in range(1, i): gams = gamma[i-1][j-1]/2 if gams != 0: for a in range(i+1, Ne+1): mu = Mu(a, i, 1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True mu = Mu(a, i, -1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True for b in range(1, i): mu = Mu(i, b, 1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True mu = Mu(i, b, -1, Ne, excluded_mu) code += ' A('+str(mu)+','+str(mu)+')=A('+str(mu)+',' code += str(mu)+')' code += '-('+format_double(gams)+')\n' row_check[mu-1] = True; col_check[mu-1] = True code += '\n' code = code0+code Nd = sum([len(detunings[l]) for l in range(Nl)]) res = [code, Nd, row_check, col_check, rhs_check, Ne, N_excluded_mu, states, omega_min, detuningsij, omega_rescaled] return res
[ "def", "write_equations_code", "(", "path", ",", "name", ",", "laser", ",", "omega", ",", "gamma", ",", "r", ",", "Lij", ",", "states", "=", "None", ",", "excluded_mu", "=", "[", "]", ",", "verbose", "=", "1", ")", ":", "Ne", "=", "len", "(", "omega", "[", "0", "]", ")", "Nl", "=", "len", "(", "laser", ")", "N_excluded_mu", "=", "len", "(", "excluded_mu", ")", "if", "states", "is", "None", ":", "states", "=", "range", "(", "1", ",", "Ne", "+", "1", ")", "omega_rescaled", "=", "omega", "[", ":", "]", "# We determine whether it is possible to eliminate explicit time-dependance", "theta", "=", "find_phase_transformation", "(", "Ne", ",", "Nl", ",", "r", ",", "Lij", ")", "# We construct the correspondence i <-> I between degenerate and", "# non-degenerate indices.", "i_d", ",", "I_nd", ",", "Nnd", "=", "calculate_iI_correspondence", "(", "omega", ")", "# We find the non-degenerate detunings", "detunings", ",", "detuningsij", "=", "laser_detunings", "(", "Lij", ",", "Nl", ",", "i_d", ",", "I_nd", ",", "Nnd", ")", "aux", "=", "find_omega_min", "(", "omega_rescaled", ",", "Nl", ",", "detuningsij", ",", "i_d", ",", "I_nd", ")", "omega_min", ",", "omega_min_indices", "=", "aux", "detuning_indices", "=", "[", "len", "(", "detunings", "[", "i", "]", ")", "for", "i", "in", "range", "(", "Nl", ")", "]", "Nd", "=", "sum", "(", "[", "len", "(", "detunings", "[", "l", "]", ")", "for", "l", "in", "range", "(", "Nl", ")", "]", ")", "combinations", "=", "detuning_combinations", "(", "detuning_indices", ")", "##########################################################################", "# We add the code to caculate the detunings for each laser.", "code0", "=", "''", "code0", "+=", "'\t!We calculate the detunings.\\n'", "# We find the minimal frequency corresponding to each laser.", "code0", "+=", "'\t!The list of detunings has the following meaning:\\n'", "conta", "=", "0", "for", "ll", "in", "range", "(", "Nl", ")", ":", "for", "kk", "in", "range", "(", "len", "(", "detuningsij", "[", "ll", "]", ")", ")", ":", "conta", "+=", "1", "ii", ",", "jj", "=", "detuningsij", "[", "ll", "]", "[", "kk", "]", "if", "states", "is", "None", ":", "code0", "+=", "'\t!detuning('", "+", "str", "(", "conta", ")", "+", "')= delta^'", "+", "str", "(", "ll", "+", "1", ")", "+", "'_'", "code0", "+=", "str", "(", "i_d", "(", "ii", "+", "1", ")", ")", "+", "','", "+", "str", "(", "i_d", "(", "jj", "+", "1", ")", ")", "+", "'\\n'", "else", ":", "state_i", "=", "str", "(", "states", "[", "i_d", "(", "ii", "+", "1", ")", "-", "1", "]", ")", "[", "5", ":", "]", "state_j", "=", "str", "(", "states", "[", "i_d", "(", "jj", "+", "1", ")", "-", "1", "]", ")", "[", "5", ":", "]", "code0", "+=", "'\t!detuning('", "+", "str", "(", "conta", ")", "+", "')= delta^'", "+", "str", "(", "ll", "+", "1", ")", "+", "'_'", "code0", "+=", "state_i", "+", "','", "+", "state_j", "+", "'\\n'", "det_index", "=", "1", "for", "l", "in", "range", "(", "Nl", ")", ":", "# omega0 = omega_min[l]", "i_min", ",", "j_min", "=", "omega_min_indices", "[", "l", "]", "for", "ii", ",", "jj", "in", "detuningsij", "[", "l", "]", ":", "code0", "+=", "'\tdetuning('", "+", "str", "(", "det_index", ")", "+", "')='", "# code0+=format_double(omega0-omega_rescaled[ii][jj])+'+(detuning_knob('+str(l+1)+'))\\n'", "code0", "+=", "'detuning_knob('", "+", "str", "(", "l", "+", "1", ")", "+", "') '", "code0", "+=", "'-('", "+", "format_double", "(", "omega_rescaled", "[", "i_d", "(", "ii", "+", "1", ")", "-", "1", "]", "[", "i_d", "(", "i_min", "+", "1", ")", "-", "1", "]", ")", "+", "')'", "code0", "+=", "'-('", "+", "format_double", "(", "omega_rescaled", "[", "i_d", "(", "j_min", "+", "1", ")", "-", "1", "]", "[", "i_d", "(", "jj", "+", "1", ")", "-", "1", "]", ")", "+", "')\\n'", "det_index", "+=", "1", "code0", "+=", "'\\n'", "###########################################################################", "# We add here the code for the equations", "###########################################################################", "code", "=", "''", "###########################################################################", "# We need to check that the resulting matrix A doesn't have any", "# row or column made of zeroes. If there is such a row or column", "# it means that for that particular i(mu),j(mu) or i(nu),j(nu)", "# neither the hamiltonian part of the correspondin equation nor the", "# phase transformation part nor the decay part were nonzero", "# (at least for the given light polarizations).", "# In this cases it is necessary to re-calculate all of the problem", "# without the corresponding mu components of A.", "# Also the right hand side will be checked for non zero elements.", "# Now we start the check for these exceptions.", "row_check", "=", "[", "False", "for", "mu", "in", "range", "(", "Ne", "**", "2", "-", "1", "-", "N_excluded_mu", ")", "]", "col_check", "=", "[", "False", "for", "nu", "in", "range", "(", "Ne", "**", "2", "-", "1", "-", "N_excluded_mu", ")", "]", "rhs_check", "=", "[", "False", "for", "nu", "in", "range", "(", "Ne", "**", "2", "-", "1", "-", "N_excluded_mu", ")", "]", "##########################################################################", "# We give the code to calculate the independent vector.", "code", "+=", "'\t!We calculate the independent vector.\\n'", "for", "i", "in", "range", "(", "2", ",", "Ne", "+", "1", "-", "N_excluded_mu", ")", ":", "for", "s", "in", "[", "1", ",", "-", "1", "]", ":", "nu", "=", "Mu", "(", "i", ",", "1", ",", "s", ",", "Ne", ",", "excluded_mu", ")", "rhs_check", "[", "nu", "-", "1", "]", "=", "True", "for", "l", "in", "Lij", "[", "i", "-", "1", "]", "[", "0", "]", ":", "dp", "=", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "1", ",", "r", ",", "i", ",", "1", ")", "dp", "=", "s", "*", "part", "(", "dp", ",", "-", "s", ")", "if", "dp", "!=", "0", ":", "code", "+=", "'\tB('", "+", "str", "(", "nu", ")", "+", "',1)=B('", "+", "str", "(", "nu", ")", "+", "',1) +E0('", "+", "str", "(", "l", ")", "code", "+=", "')*('", "+", "format_double", "(", "dp", ")", "+", "')\\n'", "code", "+=", "'\\n'", "code", "+=", "'\tB=B/2.0d0\\n\\n'", "# +str(1/sqrt(2.0))+'d0\\n\\n'", "###########################################################################", "# We give the code to calculate the equations for populations.", "code", "+=", "'\t!We calculate the equations for populations.\\n'", "for", "i", "in", "range", "(", "2", ",", "Ne", "+", "1", ")", ":", "mu", "=", "Mu", "(", "i", ",", "i", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "for", "k", "in", "range", "(", "1", ",", "Ne", "+", "1", ")", ":", "if", "k", "<", "i", ":", "for", "l", "in", "Lij", "[", "k", "-", "1", "]", "[", "i", "-", "1", "]", ":", "dp1", "=", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "-", "1", ",", "r", ",", "k", ",", "i", ")", "dp2", "=", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "1", ",", "r", ",", "i", ",", "k", ")", "real_coef", "=", "part", "(", "dp1", "-", "dp2", ",", "-", "1", ")", "imag_coef", "=", "part", "(", "dp1", "+", "dp2", ",", "1", ")", "if", "real_coef", "!=", "0", ":", "nu", "=", "Mu", "(", "i", ",", "k", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "+", "format_double", "(", "real_coef", ")", "code", "+=", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "if", "imag_coef", "!=", "0", ":", "nu", "=", "Mu", "(", "i", ",", "k", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "+", "format_double", "(", "imag_coef", ")", "code", "+=", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "if", "k", ">", "i", ":", "for", "l", "in", "Lij", "[", "k", "-", "1", "]", "[", "i", "-", "1", "]", ":", "dp1", "=", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "-", "1", ",", "r", ",", "i", ",", "k", ")", "dp2", "=", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "1", ",", "r", ",", "k", ",", "i", ")", "real_coef", "=", "-", "part", "(", "dp1", "-", "dp2", ",", "-", "1", ")", "imag_coef", "=", "-", "part", "(", "dp1", "+", "dp2", ",", "1", ")", "if", "real_coef", "!=", "0", ":", "nu", "=", "Mu", "(", "k", ",", "i", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "+", "format_double", "(", "real_coef", ")", "code", "+=", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "if", "imag_coef", "!=", "0", ":", "nu", "=", "Mu", "(", "k", ",", "i", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "+", "format_double", "(", "imag_coef", ")", "code", "+=", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "code", "+=", "'\\n'", "###########################################################################", "# We give the code to calculate the equations for coherences", "# given in equations with label \"stationary-coherences\"", "code", "+=", "'\t!The code to calculate the equations for coherences.\\n'", "for", "i", "in", "range", "(", "2", ",", "Ne", "+", "1", ")", ":", "for", "j", "in", "range", "(", "1", ",", "i", ")", ":", "for", "s", "in", "[", "1", ",", "-", "1", "]", ":", "mu", "=", "Mu", "(", "i", ",", "j", ",", "s", ",", "Ne", ",", "excluded_mu", ")", "for", "k", "in", "range", "(", "1", ",", "Ne", "+", "1", ")", ":", "for", "l", "in", "Lij", "[", "k", "-", "1", "]", "[", "j", "-", "1", "]", ":", "if", "k", "<", "i", ":", "if", "k", "<", "j", ":", "dp", "=", "s", "*", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "-", "1", ",", "r", ",", "k", ",", "j", ")", "dp1", "=", "part", "(", "dp", ",", "-", "s", ")", "dp2", "=", "part", "(", "s", "*", "dp", ",", "+", "s", ")", "nu", "=", "Mu", "(", "i", ",", "k", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp1", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp1", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "nu", "=", "Mu", "(", "i", ",", "k", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp2", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp2", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "elif", "k", ">", "j", ":", "dp", "=", "s", "*", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "+", "1", ",", "r", ",", "k", ",", "j", ")", "dp1", "=", "part", "(", "dp", ",", "-", "s", ")", "dp2", "=", "part", "(", "s", "*", "dp", ",", "s", ")", "nu", "=", "Mu", "(", "i", ",", "k", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp1", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp1", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "nu", "=", "Mu", "(", "i", ",", "k", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp2", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp2", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "elif", "k", ">", "i", ":", "dp", "=", "s", "*", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "1", ",", "r", ",", "k", ",", "j", ")", "dp1", "=", "part", "(", "dp", ",", "-", "s", ")", "dp2", "=", "part", "(", "-", "s", "*", "dp", ",", "s", ")", "nu", "=", "Mu", "(", "k", ",", "i", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp1", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "code", "+=", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp1", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "nu", "=", "Mu", "(", "k", ",", "i", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp2", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "+", "format_double", "(", "dp2", ")", "code", "+=", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "for", "l", "in", "Lij", "[", "i", "-", "1", "]", "[", "k", "-", "1", "]", ":", "if", "k", ">", "j", ":", "if", "k", ">", "i", ":", "dp", "=", "-", "s", "*", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "-", "1", ",", "r", ",", "i", ",", "k", ")", "dp1", "=", "part", "(", "dp", ",", "-", "s", ")", "dp2", "=", "part", "(", "s", "*", "dp", ",", "s", ")", "nu", "=", "Mu", "(", "k", ",", "j", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp1", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "code", "+=", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp1", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "nu", "=", "Mu", "(", "k", ",", "j", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp2", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "code", "+=", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp2", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "elif", "k", "<", "i", ":", "dp", "=", "-", "s", "*", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "1", ",", "r", ",", "i", ",", "k", ")", "dp1", "=", "part", "(", "dp", ",", "-", "s", ")", "dp2", "=", "part", "(", "s", "*", "dp", ",", "s", ")", "nu", "=", "Mu", "(", "k", ",", "j", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp1", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "code", "+=", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp1", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "nu", "=", "Mu", "(", "k", ",", "j", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp2", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "code", "+=", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp2", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "elif", "k", "<", "j", ":", "dp", "=", "-", "s", "*", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "1", ",", "r", ",", "i", ",", "k", ")", "dp1", "=", "part", "(", "dp", ",", "-", "s", ")", "dp2", "=", "part", "(", "-", "s", "*", "dp", ",", "s", ")", "nu", "=", "Mu", "(", "j", ",", "k", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp1", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "code", "+=", "format_double", "(", "dp1", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "nu", "=", "Mu", "(", "j", ",", "k", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp2", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "+", "format_double", "(", "dp2", ")", "code", "+=", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "for", "l", "in", "Lij", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", ":", "dp", "=", "s", "*", "part", "(", "dot_product", "(", "laser", "[", "l", "-", "1", "]", ",", "1", ",", "r", ",", "i", ",", "j", ")", ",", "-", "s", ")", "nu", "=", "Mu", "(", "i", ",", "i", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "dp", "!=", "0", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "+", "format_double", "(", "dp", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "nu", "=", "Mu", "(", "j", ",", "j", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "if", "nu", "==", "0", ":", "for", "n", "in", "range", "(", "1", ",", "Ne", ")", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "n", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "n", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "+", "format_double", "(", "dp", ")", "code", "+=", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "n", "-", "1", "]", "=", "True", "else", ":", "code", "+=", "'\tA('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "code", "+=", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'+E0('", "+", "str", "(", "l", ")", "+", "')*('", "+", "format_double", "(", "-", "dp", ")", "code", "+=", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "code", "+=", "'\\n'", "code", "+=", "'\tA=A/2.0d0\\n\\n'", "# +str(1/sqrt(2.0))+'d0\\n\\n'", "###########################################################################", "# We add the terms associated with the phase transformation.", "code", "+=", "'\t!We calculate the terms associated with the phase '", "code", "+=", "'transformation.\\n'", "# for i in range(2,10):", "for", "i", "in", "range", "(", "2", ",", "Ne", "+", "1", ")", ":", "for", "j", "in", "range", "(", "1", ",", "i", ")", ":", "extra", "=", "Theta", "(", "i", ",", "j", ",", "theta", ",", "omega_rescaled", ",", "omega_min", ",", "detunings", ",", "detuningsij", ",", "combinations", ",", "detuning_indices", ",", "Lij", ",", "i_d", ",", "I_nd", ",", "Nnd", ",", "verbose", "=", "verbose", ",", "states", "=", "states", ")", "if", "extra", "!=", "''", ":", "for", "s", "in", "[", "1", ",", "-", "1", "]", ":", "mu", "=", "Mu", "(", "i", ",", "j", ",", "s", ",", "Ne", ",", "excluded_mu", ")", "nu", "=", "Mu", "(", "i", ",", "j", ",", "-", "s", ",", "Ne", ",", "excluded_mu", ")", "code", "+=", "' A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "nu", ")", "+", "')'", "if", "s", "==", "1", ":", "code", "+=", "'-('", "+", "str", "(", "extra", ")", "+", "')\\n'", "elif", "s", "==", "-", "1", ":", "code", "+=", "'+('", "+", "str", "(", "extra", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "code", "+=", "'\\n'", "###########################################################################", "# We add the terms associated with spontaneous decay.", "code", "+=", "'\t!We calculate the terms associated with spontaneous decay.\\n'", "# First for populations.", "for", "i", "in", "range", "(", "2", ",", "Ne", "+", "1", ")", ":", "mu", "=", "Mu", "(", "i", ",", "i", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "for", "k", "in", "range", "(", "1", ",", "Ne", "+", "1", ")", ":", "gams", "=", "0", "if", "k", "<", "i", ":", "gams", "+=", "gamma", "[", "i", "-", "1", "]", "[", "k", "-", "1", "]", "elif", "k", ">", "i", ":", "nu", "=", "Mu", "(", "k", ",", "k", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "ga", "=", "gamma", "[", "i", "-", "1", "]", "[", "k", "-", "1", "]", "if", "ga", "!=", "0", ":", "code", "+=", "' A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "nu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "nu", ")", "+", "')'", "code", "+=", "'-('", "+", "format_double", "(", "ga", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "nu", "-", "1", "]", "=", "True", "if", "gams", "!=", "0", ":", "code", "+=", "' A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "mu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "mu", ")", "+", "')'", "code", "+=", "'-('", "+", "format_double", "(", "gams", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "mu", "-", "1", "]", "=", "True", "# And now for coherences", "for", "i", "in", "range", "(", "1", ",", "Ne", "+", "1", ")", ":", "for", "j", "in", "range", "(", "1", ",", "i", ")", ":", "gams", "=", "gamma", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "/", "2", "if", "gams", "!=", "0", ":", "for", "a", "in", "range", "(", "i", "+", "1", ",", "Ne", "+", "1", ")", ":", "mu", "=", "Mu", "(", "a", ",", "i", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "code", "+=", "' A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "mu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "mu", ")", "+", "')'", "code", "+=", "'-('", "+", "format_double", "(", "gams", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "mu", "-", "1", "]", "=", "True", "mu", "=", "Mu", "(", "a", ",", "i", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "code", "+=", "' A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "mu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "mu", ")", "+", "')'", "code", "+=", "'-('", "+", "format_double", "(", "gams", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "mu", "-", "1", "]", "=", "True", "for", "b", "in", "range", "(", "1", ",", "i", ")", ":", "mu", "=", "Mu", "(", "i", ",", "b", ",", "1", ",", "Ne", ",", "excluded_mu", ")", "code", "+=", "' A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "mu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "mu", ")", "+", "')'", "code", "+=", "'-('", "+", "format_double", "(", "gams", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "mu", "-", "1", "]", "=", "True", "mu", "=", "Mu", "(", "i", ",", "b", ",", "-", "1", ",", "Ne", ",", "excluded_mu", ")", "code", "+=", "' A('", "+", "str", "(", "mu", ")", "+", "','", "+", "str", "(", "mu", ")", "+", "')=A('", "+", "str", "(", "mu", ")", "+", "','", "code", "+=", "str", "(", "mu", ")", "+", "')'", "code", "+=", "'-('", "+", "format_double", "(", "gams", ")", "+", "')\\n'", "row_check", "[", "mu", "-", "1", "]", "=", "True", "col_check", "[", "mu", "-", "1", "]", "=", "True", "code", "+=", "'\\n'", "code", "=", "code0", "+", "code", "Nd", "=", "sum", "(", "[", "len", "(", "detunings", "[", "l", "]", ")", "for", "l", "in", "range", "(", "Nl", ")", "]", ")", "res", "=", "[", "code", ",", "Nd", ",", "row_check", ",", "col_check", ",", "rhs_check", ",", "Ne", ",", "N_excluded_mu", ",", "states", ",", "omega_min", ",", "detuningsij", ",", "omega_rescaled", "]", "return", "res" ]
r"""Write code for the equations.
[ "r", "Write", "code", "for", "the", "equations", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L616-L1012
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", "=", "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" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L1088-L1143
abn/cafeteria
cafeteria/datastructs/dict.py
MergingDict.replace
def replace(self, key, value): """ Convenience method provided as a way to replace a value mapped by a key.This is required since a MergingDict always merges via assignment of item/attribute. :param key: Attribute name or item key to replace rvalue for. :type key: object :param value: The new value to assign. :type value: object :return: """ super(MergingDict, self).__setitem__(key, value)
python
def replace(self, key, value): """ Convenience method provided as a way to replace a value mapped by a key.This is required since a MergingDict always merges via assignment of item/attribute. :param key: Attribute name or item key to replace rvalue for. :type key: object :param value: The new value to assign. :type value: object :return: """ super(MergingDict, self).__setitem__(key, value)
[ "def", "replace", "(", "self", ",", "key", ",", "value", ")", ":", "super", "(", "MergingDict", ",", "self", ")", ".", "__setitem__", "(", "key", ",", "value", ")" ]
Convenience method provided as a way to replace a value mapped by a key.This is required since a MergingDict always merges via assignment of item/attribute. :param key: Attribute name or item key to replace rvalue for. :type key: object :param value: The new value to assign. :type value: object :return:
[ "Convenience", "method", "provided", "as", "a", "way", "to", "replace", "a", "value", "mapped", "by", "a", "key", ".", "This", "is", "required", "since", "a", "MergingDict", "always", "merges", "via", "assignment", "of", "item", "/", "attribute", "." ]
train
https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/datastructs/dict.py#L51-L63
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", "]", "=", "other", "[", "key", "]", "else", ":", "# noinspection PyTypeChecker", "super", "(", "MergingDict", ",", "self", ")", ".", "update", "(", "other", ")", "for", "key", "in", "kwargs", ":", "self", ".", "_merge", "(", "key", ",", "kwargs", "[", "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", "use", "of", "the", "internal", "merging", "logic", "." ]
train
https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/datastructs/dict.py#L65-L85
abn/cafeteria
cafeteria/datastructs/dict.py
MergingDict._merge_method
def _merge_method(self, key): """ Identify a merge compatible method available in self[key]. Currently we support 'update' and 'append'. :param key: Attribute name or item key :return: Method name usable to merge a value into the instance mapped by key :rtype: str """ if key in self: for method in ["update", "append"]: if hasattr(self[key], method): return method return None
python
def _merge_method(self, key): """ Identify a merge compatible method available in self[key]. Currently we support 'update' and 'append'. :param key: Attribute name or item key :return: Method name usable to merge a value into the instance mapped by key :rtype: str """ if key in self: for method in ["update", "append"]: if hasattr(self[key], method): return method return None
[ "def", "_merge_method", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ":", "for", "method", "in", "[", "\"update\"", ",", "\"append\"", "]", ":", "if", "hasattr", "(", "self", "[", "key", "]", ",", "method", ")", ":", "return", "method", "return", "None" ]
Identify a merge compatible method available in self[key]. Currently we support 'update' and 'append'. :param key: Attribute name or item key :return: Method name usable to merge a value into the instance mapped by key :rtype: str
[ "Identify", "a", "merge", "compatible", "method", "available", "in", "self", "[", "key", "]", ".", "Currently", "we", "support", "update", "and", "append", "." ]
train
https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/datastructs/dict.py#L87-L101
abn/cafeteria
cafeteria/datastructs/dict.py
MergingDict._merge
def _merge(self, key, value): """ Internal merge logic implementation to allow merging of values when setting attributes/items. :param key: Attribute name or item key :type key: str :param value: Value to set attribute/item as. :type value: object :rtype: None """ method = self._merge_method(key) if method is not None: # strings are special, update methods like set.update looks for # iterables if method == "update" and is_str(value): value = [value] if ( method == "append" and isinstance(self[key], list) and isinstance(value, list) ): # if rvalue is a list and given object is a list, we expect all # values to be appended method = "extend" getattr(self[key], method)(value) else: super(MergingDict, self).__setitem__(key, value)
python
def _merge(self, key, value): """ Internal merge logic implementation to allow merging of values when setting attributes/items. :param key: Attribute name or item key :type key: str :param value: Value to set attribute/item as. :type value: object :rtype: None """ method = self._merge_method(key) if method is not None: # strings are special, update methods like set.update looks for # iterables if method == "update" and is_str(value): value = [value] if ( method == "append" and isinstance(self[key], list) and isinstance(value, list) ): # if rvalue is a list and given object is a list, we expect all # values to be appended method = "extend" getattr(self[key], method)(value) else: super(MergingDict, self).__setitem__(key, value)
[ "def", "_merge", "(", "self", ",", "key", ",", "value", ")", ":", "method", "=", "self", ".", "_merge_method", "(", "key", ")", "if", "method", "is", "not", "None", ":", "# strings are special, update methods like set.update looks for", "# iterables", "if", "method", "==", "\"update\"", "and", "is_str", "(", "value", ")", ":", "value", "=", "[", "value", "]", "if", "(", "method", "==", "\"append\"", "and", "isinstance", "(", "self", "[", "key", "]", ",", "list", ")", "and", "isinstance", "(", "value", ",", "list", ")", ")", ":", "# if rvalue is a list and given object is a list, we expect all", "# values to be appended", "method", "=", "\"extend\"", "getattr", "(", "self", "[", "key", "]", ",", "method", ")", "(", "value", ")", "else", ":", "super", "(", "MergingDict", ",", "self", ")", ".", "__setitem__", "(", "key", ",", "value", ")" ]
Internal merge logic implementation to allow merging of values when setting attributes/items. :param key: Attribute name or item key :type key: str :param value: Value to set attribute/item as. :type value: object :rtype: None
[ "Internal", "merge", "logic", "implementation", "to", "allow", "merging", "of", "values", "when", "setting", "attributes", "/", "items", "." ]
train
https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/datastructs/dict.py#L103-L130
FrancoisConstant/django-twitter-feed
twitter_feed/import_tweets.py
ImportTweets._tweepy_status_to_tweet
def _tweepy_status_to_tweet(self, status): """ Fields documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline """ tweet = Tweet() tweet.published_at = status.created_at tweet.content = status.text return tweet
python
def _tweepy_status_to_tweet(self, status): """ Fields documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline """ tweet = Tweet() tweet.published_at = status.created_at tweet.content = status.text return tweet
[ "def", "_tweepy_status_to_tweet", "(", "self", ",", "status", ")", ":", "tweet", "=", "Tweet", "(", ")", "tweet", ".", "published_at", "=", "status", ".", "created_at", "tweet", ".", "content", "=", "status", ".", "text", "return", "tweet" ]
Fields documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
[ "Fields", "documentation", ":", "https", ":", "//", "dev", ".", "twitter", ".", "com", "/", "docs", "/", "api", "/", "1", ".", "1", "/", "get", "/", "statuses", "/", "home_timeline" ]
train
https://github.com/FrancoisConstant/django-twitter-feed/blob/4ef90cdc2a3e12852380f07ebf224834ce510396/twitter_feed/import_tweets.py#L31-L39
oscarlazoarjona/fast
build/lib/fast/misc.py
formatLij
def formatLij(Lij0,Ne): """This function transforms a list of laser conections of the form [i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a Ne x Ne matrix whose elements are the lasers connecting the corresponding indices.""" #We create Lij as a matrix of lists of laser indices global Lij Lij=[] for i in range(Ne): fila=[] for j in range(Ne): band=False for tri in Lij0: if [i+1,j+1] == tri[:2]: band=True break elif [j+1,i+1] == tri[:2]: band=True break if band: fila+=[tri[2]] else: fila+=[[]] Lij+=[fila] return Lij
python
def formatLij(Lij0,Ne): """This function transforms a list of laser conections of the form [i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a Ne x Ne matrix whose elements are the lasers connecting the corresponding indices.""" #We create Lij as a matrix of lists of laser indices global Lij Lij=[] for i in range(Ne): fila=[] for j in range(Ne): band=False for tri in Lij0: if [i+1,j+1] == tri[:2]: band=True break elif [j+1,i+1] == tri[:2]: band=True break if band: fila+=[tri[2]] else: fila+=[[]] Lij+=[fila] return Lij
[ "def", "formatLij", "(", "Lij0", ",", "Ne", ")", ":", "#We create Lij as a matrix of lists of laser indices", "global", "Lij", "Lij", "=", "[", "]", "for", "i", "in", "range", "(", "Ne", ")", ":", "fila", "=", "[", "]", "for", "j", "in", "range", "(", "Ne", ")", ":", "band", "=", "False", "for", "tri", "in", "Lij0", ":", "if", "[", "i", "+", "1", ",", "j", "+", "1", "]", "==", "tri", "[", ":", "2", "]", ":", "band", "=", "True", "break", "elif", "[", "j", "+", "1", ",", "i", "+", "1", "]", "==", "tri", "[", ":", "2", "]", ":", "band", "=", "True", "break", "if", "band", ":", "fila", "+=", "[", "tri", "[", "2", "]", "]", "else", ":", "fila", "+=", "[", "[", "]", "]", "Lij", "+=", "[", "fila", "]", "return", "Lij" ]
This function transforms a list of laser conections of the form [i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a Ne x Ne matrix whose elements are the lasers connecting the corresponding indices.
[ "This", "function", "transforms", "a", "list", "of", "laser", "conections", "of", "the", "form", "[", "i", "j", "[", "l1", "l2", "...", "]]", "between", "states", "i", "and", "j", "by", "lasers", "l1", "l2", "...", "into", "a", "Ne", "x", "Ne", "matrix", "whose", "elements", "are", "the", "lasers", "connecting", "the", "corresponding", "indices", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/misc.py#L183-L207
oscarlazoarjona/fast
build/lib/fast/misc.py
Theta
def Theta(i,j,theta,omega_rescaled,omega_min, detunings,detuningsij,combinations,detuning_indices, Lij,i_d,I_nd,Nnd, states=None,verbose=1,other_the=None): """This function returns code for Theta_i j as defined in the equation labeled Theta. in terms of detunings. It recieves indexes i,j starting from 1.""" if i==j: return '' elif j>i: raise ValueError,'i should never be less than j.' Ne=len(omega_rescaled[0]); Nl=len(theta[0]) if other_the!=None: the=other_the[:] else: the=[theta[j-1][l]-theta[i-1][l] for l in range(Nl)] ########################################################################################### #This part is about finding detunings that reduce to -omega_ij if the==[0 for l in range(Nl)]: if omega_rescaled[i-1][j-1]==0: return '' #We need a combination of detunings that yields -omega_i,j. #According to equation labeled "detuning-exception1" #-omega_ij= delta^l_ik - delta^l_jk #so we seek a k that is lower than i and j #and an l such that l is in L_ik and in L_jk ii=min(i,j) band1=False band2=False for k in range(1,ii): for l in range(1,Nl+1): if l in Lij[i-1][k-1] and l in Lij[j-1][k-1]: s ='I found that -omega_'+str(i)+','+str(j) s+='= delta^'+str(l)+'_'+str(i)+','+str(k) s+= '-delta^'+str(l)+'_'+str(j)+','+str(k) s+='\n and also l='+str(l) s+=' is in L'+str(i)+','+str(k)+'='+str(Lij[i-1][k-1]) s+=' and in L'+str(j)+','+str(k)+'='+str(Lij[j-1][k-1])+'\n' #print s band1=True break if band1: break if not band1: #If no such a k exists then we follow te equation labeled "detuning-exception2" #-omega_ij= delta^l_kj - delta^l_ki #to look for a k greater than i and j #and an l such that l is in L_ik and in L_jk for k in range(ii+1,Ne+1): for l in range(1,Nl+1): if l in Lij[i-1][k-1] and l in Lij[j-1][k-1]: s ='I found that -omega_'+str(i)+','+str(j) s+='= delta^'+str(l)+'_'+str(k)+','+str(j) s+='-delta^'+str(l)+'_'+str(k)+','+str(i) s+='\n and also l='+str(l) s+=' is in L'+str(i)+','+str(k)+'='+str(Lij[i-1][k-1]) s+=' and in L'+str(j)+','+str(k)+'='+str(Lij[j-1][k-1])+'\n' #print s band2=True break if band2: break if band1: The='' #We need to find which detunings are delta^l_i,k and delta^l_j,k. #Since they are detunings of laser l, they must have a number greater #than those with smaller l: acum=sum([detuning_indices[ll] for ll in range(l-1)]) #We test the indices of all detunings of laser l to find the ones we need. for kk in range(detuning_indices[l-1]): if detuningsij[l-1][kk][0]+1==I_nd(i) and detuningsij[l-1][kk][1]+1==I_nd(k): The+='+detuning('+str(acum+kk+1)+')' if detuningsij[l-1][kk][0]+1==I_nd(j) and detuningsij[l-1][kk][1]+1==I_nd(k): The+='-detuning('+str(acum+kk+1)+')' return The elif band2: The='' #We need to find which detunings are delta^l_k,j and delta^l_k,i. #Since they are detunings of laser l, they must have a number greater #than those with smaller l: acum=sum([detuning_indices[ll] for ll in range(l-1)]) #We test the indices of all detunings of laser l to find the ones we need. for kk in range(detuning_indices[l-1]): if detuningsij[l-1][kk][0]+1==I_nd(k) and detuningsij[l-1][kk][1]+1==I_nd(j): The+='+detuning('+str(acum+kk+1)+')' if detuningsij[l-1][kk][0]+1==I_nd(k) and detuningsij[l-1][kk][1]+1==I_nd(i): The+='-detuning('+str(acum+kk+1)+')' return The else: if verbose>1: print 'WARNING: Optical frequencies will be used instead for -omega_',i,j,'=',omega_rescaled[i-1][j-1],'\n' return format_double(-omega_rescaled[i-1][j-1]) ########################################################################################### #This part is about finding detunings that reduce to (theta_j -theta_i -omega_ij) #We establish to which omegaij the detunings should reduce to omegaij=[0 for k in range(Nnd)] omegaij[I_nd(i)-1]=1;omegaij[I_nd(j)-1]=-1 #We search for a combination of detunings that reduces to omegaij #That is a linear combination of detunings with coefficients the #that reduces to omegaij. Here detuning_failure=True for comb in combinations: suma=[sum([the[l]*detunings[l][comb[l]][ii] for l in range(Nl)]) for ii in range(Nnd)] if suma==omegaij: detuning_failure=False break #We stop if no combination reduces to the needed expression. if detuning_failure: if verbose>1: print 'We will see if it is possible to express Theta_'+str(i)+','+str(j)+'=theta_'+str(j)+'-theta_'+str(i)+'-omega_'+str(i)+','+str(j) if verbose>1: print 'in terms of other indices a,b such that omega_ab=omega_ij and transition i -> j is allowed by Lij.' band3=False for a in range(Ne): for b in range(a): if omega_rescaled[a][b]==omega_rescaled[i-1][j-1] and Lij[a][b]!=[]: band3=True break if band3: break if verbose>1: print band3,a,b,i,j a=a+1; b=b+1 if band3 and (i!=a or j!=b): if verbose>1: print omega_rescaled[i-1][j-1],omega_rescaled[a-1][b-1] if verbose>1: print the if verbose>1: print 'This was possible for omega_'+str(a)+','+str(b) return Theta(a,b,theta,omega_rescaled,omega_min, detunings,detuningsij,combinations,detuning_indices ,Lij,other_the=the,verbose=verbose,states=states) else: #verbose=2 #print 111 #qi=states[i-1].quantum_numbers #qj=states[j-1].quantum_numbers #print verbose if verbose>0: print 'WARNING: It was impossible to express laser frequencies',the if verbose>0: print 'and atomic transition -omega_',i,j,'=',-omega_rescaled[i-1][j-1] if verbose>0: print 'in terms of detunings from the transitions given by Lij' #for i in range(Ne): # print i+1,Lij[i] #print if verbose>0: print 'I Will use optical frequencies instead.' The='' #We give the optical frequencies for l in range(Nl): a=the[l] if a==1: The+='+'+format_double(omega_min[l])+'+detuning_knob('+str(l+1)+')' elif a==-1: The+='-('+format_double(omega_min[l])+'+detuning_knob('+str(l+1)+'))' elif a==0: The+='' elif a>0: The+='+'+str(a)+'*'+format_double(omega_min[l])+'+detuning_knob('+str(l+1)+')' else: The+= str(a)+'*('+format_double(omega_min[l])+'+detuning_knob('+str(l+1)+'))' #We substract omega_ij The+=format_double(-omega_rescaled[i-1][j-1]) if verbose>1: print The if verbose>1: print return The #For each optical frequency in the, we write the corresponding detuning. #This way of assigining a global index ll to the detunings ammounts to # ll= number_of_previous_detunings # + number_of_detuning_ordered_by_row_and_from_left_to_right_column The='' acum=0 #################################################################### #print 'comb',comb,'the',the,'i,j',i,j for l in range(Nl): if the[l]==1: The+='+detuning('+str(acum+comb[l]+1)+')' elif the[l]==-1: The+='-detuning('+str(acum+comb[l]+1)+')' elif the[l]==0: pass elif the[l]>0: The+='+'+str(the[l])+'*detuning('+str(acum+comb[l]+1)+')' else: The+= str(the[l])+'*detuning('+str(acum+comb[l]+1)+')' acum+=detuning_indices[l] if The[:1]=='+': The=The[1:] #################################################################### #print 'The',The return The
python
def Theta(i,j,theta,omega_rescaled,omega_min, detunings,detuningsij,combinations,detuning_indices, Lij,i_d,I_nd,Nnd, states=None,verbose=1,other_the=None): """This function returns code for Theta_i j as defined in the equation labeled Theta. in terms of detunings. It recieves indexes i,j starting from 1.""" if i==j: return '' elif j>i: raise ValueError,'i should never be less than j.' Ne=len(omega_rescaled[0]); Nl=len(theta[0]) if other_the!=None: the=other_the[:] else: the=[theta[j-1][l]-theta[i-1][l] for l in range(Nl)] ########################################################################################### #This part is about finding detunings that reduce to -omega_ij if the==[0 for l in range(Nl)]: if omega_rescaled[i-1][j-1]==0: return '' #We need a combination of detunings that yields -omega_i,j. #According to equation labeled "detuning-exception1" #-omega_ij= delta^l_ik - delta^l_jk #so we seek a k that is lower than i and j #and an l such that l is in L_ik and in L_jk ii=min(i,j) band1=False band2=False for k in range(1,ii): for l in range(1,Nl+1): if l in Lij[i-1][k-1] and l in Lij[j-1][k-1]: s ='I found that -omega_'+str(i)+','+str(j) s+='= delta^'+str(l)+'_'+str(i)+','+str(k) s+= '-delta^'+str(l)+'_'+str(j)+','+str(k) s+='\n and also l='+str(l) s+=' is in L'+str(i)+','+str(k)+'='+str(Lij[i-1][k-1]) s+=' and in L'+str(j)+','+str(k)+'='+str(Lij[j-1][k-1])+'\n' #print s band1=True break if band1: break if not band1: #If no such a k exists then we follow te equation labeled "detuning-exception2" #-omega_ij= delta^l_kj - delta^l_ki #to look for a k greater than i and j #and an l such that l is in L_ik and in L_jk for k in range(ii+1,Ne+1): for l in range(1,Nl+1): if l in Lij[i-1][k-1] and l in Lij[j-1][k-1]: s ='I found that -omega_'+str(i)+','+str(j) s+='= delta^'+str(l)+'_'+str(k)+','+str(j) s+='-delta^'+str(l)+'_'+str(k)+','+str(i) s+='\n and also l='+str(l) s+=' is in L'+str(i)+','+str(k)+'='+str(Lij[i-1][k-1]) s+=' and in L'+str(j)+','+str(k)+'='+str(Lij[j-1][k-1])+'\n' #print s band2=True break if band2: break if band1: The='' #We need to find which detunings are delta^l_i,k and delta^l_j,k. #Since they are detunings of laser l, they must have a number greater #than those with smaller l: acum=sum([detuning_indices[ll] for ll in range(l-1)]) #We test the indices of all detunings of laser l to find the ones we need. for kk in range(detuning_indices[l-1]): if detuningsij[l-1][kk][0]+1==I_nd(i) and detuningsij[l-1][kk][1]+1==I_nd(k): The+='+detuning('+str(acum+kk+1)+')' if detuningsij[l-1][kk][0]+1==I_nd(j) and detuningsij[l-1][kk][1]+1==I_nd(k): The+='-detuning('+str(acum+kk+1)+')' return The elif band2: The='' #We need to find which detunings are delta^l_k,j and delta^l_k,i. #Since they are detunings of laser l, they must have a number greater #than those with smaller l: acum=sum([detuning_indices[ll] for ll in range(l-1)]) #We test the indices of all detunings of laser l to find the ones we need. for kk in range(detuning_indices[l-1]): if detuningsij[l-1][kk][0]+1==I_nd(k) and detuningsij[l-1][kk][1]+1==I_nd(j): The+='+detuning('+str(acum+kk+1)+')' if detuningsij[l-1][kk][0]+1==I_nd(k) and detuningsij[l-1][kk][1]+1==I_nd(i): The+='-detuning('+str(acum+kk+1)+')' return The else: if verbose>1: print 'WARNING: Optical frequencies will be used instead for -omega_',i,j,'=',omega_rescaled[i-1][j-1],'\n' return format_double(-omega_rescaled[i-1][j-1]) ########################################################################################### #This part is about finding detunings that reduce to (theta_j -theta_i -omega_ij) #We establish to which omegaij the detunings should reduce to omegaij=[0 for k in range(Nnd)] omegaij[I_nd(i)-1]=1;omegaij[I_nd(j)-1]=-1 #We search for a combination of detunings that reduces to omegaij #That is a linear combination of detunings with coefficients the #that reduces to omegaij. Here detuning_failure=True for comb in combinations: suma=[sum([the[l]*detunings[l][comb[l]][ii] for l in range(Nl)]) for ii in range(Nnd)] if suma==omegaij: detuning_failure=False break #We stop if no combination reduces to the needed expression. if detuning_failure: if verbose>1: print 'We will see if it is possible to express Theta_'+str(i)+','+str(j)+'=theta_'+str(j)+'-theta_'+str(i)+'-omega_'+str(i)+','+str(j) if verbose>1: print 'in terms of other indices a,b such that omega_ab=omega_ij and transition i -> j is allowed by Lij.' band3=False for a in range(Ne): for b in range(a): if omega_rescaled[a][b]==omega_rescaled[i-1][j-1] and Lij[a][b]!=[]: band3=True break if band3: break if verbose>1: print band3,a,b,i,j a=a+1; b=b+1 if band3 and (i!=a or j!=b): if verbose>1: print omega_rescaled[i-1][j-1],omega_rescaled[a-1][b-1] if verbose>1: print the if verbose>1: print 'This was possible for omega_'+str(a)+','+str(b) return Theta(a,b,theta,omega_rescaled,omega_min, detunings,detuningsij,combinations,detuning_indices ,Lij,other_the=the,verbose=verbose,states=states) else: #verbose=2 #print 111 #qi=states[i-1].quantum_numbers #qj=states[j-1].quantum_numbers #print verbose if verbose>0: print 'WARNING: It was impossible to express laser frequencies',the if verbose>0: print 'and atomic transition -omega_',i,j,'=',-omega_rescaled[i-1][j-1] if verbose>0: print 'in terms of detunings from the transitions given by Lij' #for i in range(Ne): # print i+1,Lij[i] #print if verbose>0: print 'I Will use optical frequencies instead.' The='' #We give the optical frequencies for l in range(Nl): a=the[l] if a==1: The+='+'+format_double(omega_min[l])+'+detuning_knob('+str(l+1)+')' elif a==-1: The+='-('+format_double(omega_min[l])+'+detuning_knob('+str(l+1)+'))' elif a==0: The+='' elif a>0: The+='+'+str(a)+'*'+format_double(omega_min[l])+'+detuning_knob('+str(l+1)+')' else: The+= str(a)+'*('+format_double(omega_min[l])+'+detuning_knob('+str(l+1)+'))' #We substract omega_ij The+=format_double(-omega_rescaled[i-1][j-1]) if verbose>1: print The if verbose>1: print return The #For each optical frequency in the, we write the corresponding detuning. #This way of assigining a global index ll to the detunings ammounts to # ll= number_of_previous_detunings # + number_of_detuning_ordered_by_row_and_from_left_to_right_column The='' acum=0 #################################################################### #print 'comb',comb,'the',the,'i,j',i,j for l in range(Nl): if the[l]==1: The+='+detuning('+str(acum+comb[l]+1)+')' elif the[l]==-1: The+='-detuning('+str(acum+comb[l]+1)+')' elif the[l]==0: pass elif the[l]>0: The+='+'+str(the[l])+'*detuning('+str(acum+comb[l]+1)+')' else: The+= str(the[l])+'*detuning('+str(acum+comb[l]+1)+')' acum+=detuning_indices[l] if The[:1]=='+': The=The[1:] #################################################################### #print 'The',The return The
[ "def", "Theta", "(", "i", ",", "j", ",", "theta", ",", "omega_rescaled", ",", "omega_min", ",", "detunings", ",", "detuningsij", ",", "combinations", ",", "detuning_indices", ",", "Lij", ",", "i_d", ",", "I_nd", ",", "Nnd", ",", "states", "=", "None", ",", "verbose", "=", "1", ",", "other_the", "=", "None", ")", ":", "if", "i", "==", "j", ":", "return", "''", "elif", "j", ">", "i", ":", "raise", "ValueError", ",", "'i should never be less than j.'", "Ne", "=", "len", "(", "omega_rescaled", "[", "0", "]", ")", "Nl", "=", "len", "(", "theta", "[", "0", "]", ")", "if", "other_the", "!=", "None", ":", "the", "=", "other_the", "[", ":", "]", "else", ":", "the", "=", "[", "theta", "[", "j", "-", "1", "]", "[", "l", "]", "-", "theta", "[", "i", "-", "1", "]", "[", "l", "]", "for", "l", "in", "range", "(", "Nl", ")", "]", "###########################################################################################", "#This part is about finding detunings that reduce to -omega_ij", "if", "the", "==", "[", "0", "for", "l", "in", "range", "(", "Nl", ")", "]", ":", "if", "omega_rescaled", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "==", "0", ":", "return", "''", "#We need a combination of detunings that yields -omega_i,j.", "#According to equation labeled \"detuning-exception1\"", "#-omega_ij= delta^l_ik - delta^l_jk", "#so we seek a k that is lower than i and j", "#and an l such that l is in L_ik and in L_jk", "ii", "=", "min", "(", "i", ",", "j", ")", "band1", "=", "False", "band2", "=", "False", "for", "k", "in", "range", "(", "1", ",", "ii", ")", ":", "for", "l", "in", "range", "(", "1", ",", "Nl", "+", "1", ")", ":", "if", "l", "in", "Lij", "[", "i", "-", "1", "]", "[", "k", "-", "1", "]", "and", "l", "in", "Lij", "[", "j", "-", "1", "]", "[", "k", "-", "1", "]", ":", "s", "=", "'I found that -omega_'", "+", "str", "(", "i", ")", "+", "','", "+", "str", "(", "j", ")", "s", "+=", "'= delta^'", "+", "str", "(", "l", ")", "+", "'_'", "+", "str", "(", "i", ")", "+", "','", "+", "str", "(", "k", ")", "s", "+=", "'-delta^'", "+", "str", "(", "l", ")", "+", "'_'", "+", "str", "(", "j", ")", "+", "','", "+", "str", "(", "k", ")", "s", "+=", "'\\n and also l='", "+", "str", "(", "l", ")", "s", "+=", "' is in L'", "+", "str", "(", "i", ")", "+", "','", "+", "str", "(", "k", ")", "+", "'='", "+", "str", "(", "Lij", "[", "i", "-", "1", "]", "[", "k", "-", "1", "]", ")", "s", "+=", "' and in L'", "+", "str", "(", "j", ")", "+", "','", "+", "str", "(", "k", ")", "+", "'='", "+", "str", "(", "Lij", "[", "j", "-", "1", "]", "[", "k", "-", "1", "]", ")", "+", "'\\n'", "#print s", "band1", "=", "True", "break", "if", "band1", ":", "break", "if", "not", "band1", ":", "#If no such a k exists then we follow te equation labeled \"detuning-exception2\"", "#-omega_ij= delta^l_kj - delta^l_ki", "#to look for a k greater than i and j", "#and an l such that l is in L_ik and in L_jk", "for", "k", "in", "range", "(", "ii", "+", "1", ",", "Ne", "+", "1", ")", ":", "for", "l", "in", "range", "(", "1", ",", "Nl", "+", "1", ")", ":", "if", "l", "in", "Lij", "[", "i", "-", "1", "]", "[", "k", "-", "1", "]", "and", "l", "in", "Lij", "[", "j", "-", "1", "]", "[", "k", "-", "1", "]", ":", "s", "=", "'I found that -omega_'", "+", "str", "(", "i", ")", "+", "','", "+", "str", "(", "j", ")", "s", "+=", "'= delta^'", "+", "str", "(", "l", ")", "+", "'_'", "+", "str", "(", "k", ")", "+", "','", "+", "str", "(", "j", ")", "s", "+=", "'-delta^'", "+", "str", "(", "l", ")", "+", "'_'", "+", "str", "(", "k", ")", "+", "','", "+", "str", "(", "i", ")", "s", "+=", "'\\n and also l='", "+", "str", "(", "l", ")", "s", "+=", "' is in L'", "+", "str", "(", "i", ")", "+", "','", "+", "str", "(", "k", ")", "+", "'='", "+", "str", "(", "Lij", "[", "i", "-", "1", "]", "[", "k", "-", "1", "]", ")", "s", "+=", "' and in L'", "+", "str", "(", "j", ")", "+", "','", "+", "str", "(", "k", ")", "+", "'='", "+", "str", "(", "Lij", "[", "j", "-", "1", "]", "[", "k", "-", "1", "]", ")", "+", "'\\n'", "#print s", "band2", "=", "True", "break", "if", "band2", ":", "break", "if", "band1", ":", "The", "=", "''", "#We need to find which detunings are delta^l_i,k and delta^l_j,k.", "#Since they are detunings of laser l, they must have a number greater", "#than those with smaller l:", "acum", "=", "sum", "(", "[", "detuning_indices", "[", "ll", "]", "for", "ll", "in", "range", "(", "l", "-", "1", ")", "]", ")", "#We test the indices of all detunings of laser l to find the ones we need.", "for", "kk", "in", "range", "(", "detuning_indices", "[", "l", "-", "1", "]", ")", ":", "if", "detuningsij", "[", "l", "-", "1", "]", "[", "kk", "]", "[", "0", "]", "+", "1", "==", "I_nd", "(", "i", ")", "and", "detuningsij", "[", "l", "-", "1", "]", "[", "kk", "]", "[", "1", "]", "+", "1", "==", "I_nd", "(", "k", ")", ":", "The", "+=", "'+detuning('", "+", "str", "(", "acum", "+", "kk", "+", "1", ")", "+", "')'", "if", "detuningsij", "[", "l", "-", "1", "]", "[", "kk", "]", "[", "0", "]", "+", "1", "==", "I_nd", "(", "j", ")", "and", "detuningsij", "[", "l", "-", "1", "]", "[", "kk", "]", "[", "1", "]", "+", "1", "==", "I_nd", "(", "k", ")", ":", "The", "+=", "'-detuning('", "+", "str", "(", "acum", "+", "kk", "+", "1", ")", "+", "')'", "return", "The", "elif", "band2", ":", "The", "=", "''", "#We need to find which detunings are delta^l_k,j and delta^l_k,i.", "#Since they are detunings of laser l, they must have a number greater", "#than those with smaller l:", "acum", "=", "sum", "(", "[", "detuning_indices", "[", "ll", "]", "for", "ll", "in", "range", "(", "l", "-", "1", ")", "]", ")", "#We test the indices of all detunings of laser l to find the ones we need.", "for", "kk", "in", "range", "(", "detuning_indices", "[", "l", "-", "1", "]", ")", ":", "if", "detuningsij", "[", "l", "-", "1", "]", "[", "kk", "]", "[", "0", "]", "+", "1", "==", "I_nd", "(", "k", ")", "and", "detuningsij", "[", "l", "-", "1", "]", "[", "kk", "]", "[", "1", "]", "+", "1", "==", "I_nd", "(", "j", ")", ":", "The", "+=", "'+detuning('", "+", "str", "(", "acum", "+", "kk", "+", "1", ")", "+", "')'", "if", "detuningsij", "[", "l", "-", "1", "]", "[", "kk", "]", "[", "0", "]", "+", "1", "==", "I_nd", "(", "k", ")", "and", "detuningsij", "[", "l", "-", "1", "]", "[", "kk", "]", "[", "1", "]", "+", "1", "==", "I_nd", "(", "i", ")", ":", "The", "+=", "'-detuning('", "+", "str", "(", "acum", "+", "kk", "+", "1", ")", "+", "')'", "return", "The", "else", ":", "if", "verbose", ">", "1", ":", "print", "'WARNING: Optical frequencies will be used instead for -omega_'", ",", "i", ",", "j", ",", "'='", ",", "omega_rescaled", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", ",", "'\\n'", "return", "format_double", "(", "-", "omega_rescaled", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", ")", "###########################################################################################", "#This part is about finding detunings that reduce to (theta_j -theta_i -omega_ij)", "#We establish to which omegaij the detunings should reduce to", "omegaij", "=", "[", "0", "for", "k", "in", "range", "(", "Nnd", ")", "]", "omegaij", "[", "I_nd", "(", "i", ")", "-", "1", "]", "=", "1", "omegaij", "[", "I_nd", "(", "j", ")", "-", "1", "]", "=", "-", "1", "#We search for a combination of detunings that reduces to omegaij", "#That is a linear combination of detunings with coefficients the", "#that reduces to omegaij. Here", "detuning_failure", "=", "True", "for", "comb", "in", "combinations", ":", "suma", "=", "[", "sum", "(", "[", "the", "[", "l", "]", "*", "detunings", "[", "l", "]", "[", "comb", "[", "l", "]", "]", "[", "ii", "]", "for", "l", "in", "range", "(", "Nl", ")", "]", ")", "for", "ii", "in", "range", "(", "Nnd", ")", "]", "if", "suma", "==", "omegaij", ":", "detuning_failure", "=", "False", "break", "#We stop if no combination reduces to the needed expression.", "if", "detuning_failure", ":", "if", "verbose", ">", "1", ":", "print", "'We will see if it is possible to express Theta_'", "+", "str", "(", "i", ")", "+", "','", "+", "str", "(", "j", ")", "+", "'=theta_'", "+", "str", "(", "j", ")", "+", "'-theta_'", "+", "str", "(", "i", ")", "+", "'-omega_'", "+", "str", "(", "i", ")", "+", "','", "+", "str", "(", "j", ")", "if", "verbose", ">", "1", ":", "print", "'in terms of other indices a,b such that omega_ab=omega_ij and transition i -> j is allowed by Lij.'", "band3", "=", "False", "for", "a", "in", "range", "(", "Ne", ")", ":", "for", "b", "in", "range", "(", "a", ")", ":", "if", "omega_rescaled", "[", "a", "]", "[", "b", "]", "==", "omega_rescaled", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "and", "Lij", "[", "a", "]", "[", "b", "]", "!=", "[", "]", ":", "band3", "=", "True", "break", "if", "band3", ":", "break", "if", "verbose", ">", "1", ":", "print", "band3", ",", "a", ",", "b", ",", "i", ",", "j", "a", "=", "a", "+", "1", "b", "=", "b", "+", "1", "if", "band3", "and", "(", "i", "!=", "a", "or", "j", "!=", "b", ")", ":", "if", "verbose", ">", "1", ":", "print", "omega_rescaled", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", ",", "omega_rescaled", "[", "a", "-", "1", "]", "[", "b", "-", "1", "]", "if", "verbose", ">", "1", ":", "print", "the", "if", "verbose", ">", "1", ":", "print", "'This was possible for omega_'", "+", "str", "(", "a", ")", "+", "','", "+", "str", "(", "b", ")", "return", "Theta", "(", "a", ",", "b", ",", "theta", ",", "omega_rescaled", ",", "omega_min", ",", "detunings", ",", "detuningsij", ",", "combinations", ",", "detuning_indices", ",", "Lij", ",", "other_the", "=", "the", ",", "verbose", "=", "verbose", ",", "states", "=", "states", ")", "else", ":", "#verbose=2", "#print 111", "#qi=states[i-1].quantum_numbers", "#qj=states[j-1].quantum_numbers", "#print verbose", "if", "verbose", ">", "0", ":", "print", "'WARNING: It was impossible to express laser frequencies'", ",", "the", "if", "verbose", ">", "0", ":", "print", "'and atomic transition -omega_'", ",", "i", ",", "j", ",", "'='", ",", "-", "omega_rescaled", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "if", "verbose", ">", "0", ":", "print", "'in terms of detunings from the transitions given by Lij'", "#for i in range(Ne):", "#\tprint i+1,Lij[i]", "#print", "if", "verbose", ">", "0", ":", "print", "'I Will use optical frequencies instead.'", "The", "=", "''", "#We give the optical frequencies", "for", "l", "in", "range", "(", "Nl", ")", ":", "a", "=", "the", "[", "l", "]", "if", "a", "==", "1", ":", "The", "+=", "'+'", "+", "format_double", "(", "omega_min", "[", "l", "]", ")", "+", "'+detuning_knob('", "+", "str", "(", "l", "+", "1", ")", "+", "')'", "elif", "a", "==", "-", "1", ":", "The", "+=", "'-('", "+", "format_double", "(", "omega_min", "[", "l", "]", ")", "+", "'+detuning_knob('", "+", "str", "(", "l", "+", "1", ")", "+", "'))'", "elif", "a", "==", "0", ":", "The", "+=", "''", "elif", "a", ">", "0", ":", "The", "+=", "'+'", "+", "str", "(", "a", ")", "+", "'*'", "+", "format_double", "(", "omega_min", "[", "l", "]", ")", "+", "'+detuning_knob('", "+", "str", "(", "l", "+", "1", ")", "+", "')'", "else", ":", "The", "+=", "str", "(", "a", ")", "+", "'*('", "+", "format_double", "(", "omega_min", "[", "l", "]", ")", "+", "'+detuning_knob('", "+", "str", "(", "l", "+", "1", ")", "+", "'))'", "#We substract omega_ij", "The", "+=", "format_double", "(", "-", "omega_rescaled", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", ")", "if", "verbose", ">", "1", ":", "print", "The", "if", "verbose", ">", "1", ":", "print", "return", "The", "#For each optical frequency in the, we write the corresponding detuning.", "#This way of assigining a global index ll to the detunings ammounts to", "# ll= number_of_previous_detunings", "# + number_of_detuning_ordered_by_row_and_from_left_to_right_column", "The", "=", "''", "acum", "=", "0", "####################################################################", "#print 'comb',comb,'the',the,'i,j',i,j", "for", "l", "in", "range", "(", "Nl", ")", ":", "if", "the", "[", "l", "]", "==", "1", ":", "The", "+=", "'+detuning('", "+", "str", "(", "acum", "+", "comb", "[", "l", "]", "+", "1", ")", "+", "')'", "elif", "the", "[", "l", "]", "==", "-", "1", ":", "The", "+=", "'-detuning('", "+", "str", "(", "acum", "+", "comb", "[", "l", "]", "+", "1", ")", "+", "')'", "elif", "the", "[", "l", "]", "==", "0", ":", "pass", "elif", "the", "[", "l", "]", ">", "0", ":", "The", "+=", "'+'", "+", "str", "(", "the", "[", "l", "]", ")", "+", "'*detuning('", "+", "str", "(", "acum", "+", "comb", "[", "l", "]", "+", "1", ")", "+", "')'", "else", ":", "The", "+=", "str", "(", "the", "[", "l", "]", ")", "+", "'*detuning('", "+", "str", "(", "acum", "+", "comb", "[", "l", "]", "+", "1", ")", "+", "')'", "acum", "+=", "detuning_indices", "[", "l", "]", "if", "The", "[", ":", "1", "]", "==", "'+'", ":", "The", "=", "The", "[", "1", ":", "]", "####################################################################", "#print 'The',The", "return", "The" ]
This function returns code for Theta_i j as defined in the equation labeled Theta. in terms of detunings. It recieves indexes i,j starting from 1.
[ "This", "function", "returns", "code", "for", "Theta_i", "j", "as", "defined", "in", "the", "equation", "labeled", "Theta", ".", "in", "terms", "of", "detunings", ".", "It", "recieves", "indexes", "i", "j", "starting", "from", "1", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/misc.py#L329-L527
oscarlazoarjona/fast
build/lib/fast/misc.py
dot_product
def dot_product(laserl,sign,r,i,j): "This function calculates the dot product epsilon^(l(+-)) . vec(r_ij)." if sign==1: dp=sum([laserl.Yp[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)]) elif sign==-1: dp=sum([laserl.Ym[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)]) #~ if i==2 and j==9 and sign==-1: #~ print 222 #~ print dp #~ print [(laserl.Yp[1-p],r[p+1][i-1][j-1]) for p in range(-1,2)] if not sage_included: return complex(dp) else: return dp
python
def dot_product(laserl,sign,r,i,j): "This function calculates the dot product epsilon^(l(+-)) . vec(r_ij)." if sign==1: dp=sum([laserl.Yp[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)]) elif sign==-1: dp=sum([laserl.Ym[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)]) #~ if i==2 and j==9 and sign==-1: #~ print 222 #~ print dp #~ print [(laserl.Yp[1-p],r[p+1][i-1][j-1]) for p in range(-1,2)] if not sage_included: return complex(dp) else: return dp
[ "def", "dot_product", "(", "laserl", ",", "sign", ",", "r", ",", "i", ",", "j", ")", ":", "if", "sign", "==", "1", ":", "dp", "=", "sum", "(", "[", "laserl", ".", "Yp", "[", "1", "-", "p", "]", "*", "r", "[", "p", "+", "1", "]", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "*", "(", "-", "1", ")", "**", "p", "for", "p", "in", "range", "(", "-", "1", ",", "2", ")", "]", ")", "elif", "sign", "==", "-", "1", ":", "dp", "=", "sum", "(", "[", "laserl", ".", "Ym", "[", "1", "-", "p", "]", "*", "r", "[", "p", "+", "1", "]", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "*", "(", "-", "1", ")", "**", "p", "for", "p", "in", "range", "(", "-", "1", ",", "2", ")", "]", ")", "#~ if i==2 and j==9 and sign==-1:", "#~ print 222", "#~ print dp", "#~ print [(laserl.Yp[1-p],r[p+1][i-1][j-1]) for p in range(-1,2)]", "if", "not", "sage_included", ":", "return", "complex", "(", "dp", ")", "else", ":", "return", "dp" ]
This function calculates the dot product epsilon^(l(+-)) . vec(r_ij).
[ "This", "function", "calculates", "the", "dot", "product", "epsilon^", "(", "l", "(", "+", "-", "))", ".", "vec", "(", "r_ij", ")", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/misc.py#L529-L545
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 '&mdash;' elif entity['source'] == 'bandgap': html_class = ' class=_g' out = json_obj.get('bandgap') if out is None: out = '&mdash;' # dynamic determination below: elif entity['source'] == 'energy': html_class = ' class=_e' out = "%6.5f" % json_obj['energy'] if json_obj['energy'] else '&mdash;' elif entity['source'] == 'dims': out = "%4.2f" % json_obj['dims'] if json_obj['periodicity'] in [2, 3] else '&mdash;' else: out = num2name(json_obj.get(entity['source']), entity, mapping) or '&mdash;' 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 '&mdash;' elif entity['source'] == 'bandgap': html_class = ' class=_g' out = json_obj.get('bandgap') if out is None: out = '&mdash;' # dynamic determination below: elif entity['source'] == 'energy': html_class = ' class=_e' out = "%6.5f" % json_obj['energy'] if json_obj['energy'] else '&mdash;' elif entity['source'] == 'dims': out = "%4.2f" % json_obj['dims'] if json_obj['periodicity'] in [2, 3] else '&mdash;' else: out = num2name(json_obj.get(entity['source']), entity, mapping) or '&mdash;' 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 = 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", "'&mdash;'", "elif", "entity", "[", "'source'", "]", "==", "'bandgap'", ":", "html_class", "=", "' class=_g'", "out", "=", "json_obj", ".", "get", "(", "'bandgap'", ")", "if", "out", "is", "None", ":", "out", "=", "'&mdash;'", "# dynamic determination below:", "elif", "entity", "[", "'source'", "]", "==", "'energy'", ":", "html_class", "=", "' class=_e'", "out", "=", "\"%6.5f\"", "%", "json_obj", "[", "'energy'", "]", "if", "json_obj", "[", "'energy'", "]", "else", "'&mdash;'", "elif", "entity", "[", "'source'", "]", "==", "'dims'", ":", "out", "=", "\"%4.2f\"", "%", "json_obj", "[", "'dims'", "]", "if", "json_obj", "[", "'periodicity'", "]", "in", "[", "2", ",", "3", "]", "else", "'&mdash;'", "else", ":", "out", "=", "num2name", "(", "json_obj", ".", "get", "(", "entity", "[", "'source'", "]", ")", ",", "entity", ",", "mapping", ")", "or", "'&mdash;'", "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", ")" ]
Cell wrappers for customizing the GUI data table TODO : must coincide with hierarchy! TODO : simplify this!
[ "Cell", "wrappers", "for", "customizing", "the", "GUI", "data", "table" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/categs.py#L4-L46
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", "]", "==", "\"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" ]
Get the amount of memory and swap, Mebibytes
[ "Get", "the", "amount", "of", "memory", "and", "swap", "Mebibytes" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L34-L47
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", "[", "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" ]
Get the cpu info
[ "Get", "the", "cpu", "info" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L49-L63
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'", ")", "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" ]
Get data about the graphics card.
[ "Get", "data", "about", "the", "graphics", "card", "." ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L70-L84
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", "(", ")", ".", "strip", "(", ")", "except", ":", "for", "line", "in", "os", ".", "popen", "(", "'/usr/sbin/dmidecode -s system-serial-number'", ")", ":", "sdata", "[", "'Serial'", "]", "=", "line", ".", "strip", "(", ")", "return", "sdata" ]
Get the serial number. Requires root access
[ "Get", "the", "serial", "number", ".", "Requires", "root", "access" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L86-L96
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'", ")", ".", "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" ]
Get manufacturer and model number. On older Linux kernel versions without /sys/class/dmi/id this requires root access.
[ "Get", "manufacturer", "and", "model", "number", "." ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L98-L125
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", "(", "\"/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" ]
Get total disk size in GB.
[ "Get", "total", "disk", "size", "in", "GB", "." ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L127-L138
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", "=", "s", ".", "getsockname", "(", ")", "[", "0", "]", "s", ".", "close", "(", ")", "return", "ip" ]
Get the IP address used for public connections.
[ "Get", "the", "IP", "address", "used", "for", "public", "connections", "." ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L155-L162
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", "]", "==", "'HWaddr'", ":", "mac", "=", "s", "[", "4", "]", "elif", "s", "[", "2", "]", "==", "ip", ":", "break", "return", "{", "'MAC'", ":", "mac", "}" ]
Get the MAC address
[ "Get", "the", "MAC", "address" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L164-L174
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", ".", "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" ]
Get all the hw info.
[ "Get", "all", "the", "hw", "info", "." ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L176-L190
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", "." ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L200-L203
tilde-lab/tilde
utils/syshwinfo.py
printtable
def printtable(h, header): """Print as a table.""" hk = header_fields(h) if (header): printheader() writer = csv.DictWriter(sys.stdout, hk, extrasaction='ignore') writer.writerow(h)
python
def printtable(h, header): """Print as a table.""" hk = header_fields(h) if (header): printheader() writer = csv.DictWriter(sys.stdout, hk, extrasaction='ignore') writer.writerow(h)
[ "def", "printtable", "(", "h", ",", "header", ")", ":", "hk", "=", "header_fields", "(", "h", ")", "if", "(", "header", ")", ":", "printheader", "(", ")", "writer", "=", "csv", ".", "DictWriter", "(", "sys", ".", "stdout", ",", "hk", ",", "extrasaction", "=", "'ignore'", ")", "writer", ".", "writerow", "(", "h", ")" ]
Print as a table.
[ "Print", "as", "a", "table", "." ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L205-L211
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", "(", ")", "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", ")" ]
Run in agent mode. This gathers data, and sends it to a server given by the server argument.
[ "Run", "in", "agent", "mode", "." ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L213-L229
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", "]", ".", "nu", ")", "/", "Omega", "for", "j", "in", "range", "(", "N", ")", "]", "for", "i", "in", "range", "(", "N", ")", "]", "return", "omega" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1279-L1290
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", "(", "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" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1316-L1386
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", "# 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" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1526-L1567
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", "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" ]
Exclude states from matrices. This function takes the matrices and excludes the states listed in excluded_states.
[ "Exclude", "states", "from", "matrices", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1604-L1637
oscarlazoarjona/fast
build/lib/fast/atomic_structure.py
calculate_reduced_matrix_elements_0
def calculate_reduced_matrix_elements_0(fine_states): '''This function calculates the reduced matrix elments <N,L,J||T^1(r)||N',L',J'> given a list of fine states.''' #We calculate the reduced matrix elements starting from the list of fine_states #The factor composed of physical quantities. factor=sqrt(3*c**3*me**2*e**2/(16*Pi*epsilon0*hbar**3)) #We read the database to obtain the Einstein A coefficients in Hz. einsteinA=get_einstein_A_matrix(fine_states) #We read the database to obtain the transition frequencies in Hz. omega_fine=calculate_omega_matrix(fine_states) reduced_matrix_elements=[[0.0 for jj in range(len(fine_states))] for ii in range(len(fine_states))] for ii in range(len(fine_states)): i=fine_states[ii] for jj in range(ii): j=fine_states[jj] t=Transition(i,j) einsteinAij=einsteinA[ii][jj] omega0=omega_fine[ii][jj] #The formula is valid only for i =/= j so that omega0 =/= 0. #Because fine states are asumed to be ordered by their energies we can asume that # i decays in j. Ji=i.j; Jj=j.j rij=sqrt((2.0*Ji+1)/(2*Jj+1))*sqrt(einsteinAij/omega0**3) rij=factor*rij reduced_matrix_elements[ii][jj]=rij #We add the matrix elements on the other side of the diagonal. reduced_matrix_elements[jj][ii]=rij*(-1)**(Jj-Ji) return reduced_matrix_elements
python
def calculate_reduced_matrix_elements_0(fine_states): '''This function calculates the reduced matrix elments <N,L,J||T^1(r)||N',L',J'> given a list of fine states.''' #We calculate the reduced matrix elements starting from the list of fine_states #The factor composed of physical quantities. factor=sqrt(3*c**3*me**2*e**2/(16*Pi*epsilon0*hbar**3)) #We read the database to obtain the Einstein A coefficients in Hz. einsteinA=get_einstein_A_matrix(fine_states) #We read the database to obtain the transition frequencies in Hz. omega_fine=calculate_omega_matrix(fine_states) reduced_matrix_elements=[[0.0 for jj in range(len(fine_states))] for ii in range(len(fine_states))] for ii in range(len(fine_states)): i=fine_states[ii] for jj in range(ii): j=fine_states[jj] t=Transition(i,j) einsteinAij=einsteinA[ii][jj] omega0=omega_fine[ii][jj] #The formula is valid only for i =/= j so that omega0 =/= 0. #Because fine states are asumed to be ordered by their energies we can asume that # i decays in j. Ji=i.j; Jj=j.j rij=sqrt((2.0*Ji+1)/(2*Jj+1))*sqrt(einsteinAij/omega0**3) rij=factor*rij reduced_matrix_elements[ii][jj]=rij #We add the matrix elements on the other side of the diagonal. reduced_matrix_elements[jj][ii]=rij*(-1)**(Jj-Ji) return reduced_matrix_elements
[ "def", "calculate_reduced_matrix_elements_0", "(", "fine_states", ")", ":", "#We calculate the reduced matrix elements starting from the list of fine_states", "#The factor composed of physical quantities.", "factor", "=", "sqrt", "(", "3", "*", "c", "**", "3", "*", "me", "**", "2", "*", "e", "**", "2", "/", "(", "16", "*", "Pi", "*", "epsilon0", "*", "hbar", "**", "3", ")", ")", "#We read the database to obtain the Einstein A coefficients in Hz.", "einsteinA", "=", "get_einstein_A_matrix", "(", "fine_states", ")", "#We read the database to obtain the transition frequencies in Hz.", "omega_fine", "=", "calculate_omega_matrix", "(", "fine_states", ")", "reduced_matrix_elements", "=", "[", "[", "0.0", "for", "jj", "in", "range", "(", "len", "(", "fine_states", ")", ")", "]", "for", "ii", "in", "range", "(", "len", "(", "fine_states", ")", ")", "]", "for", "ii", "in", "range", "(", "len", "(", "fine_states", ")", ")", ":", "i", "=", "fine_states", "[", "ii", "]", "for", "jj", "in", "range", "(", "ii", ")", ":", "j", "=", "fine_states", "[", "jj", "]", "t", "=", "Transition", "(", "i", ",", "j", ")", "einsteinAij", "=", "einsteinA", "[", "ii", "]", "[", "jj", "]", "omega0", "=", "omega_fine", "[", "ii", "]", "[", "jj", "]", "#The formula is valid only for i =/= j so that omega0 =/= 0.", "#Because fine states are asumed to be ordered by their energies we can asume that", "# i decays in j.", "Ji", "=", "i", ".", "j", "Jj", "=", "j", ".", "j", "rij", "=", "sqrt", "(", "(", "2.0", "*", "Ji", "+", "1", ")", "/", "(", "2", "*", "Jj", "+", "1", ")", ")", "*", "sqrt", "(", "einsteinAij", "/", "omega0", "**", "3", ")", "rij", "=", "factor", "*", "rij", "reduced_matrix_elements", "[", "ii", "]", "[", "jj", "]", "=", "rij", "#We add the matrix elements on the other side of the diagonal.", "reduced_matrix_elements", "[", "jj", "]", "[", "ii", "]", "=", "rij", "*", "(", "-", "1", ")", "**", "(", "Jj", "-", "Ji", ")", "return", "reduced_matrix_elements" ]
This function calculates the reduced matrix elments <N,L,J||T^1(r)||N',L',J'> given a list of fine states.
[ "This", "function", "calculates", "the", "reduced", "matrix", "elments", "<N", "L", "J||T^1", "(", "r", ")", "||N", "L", "J", ">", "given", "a", "list", "of", "fine", "states", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1734-L1767
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", "-", "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" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1904-L1956
oscarlazoarjona/fast
build/lib/fast/atomic_structure.py
speed_average
def speed_average(Temperature,element,isotope): r"""This function calculates the average speed (in meters per second) of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution. This is simply sqrt(8*k_B*T/m/pi) where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and m is the mass of the atom (in kilograms). >>> print speed_average(25+273.15,"Rb",85) 272.65940782 >>> print speed_average(25+273.15,"Cs",133) 217.938062809 """ atom = Atom(element, isotope) return sqrt(8*k_B*Temperature/atom.mass/pi)
python
def speed_average(Temperature,element,isotope): r"""This function calculates the average speed (in meters per second) of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution. This is simply sqrt(8*k_B*T/m/pi) where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and m is the mass of the atom (in kilograms). >>> print speed_average(25+273.15,"Rb",85) 272.65940782 >>> print speed_average(25+273.15,"Cs",133) 217.938062809 """ atom = Atom(element, isotope) return sqrt(8*k_B*Temperature/atom.mass/pi)
[ "def", "speed_average", "(", "Temperature", ",", "element", ",", "isotope", ")", ":", "atom", "=", "Atom", "(", "element", ",", "isotope", ")", "return", "sqrt", "(", "8", "*", "k_B", "*", "Temperature", "/", "atom", ".", "mass", "/", "pi", ")" ]
r"""This function calculates the average speed (in meters per second) of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution. This is simply sqrt(8*k_B*T/m/pi) where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and m is the mass of the atom (in kilograms). >>> print speed_average(25+273.15,"Rb",85) 272.65940782 >>> print speed_average(25+273.15,"Cs",133) 217.938062809
[ "r", "This", "function", "calculates", "the", "average", "speed", "(", "in", "meters", "per", "second", ")", "of", "an", "atom", "in", "a", "vapour", "assuming", "a", "Maxwell", "-", "Boltzmann", "velocity", "distribution", ".", "This", "is", "simply" ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L2021-L2039
oscarlazoarjona/fast
build/lib/fast/atomic_structure.py
speed_rms
def speed_rms(Temperature,element,isotope): r"""This function calculates the average speed (in meters per second) of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution. This is simply sqrt(8*k_B*T/m/pi) where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and m is the mass of the atom (in kilograms). >>> print speed_rms(25+273.15,"Rb",85) 295.945034349 >>> print speed_rms(25+273.15,"Cs",133) 236.550383496 """ atom = Atom(element, isotope) return sqrt(3*Temperature*k_B/atom.mass)
python
def speed_rms(Temperature,element,isotope): r"""This function calculates the average speed (in meters per second) of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution. This is simply sqrt(8*k_B*T/m/pi) where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and m is the mass of the atom (in kilograms). >>> print speed_rms(25+273.15,"Rb",85) 295.945034349 >>> print speed_rms(25+273.15,"Cs",133) 236.550383496 """ atom = Atom(element, isotope) return sqrt(3*Temperature*k_B/atom.mass)
[ "def", "speed_rms", "(", "Temperature", ",", "element", ",", "isotope", ")", ":", "atom", "=", "Atom", "(", "element", ",", "isotope", ")", "return", "sqrt", "(", "3", "*", "Temperature", "*", "k_B", "/", "atom", ".", "mass", ")" ]
r"""This function calculates the average speed (in meters per second) of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution. This is simply sqrt(8*k_B*T/m/pi) where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and m is the mass of the atom (in kilograms). >>> print speed_rms(25+273.15,"Rb",85) 295.945034349 >>> print speed_rms(25+273.15,"Cs",133) 236.550383496
[ "r", "This", "function", "calculates", "the", "average", "speed", "(", "in", "meters", "per", "second", ")", "of", "an", "atom", "in", "a", "vapour", "assuming", "a", "Maxwell", "-", "Boltzmann", "velocity", "distribution", ".", "This", "is", "simply" ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L2042-L2060
oscarlazoarjona/fast
build/lib/fast/atomic_structure.py
collision_rate
def collision_rate(Temperature, element, isotope): r"""This function recieves the temperature of an atomic vapour (in Kelvin), the element, and the isotope of the atoms, and returns the angular frequency rate of collisions (in rad/s) in a vapour assuming a Maxwell-Boltzmann velocity distribution, and taking the cross section of the collision to be sigma=pi*(2*r)**2 where r is the atomic radius. colission rate returned is gamma_col=2*pi* ( sigma * v * n ) where v is the average velocity of the distribution, and n is the number density of the vapour. A few examples (in Hz): >>> print collision_rate(25 + 273.15, "Cs", 133)/2/pi 9.0607260277 For cesium collisions become important for temperatures above 120 Celsius. >>> print collision_rate(120 + 273.15, "Cs", 133)/2/pi 10519.235289 """ atom=Atom(element,isotope) sigma=pi*(2*atom.radius)**2 v=speed_average(Temperature,element,isotope) n=vapour_number_density(Temperature,element) return 2*pi*sigma*v*n
python
def collision_rate(Temperature, element, isotope): r"""This function recieves the temperature of an atomic vapour (in Kelvin), the element, and the isotope of the atoms, and returns the angular frequency rate of collisions (in rad/s) in a vapour assuming a Maxwell-Boltzmann velocity distribution, and taking the cross section of the collision to be sigma=pi*(2*r)**2 where r is the atomic radius. colission rate returned is gamma_col=2*pi* ( sigma * v * n ) where v is the average velocity of the distribution, and n is the number density of the vapour. A few examples (in Hz): >>> print collision_rate(25 + 273.15, "Cs", 133)/2/pi 9.0607260277 For cesium collisions become important for temperatures above 120 Celsius. >>> print collision_rate(120 + 273.15, "Cs", 133)/2/pi 10519.235289 """ atom=Atom(element,isotope) sigma=pi*(2*atom.radius)**2 v=speed_average(Temperature,element,isotope) n=vapour_number_density(Temperature,element) return 2*pi*sigma*v*n
[ "def", "collision_rate", "(", "Temperature", ",", "element", ",", "isotope", ")", ":", "atom", "=", "Atom", "(", "element", ",", "isotope", ")", "sigma", "=", "pi", "*", "(", "2", "*", "atom", ".", "radius", ")", "**", "2", "v", "=", "speed_average", "(", "Temperature", ",", "element", ",", "isotope", ")", "n", "=", "vapour_number_density", "(", "Temperature", ",", "element", ")", "return", "2", "*", "pi", "*", "sigma", "*", "v", "*", "n" ]
r"""This function recieves the temperature of an atomic vapour (in Kelvin), the element, and the isotope of the atoms, and returns the angular frequency rate of collisions (in rad/s) in a vapour assuming a Maxwell-Boltzmann velocity distribution, and taking the cross section of the collision to be sigma=pi*(2*r)**2 where r is the atomic radius. colission rate returned is gamma_col=2*pi* ( sigma * v * n ) where v is the average velocity of the distribution, and n is the number density of the vapour. A few examples (in Hz): >>> print collision_rate(25 + 273.15, "Cs", 133)/2/pi 9.0607260277 For cesium collisions become important for temperatures above 120 Celsius. >>> print collision_rate(120 + 273.15, "Cs", 133)/2/pi 10519.235289
[ "r", "This", "function", "recieves", "the", "temperature", "of", "an", "atomic", "vapour", "(", "in", "Kelvin", ")", "the", "element", "and", "the", "isotope", "of", "the", "atoms", "and", "returns", "the", "angular", "frequency", "rate", "of", "collisions", "(", "in", "rad", "/", "s", ")", "in", "a", "vapour", "assuming", "a", "Maxwell", "-", "Boltzmann", "velocity", "distribution", "and", "taking", "the", "cross", "section", "of", "the", "collision", "to", "be" ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L2063-L2093
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", "(", "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" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L229-L292
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", ":", "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" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L342-L381
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", ".", "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" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L926-L955
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", ".", "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_", "(", ")" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1163-L1179
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 '''", "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" ]
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" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/cubicspline.py#L23-L77
tilde-lab/tilde
tilde/berlinium/cubicspline.py
NaturalCubicSpline._findSegment
def _findSegment(self, x): ''' :param x: x value to place in segment defined by the xData (instantiation) :return: The lower index in the segment ''' iLeft = 0 iRight = len(self.xData) - 1 while True: if iRight - iLeft <= 1: return iLeft i = (iRight + iLeft) / 2 if x < self.xData[i]: iRight = i else: iLeft = i
python
def _findSegment(self, x): ''' :param x: x value to place in segment defined by the xData (instantiation) :return: The lower index in the segment ''' iLeft = 0 iRight = len(self.xData) - 1 while True: if iRight - iLeft <= 1: return iLeft i = (iRight + iLeft) / 2 if x < self.xData[i]: iRight = i else: iLeft = i
[ "def", "_findSegment", "(", "self", ",", "x", ")", ":", "iLeft", "=", "0", "iRight", "=", "len", "(", "self", ".", "xData", ")", "-", "1", "while", "True", ":", "if", "iRight", "-", "iLeft", "<=", "1", ":", "return", "iLeft", "i", "=", "(", "iRight", "+", "iLeft", ")", "/", "2", "if", "x", "<", "self", ".", "xData", "[", "i", "]", ":", "iRight", "=", "i", "else", ":", "iLeft", "=", "i" ]
:param x: x value to place in segment defined by the xData (instantiation) :return: The lower index in the segment
[ ":", "param", "x", ":", "x", "value", "to", "place", "in", "segment", "defined", "by", "the", "xData", "(", "instantiation", ")", ":", "return", ":", "The", "lower", "index", "in", "the", "segment" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/cubicspline.py#L240-L254
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", ",", "i", "]", "=", "hbar", "*", "states", "[", "i", "]", ".", "omega", "return", "H0" ]
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", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1433-L1449