id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,600 | planetarypy/planetaryimage | planetaryimage/image.py | PlanetaryImage.image | def image(self):
"""An Image like array of ``self.data`` convenient for image processing tasks
* 2D array for single band, grayscale image data
* 3D array for three band, RGB image data
Enables working with ``self.data`` as if it were a PIL image.
See https://planetaryimage.readthedocs.io/en/latest/usage.html to see
how to open images to view them and make manipulations.
"""
if self.bands == 1:
return self.data.squeeze()
elif self.bands == 3:
return numpy.dstack(self.data) | python | def image(self):
if self.bands == 1:
return self.data.squeeze()
elif self.bands == 3:
return numpy.dstack(self.data) | [
"def",
"image",
"(",
"self",
")",
":",
"if",
"self",
".",
"bands",
"==",
"1",
":",
"return",
"self",
".",
"data",
".",
"squeeze",
"(",
")",
"elif",
"self",
".",
"bands",
"==",
"3",
":",
"return",
"numpy",
".",
"dstack",
"(",
"self",
".",
"data",
... | An Image like array of ``self.data`` convenient for image processing tasks
* 2D array for single band, grayscale image data
* 3D array for three band, RGB image data
Enables working with ``self.data`` as if it were a PIL image.
See https://planetaryimage.readthedocs.io/en/latest/usage.html to see
how to open images to view them and make manipulations. | [
"An",
"Image",
"like",
"array",
"of",
"self",
".",
"data",
"convenient",
"for",
"image",
"processing",
"tasks"
] | ee9aef4746ff7a003b1457565acb13f5f1db0375 | https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/image.py#L131-L146 |
22,601 | planetarypy/planetaryimage | planetaryimage/cubefile.py | CubeFile.apply_numpy_specials | def apply_numpy_specials(self, copy=True):
"""Convert isis special pixel values to numpy special pixel values.
======= =======
Isis Numpy
======= =======
Null nan
Lrs -inf
Lis -inf
His inf
Hrs inf
======= =======
Parameters
----------
copy : bool [True]
Whether to apply the new special values to a copy of the
pixel data and leave the original unaffected
Returns
-------
Numpy Array
A numpy array with special values converted to numpy's nan, inf,
and -inf
"""
if copy:
data = self.data.astype(numpy.float64)
elif self.data.dtype != numpy.float64:
data = self.data = self.data.astype(numpy.float64)
else:
data = self.data
data[data == self.specials['Null']] = numpy.nan
data[data < self.specials['Min']] = numpy.NINF
data[data > self.specials['Max']] = numpy.inf
return data | python | def apply_numpy_specials(self, copy=True):
if copy:
data = self.data.astype(numpy.float64)
elif self.data.dtype != numpy.float64:
data = self.data = self.data.astype(numpy.float64)
else:
data = self.data
data[data == self.specials['Null']] = numpy.nan
data[data < self.specials['Min']] = numpy.NINF
data[data > self.specials['Max']] = numpy.inf
return data | [
"def",
"apply_numpy_specials",
"(",
"self",
",",
"copy",
"=",
"True",
")",
":",
"if",
"copy",
":",
"data",
"=",
"self",
".",
"data",
".",
"astype",
"(",
"numpy",
".",
"float64",
")",
"elif",
"self",
".",
"data",
".",
"dtype",
"!=",
"numpy",
".",
"f... | Convert isis special pixel values to numpy special pixel values.
======= =======
Isis Numpy
======= =======
Null nan
Lrs -inf
Lis -inf
His inf
Hrs inf
======= =======
Parameters
----------
copy : bool [True]
Whether to apply the new special values to a copy of the
pixel data and leave the original unaffected
Returns
-------
Numpy Array
A numpy array with special values converted to numpy's nan, inf,
and -inf | [
"Convert",
"isis",
"special",
"pixel",
"values",
"to",
"numpy",
"special",
"pixel",
"values",
"."
] | ee9aef4746ff7a003b1457565acb13f5f1db0375 | https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/cubefile.py#L161-L199 |
22,602 | planetarypy/planetaryimage | planetaryimage/pds3image.py | Pointer.parse | def parse(cls, value, record_bytes):
"""Parses the pointer label.
Parameters
----------
pointer_data
Supported values for `pointer_data` are::
^PTR = nnn
^PTR = nnn <BYTES>
^PTR = "filename"
^PTR = ("filename")
^PTR = ("filename", nnn)
^PTR = ("filename", nnn <BYTES>)
record_bytes
Record multiplier value
Returns
-------
Pointer object
"""
if isinstance(value, six.string_types):
return cls(value, 0)
if isinstance(value, list):
if len(value) == 1:
return cls(value[0], 0)
if len(value) == 2:
return cls(value[0], cls._parse_bytes(value[1], record_bytes))
raise ValueError('Unsupported pointer type')
return cls(None, cls._parse_bytes(value, record_bytes)) | python | def parse(cls, value, record_bytes):
if isinstance(value, six.string_types):
return cls(value, 0)
if isinstance(value, list):
if len(value) == 1:
return cls(value[0], 0)
if len(value) == 2:
return cls(value[0], cls._parse_bytes(value[1], record_bytes))
raise ValueError('Unsupported pointer type')
return cls(None, cls._parse_bytes(value, record_bytes)) | [
"def",
"parse",
"(",
"cls",
",",
"value",
",",
"record_bytes",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"return",
"cls",
"(",
"value",
",",
"0",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
... | Parses the pointer label.
Parameters
----------
pointer_data
Supported values for `pointer_data` are::
^PTR = nnn
^PTR = nnn <BYTES>
^PTR = "filename"
^PTR = ("filename")
^PTR = ("filename", nnn)
^PTR = ("filename", nnn <BYTES>)
record_bytes
Record multiplier value
Returns
-------
Pointer object | [
"Parses",
"the",
"pointer",
"label",
"."
] | ee9aef4746ff7a003b1457565acb13f5f1db0375 | https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/pds3image.py#L24-L58 |
22,603 | planetarypy/planetaryimage | planetaryimage/pds3image.py | PDS3Image._save | def _save(self, file_to_write, overwrite):
"""Save PDS3Image object as PDS3 file.
Parameters
----------
filename: Set filename for the pds image to be saved.
Overwrite: Use this keyword to save image with same filename.
Usage: image.save('temp.IMG', overwrite=True)
"""
if overwrite:
file_to_write = self.filename
elif os.path.isfile(file_to_write):
msg = 'File ' + file_to_write + ' already exists !\n' + \
'Call save() with "overwrite = True" to overwrite the file.'
raise IOError(msg)
encoder = pvl.encoder.PDSLabelEncoder
serial_label = pvl.dumps(self.label, cls=encoder)
label_sz = len(serial_label)
image_pointer = int(label_sz / self.label['RECORD_BYTES']) + 1
self.label['^IMAGE'] = image_pointer + 1
if self._sample_bytes != self.label['IMAGE']['SAMPLE_BITS'] * 8:
self.label['IMAGE']['SAMPLE_BITS'] = self.data.itemsize * 8
sample_type_to_save = self.DTYPES[self._sample_type[0] + self.dtype.kind]
self.label['IMAGE']['SAMPLE_TYPE'] = sample_type_to_save
if len(self.data.shape) == 3:
self.label['IMAGE']['BANDS'] = self.data.shape[0]
self.label['IMAGE']['LINES'] = self.data.shape[1]
self.label['IMAGE']['LINE_SAMPLES'] = self.data.shape[2]
else:
self.label['IMAGE']['BANDS'] = 1
self.label['IMAGE']['LINES'] = self.data.shape[0]
self.label['IMAGE']['LINE_SAMPLES'] = self.data.shape[1]
diff = 0
if len(pvl.dumps(self.label, cls=encoder)) != label_sz:
diff = abs(label_sz - len(pvl.dumps(self.label, cls=encoder)))
pvl.dump(self.label, file_to_write, cls=encoder)
offset = image_pointer * self.label['RECORD_BYTES'] - label_sz
stream = open(file_to_write, 'a')
for i in range(0, offset+diff):
stream.write(" ")
if (self._bands > 1 and self._format != 'BAND_SEQUENTIAL'):
raise NotImplementedError
else:
self.data.tofile(stream, format='%' + self.dtype.kind)
stream.close() | python | def _save(self, file_to_write, overwrite):
if overwrite:
file_to_write = self.filename
elif os.path.isfile(file_to_write):
msg = 'File ' + file_to_write + ' already exists !\n' + \
'Call save() with "overwrite = True" to overwrite the file.'
raise IOError(msg)
encoder = pvl.encoder.PDSLabelEncoder
serial_label = pvl.dumps(self.label, cls=encoder)
label_sz = len(serial_label)
image_pointer = int(label_sz / self.label['RECORD_BYTES']) + 1
self.label['^IMAGE'] = image_pointer + 1
if self._sample_bytes != self.label['IMAGE']['SAMPLE_BITS'] * 8:
self.label['IMAGE']['SAMPLE_BITS'] = self.data.itemsize * 8
sample_type_to_save = self.DTYPES[self._sample_type[0] + self.dtype.kind]
self.label['IMAGE']['SAMPLE_TYPE'] = sample_type_to_save
if len(self.data.shape) == 3:
self.label['IMAGE']['BANDS'] = self.data.shape[0]
self.label['IMAGE']['LINES'] = self.data.shape[1]
self.label['IMAGE']['LINE_SAMPLES'] = self.data.shape[2]
else:
self.label['IMAGE']['BANDS'] = 1
self.label['IMAGE']['LINES'] = self.data.shape[0]
self.label['IMAGE']['LINE_SAMPLES'] = self.data.shape[1]
diff = 0
if len(pvl.dumps(self.label, cls=encoder)) != label_sz:
diff = abs(label_sz - len(pvl.dumps(self.label, cls=encoder)))
pvl.dump(self.label, file_to_write, cls=encoder)
offset = image_pointer * self.label['RECORD_BYTES'] - label_sz
stream = open(file_to_write, 'a')
for i in range(0, offset+diff):
stream.write(" ")
if (self._bands > 1 and self._format != 'BAND_SEQUENTIAL'):
raise NotImplementedError
else:
self.data.tofile(stream, format='%' + self.dtype.kind)
stream.close() | [
"def",
"_save",
"(",
"self",
",",
"file_to_write",
",",
"overwrite",
")",
":",
"if",
"overwrite",
":",
"file_to_write",
"=",
"self",
".",
"filename",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"file_to_write",
")",
":",
"msg",
"=",
"'File '",
"+",
... | Save PDS3Image object as PDS3 file.
Parameters
----------
filename: Set filename for the pds image to be saved.
Overwrite: Use this keyword to save image with same filename.
Usage: image.save('temp.IMG', overwrite=True) | [
"Save",
"PDS3Image",
"object",
"as",
"PDS3",
"file",
"."
] | ee9aef4746ff7a003b1457565acb13f5f1db0375 | https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/pds3image.py#L129-L181 |
22,604 | planetarypy/planetaryimage | planetaryimage/pds3image.py | PDS3Image._create_label | def _create_label(self, array):
"""Create sample PDS3 label for NumPy Array.
It is called by 'image.py' to create PDS3Image object
from Numpy Array.
Returns
-------
PVLModule label for the given NumPy array.
Usage: self.label = _create_label(array)
"""
if len(array.shape) == 3:
bands = array.shape[0]
lines = array.shape[1]
line_samples = array.shape[2]
else:
bands = 1
lines = array.shape[0]
line_samples = array.shape[1]
record_bytes = line_samples * array.itemsize
label_module = pvl.PVLModule([
('PDS_VERSION_ID', 'PDS3'),
('RECORD_TYPE', 'FIXED_LENGTH'),
('RECORD_BYTES', record_bytes),
('LABEL_RECORDS', 1),
('^IMAGE', 1),
('IMAGE',
{'BANDS': bands,
'LINES': lines,
'LINE_SAMPLES': line_samples,
'MAXIMUM': 0,
'MEAN': 0,
'MEDIAN': 0,
'MINIMUM': 0,
'SAMPLE_BITS': array.itemsize * 8,
'SAMPLE_TYPE': 'MSB_INTEGER',
'STANDARD_DEVIATION': 0})
])
return self._update_label(label_module, array) | python | def _create_label(self, array):
if len(array.shape) == 3:
bands = array.shape[0]
lines = array.shape[1]
line_samples = array.shape[2]
else:
bands = 1
lines = array.shape[0]
line_samples = array.shape[1]
record_bytes = line_samples * array.itemsize
label_module = pvl.PVLModule([
('PDS_VERSION_ID', 'PDS3'),
('RECORD_TYPE', 'FIXED_LENGTH'),
('RECORD_BYTES', record_bytes),
('LABEL_RECORDS', 1),
('^IMAGE', 1),
('IMAGE',
{'BANDS': bands,
'LINES': lines,
'LINE_SAMPLES': line_samples,
'MAXIMUM': 0,
'MEAN': 0,
'MEDIAN': 0,
'MINIMUM': 0,
'SAMPLE_BITS': array.itemsize * 8,
'SAMPLE_TYPE': 'MSB_INTEGER',
'STANDARD_DEVIATION': 0})
])
return self._update_label(label_module, array) | [
"def",
"_create_label",
"(",
"self",
",",
"array",
")",
":",
"if",
"len",
"(",
"array",
".",
"shape",
")",
"==",
"3",
":",
"bands",
"=",
"array",
".",
"shape",
"[",
"0",
"]",
"lines",
"=",
"array",
".",
"shape",
"[",
"1",
"]",
"line_samples",
"="... | Create sample PDS3 label for NumPy Array.
It is called by 'image.py' to create PDS3Image object
from Numpy Array.
Returns
-------
PVLModule label for the given NumPy array.
Usage: self.label = _create_label(array) | [
"Create",
"sample",
"PDS3",
"label",
"for",
"NumPy",
"Array",
".",
"It",
"is",
"called",
"by",
"image",
".",
"py",
"to",
"create",
"PDS3Image",
"object",
"from",
"Numpy",
"Array",
"."
] | ee9aef4746ff7a003b1457565acb13f5f1db0375 | https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/pds3image.py#L183-L222 |
22,605 | planetarypy/planetaryimage | planetaryimage/pds3image.py | PDS3Image._update_label | def _update_label(self, label, array):
"""Update PDS3 label for NumPy Array.
It is called by '_create_label' to update label values
such as,
- ^IMAGE, RECORD_BYTES
- STANDARD_DEVIATION
- MAXIMUM, MINIMUM
- MEDIAN, MEAN
Returns
-------
Update label module for the NumPy array.
Usage: self.label = self._update_label(label, array)
"""
maximum = float(numpy.max(array))
mean = float(numpy.mean(array))
median = float(numpy.median(array))
minimum = float(numpy.min(array))
stdev = float(numpy.std(array, ddof=1))
encoder = pvl.encoder.PDSLabelEncoder
serial_label = pvl.dumps(label, cls=encoder)
label_sz = len(serial_label)
image_pointer = int(label_sz / label['RECORD_BYTES']) + 1
label['^IMAGE'] = image_pointer + 1
label['LABEL_RECORDS'] = image_pointer
label['IMAGE']['MEAN'] = mean
label['IMAGE']['MAXIMUM'] = maximum
label['IMAGE']['MEDIAN'] = median
label['IMAGE']['MINIMUM'] = minimum
label['IMAGE']['STANDARD_DEVIATION'] = stdev
return label | python | def _update_label(self, label, array):
maximum = float(numpy.max(array))
mean = float(numpy.mean(array))
median = float(numpy.median(array))
minimum = float(numpy.min(array))
stdev = float(numpy.std(array, ddof=1))
encoder = pvl.encoder.PDSLabelEncoder
serial_label = pvl.dumps(label, cls=encoder)
label_sz = len(serial_label)
image_pointer = int(label_sz / label['RECORD_BYTES']) + 1
label['^IMAGE'] = image_pointer + 1
label['LABEL_RECORDS'] = image_pointer
label['IMAGE']['MEAN'] = mean
label['IMAGE']['MAXIMUM'] = maximum
label['IMAGE']['MEDIAN'] = median
label['IMAGE']['MINIMUM'] = minimum
label['IMAGE']['STANDARD_DEVIATION'] = stdev
return label | [
"def",
"_update_label",
"(",
"self",
",",
"label",
",",
"array",
")",
":",
"maximum",
"=",
"float",
"(",
"numpy",
".",
"max",
"(",
"array",
")",
")",
"mean",
"=",
"float",
"(",
"numpy",
".",
"mean",
"(",
"array",
")",
")",
"median",
"=",
"float",
... | Update PDS3 label for NumPy Array.
It is called by '_create_label' to update label values
such as,
- ^IMAGE, RECORD_BYTES
- STANDARD_DEVIATION
- MAXIMUM, MINIMUM
- MEDIAN, MEAN
Returns
-------
Update label module for the NumPy array.
Usage: self.label = self._update_label(label, array) | [
"Update",
"PDS3",
"label",
"for",
"NumPy",
"Array",
".",
"It",
"is",
"called",
"by",
"_create_label",
"to",
"update",
"label",
"values",
"such",
"as",
"-",
"^IMAGE",
"RECORD_BYTES",
"-",
"STANDARD_DEVIATION",
"-",
"MAXIMUM",
"MINIMUM",
"-",
"MEDIAN",
"MEAN"
] | ee9aef4746ff7a003b1457565acb13f5f1db0375 | https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/pds3image.py#L224-L259 |
22,606 | web-push-libs/encrypted-content-encoding | python/http_ece/__init__.py | iv | def iv(base, counter):
"""Generate an initialization vector.
"""
if (counter >> 64) != 0:
raise ECEException(u"Counter too big")
(mask,) = struct.unpack("!Q", base[4:])
return base[:4] + struct.pack("!Q", counter ^ mask) | python | def iv(base, counter):
if (counter >> 64) != 0:
raise ECEException(u"Counter too big")
(mask,) = struct.unpack("!Q", base[4:])
return base[:4] + struct.pack("!Q", counter ^ mask) | [
"def",
"iv",
"(",
"base",
",",
"counter",
")",
":",
"if",
"(",
"counter",
">>",
"64",
")",
"!=",
"0",
":",
"raise",
"ECEException",
"(",
"u\"Counter too big\"",
")",
"(",
"mask",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"\"!Q\"",
",",
"base",
"... | Generate an initialization vector. | [
"Generate",
"an",
"initialization",
"vector",
"."
] | 849aebea751752e17fc84a64ce1bbf65dc994e6c | https://github.com/web-push-libs/encrypted-content-encoding/blob/849aebea751752e17fc84a64ce1bbf65dc994e6c/python/http_ece/__init__.py#L164-L171 |
22,607 | web-push-libs/encrypted-content-encoding | python/http_ece/__init__.py | encrypt | def encrypt(content, salt=None, key=None,
private_key=None, dh=None, auth_secret=None,
keyid=None, keylabel="P-256",
rs=4096, version="aes128gcm"):
"""
Encrypt a data block
:param content: block of data to encrypt
:type content: str
:param salt: Encryption salt
:type salt: str
:param key: Encryption key data
:type key: str
:param private_key: DH private key
:type key: object
:param keyid: Internal key identifier for private key info
:type keyid: str
:param dh: Remote Diffie Hellman sequence
:type dh: str
:param rs: Record size
:type rs: int
:param auth_secret: Authorization secret
:type auth_secret: str
:param version: ECE Method version
:type version: enumerate('aes128gcm', 'aesgcm', 'aesgcm128')
:return: Encrypted message content
:rtype str
"""
def encrypt_record(key, nonce, counter, buf, last):
encryptor = Cipher(
algorithms.AES(key),
modes.GCM(iv(nonce, counter)),
backend=default_backend()
).encryptor()
if version == 'aes128gcm':
data = encryptor.update(buf + (b'\x02' if last else b'\x01'))
else:
data = encryptor.update((b"\x00" * versions[version]['pad']) + buf)
data += encryptor.finalize()
data += encryptor.tag
return data
def compose_aes128gcm(salt, content, rs, keyid):
"""Compose the header and content of an aes128gcm encrypted
message body
:param salt: The sender's salt value
:type salt: str
:param content: The encrypted body of the message
:type content: str
:param rs: Override for the content length
:type rs: int
:param keyid: The keyid to use for this message
:type keyid: str
"""
if len(keyid) > 255:
raise ECEException("keyid is too long")
header = salt
if rs > MAX_RECORD_SIZE:
raise ECEException("Too much content")
header += struct.pack("!L", rs)
header += struct.pack("!B", len(keyid))
header += keyid
return header + content
if version not in versions:
raise ECEException(u"Invalid version")
if salt is None:
salt = os.urandom(16)
(key_, nonce_) = derive_key("encrypt", version=version,
salt=salt, key=key,
private_key=private_key, dh=dh,
auth_secret=auth_secret,
keyid=keyid, keylabel=keylabel)
overhead = versions[version]['pad']
if version == 'aes128gcm':
overhead += 16
end = len(content)
else:
end = len(content) + 1
if rs <= overhead:
raise ECEException(u"Record size too small")
chunk_size = rs - overhead
result = b""
counter = 0
# the extra one on the loop ensures that we produce a padding only
# record if the data length is an exact multiple of the chunk size
for i in list(range(0, end, chunk_size)):
result += encrypt_record(key_, nonce_, counter,
content[i:i + chunk_size],
(i + chunk_size) >= end)
counter += 1
if version == "aes128gcm":
if keyid is None and private_key is not None:
kid = private_key.public_key().public_bytes(
Encoding.X962,
PublicFormat.UncompressedPoint)
else:
kid = (keyid or '').encode('utf-8')
return compose_aes128gcm(salt, result, rs, keyid=kid)
return result | python | def encrypt(content, salt=None, key=None,
private_key=None, dh=None, auth_secret=None,
keyid=None, keylabel="P-256",
rs=4096, version="aes128gcm"):
def encrypt_record(key, nonce, counter, buf, last):
encryptor = Cipher(
algorithms.AES(key),
modes.GCM(iv(nonce, counter)),
backend=default_backend()
).encryptor()
if version == 'aes128gcm':
data = encryptor.update(buf + (b'\x02' if last else b'\x01'))
else:
data = encryptor.update((b"\x00" * versions[version]['pad']) + buf)
data += encryptor.finalize()
data += encryptor.tag
return data
def compose_aes128gcm(salt, content, rs, keyid):
"""Compose the header and content of an aes128gcm encrypted
message body
:param salt: The sender's salt value
:type salt: str
:param content: The encrypted body of the message
:type content: str
:param rs: Override for the content length
:type rs: int
:param keyid: The keyid to use for this message
:type keyid: str
"""
if len(keyid) > 255:
raise ECEException("keyid is too long")
header = salt
if rs > MAX_RECORD_SIZE:
raise ECEException("Too much content")
header += struct.pack("!L", rs)
header += struct.pack("!B", len(keyid))
header += keyid
return header + content
if version not in versions:
raise ECEException(u"Invalid version")
if salt is None:
salt = os.urandom(16)
(key_, nonce_) = derive_key("encrypt", version=version,
salt=salt, key=key,
private_key=private_key, dh=dh,
auth_secret=auth_secret,
keyid=keyid, keylabel=keylabel)
overhead = versions[version]['pad']
if version == 'aes128gcm':
overhead += 16
end = len(content)
else:
end = len(content) + 1
if rs <= overhead:
raise ECEException(u"Record size too small")
chunk_size = rs - overhead
result = b""
counter = 0
# the extra one on the loop ensures that we produce a padding only
# record if the data length is an exact multiple of the chunk size
for i in list(range(0, end, chunk_size)):
result += encrypt_record(key_, nonce_, counter,
content[i:i + chunk_size],
(i + chunk_size) >= end)
counter += 1
if version == "aes128gcm":
if keyid is None and private_key is not None:
kid = private_key.public_key().public_bytes(
Encoding.X962,
PublicFormat.UncompressedPoint)
else:
kid = (keyid or '').encode('utf-8')
return compose_aes128gcm(salt, result, rs, keyid=kid)
return result | [
"def",
"encrypt",
"(",
"content",
",",
"salt",
"=",
"None",
",",
"key",
"=",
"None",
",",
"private_key",
"=",
"None",
",",
"dh",
"=",
"None",
",",
"auth_secret",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"keylabel",
"=",
"\"P-256\"",
",",
"rs",
... | Encrypt a data block
:param content: block of data to encrypt
:type content: str
:param salt: Encryption salt
:type salt: str
:param key: Encryption key data
:type key: str
:param private_key: DH private key
:type key: object
:param keyid: Internal key identifier for private key info
:type keyid: str
:param dh: Remote Diffie Hellman sequence
:type dh: str
:param rs: Record size
:type rs: int
:param auth_secret: Authorization secret
:type auth_secret: str
:param version: ECE Method version
:type version: enumerate('aes128gcm', 'aesgcm', 'aesgcm128')
:return: Encrypted message content
:rtype str | [
"Encrypt",
"a",
"data",
"block"
] | 849aebea751752e17fc84a64ce1bbf65dc994e6c | https://github.com/web-push-libs/encrypted-content-encoding/blob/849aebea751752e17fc84a64ce1bbf65dc994e6c/python/http_ece/__init__.py#L297-L405 |
22,608 | varlink/python | varlink/error.py | VarlinkError.parameters | def parameters(self, namespaced=False):
"""returns the exception varlink error parameters"""
if namespaced:
return json.loads(json.dumps(self.args[0]['parameters']), object_hook=lambda d: SimpleNamespace(**d))
else:
return self.args[0].get('parameters') | python | def parameters(self, namespaced=False):
if namespaced:
return json.loads(json.dumps(self.args[0]['parameters']), object_hook=lambda d: SimpleNamespace(**d))
else:
return self.args[0].get('parameters') | [
"def",
"parameters",
"(",
"self",
",",
"namespaced",
"=",
"False",
")",
":",
"if",
"namespaced",
":",
"return",
"json",
".",
"loads",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"args",
"[",
"0",
"]",
"[",
"'parameters'",
"]",
")",
",",
"object_hook... | returns the exception varlink error parameters | [
"returns",
"the",
"exception",
"varlink",
"error",
"parameters"
] | b021a29dd9def06b03416d20e8b37be39c3edd33 | https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/error.py#L66-L71 |
22,609 | varlink/python | varlink/server.py | Service.handle | def handle(self, message, _server=None, _request=None):
"""This generator function handles any incoming message.
Write any returned bytes to the output stream.
>>> for outgoing_message in service.handle(incoming_message):
>>> connection.write(outgoing_message)
"""
if not message:
return
if message[-1] == 0:
message = message[:-1]
string = message.decode('utf-8')
handle = self._handle(json.loads(string), message, _server, _request)
for out in handle:
if out == None:
return
try:
yield json.dumps(out, cls=VarlinkEncoder).encode('utf-8')
except ConnectionError as e:
try:
handle.throw(e)
except StopIteration:
pass | python | def handle(self, message, _server=None, _request=None):
if not message:
return
if message[-1] == 0:
message = message[:-1]
string = message.decode('utf-8')
handle = self._handle(json.loads(string), message, _server, _request)
for out in handle:
if out == None:
return
try:
yield json.dumps(out, cls=VarlinkEncoder).encode('utf-8')
except ConnectionError as e:
try:
handle.throw(e)
except StopIteration:
pass | [
"def",
"handle",
"(",
"self",
",",
"message",
",",
"_server",
"=",
"None",
",",
"_request",
"=",
"None",
")",
":",
"if",
"not",
"message",
":",
"return",
"if",
"message",
"[",
"-",
"1",
"]",
"==",
"0",
":",
"message",
"=",
"message",
"[",
":",
"-... | This generator function handles any incoming message.
Write any returned bytes to the output stream.
>>> for outgoing_message in service.handle(incoming_message):
>>> connection.write(outgoing_message) | [
"This",
"generator",
"function",
"handles",
"any",
"incoming",
"message",
"."
] | b021a29dd9def06b03416d20e8b37be39c3edd33 | https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/server.py#L227-L252 |
22,610 | varlink/python | varlink/server.py | Server.server_close | def server_close(self):
"""Called to clean-up the server.
May be overridden.
"""
if self.remove_file:
try:
os.remove(self.remove_file)
except:
pass
self.socket.close() | python | def server_close(self):
if self.remove_file:
try:
os.remove(self.remove_file)
except:
pass
self.socket.close() | [
"def",
"server_close",
"(",
"self",
")",
":",
"if",
"self",
".",
"remove_file",
":",
"try",
":",
"os",
".",
"remove",
"(",
"self",
".",
"remove_file",
")",
"except",
":",
"pass",
"self",
".",
"socket",
".",
"close",
"(",
")"
] | Called to clean-up the server.
May be overridden. | [
"Called",
"to",
"clean",
"-",
"up",
"the",
"server",
"."
] | b021a29dd9def06b03416d20e8b37be39c3edd33 | https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/server.py#L473-L484 |
22,611 | varlink/python | varlink/client.py | Client.open | def open(self, interface_name, namespaced=False, connection=None):
"""Open a new connection and get a client interface handle with the varlink methods installed.
:param interface_name: an interface name, which the service this client object is
connected to, provides.
:param namespaced: If arguments and return values are instances of SimpleNamespace
rather than dictionaries.
:param connection: If set, get the interface handle for an already opened connection.
:exception InterfaceNotFound: if the interface is not found
"""
if not connection:
connection = self.open_connection()
if interface_name not in self._interfaces:
self.get_interface(interface_name, socket_connection=connection)
if interface_name not in self._interfaces:
raise InterfaceNotFound(interface_name)
return self.handler(self._interfaces[interface_name], connection, namespaced=namespaced) | python | def open(self, interface_name, namespaced=False, connection=None):
if not connection:
connection = self.open_connection()
if interface_name not in self._interfaces:
self.get_interface(interface_name, socket_connection=connection)
if interface_name not in self._interfaces:
raise InterfaceNotFound(interface_name)
return self.handler(self._interfaces[interface_name], connection, namespaced=namespaced) | [
"def",
"open",
"(",
"self",
",",
"interface_name",
",",
"namespaced",
"=",
"False",
",",
"connection",
"=",
"None",
")",
":",
"if",
"not",
"connection",
":",
"connection",
"=",
"self",
".",
"open_connection",
"(",
")",
"if",
"interface_name",
"not",
"in",
... | Open a new connection and get a client interface handle with the varlink methods installed.
:param interface_name: an interface name, which the service this client object is
connected to, provides.
:param namespaced: If arguments and return values are instances of SimpleNamespace
rather than dictionaries.
:param connection: If set, get the interface handle for an already opened connection.
:exception InterfaceNotFound: if the interface is not found | [
"Open",
"a",
"new",
"connection",
"and",
"get",
"a",
"client",
"interface",
"handle",
"with",
"the",
"varlink",
"methods",
"installed",
"."
] | b021a29dd9def06b03416d20e8b37be39c3edd33 | https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/client.py#L585-L606 |
22,612 | varlink/python | varlink/client.py | Client.get_interfaces | def get_interfaces(self, socket_connection=None):
"""Returns the a list of Interface objects the service implements."""
if not socket_connection:
socket_connection = self.open_connection()
close_socket = True
else:
close_socket = False
# noinspection PyUnresolvedReferences
_service = self.handler(self._interfaces["org.varlink.service"], socket_connection)
self.info = _service.GetInfo()
if close_socket:
socket_connection.close()
return self.info['interfaces'] | python | def get_interfaces(self, socket_connection=None):
if not socket_connection:
socket_connection = self.open_connection()
close_socket = True
else:
close_socket = False
# noinspection PyUnresolvedReferences
_service = self.handler(self._interfaces["org.varlink.service"], socket_connection)
self.info = _service.GetInfo()
if close_socket:
socket_connection.close()
return self.info['interfaces'] | [
"def",
"get_interfaces",
"(",
"self",
",",
"socket_connection",
"=",
"None",
")",
":",
"if",
"not",
"socket_connection",
":",
"socket_connection",
"=",
"self",
".",
"open_connection",
"(",
")",
"close_socket",
"=",
"True",
"else",
":",
"close_socket",
"=",
"Fa... | Returns the a list of Interface objects the service implements. | [
"Returns",
"the",
"a",
"list",
"of",
"Interface",
"objects",
"the",
"service",
"implements",
"."
] | b021a29dd9def06b03416d20e8b37be39c3edd33 | https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/client.py#L615-L630 |
22,613 | varlink/python | varlink/client.py | Client.add_interface | def add_interface(self, interface):
"""Manually add or overwrite an interface definition from an Interface object.
:param interface: an Interface() object
"""
if not isinstance(interface, Interface):
raise TypeError
self._interfaces[interface.name] = interface | python | def add_interface(self, interface):
if not isinstance(interface, Interface):
raise TypeError
self._interfaces[interface.name] = interface | [
"def",
"add_interface",
"(",
"self",
",",
"interface",
")",
":",
"if",
"not",
"isinstance",
"(",
"interface",
",",
"Interface",
")",
":",
"raise",
"TypeError",
"self",
".",
"_interfaces",
"[",
"interface",
".",
"name",
"]",
"=",
"interface"
] | Manually add or overwrite an interface definition from an Interface object.
:param interface: an Interface() object | [
"Manually",
"add",
"or",
"overwrite",
"an",
"interface",
"definition",
"from",
"an",
"Interface",
"object",
"."
] | b021a29dd9def06b03416d20e8b37be39c3edd33 | https://github.com/varlink/python/blob/b021a29dd9def06b03416d20e8b37be39c3edd33/varlink/client.py#L650-L659 |
22,614 | SINGROUP/SOAPLite | utilities/batchSoapPy.py | create | def create(atoms_list,N, L, cutoff = 0, all_atomtypes=[]):
"""Takes a trajectory xyz file and writes soap features
"""
myAlphas, myBetas = genBasis.getBasisFunc(cutoff, N)
# get information about feature length
n_datapoints = len(atoms_list)
atoms = atoms_list[0]
x = get_lastatom_soap(atoms, cutoff, myAlphas, myBetas,N,L, all_atomtypes=all_atomtypes)
n_features = x.shape[1]
print("soap first", x.shape)
print(n_datapoints, n_features)
soapmatrix = np.zeros((n_datapoints, n_features))
i = -1
for atoms in atoms_list:
i +=1
#atoms
print("Processing " + str(atoms.info)," Run time: " + str(time.time()-t0_total), end="\r")
soapmatrix[i,:] = get_lastatom_soap(atoms, cutoff, myAlphas, myBetas, N, L, all_atomtypes=all_atomtypes)
print("")
# infos
print("shape", soapmatrix.shape)
return soapmatrix | python | def create(atoms_list,N, L, cutoff = 0, all_atomtypes=[]):
myAlphas, myBetas = genBasis.getBasisFunc(cutoff, N)
# get information about feature length
n_datapoints = len(atoms_list)
atoms = atoms_list[0]
x = get_lastatom_soap(atoms, cutoff, myAlphas, myBetas,N,L, all_atomtypes=all_atomtypes)
n_features = x.shape[1]
print("soap first", x.shape)
print(n_datapoints, n_features)
soapmatrix = np.zeros((n_datapoints, n_features))
i = -1
for atoms in atoms_list:
i +=1
#atoms
print("Processing " + str(atoms.info)," Run time: " + str(time.time()-t0_total), end="\r")
soapmatrix[i,:] = get_lastatom_soap(atoms, cutoff, myAlphas, myBetas, N, L, all_atomtypes=all_atomtypes)
print("")
# infos
print("shape", soapmatrix.shape)
return soapmatrix | [
"def",
"create",
"(",
"atoms_list",
",",
"N",
",",
"L",
",",
"cutoff",
"=",
"0",
",",
"all_atomtypes",
"=",
"[",
"]",
")",
":",
"myAlphas",
",",
"myBetas",
"=",
"genBasis",
".",
"getBasisFunc",
"(",
"cutoff",
",",
"N",
")",
"# get information about featu... | Takes a trajectory xyz file and writes soap features | [
"Takes",
"a",
"trajectory",
"xyz",
"file",
"and",
"writes",
"soap",
"features"
] | 80e27cc8d5b4c887011542c5a799583bfc6ff643 | https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/utilities/batchSoapPy.py#L21-L44 |
22,615 | SINGROUP/SOAPLite | soaplite/getBasis.py | getPoly | def getPoly(rCut, nMax):
"""Used to calculate discrete vectors for the polynomial basis functions.
Args:
rCut(float): Radial cutoff
nMax(int): Number of polynomial radial functions
"""
rCutVeryHard = rCut+5.0
rx = 0.5*rCutVeryHard*(x + 1)
basisFunctions = []
for i in range(1, nMax + 1):
basisFunctions.append(lambda rr, i=i, rCut=rCut: (rCut - np.clip(rr, 0, rCut))**(i+2))
# Calculate the overlap of the different polynomial functions in a
# matrix S. These overlaps defined through the dot product over the
# radial coordinate are analytically calculable: Integrate[(rc - r)^(a
# + 2) (rc - r)^(b + 2) r^2, {r, 0, rc}]. Then the weights B that make
# the basis orthonormal are given by B=S^{-1/2}
S = np.zeros((nMax, nMax))
for i in range(1, nMax+1):
for j in range(1, nMax+1):
S[i-1, j-1] = (2*(rCut)**(7+i+j))/((5+i+j)*(6+i+j)*(7+i+j))
betas = sqrtm(np.linalg.inv(S))
# If the result is complex, the calculation is currently halted.
if (betas.dtype == np.complex128):
raise ValueError(
"Could not calculate normalization factors for the polynomial basis"
" in the domain of real numbers. Lowering the number of radial "
"basis functions is advised."
)
fs = np.zeros([nMax, len(x)])
for n in range(1, nMax+1):
fs[n-1, :] = (rCut-np.clip(rx, 0, rCut))**(n+2)
gss = np.dot(betas, fs)
return nMax, rx, gss | python | def getPoly(rCut, nMax):
rCutVeryHard = rCut+5.0
rx = 0.5*rCutVeryHard*(x + 1)
basisFunctions = []
for i in range(1, nMax + 1):
basisFunctions.append(lambda rr, i=i, rCut=rCut: (rCut - np.clip(rr, 0, rCut))**(i+2))
# Calculate the overlap of the different polynomial functions in a
# matrix S. These overlaps defined through the dot product over the
# radial coordinate are analytically calculable: Integrate[(rc - r)^(a
# + 2) (rc - r)^(b + 2) r^2, {r, 0, rc}]. Then the weights B that make
# the basis orthonormal are given by B=S^{-1/2}
S = np.zeros((nMax, nMax))
for i in range(1, nMax+1):
for j in range(1, nMax+1):
S[i-1, j-1] = (2*(rCut)**(7+i+j))/((5+i+j)*(6+i+j)*(7+i+j))
betas = sqrtm(np.linalg.inv(S))
# If the result is complex, the calculation is currently halted.
if (betas.dtype == np.complex128):
raise ValueError(
"Could not calculate normalization factors for the polynomial basis"
" in the domain of real numbers. Lowering the number of radial "
"basis functions is advised."
)
fs = np.zeros([nMax, len(x)])
for n in range(1, nMax+1):
fs[n-1, :] = (rCut-np.clip(rx, 0, rCut))**(n+2)
gss = np.dot(betas, fs)
return nMax, rx, gss | [
"def",
"getPoly",
"(",
"rCut",
",",
"nMax",
")",
":",
"rCutVeryHard",
"=",
"rCut",
"+",
"5.0",
"rx",
"=",
"0.5",
"*",
"rCutVeryHard",
"*",
"(",
"x",
"+",
"1",
")",
"basisFunctions",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"nMax",... | Used to calculate discrete vectors for the polynomial basis functions.
Args:
rCut(float): Radial cutoff
nMax(int): Number of polynomial radial functions | [
"Used",
"to",
"calculate",
"discrete",
"vectors",
"for",
"the",
"polynomial",
"basis",
"functions",
"."
] | 80e27cc8d5b4c887011542c5a799583bfc6ff643 | https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/soaplite/getBasis.py#L303-L342 |
22,616 | SINGROUP/SOAPLite | soaplite/core.py | _format_ase2clusgeo | def _format_ase2clusgeo(obj, all_atomtypes=None):
""" Takes an ase Atoms object and returns numpy arrays and integers
which are read by the internal clusgeo. Apos is currently a flattened
out numpy array
Args:
obj():
all_atomtypes():
sort():
"""
#atoms metadata
totalAN = len(obj)
if all_atomtypes is not None:
atomtype_set = set(all_atomtypes)
else:
atomtype_set = set(obj.get_atomic_numbers())
atomtype_lst = np.sort(list(atomtype_set))
n_atoms_per_type_lst = []
pos_lst = []
for atomtype in atomtype_lst:
condition = obj.get_atomic_numbers() == atomtype
pos_onetype = obj.get_positions()[condition]
n_onetype = pos_onetype.shape[0]
# store data in lists
pos_lst.append(pos_onetype)
n_atoms_per_type_lst.append(n_onetype)
typeNs = n_atoms_per_type_lst
Ntypes = len(n_atoms_per_type_lst)
atomtype_lst
Apos = np.concatenate(pos_lst).ravel()
return Apos, typeNs, Ntypes, atomtype_lst, totalAN | python | def _format_ase2clusgeo(obj, all_atomtypes=None):
#atoms metadata
totalAN = len(obj)
if all_atomtypes is not None:
atomtype_set = set(all_atomtypes)
else:
atomtype_set = set(obj.get_atomic_numbers())
atomtype_lst = np.sort(list(atomtype_set))
n_atoms_per_type_lst = []
pos_lst = []
for atomtype in atomtype_lst:
condition = obj.get_atomic_numbers() == atomtype
pos_onetype = obj.get_positions()[condition]
n_onetype = pos_onetype.shape[0]
# store data in lists
pos_lst.append(pos_onetype)
n_atoms_per_type_lst.append(n_onetype)
typeNs = n_atoms_per_type_lst
Ntypes = len(n_atoms_per_type_lst)
atomtype_lst
Apos = np.concatenate(pos_lst).ravel()
return Apos, typeNs, Ntypes, atomtype_lst, totalAN | [
"def",
"_format_ase2clusgeo",
"(",
"obj",
",",
"all_atomtypes",
"=",
"None",
")",
":",
"#atoms metadata",
"totalAN",
"=",
"len",
"(",
"obj",
")",
"if",
"all_atomtypes",
"is",
"not",
"None",
":",
"atomtype_set",
"=",
"set",
"(",
"all_atomtypes",
")",
"else",
... | Takes an ase Atoms object and returns numpy arrays and integers
which are read by the internal clusgeo. Apos is currently a flattened
out numpy array
Args:
obj():
all_atomtypes():
sort(): | [
"Takes",
"an",
"ase",
"Atoms",
"object",
"and",
"returns",
"numpy",
"arrays",
"and",
"integers",
"which",
"are",
"read",
"by",
"the",
"internal",
"clusgeo",
".",
"Apos",
"is",
"currently",
"a",
"flattened",
"out",
"numpy",
"array"
] | 80e27cc8d5b4c887011542c5a799583bfc6ff643 | https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/soaplite/core.py#L11-L44 |
22,617 | SINGROUP/SOAPLite | soaplite/core.py | get_soap_structure | def get_soap_structure(obj, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0):
"""Get the RBF basis SOAP output for atoms in a finite structure.
Args:
obj(ase.Atoms): Atomic structure for which the SOAP output is
calculated.
alp: Alphas
bet: Betas
rCut: Radial cutoff.
nMax: Maximum nmber of radial basis functions
Lmax: Maximum spherical harmonics degree
crossOver:
all_atomtypes: Can be used to specify the atomic elements for which to
calculate the output. If given the output is calculated only for the
given species.
eta: The gaussian smearing width.
Returns:
np.ndarray: SOAP output for the given structure.
"""
Hpos = obj.get_positions()
arrsoap = get_soap_locals(obj, Hpos, alp, bet, rCut, nMax, Lmax, crossOver, all_atomtypes=all_atomtypes, eta=eta)
return arrsoap | python | def get_soap_structure(obj, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0):
Hpos = obj.get_positions()
arrsoap = get_soap_locals(obj, Hpos, alp, bet, rCut, nMax, Lmax, crossOver, all_atomtypes=all_atomtypes, eta=eta)
return arrsoap | [
"def",
"get_soap_structure",
"(",
"obj",
",",
"alp",
",",
"bet",
",",
"rCut",
"=",
"5.0",
",",
"nMax",
"=",
"5",
",",
"Lmax",
"=",
"5",
",",
"crossOver",
"=",
"True",
",",
"all_atomtypes",
"=",
"None",
",",
"eta",
"=",
"1.0",
")",
":",
"Hpos",
"=... | Get the RBF basis SOAP output for atoms in a finite structure.
Args:
obj(ase.Atoms): Atomic structure for which the SOAP output is
calculated.
alp: Alphas
bet: Betas
rCut: Radial cutoff.
nMax: Maximum nmber of radial basis functions
Lmax: Maximum spherical harmonics degree
crossOver:
all_atomtypes: Can be used to specify the atomic elements for which to
calculate the output. If given the output is calculated only for the
given species.
eta: The gaussian smearing width.
Returns:
np.ndarray: SOAP output for the given structure. | [
"Get",
"the",
"RBF",
"basis",
"SOAP",
"output",
"for",
"atoms",
"in",
"a",
"finite",
"structure",
"."
] | 80e27cc8d5b4c887011542c5a799583bfc6ff643 | https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/soaplite/core.py#L172-L195 |
22,618 | SINGROUP/SOAPLite | soaplite/core.py | get_periodic_soap_locals | def get_periodic_soap_locals(obj, Hpos, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0):
"""Get the RBF basis SOAP output for the given position in a periodic system.
Args:
obj(ase.Atoms): Atomic structure for which the SOAP output is
calculated.
alp: Alphas
bet: Betas
rCut: Radial cutoff.
nMax: Maximum nmber of radial basis functions
Lmax: Maximum spherical harmonics degree
crossOver:
all_atomtypes: Can be used to specify the atomic elements for which to
calculate the output. If given the output is calculated only for the
given species.
eta: The gaussian smearing width.
Returns:
np.ndarray: SOAP output for the given position.
"""
suce = _get_supercell(obj, rCut)
arrsoap = get_soap_locals(suce, Hpos, alp, bet, rCut, nMax=nMax, Lmax=Lmax, crossOver=crossOver, all_atomtypes=all_atomtypes, eta=eta)
return arrsoap | python | def get_periodic_soap_locals(obj, Hpos, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0):
suce = _get_supercell(obj, rCut)
arrsoap = get_soap_locals(suce, Hpos, alp, bet, rCut, nMax=nMax, Lmax=Lmax, crossOver=crossOver, all_atomtypes=all_atomtypes, eta=eta)
return arrsoap | [
"def",
"get_periodic_soap_locals",
"(",
"obj",
",",
"Hpos",
",",
"alp",
",",
"bet",
",",
"rCut",
"=",
"5.0",
",",
"nMax",
"=",
"5",
",",
"Lmax",
"=",
"5",
",",
"crossOver",
"=",
"True",
",",
"all_atomtypes",
"=",
"None",
",",
"eta",
"=",
"1.0",
")"... | Get the RBF basis SOAP output for the given position in a periodic system.
Args:
obj(ase.Atoms): Atomic structure for which the SOAP output is
calculated.
alp: Alphas
bet: Betas
rCut: Radial cutoff.
nMax: Maximum nmber of radial basis functions
Lmax: Maximum spherical harmonics degree
crossOver:
all_atomtypes: Can be used to specify the atomic elements for which to
calculate the output. If given the output is calculated only for the
given species.
eta: The gaussian smearing width.
Returns:
np.ndarray: SOAP output for the given position. | [
"Get",
"the",
"RBF",
"basis",
"SOAP",
"output",
"for",
"the",
"given",
"position",
"in",
"a",
"periodic",
"system",
"."
] | 80e27cc8d5b4c887011542c5a799583bfc6ff643 | https://github.com/SINGROUP/SOAPLite/blob/80e27cc8d5b4c887011542c5a799583bfc6ff643/soaplite/core.py#L198-L221 |
22,619 | adrn/gala | gala/dynamics/orbit.py | Orbit.orbit_gen | def orbit_gen(self):
"""
Generator for iterating over each orbit.
"""
if self.norbits == 1:
yield self
else:
for i in range(self.norbits):
yield self[:, i] | python | def orbit_gen(self):
if self.norbits == 1:
yield self
else:
for i in range(self.norbits):
yield self[:, i] | [
"def",
"orbit_gen",
"(",
"self",
")",
":",
"if",
"self",
".",
"norbits",
"==",
"1",
":",
"yield",
"self",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"norbits",
")",
":",
"yield",
"self",
"[",
":",
",",
"i",
"]"
] | Generator for iterating over each orbit. | [
"Generator",
"for",
"iterating",
"over",
"each",
"orbit",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L294-L303 |
22,620 | adrn/gala | gala/dynamics/orbit.py | Orbit.zmax | def zmax(self, return_times=False, func=np.mean,
interp_kwargs=None, minimize_kwargs=None,
approximate=False):
"""
Estimate the maximum ``z`` height of the orbit by identifying local
maxima in the absolute value of the ``z`` position and interpolating
between timesteps near the maxima.
By default, this returns the mean of all local maxima. To get, e.g., the
largest ``z`` excursion, pass in ``func=np.max``. To get all ``z``
maxima, pass in ``func=None``.
Parameters
----------
func : func (optional)
A function to evaluate on all of the identified z maximum times.
return_times : bool (optional)
Also return the times of maximum.
interp_kwargs : dict (optional)
Keyword arguments to be passed to
:class:`scipy.interpolate.InterpolatedUnivariateSpline`.
minimize_kwargs : dict (optional)
Keyword arguments to be passed to :class:`scipy.optimize.minimize`.
approximate : bool (optional)
Compute approximate values by skipping interpolation.
Returns
-------
zs : float, :class:`~numpy.ndarray`
Either a single number or an array of maximum z heights.
times : :class:`~numpy.ndarray` (optional, see ``return_times``)
If ``return_times=True``, also returns an array of the apocenter
times.
"""
if return_times and func is not None:
raise ValueError("Cannot return times if reducing "
"using an input function. Pass `func=None` if "
"you want to return all individual values "
"and times.")
if func is None:
reduce = False
func = lambda x: x
else:
reduce = True
# time must increase
if self.t[-1] < self.t[0]:
self = self[::-1]
vals = []
times = []
for orbit in self.orbit_gen():
v, t = orbit._max_helper(np.abs(orbit.cylindrical.z),
interp_kwargs=interp_kwargs,
minimize_kwargs=minimize_kwargs,
approximate=approximate)
vals.append(func(v))
times.append(t)
return self._max_return_helper(vals, times, return_times, reduce) | python | def zmax(self, return_times=False, func=np.mean,
interp_kwargs=None, minimize_kwargs=None,
approximate=False):
if return_times and func is not None:
raise ValueError("Cannot return times if reducing "
"using an input function. Pass `func=None` if "
"you want to return all individual values "
"and times.")
if func is None:
reduce = False
func = lambda x: x
else:
reduce = True
# time must increase
if self.t[-1] < self.t[0]:
self = self[::-1]
vals = []
times = []
for orbit in self.orbit_gen():
v, t = orbit._max_helper(np.abs(orbit.cylindrical.z),
interp_kwargs=interp_kwargs,
minimize_kwargs=minimize_kwargs,
approximate=approximate)
vals.append(func(v))
times.append(t)
return self._max_return_helper(vals, times, return_times, reduce) | [
"def",
"zmax",
"(",
"self",
",",
"return_times",
"=",
"False",
",",
"func",
"=",
"np",
".",
"mean",
",",
"interp_kwargs",
"=",
"None",
",",
"minimize_kwargs",
"=",
"None",
",",
"approximate",
"=",
"False",
")",
":",
"if",
"return_times",
"and",
"func",
... | Estimate the maximum ``z`` height of the orbit by identifying local
maxima in the absolute value of the ``z`` position and interpolating
between timesteps near the maxima.
By default, this returns the mean of all local maxima. To get, e.g., the
largest ``z`` excursion, pass in ``func=np.max``. To get all ``z``
maxima, pass in ``func=None``.
Parameters
----------
func : func (optional)
A function to evaluate on all of the identified z maximum times.
return_times : bool (optional)
Also return the times of maximum.
interp_kwargs : dict (optional)
Keyword arguments to be passed to
:class:`scipy.interpolate.InterpolatedUnivariateSpline`.
minimize_kwargs : dict (optional)
Keyword arguments to be passed to :class:`scipy.optimize.minimize`.
approximate : bool (optional)
Compute approximate values by skipping interpolation.
Returns
-------
zs : float, :class:`~numpy.ndarray`
Either a single number or an array of maximum z heights.
times : :class:`~numpy.ndarray` (optional, see ``return_times``)
If ``return_times=True``, also returns an array of the apocenter
times. | [
"Estimate",
"the",
"maximum",
"z",
"height",
"of",
"the",
"orbit",
"by",
"identifying",
"local",
"maxima",
"in",
"the",
"absolute",
"value",
"of",
"the",
"z",
"position",
"and",
"interpolating",
"between",
"timesteps",
"near",
"the",
"maxima",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L550-L612 |
22,621 | adrn/gala | gala/dynamics/orbit.py | Orbit.eccentricity | def eccentricity(self, **kw):
r"""
Returns the eccentricity computed from the mean apocenter and
mean pericenter.
.. math::
e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}}
Parameters
----------
**kw
Any keyword arguments passed to ``apocenter()`` and
``pericenter()``. For example, ``approximate=True``.
Returns
-------
ecc : float
The orbital eccentricity.
"""
ra = self.apocenter(**kw)
rp = self.pericenter(**kw)
return (ra - rp) / (ra + rp) | python | def eccentricity(self, **kw):
r"""
Returns the eccentricity computed from the mean apocenter and
mean pericenter.
.. math::
e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}}
Parameters
----------
**kw
Any keyword arguments passed to ``apocenter()`` and
``pericenter()``. For example, ``approximate=True``.
Returns
-------
ecc : float
The orbital eccentricity.
"""
ra = self.apocenter(**kw)
rp = self.pericenter(**kw)
return (ra - rp) / (ra + rp) | [
"def",
"eccentricity",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"ra",
"=",
"self",
".",
"apocenter",
"(",
"*",
"*",
"kw",
")",
"rp",
"=",
"self",
".",
"pericenter",
"(",
"*",
"*",
"kw",
")",
"return",
"(",
"ra",
"-",
"rp",
")",
"/",
"(",
... | r"""
Returns the eccentricity computed from the mean apocenter and
mean pericenter.
.. math::
e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}}
Parameters
----------
**kw
Any keyword arguments passed to ``apocenter()`` and
``pericenter()``. For example, ``approximate=True``.
Returns
-------
ecc : float
The orbital eccentricity. | [
"r",
"Returns",
"the",
"eccentricity",
"computed",
"from",
"the",
"mean",
"apocenter",
"and",
"mean",
"pericenter",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L614-L637 |
22,622 | adrn/gala | gala/dynamics/orbit.py | Orbit.estimate_period | def estimate_period(self, radial=True):
"""
Estimate the period of the orbit. By default, computes the radial
period. If ``radial==False``, this returns period estimates for
each dimension of the orbit.
Parameters
----------
radial : bool (optional)
What period to estimate. If ``True``, estimates the radial
period. If ``False``, estimates period in each dimension, e.g.,
if the orbit is 3D, along x, y, and z.
Returns
-------
T : `~astropy.units.Quantity`
The period or periods.
"""
if self.t is None:
raise ValueError("To compute the period, a time array is needed."
" Specify a time array when creating this object.")
if radial:
r = self.physicsspherical.r.value
if self.norbits == 1:
T = peak_to_peak_period(self.t.value, r)
T = T * self.t.unit
else:
T = [peak_to_peak_period(self.t.value, r[:,n])
for n in range(r.shape[1])]
T = T * self.t.unit
else:
raise NotImplementedError("sorry 'bout that...")
return T | python | def estimate_period(self, radial=True):
if self.t is None:
raise ValueError("To compute the period, a time array is needed."
" Specify a time array when creating this object.")
if radial:
r = self.physicsspherical.r.value
if self.norbits == 1:
T = peak_to_peak_period(self.t.value, r)
T = T * self.t.unit
else:
T = [peak_to_peak_period(self.t.value, r[:,n])
for n in range(r.shape[1])]
T = T * self.t.unit
else:
raise NotImplementedError("sorry 'bout that...")
return T | [
"def",
"estimate_period",
"(",
"self",
",",
"radial",
"=",
"True",
")",
":",
"if",
"self",
".",
"t",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"To compute the period, a time array is needed.\"",
"\" Specify a time array when creating this object.\"",
")",
"if",
... | Estimate the period of the orbit. By default, computes the radial
period. If ``radial==False``, this returns period estimates for
each dimension of the orbit.
Parameters
----------
radial : bool (optional)
What period to estimate. If ``True``, estimates the radial
period. If ``False``, estimates period in each dimension, e.g.,
if the orbit is 3D, along x, y, and z.
Returns
-------
T : `~astropy.units.Quantity`
The period or periods. | [
"Estimate",
"the",
"period",
"of",
"the",
"orbit",
".",
"By",
"default",
"computes",
"the",
"radial",
"period",
".",
"If",
"radial",
"==",
"False",
"this",
"returns",
"period",
"estimates",
"for",
"each",
"dimension",
"of",
"the",
"orbit",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L639-L675 |
22,623 | adrn/gala | gala/dynamics/orbit.py | Orbit.circulation | def circulation(self):
"""
Determine which axes the Orbit circulates around by checking
whether there is a change of sign of the angular momentum
about an axis. Returns a 2D array with ``ndim`` integers per orbit
point. If a box orbit, all integers will be 0. A 1 indicates
circulation about the corresponding axis.
TODO: clockwise / counterclockwise?
For example, for a single 3D orbit:
- Box and boxlet = [0,0,0]
- z-axis (short-axis) tube = [0,0,1]
- x-axis (long-axis) tube = [1,0,0]
Returns
-------
circulation : :class:`numpy.ndarray`
An array that specifies whether there is circulation about any of
the axes of the input orbit. For a single orbit, will return a
1D array, but for multiple orbits, the shape will be
``(3, norbits)``.
"""
L = self.angular_momentum()
# if only 2D, add another empty axis
if L.ndim == 2:
single_orbit = True
L = L[...,None]
else:
single_orbit = False
ndim,ntimes,norbits = L.shape
# initial angular momentum
L0 = L[:,0]
# see if at any timestep the sign has changed
circ = np.ones((ndim,norbits))
for ii in range(ndim):
cnd = (np.sign(L0[ii]) != np.sign(L[ii,1:])) | \
(np.abs(L[ii,1:]).value < 1E-13)
ix = np.atleast_1d(np.any(cnd, axis=0))
circ[ii,ix] = 0
circ = circ.astype(int)
if single_orbit:
return circ.reshape((ndim,))
else:
return circ | python | def circulation(self):
L = self.angular_momentum()
# if only 2D, add another empty axis
if L.ndim == 2:
single_orbit = True
L = L[...,None]
else:
single_orbit = False
ndim,ntimes,norbits = L.shape
# initial angular momentum
L0 = L[:,0]
# see if at any timestep the sign has changed
circ = np.ones((ndim,norbits))
for ii in range(ndim):
cnd = (np.sign(L0[ii]) != np.sign(L[ii,1:])) | \
(np.abs(L[ii,1:]).value < 1E-13)
ix = np.atleast_1d(np.any(cnd, axis=0))
circ[ii,ix] = 0
circ = circ.astype(int)
if single_orbit:
return circ.reshape((ndim,))
else:
return circ | [
"def",
"circulation",
"(",
"self",
")",
":",
"L",
"=",
"self",
".",
"angular_momentum",
"(",
")",
"# if only 2D, add another empty axis",
"if",
"L",
".",
"ndim",
"==",
"2",
":",
"single_orbit",
"=",
"True",
"L",
"=",
"L",
"[",
"...",
",",
"None",
"]",
... | Determine which axes the Orbit circulates around by checking
whether there is a change of sign of the angular momentum
about an axis. Returns a 2D array with ``ndim`` integers per orbit
point. If a box orbit, all integers will be 0. A 1 indicates
circulation about the corresponding axis.
TODO: clockwise / counterclockwise?
For example, for a single 3D orbit:
- Box and boxlet = [0,0,0]
- z-axis (short-axis) tube = [0,0,1]
- x-axis (long-axis) tube = [1,0,0]
Returns
-------
circulation : :class:`numpy.ndarray`
An array that specifies whether there is circulation about any of
the axes of the input orbit. For a single orbit, will return a
1D array, but for multiple orbits, the shape will be
``(3, norbits)``. | [
"Determine",
"which",
"axes",
"the",
"Orbit",
"circulates",
"around",
"by",
"checking",
"whether",
"there",
"is",
"a",
"change",
"of",
"sign",
"of",
"the",
"angular",
"momentum",
"about",
"an",
"axis",
".",
"Returns",
"a",
"2D",
"array",
"with",
"ndim",
"i... | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L680-L731 |
22,624 | adrn/gala | gala/dynamics/orbit.py | Orbit.align_circulation_with_z | def align_circulation_with_z(self, circulation=None):
"""
If the input orbit is a tube orbit, this function aligns the circulation
axis with the z axis and returns a copy.
Parameters
----------
circulation : array_like (optional)
Array of bits that specify the axis about which the orbit
circulates. If not provided, will compute this using
:meth:`~gala.dynamics.Orbit.circulation`. See that method for more
information.
Returns
-------
orb : :class:`~gala.dynamics.Orbit`
A copy of the original orbit object with circulation aligned with
the z axis.
"""
if circulation is None:
circulation = self.circulation()
circulation = atleast_2d(circulation, insert_axis=1)
cart = self.cartesian
pos = cart.xyz
vel = np.vstack((cart.v_x.value[None],
cart.v_y.value[None],
cart.v_z.value[None])) * cart.v_x.unit
if pos.ndim < 3:
pos = pos[...,np.newaxis]
vel = vel[...,np.newaxis]
if (circulation.shape[0] != self.ndim or
circulation.shape[1] != pos.shape[2]):
raise ValueError("Shape of 'circulation' array should match the "
"shape of the position/velocity (minus the time "
"axis).")
new_pos = pos.copy()
new_vel = vel.copy()
for n in range(pos.shape[2]):
if circulation[2,n] == 1 or np.all(circulation[:,n] == 0):
# already circulating about z or box orbit
continue
if sum(circulation[:,n]) > 1:
logger.warning("Circulation about multiple axes - are you sure "
"the orbit has been integrated for long enough?")
if circulation[0,n] == 1:
circ = 0
elif circulation[1,n] == 1:
circ = 1
else:
raise RuntimeError("Should never get here...")
new_pos[circ,:,n] = pos[2,:,n]
new_pos[2,:,n] = pos[circ,:,n]
new_vel[circ,:,n] = vel[2,:,n]
new_vel[2,:,n] = vel[circ,:,n]
return self.__class__(pos=new_pos.reshape(cart.xyz.shape),
vel=new_vel.reshape(cart.xyz.shape),
t=self.t,
hamiltonian=self.hamiltonian) | python | def align_circulation_with_z(self, circulation=None):
if circulation is None:
circulation = self.circulation()
circulation = atleast_2d(circulation, insert_axis=1)
cart = self.cartesian
pos = cart.xyz
vel = np.vstack((cart.v_x.value[None],
cart.v_y.value[None],
cart.v_z.value[None])) * cart.v_x.unit
if pos.ndim < 3:
pos = pos[...,np.newaxis]
vel = vel[...,np.newaxis]
if (circulation.shape[0] != self.ndim or
circulation.shape[1] != pos.shape[2]):
raise ValueError("Shape of 'circulation' array should match the "
"shape of the position/velocity (minus the time "
"axis).")
new_pos = pos.copy()
new_vel = vel.copy()
for n in range(pos.shape[2]):
if circulation[2,n] == 1 or np.all(circulation[:,n] == 0):
# already circulating about z or box orbit
continue
if sum(circulation[:,n]) > 1:
logger.warning("Circulation about multiple axes - are you sure "
"the orbit has been integrated for long enough?")
if circulation[0,n] == 1:
circ = 0
elif circulation[1,n] == 1:
circ = 1
else:
raise RuntimeError("Should never get here...")
new_pos[circ,:,n] = pos[2,:,n]
new_pos[2,:,n] = pos[circ,:,n]
new_vel[circ,:,n] = vel[2,:,n]
new_vel[2,:,n] = vel[circ,:,n]
return self.__class__(pos=new_pos.reshape(cart.xyz.shape),
vel=new_vel.reshape(cart.xyz.shape),
t=self.t,
hamiltonian=self.hamiltonian) | [
"def",
"align_circulation_with_z",
"(",
"self",
",",
"circulation",
"=",
"None",
")",
":",
"if",
"circulation",
"is",
"None",
":",
"circulation",
"=",
"self",
".",
"circulation",
"(",
")",
"circulation",
"=",
"atleast_2d",
"(",
"circulation",
",",
"insert_axis... | If the input orbit is a tube orbit, this function aligns the circulation
axis with the z axis and returns a copy.
Parameters
----------
circulation : array_like (optional)
Array of bits that specify the axis about which the orbit
circulates. If not provided, will compute this using
:meth:`~gala.dynamics.Orbit.circulation`. See that method for more
information.
Returns
-------
orb : :class:`~gala.dynamics.Orbit`
A copy of the original orbit object with circulation aligned with
the z axis. | [
"If",
"the",
"input",
"orbit",
"is",
"a",
"tube",
"orbit",
"this",
"function",
"aligns",
"the",
"circulation",
"axis",
"with",
"the",
"z",
"axis",
"and",
"returns",
"a",
"copy",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/orbit.py#L733-L800 |
22,625 | adrn/gala | gala/coordinates/greatcircle.py | greatcircle_to_greatcircle | def greatcircle_to_greatcircle(from_greatcircle_coord,
to_greatcircle_frame):
"""Transform between two greatcircle frames."""
# This transform goes through the parent frames on each side.
# from_frame -> from_frame.origin -> to_frame.origin -> to_frame
intermediate_from = from_greatcircle_coord.transform_to(
from_greatcircle_coord.pole)
intermediate_to = intermediate_from.transform_to(
to_greatcircle_frame.pole)
return intermediate_to.transform_to(to_greatcircle_frame) | python | def greatcircle_to_greatcircle(from_greatcircle_coord,
to_greatcircle_frame):
# This transform goes through the parent frames on each side.
# from_frame -> from_frame.origin -> to_frame.origin -> to_frame
intermediate_from = from_greatcircle_coord.transform_to(
from_greatcircle_coord.pole)
intermediate_to = intermediate_from.transform_to(
to_greatcircle_frame.pole)
return intermediate_to.transform_to(to_greatcircle_frame) | [
"def",
"greatcircle_to_greatcircle",
"(",
"from_greatcircle_coord",
",",
"to_greatcircle_frame",
")",
":",
"# This transform goes through the parent frames on each side.",
"# from_frame -> from_frame.origin -> to_frame.origin -> to_frame",
"intermediate_from",
"=",
"from_greatcircle_coord",
... | Transform between two greatcircle frames. | [
"Transform",
"between",
"two",
"greatcircle",
"frames",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/greatcircle.py#L21-L31 |
22,626 | adrn/gala | gala/coordinates/greatcircle.py | reference_to_greatcircle | def reference_to_greatcircle(reference_frame, greatcircle_frame):
"""Convert a reference coordinate to a great circle frame."""
# Define rotation matrices along the position angle vector, and
# relative to the origin.
pole = greatcircle_frame.pole.transform_to(coord.ICRS)
ra0 = greatcircle_frame.ra0
center = greatcircle_frame.center
R_rot = rotation_matrix(greatcircle_frame.rotation, 'z')
if not np.isnan(ra0):
xaxis = np.array([np.cos(ra0), np.sin(ra0), 0.])
zaxis = pole.cartesian.xyz.value
if np.abs(zaxis[2]) >= 1e-15:
xaxis[2] = -(zaxis[0]*xaxis[0] + zaxis[1]*xaxis[1]) / zaxis[2] # what?
else:
xaxis[2] = 0.
xaxis = xaxis / np.sqrt(np.sum(xaxis**2))
yaxis = np.cross(zaxis, xaxis)
R = np.stack((xaxis, yaxis, zaxis))
elif center is not None:
R1 = rotation_matrix(pole.ra, 'z')
R2 = rotation_matrix(90*u.deg - pole.dec, 'y')
Rtmp = matrix_product(R2, R1)
rot = center.cartesian.transform(Rtmp)
rot_lon = rot.represent_as(coord.UnitSphericalRepresentation).lon
R3 = rotation_matrix(rot_lon, 'z')
R = matrix_product(R3, R2, R1)
else:
R1 = rotation_matrix(pole.ra, 'z')
R2 = rotation_matrix(pole.dec, 'y')
R = matrix_product(R2, R1)
return matrix_product(R_rot, R) | python | def reference_to_greatcircle(reference_frame, greatcircle_frame):
# Define rotation matrices along the position angle vector, and
# relative to the origin.
pole = greatcircle_frame.pole.transform_to(coord.ICRS)
ra0 = greatcircle_frame.ra0
center = greatcircle_frame.center
R_rot = rotation_matrix(greatcircle_frame.rotation, 'z')
if not np.isnan(ra0):
xaxis = np.array([np.cos(ra0), np.sin(ra0), 0.])
zaxis = pole.cartesian.xyz.value
if np.abs(zaxis[2]) >= 1e-15:
xaxis[2] = -(zaxis[0]*xaxis[0] + zaxis[1]*xaxis[1]) / zaxis[2] # what?
else:
xaxis[2] = 0.
xaxis = xaxis / np.sqrt(np.sum(xaxis**2))
yaxis = np.cross(zaxis, xaxis)
R = np.stack((xaxis, yaxis, zaxis))
elif center is not None:
R1 = rotation_matrix(pole.ra, 'z')
R2 = rotation_matrix(90*u.deg - pole.dec, 'y')
Rtmp = matrix_product(R2, R1)
rot = center.cartesian.transform(Rtmp)
rot_lon = rot.represent_as(coord.UnitSphericalRepresentation).lon
R3 = rotation_matrix(rot_lon, 'z')
R = matrix_product(R3, R2, R1)
else:
R1 = rotation_matrix(pole.ra, 'z')
R2 = rotation_matrix(pole.dec, 'y')
R = matrix_product(R2, R1)
return matrix_product(R_rot, R) | [
"def",
"reference_to_greatcircle",
"(",
"reference_frame",
",",
"greatcircle_frame",
")",
":",
"# Define rotation matrices along the position angle vector, and",
"# relative to the origin.",
"pole",
"=",
"greatcircle_frame",
".",
"pole",
".",
"transform_to",
"(",
"coord",
".",
... | Convert a reference coordinate to a great circle frame. | [
"Convert",
"a",
"reference",
"coordinate",
"to",
"a",
"great",
"circle",
"frame",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/greatcircle.py#L34-L70 |
22,627 | adrn/gala | gala/coordinates/greatcircle.py | pole_from_endpoints | def pole_from_endpoints(coord1, coord2):
"""Compute the pole from a great circle that connects the two specified
coordinates.
This assumes a right-handed rule from coord1 to coord2: the pole is the
north pole under that assumption.
Parameters
----------
coord1 : `~astropy.coordinates.SkyCoord`
Coordinate of one point on a great circle.
coord2 : `~astropy.coordinates.SkyCoord`
Coordinate of the other point on a great circle.
Returns
-------
pole : `~astropy.coordinates.SkyCoord`
The coordinates of the pole.
"""
c1 = coord1.cartesian / coord1.cartesian.norm()
coord2 = coord2.transform_to(coord1.frame)
c2 = coord2.cartesian / coord2.cartesian.norm()
pole = c1.cross(c2)
pole = pole / pole.norm()
return coord1.frame.realize_frame(pole) | python | def pole_from_endpoints(coord1, coord2):
c1 = coord1.cartesian / coord1.cartesian.norm()
coord2 = coord2.transform_to(coord1.frame)
c2 = coord2.cartesian / coord2.cartesian.norm()
pole = c1.cross(c2)
pole = pole / pole.norm()
return coord1.frame.realize_frame(pole) | [
"def",
"pole_from_endpoints",
"(",
"coord1",
",",
"coord2",
")",
":",
"c1",
"=",
"coord1",
".",
"cartesian",
"/",
"coord1",
".",
"cartesian",
".",
"norm",
"(",
")",
"coord2",
"=",
"coord2",
".",
"transform_to",
"(",
"coord1",
".",
"frame",
")",
"c2",
"... | Compute the pole from a great circle that connects the two specified
coordinates.
This assumes a right-handed rule from coord1 to coord2: the pole is the
north pole under that assumption.
Parameters
----------
coord1 : `~astropy.coordinates.SkyCoord`
Coordinate of one point on a great circle.
coord2 : `~astropy.coordinates.SkyCoord`
Coordinate of the other point on a great circle.
Returns
-------
pole : `~astropy.coordinates.SkyCoord`
The coordinates of the pole. | [
"Compute",
"the",
"pole",
"from",
"a",
"great",
"circle",
"that",
"connects",
"the",
"two",
"specified",
"coordinates",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/greatcircle.py#L270-L296 |
22,628 | adrn/gala | gala/coordinates/greatcircle.py | sph_midpoint | def sph_midpoint(coord1, coord2):
"""Compute the midpoint between two points on the sphere.
Parameters
----------
coord1 : `~astropy.coordinates.SkyCoord`
Coordinate of one point on a great circle.
coord2 : `~astropy.coordinates.SkyCoord`
Coordinate of the other point on a great circle.
Returns
-------
midpt : `~astropy.coordinates.SkyCoord`
The coordinates of the spherical midpoint.
"""
c1 = coord1.cartesian / coord1.cartesian.norm()
coord2 = coord2.transform_to(coord1.frame)
c2 = coord2.cartesian / coord2.cartesian.norm()
midpt = 0.5 * (c1 + c2)
usph = midpt.represent_as(coord.UnitSphericalRepresentation)
return coord1.frame.realize_frame(usph) | python | def sph_midpoint(coord1, coord2):
c1 = coord1.cartesian / coord1.cartesian.norm()
coord2 = coord2.transform_to(coord1.frame)
c2 = coord2.cartesian / coord2.cartesian.norm()
midpt = 0.5 * (c1 + c2)
usph = midpt.represent_as(coord.UnitSphericalRepresentation)
return coord1.frame.realize_frame(usph) | [
"def",
"sph_midpoint",
"(",
"coord1",
",",
"coord2",
")",
":",
"c1",
"=",
"coord1",
".",
"cartesian",
"/",
"coord1",
".",
"cartesian",
".",
"norm",
"(",
")",
"coord2",
"=",
"coord2",
".",
"transform_to",
"(",
"coord1",
".",
"frame",
")",
"c2",
"=",
"... | Compute the midpoint between two points on the sphere.
Parameters
----------
coord1 : `~astropy.coordinates.SkyCoord`
Coordinate of one point on a great circle.
coord2 : `~astropy.coordinates.SkyCoord`
Coordinate of the other point on a great circle.
Returns
-------
midpt : `~astropy.coordinates.SkyCoord`
The coordinates of the spherical midpoint. | [
"Compute",
"the",
"midpoint",
"between",
"two",
"points",
"on",
"the",
"sphere",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/greatcircle.py#L299-L322 |
22,629 | adrn/gala | gala/coordinates/pm_cov_transform.py | get_uv_tan | def get_uv_tan(c):
"""Get tangent plane basis vectors on the unit sphere at the given
spherical coordinates.
"""
l = c.spherical.lon
b = c.spherical.lat
p = np.array([-np.sin(l), np.cos(l), np.zeros_like(l.value)]).T
q = np.array([-np.cos(l)*np.sin(b), -np.sin(l)*np.sin(b), np.cos(b)]).T
return np.stack((p, q), axis=-1) | python | def get_uv_tan(c):
l = c.spherical.lon
b = c.spherical.lat
p = np.array([-np.sin(l), np.cos(l), np.zeros_like(l.value)]).T
q = np.array([-np.cos(l)*np.sin(b), -np.sin(l)*np.sin(b), np.cos(b)]).T
return np.stack((p, q), axis=-1) | [
"def",
"get_uv_tan",
"(",
"c",
")",
":",
"l",
"=",
"c",
".",
"spherical",
".",
"lon",
"b",
"=",
"c",
".",
"spherical",
".",
"lat",
"p",
"=",
"np",
".",
"array",
"(",
"[",
"-",
"np",
".",
"sin",
"(",
"l",
")",
",",
"np",
".",
"cos",
"(",
"... | Get tangent plane basis vectors on the unit sphere at the given
spherical coordinates. | [
"Get",
"tangent",
"plane",
"basis",
"vectors",
"on",
"the",
"unit",
"sphere",
"at",
"the",
"given",
"spherical",
"coordinates",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/pm_cov_transform.py#L8-L18 |
22,630 | adrn/gala | gala/coordinates/pm_cov_transform.py | transform_pm_cov | def transform_pm_cov(c, cov, to_frame):
"""Transform a proper motion covariance matrix to a new frame.
Parameters
----------
c : `~astropy.coordinates.SkyCoord`
The sky coordinates of the sources in the initial coordinate frame.
cov : array_like
The covariance matrix of the proper motions. Must have same length as
the input coordinates.
to_frame : `~astropy.coordinates.BaseCoordinateFrame` subclass
The frame to transform to as an Astropy coordinate frame class or
instance.
Returns
-------
new_cov : array_like
The transformed covariance matrix.
"""
if c.isscalar and cov.shape != (2, 2):
raise ValueError('If input coordinate object is a scalar coordinate, '
'the proper motion covariance matrix must have shape '
'(2, 2), not {}'.format(cov.shape))
elif not c.isscalar and len(c) != cov.shape[0]:
raise ValueError('Input coordinates and covariance matrix must have '
'the same number of entries ({} vs {}).'
.format(len(c), cov.shape[0]))
# 3D rotation matrix, to be projected onto the tangent plane
if hasattr(c, 'frame'):
frame = c.frame
else:
frame = c
R = get_transform_matrix(frame.__class__, to_frame)
# Get input coordinates in the desired frame:
c_to = c.transform_to(to_frame)
# Get tangent plane coordinates:
uv_in = get_uv_tan(c)
uv_to = get_uv_tan(c_to)
if not c.isscalar:
G = np.einsum('nab,nac->nbc', uv_to,
np.einsum('ji,nik->njk', R, uv_in))
# transform
cov_to = np.einsum('nba,nac->nbc', G,
np.einsum('nij,nki->njk', cov, G))
else:
G = np.einsum('ab,ac->bc', uv_to,
np.einsum('ji,ik->jk', R, uv_in))
# transform
cov_to = np.einsum('ba,ac->bc', G,
np.einsum('ij,ki->jk', cov, G))
return cov_to | python | def transform_pm_cov(c, cov, to_frame):
if c.isscalar and cov.shape != (2, 2):
raise ValueError('If input coordinate object is a scalar coordinate, '
'the proper motion covariance matrix must have shape '
'(2, 2), not {}'.format(cov.shape))
elif not c.isscalar and len(c) != cov.shape[0]:
raise ValueError('Input coordinates and covariance matrix must have '
'the same number of entries ({} vs {}).'
.format(len(c), cov.shape[0]))
# 3D rotation matrix, to be projected onto the tangent plane
if hasattr(c, 'frame'):
frame = c.frame
else:
frame = c
R = get_transform_matrix(frame.__class__, to_frame)
# Get input coordinates in the desired frame:
c_to = c.transform_to(to_frame)
# Get tangent plane coordinates:
uv_in = get_uv_tan(c)
uv_to = get_uv_tan(c_to)
if not c.isscalar:
G = np.einsum('nab,nac->nbc', uv_to,
np.einsum('ji,nik->njk', R, uv_in))
# transform
cov_to = np.einsum('nba,nac->nbc', G,
np.einsum('nij,nki->njk', cov, G))
else:
G = np.einsum('ab,ac->bc', uv_to,
np.einsum('ji,ik->jk', R, uv_in))
# transform
cov_to = np.einsum('ba,ac->bc', G,
np.einsum('ij,ki->jk', cov, G))
return cov_to | [
"def",
"transform_pm_cov",
"(",
"c",
",",
"cov",
",",
"to_frame",
")",
":",
"if",
"c",
".",
"isscalar",
"and",
"cov",
".",
"shape",
"!=",
"(",
"2",
",",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'If input coordinate object is a scalar coordinate, '",
"'the... | Transform a proper motion covariance matrix to a new frame.
Parameters
----------
c : `~astropy.coordinates.SkyCoord`
The sky coordinates of the sources in the initial coordinate frame.
cov : array_like
The covariance matrix of the proper motions. Must have same length as
the input coordinates.
to_frame : `~astropy.coordinates.BaseCoordinateFrame` subclass
The frame to transform to as an Astropy coordinate frame class or
instance.
Returns
-------
new_cov : array_like
The transformed covariance matrix. | [
"Transform",
"a",
"proper",
"motion",
"covariance",
"matrix",
"to",
"a",
"new",
"frame",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/pm_cov_transform.py#L62-L121 |
22,631 | adrn/gala | gala/potential/frame/builtin/transformations.py | rodrigues_axis_angle_rotate | def rodrigues_axis_angle_rotate(x, vec, theta):
"""
Rotated the input vector or set of vectors `x` around the axis
`vec` by the angle `theta`.
Parameters
----------
x : array_like
The vector or array of vectors to transform. Must have shape
"""
x = np.array(x).T
vec = np.array(vec).T
theta = np.array(theta).T[...,None]
out = np.cos(theta)*x + np.sin(theta)*np.cross(vec, x) + \
(1 - np.cos(theta)) * (vec * x).sum(axis=-1)[...,None] * vec
return out.T | python | def rodrigues_axis_angle_rotate(x, vec, theta):
x = np.array(x).T
vec = np.array(vec).T
theta = np.array(theta).T[...,None]
out = np.cos(theta)*x + np.sin(theta)*np.cross(vec, x) + \
(1 - np.cos(theta)) * (vec * x).sum(axis=-1)[...,None] * vec
return out.T | [
"def",
"rodrigues_axis_angle_rotate",
"(",
"x",
",",
"vec",
",",
"theta",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
".",
"T",
"vec",
"=",
"np",
".",
"array",
"(",
"vec",
")",
".",
"T",
"theta",
"=",
"np",
".",
"array",
"(",
"theta"... | Rotated the input vector or set of vectors `x` around the axis
`vec` by the angle `theta`.
Parameters
----------
x : array_like
The vector or array of vectors to transform. Must have shape | [
"Rotated",
"the",
"input",
"vector",
"or",
"set",
"of",
"vectors",
"x",
"around",
"the",
"axis",
"vec",
"by",
"the",
"angle",
"theta",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L10-L29 |
22,632 | adrn/gala | gala/potential/frame/builtin/transformations.py | z_angle_rotate | def z_angle_rotate(xy, theta):
"""
Rotated the input vector or set of vectors `xy` by the angle `theta`.
Parameters
----------
xy : array_like
The vector or array of vectors to transform. Must have shape
"""
xy = np.array(xy).T
theta = np.array(theta).T
out = np.zeros_like(xy)
out[...,0] = np.cos(theta)*xy[...,0] - np.sin(theta)*xy[...,1]
out[...,1] = np.sin(theta)*xy[...,0] + np.cos(theta)*xy[...,1]
return out.T | python | def z_angle_rotate(xy, theta):
xy = np.array(xy).T
theta = np.array(theta).T
out = np.zeros_like(xy)
out[...,0] = np.cos(theta)*xy[...,0] - np.sin(theta)*xy[...,1]
out[...,1] = np.sin(theta)*xy[...,0] + np.cos(theta)*xy[...,1]
return out.T | [
"def",
"z_angle_rotate",
"(",
"xy",
",",
"theta",
")",
":",
"xy",
"=",
"np",
".",
"array",
"(",
"xy",
")",
".",
"T",
"theta",
"=",
"np",
".",
"array",
"(",
"theta",
")",
".",
"T",
"out",
"=",
"np",
".",
"zeros_like",
"(",
"xy",
")",
"out",
"[... | Rotated the input vector or set of vectors `xy` by the angle `theta`.
Parameters
----------
xy : array_like
The vector or array of vectors to transform. Must have shape | [
"Rotated",
"the",
"input",
"vector",
"or",
"set",
"of",
"vectors",
"xy",
"by",
"the",
"angle",
"theta",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L31-L49 |
22,633 | adrn/gala | gala/potential/frame/builtin/transformations.py | static_to_constantrotating | def static_to_constantrotating(frame_i, frame_r, w, t=None):
"""
Transform from an inertial static frame to a rotating frame.
Parameters
----------
frame_i : `~gala.potential.StaticFrame`
frame_r : `~gala.potential.ConstantRotatingFrame`
w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit`
t : quantity_like (optional)
Required if input coordinates are just a phase-space position.
Returns
-------
pos : `~astropy.units.Quantity`
Position in rotating frame.
vel : `~astropy.units.Quantity`
Velocity in rotating frame.
"""
return _constantrotating_static_helper(frame_r=frame_r, frame_i=frame_i,
w=w, t=t, sign=1.) | python | def static_to_constantrotating(frame_i, frame_r, w, t=None):
return _constantrotating_static_helper(frame_r=frame_r, frame_i=frame_i,
w=w, t=t, sign=1.) | [
"def",
"static_to_constantrotating",
"(",
"frame_i",
",",
"frame_r",
",",
"w",
",",
"t",
"=",
"None",
")",
":",
"return",
"_constantrotating_static_helper",
"(",
"frame_r",
"=",
"frame_r",
",",
"frame_i",
"=",
"frame_i",
",",
"w",
"=",
"w",
",",
"t",
"=",
... | Transform from an inertial static frame to a rotating frame.
Parameters
----------
frame_i : `~gala.potential.StaticFrame`
frame_r : `~gala.potential.ConstantRotatingFrame`
w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit`
t : quantity_like (optional)
Required if input coordinates are just a phase-space position.
Returns
-------
pos : `~astropy.units.Quantity`
Position in rotating frame.
vel : `~astropy.units.Quantity`
Velocity in rotating frame. | [
"Transform",
"from",
"an",
"inertial",
"static",
"frame",
"to",
"a",
"rotating",
"frame",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L100-L120 |
22,634 | adrn/gala | gala/potential/frame/builtin/transformations.py | constantrotating_to_static | def constantrotating_to_static(frame_r, frame_i, w, t=None):
"""
Transform from a constantly rotating frame to a static, inertial frame.
Parameters
----------
frame_i : `~gala.potential.StaticFrame`
frame_r : `~gala.potential.ConstantRotatingFrame`
w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit`
t : quantity_like (optional)
Required if input coordinates are just a phase-space position.
Returns
-------
pos : `~astropy.units.Quantity`
Position in static, inertial frame.
vel : `~astropy.units.Quantity`
Velocity in static, inertial frame.
"""
return _constantrotating_static_helper(frame_r=frame_r, frame_i=frame_i,
w=w, t=t, sign=-1.) | python | def constantrotating_to_static(frame_r, frame_i, w, t=None):
return _constantrotating_static_helper(frame_r=frame_r, frame_i=frame_i,
w=w, t=t, sign=-1.) | [
"def",
"constantrotating_to_static",
"(",
"frame_r",
",",
"frame_i",
",",
"w",
",",
"t",
"=",
"None",
")",
":",
"return",
"_constantrotating_static_helper",
"(",
"frame_r",
"=",
"frame_r",
",",
"frame_i",
"=",
"frame_i",
",",
"w",
"=",
"w",
",",
"t",
"=",
... | Transform from a constantly rotating frame to a static, inertial frame.
Parameters
----------
frame_i : `~gala.potential.StaticFrame`
frame_r : `~gala.potential.ConstantRotatingFrame`
w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit`
t : quantity_like (optional)
Required if input coordinates are just a phase-space position.
Returns
-------
pos : `~astropy.units.Quantity`
Position in static, inertial frame.
vel : `~astropy.units.Quantity`
Velocity in static, inertial frame. | [
"Transform",
"from",
"a",
"constantly",
"rotating",
"frame",
"to",
"a",
"static",
"inertial",
"frame",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L122-L142 |
22,635 | adrn/gala | gala/potential/potential/io.py | to_dict | def to_dict(potential):
"""
Turn a potential object into a dictionary that fully specifies the
state of the object.
Parameters
----------
potential : :class:`~gala.potential.PotentialBase`
The instantiated :class:`~gala.potential.PotentialBase` object.
"""
from .. import potential as gp
if isinstance(potential, gp.CompositePotential):
d = dict()
d['class'] = potential.__class__.__name__
d['components'] = []
for k, p in potential.items():
comp_dict = _to_dict_help(p)
comp_dict['name'] = k
d['components'].append(comp_dict)
if potential.__class__.__name__ == 'CompositePotential' or \
potential.__class__.__name__ == 'CCompositePotential':
d['type'] = 'composite'
else:
d['type'] = 'custom'
else:
d = _to_dict_help(potential)
return d | python | def to_dict(potential):
from .. import potential as gp
if isinstance(potential, gp.CompositePotential):
d = dict()
d['class'] = potential.__class__.__name__
d['components'] = []
for k, p in potential.items():
comp_dict = _to_dict_help(p)
comp_dict['name'] = k
d['components'].append(comp_dict)
if potential.__class__.__name__ == 'CompositePotential' or \
potential.__class__.__name__ == 'CCompositePotential':
d['type'] = 'composite'
else:
d['type'] = 'custom'
else:
d = _to_dict_help(potential)
return d | [
"def",
"to_dict",
"(",
"potential",
")",
":",
"from",
".",
".",
"import",
"potential",
"as",
"gp",
"if",
"isinstance",
"(",
"potential",
",",
"gp",
".",
"CompositePotential",
")",
":",
"d",
"=",
"dict",
"(",
")",
"d",
"[",
"'class'",
"]",
"=",
"poten... | Turn a potential object into a dictionary that fully specifies the
state of the object.
Parameters
----------
potential : :class:`~gala.potential.PotentialBase`
The instantiated :class:`~gala.potential.PotentialBase` object. | [
"Turn",
"a",
"potential",
"object",
"into",
"a",
"dictionary",
"that",
"fully",
"specifies",
"the",
"state",
"of",
"the",
"object",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/io.py#L148-L179 |
22,636 | adrn/gala | gala/integrate/core.py | Integrator._prepare_ws | def _prepare_ws(self, w0, mmap, n_steps):
"""
Decide how to make the return array. If mmap is False, this returns a
full array of zeros, but with the correct shape as the output. If mmap
is True, return a pointer to a memory-mapped array. The latter is
particularly useful for integrating a large number of orbits or
integrating a large number of time steps.
"""
from ..dynamics import PhaseSpacePosition
if not isinstance(w0, PhaseSpacePosition):
w0 = PhaseSpacePosition.from_w(w0)
arr_w0 = w0.w(self._func_units)
self.ndim, self.norbits = arr_w0.shape
self.ndim = self.ndim//2
return_shape = (2*self.ndim, n_steps+1, self.norbits)
if mmap is None:
# create the return arrays
ws = np.zeros(return_shape, dtype=float)
else:
if mmap.shape != return_shape:
raise ValueError("Shape of memory-mapped array doesn't match "
"expected shape of return array ({} vs {})"
.format(mmap.shape, return_shape))
if not mmap.flags.writeable:
raise TypeError("Memory-mapped array must be a writable mode, "
" not '{}'".format(mmap.mode))
ws = mmap
return w0, arr_w0, ws | python | def _prepare_ws(self, w0, mmap, n_steps):
from ..dynamics import PhaseSpacePosition
if not isinstance(w0, PhaseSpacePosition):
w0 = PhaseSpacePosition.from_w(w0)
arr_w0 = w0.w(self._func_units)
self.ndim, self.norbits = arr_w0.shape
self.ndim = self.ndim//2
return_shape = (2*self.ndim, n_steps+1, self.norbits)
if mmap is None:
# create the return arrays
ws = np.zeros(return_shape, dtype=float)
else:
if mmap.shape != return_shape:
raise ValueError("Shape of memory-mapped array doesn't match "
"expected shape of return array ({} vs {})"
.format(mmap.shape, return_shape))
if not mmap.flags.writeable:
raise TypeError("Memory-mapped array must be a writable mode, "
" not '{}'".format(mmap.mode))
ws = mmap
return w0, arr_w0, ws | [
"def",
"_prepare_ws",
"(",
"self",
",",
"w0",
",",
"mmap",
",",
"n_steps",
")",
":",
"from",
".",
".",
"dynamics",
"import",
"PhaseSpacePosition",
"if",
"not",
"isinstance",
"(",
"w0",
",",
"PhaseSpacePosition",
")",
":",
"w0",
"=",
"PhaseSpacePosition",
"... | Decide how to make the return array. If mmap is False, this returns a
full array of zeros, but with the correct shape as the output. If mmap
is True, return a pointer to a memory-mapped array. The latter is
particularly useful for integrating a large number of orbits or
integrating a large number of time steps. | [
"Decide",
"how",
"to",
"make",
"the",
"return",
"array",
".",
"If",
"mmap",
"is",
"False",
"this",
"returns",
"a",
"full",
"array",
"of",
"zeros",
"but",
"with",
"the",
"correct",
"shape",
"as",
"the",
"output",
".",
"If",
"mmap",
"is",
"True",
"return... | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/integrate/core.py#L44-L78 |
22,637 | adrn/gala | gala/dynamics/nonlinear.py | fast_lyapunov_max | def fast_lyapunov_max(w0, hamiltonian, dt, n_steps, d0=1e-5,
n_steps_per_pullback=10, noffset_orbits=2, t1=0.,
atol=1E-10, rtol=1E-10, nmax=0, return_orbit=True):
"""
Compute the maximum Lyapunov exponent using a C-implemented estimator
that uses the DOPRI853 integrator.
Parameters
----------
w0 : `~gala.dynamics.PhaseSpacePosition`, array_like
Initial conditions.
hamiltonian : `~gala.potential.Hamiltonian`
dt : numeric
Timestep.
n_steps : int
Number of steps to run for.
d0 : numeric (optional)
The initial separation.
n_steps_per_pullback : int (optional)
Number of steps to run before re-normalizing the offset vectors.
noffset_orbits : int (optional)
Number of offset orbits to run.
t1 : numeric (optional)
Time of initial conditions. Assumed to be t=0.
return_orbit : bool (optional)
Store the full orbit for the parent and all offset orbits.
Returns
-------
LEs : :class:`~astropy.units.Quantity`
Lyapunov exponents calculated from each offset / deviation orbit.
orbit : `~gala.dynamics.Orbit` (optional)
"""
from .lyapunov import dop853_lyapunov_max, dop853_lyapunov_max_dont_save
# TODO: remove in v1.0
if isinstance(hamiltonian, PotentialBase):
from ..potential import Hamiltonian
hamiltonian = Hamiltonian(hamiltonian)
if not hamiltonian.c_enabled:
raise TypeError("Input Hamiltonian must contain a C-implemented "
"potential and frame.")
if not isinstance(w0, PhaseSpacePosition):
w0 = np.asarray(w0)
ndim = w0.shape[0]//2
w0 = PhaseSpacePosition(pos=w0[:ndim],
vel=w0[ndim:])
_w0 = np.squeeze(w0.w(hamiltonian.units))
if _w0.ndim > 1:
raise ValueError("Can only compute fast Lyapunov exponent for a single orbit.")
if return_orbit:
t,w,l = dop853_lyapunov_max(hamiltonian, _w0,
dt, n_steps+1, t1,
d0, n_steps_per_pullback, noffset_orbits,
atol, rtol, nmax)
w = np.rollaxis(w, -1)
try:
tunit = hamiltonian.units['time']
except (TypeError, AttributeError):
tunit = u.dimensionless_unscaled
orbit = Orbit.from_w(w=w, units=hamiltonian.units,
t=t*tunit, hamiltonian=hamiltonian)
return l/tunit, orbit
else:
l = dop853_lyapunov_max_dont_save(hamiltonian, _w0,
dt, n_steps+1, t1,
d0, n_steps_per_pullback, noffset_orbits,
atol, rtol, nmax)
try:
tunit = hamiltonian.units['time']
except (TypeError, AttributeError):
tunit = u.dimensionless_unscaled
return l/tunit | python | def fast_lyapunov_max(w0, hamiltonian, dt, n_steps, d0=1e-5,
n_steps_per_pullback=10, noffset_orbits=2, t1=0.,
atol=1E-10, rtol=1E-10, nmax=0, return_orbit=True):
from .lyapunov import dop853_lyapunov_max, dop853_lyapunov_max_dont_save
# TODO: remove in v1.0
if isinstance(hamiltonian, PotentialBase):
from ..potential import Hamiltonian
hamiltonian = Hamiltonian(hamiltonian)
if not hamiltonian.c_enabled:
raise TypeError("Input Hamiltonian must contain a C-implemented "
"potential and frame.")
if not isinstance(w0, PhaseSpacePosition):
w0 = np.asarray(w0)
ndim = w0.shape[0]//2
w0 = PhaseSpacePosition(pos=w0[:ndim],
vel=w0[ndim:])
_w0 = np.squeeze(w0.w(hamiltonian.units))
if _w0.ndim > 1:
raise ValueError("Can only compute fast Lyapunov exponent for a single orbit.")
if return_orbit:
t,w,l = dop853_lyapunov_max(hamiltonian, _w0,
dt, n_steps+1, t1,
d0, n_steps_per_pullback, noffset_orbits,
atol, rtol, nmax)
w = np.rollaxis(w, -1)
try:
tunit = hamiltonian.units['time']
except (TypeError, AttributeError):
tunit = u.dimensionless_unscaled
orbit = Orbit.from_w(w=w, units=hamiltonian.units,
t=t*tunit, hamiltonian=hamiltonian)
return l/tunit, orbit
else:
l = dop853_lyapunov_max_dont_save(hamiltonian, _w0,
dt, n_steps+1, t1,
d0, n_steps_per_pullback, noffset_orbits,
atol, rtol, nmax)
try:
tunit = hamiltonian.units['time']
except (TypeError, AttributeError):
tunit = u.dimensionless_unscaled
return l/tunit | [
"def",
"fast_lyapunov_max",
"(",
"w0",
",",
"hamiltonian",
",",
"dt",
",",
"n_steps",
",",
"d0",
"=",
"1e-5",
",",
"n_steps_per_pullback",
"=",
"10",
",",
"noffset_orbits",
"=",
"2",
",",
"t1",
"=",
"0.",
",",
"atol",
"=",
"1E-10",
",",
"rtol",
"=",
... | Compute the maximum Lyapunov exponent using a C-implemented estimator
that uses the DOPRI853 integrator.
Parameters
----------
w0 : `~gala.dynamics.PhaseSpacePosition`, array_like
Initial conditions.
hamiltonian : `~gala.potential.Hamiltonian`
dt : numeric
Timestep.
n_steps : int
Number of steps to run for.
d0 : numeric (optional)
The initial separation.
n_steps_per_pullback : int (optional)
Number of steps to run before re-normalizing the offset vectors.
noffset_orbits : int (optional)
Number of offset orbits to run.
t1 : numeric (optional)
Time of initial conditions. Assumed to be t=0.
return_orbit : bool (optional)
Store the full orbit for the parent and all offset orbits.
Returns
-------
LEs : :class:`~astropy.units.Quantity`
Lyapunov exponents calculated from each offset / deviation orbit.
orbit : `~gala.dynamics.Orbit` (optional) | [
"Compute",
"the",
"maximum",
"Lyapunov",
"exponent",
"using",
"a",
"C",
"-",
"implemented",
"estimator",
"that",
"uses",
"the",
"DOPRI853",
"integrator",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/nonlinear.py#L12-L95 |
22,638 | adrn/gala | gala/dynamics/nonlinear.py | surface_of_section | def surface_of_section(orbit, plane_ix, interpolate=False):
"""
Generate and return a surface of section from the given orbit.
.. warning::
This is an experimental function and the API may change.
Parameters
----------
orbit : `~gala.dynamics.Orbit`
plane_ix : int
Integer that represents the coordinate to record crossings in. For
example, for a 2D Hamiltonian where you want to make a SoS in
:math:`y-p_y`, you would specify ``plane_ix=0`` (crossing the
:math:`x` axis), and this will only record crossings for which
:math:`p_x>0`.
interpolate : bool (optional)
Whether or not to interpolate on to the plane of interest. This
makes it much slower, but will work for orbits with a coarser
sampling.
Returns
-------
Examples
--------
If your orbit of interest is a tube orbit, it probably conserves (at
least approximately) some equivalent to angular momentum in the direction
of the circulation axis. Therefore, a surface of section in R-z should
be instructive for classifying these orbits. TODO...show how to convert
an orbit to Cylindrical..etc...
"""
w = orbit.w()
if w.ndim == 2:
w = w[...,None]
ndim,ntimes,norbits = w.shape
H_dim = ndim // 2
p_ix = plane_ix + H_dim
if interpolate:
raise NotImplementedError("Not yet implemented, sorry!")
# record position on specified plane when orbit crosses
all_sos = np.zeros((ndim,norbits), dtype=object)
for n in range(norbits):
cross_ix = argrelmin(w[plane_ix,:,n]**2)[0]
cross_ix = cross_ix[w[p_ix,cross_ix,n] > 0.]
sos = w[:,cross_ix,n]
for j in range(ndim):
all_sos[j,n] = sos[j,:]
return all_sos | python | def surface_of_section(orbit, plane_ix, interpolate=False):
w = orbit.w()
if w.ndim == 2:
w = w[...,None]
ndim,ntimes,norbits = w.shape
H_dim = ndim // 2
p_ix = plane_ix + H_dim
if interpolate:
raise NotImplementedError("Not yet implemented, sorry!")
# record position on specified plane when orbit crosses
all_sos = np.zeros((ndim,norbits), dtype=object)
for n in range(norbits):
cross_ix = argrelmin(w[plane_ix,:,n]**2)[0]
cross_ix = cross_ix[w[p_ix,cross_ix,n] > 0.]
sos = w[:,cross_ix,n]
for j in range(ndim):
all_sos[j,n] = sos[j,:]
return all_sos | [
"def",
"surface_of_section",
"(",
"orbit",
",",
"plane_ix",
",",
"interpolate",
"=",
"False",
")",
":",
"w",
"=",
"orbit",
".",
"w",
"(",
")",
"if",
"w",
".",
"ndim",
"==",
"2",
":",
"w",
"=",
"w",
"[",
"...",
",",
"None",
"]",
"ndim",
",",
"nt... | Generate and return a surface of section from the given orbit.
.. warning::
This is an experimental function and the API may change.
Parameters
----------
orbit : `~gala.dynamics.Orbit`
plane_ix : int
Integer that represents the coordinate to record crossings in. For
example, for a 2D Hamiltonian where you want to make a SoS in
:math:`y-p_y`, you would specify ``plane_ix=0`` (crossing the
:math:`x` axis), and this will only record crossings for which
:math:`p_x>0`.
interpolate : bool (optional)
Whether or not to interpolate on to the plane of interest. This
makes it much slower, but will work for orbits with a coarser
sampling.
Returns
-------
Examples
--------
If your orbit of interest is a tube orbit, it probably conserves (at
least approximately) some equivalent to angular momentum in the direction
of the circulation axis. Therefore, a surface of section in R-z should
be instructive for classifying these orbits. TODO...show how to convert
an orbit to Cylindrical..etc... | [
"Generate",
"and",
"return",
"a",
"surface",
"of",
"section",
"from",
"the",
"given",
"orbit",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/nonlinear.py#L207-L263 |
22,639 | adrn/gala | gala/potential/potential/core.py | PotentialBase._remove_units | def _remove_units(self, x):
"""
Always returns an array. If a Quantity is passed in, it converts to the
units associated with this object and returns the value.
"""
if hasattr(x, 'unit'):
x = x.decompose(self.units).value
else:
x = np.array(x)
return x | python | def _remove_units(self, x):
if hasattr(x, 'unit'):
x = x.decompose(self.units).value
else:
x = np.array(x)
return x | [
"def",
"_remove_units",
"(",
"self",
",",
"x",
")",
":",
"if",
"hasattr",
"(",
"x",
",",
"'unit'",
")",
":",
"x",
"=",
"x",
".",
"decompose",
"(",
"self",
".",
"units",
")",
".",
"value",
"else",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
"... | Always returns an array. If a Quantity is passed in, it converts to the
units associated with this object and returns the value. | [
"Always",
"returns",
"an",
"array",
".",
"If",
"a",
"Quantity",
"is",
"passed",
"in",
"it",
"converts",
"to",
"the",
"units",
"associated",
"with",
"this",
"object",
"and",
"returns",
"the",
"value",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/core.py#L96-L107 |
22,640 | adrn/gala | gala/potential/potential/core.py | PotentialBase.mass_enclosed | def mass_enclosed(self, q, t=0.):
"""
Estimate the mass enclosed within the given position by assuming the potential
is spherical.
Parameters
----------
q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like
Position(s) to estimate the enclossed mass.
Returns
-------
menc : `~astropy.units.Quantity`
Mass enclosed at the given position(s). If the input position
has shape ``q.shape``, the output energy will have shape
``q.shape[1:]``.
"""
q = self._remove_units_prepare_shape(q)
orig_shape, q = self._get_c_valid_arr(q)
t = self._validate_prepare_time(t, q)
# small step-size in direction of q
h = 1E-3 # MAGIC NUMBER
# Radius
r = np.sqrt(np.sum(q**2, axis=1))
epsilon = h*q/r[:, np.newaxis]
dPhi_dr_plus = self._energy(q + epsilon, t=t)
dPhi_dr_minus = self._energy(q - epsilon, t=t)
diff = (dPhi_dr_plus - dPhi_dr_minus)
if isinstance(self.units, DimensionlessUnitSystem):
Gee = 1.
else:
Gee = G.decompose(self.units).value
Menc = np.abs(r*r * diff / Gee / (2.*h))
Menc = Menc.reshape(orig_shape[1:])
sgn = 1.
if 'm' in self.parameters and self.parameters['m'] < 0:
sgn = -1.
return sgn * Menc * self.units['mass'] | python | def mass_enclosed(self, q, t=0.):
q = self._remove_units_prepare_shape(q)
orig_shape, q = self._get_c_valid_arr(q)
t = self._validate_prepare_time(t, q)
# small step-size in direction of q
h = 1E-3 # MAGIC NUMBER
# Radius
r = np.sqrt(np.sum(q**2, axis=1))
epsilon = h*q/r[:, np.newaxis]
dPhi_dr_plus = self._energy(q + epsilon, t=t)
dPhi_dr_minus = self._energy(q - epsilon, t=t)
diff = (dPhi_dr_plus - dPhi_dr_minus)
if isinstance(self.units, DimensionlessUnitSystem):
Gee = 1.
else:
Gee = G.decompose(self.units).value
Menc = np.abs(r*r * diff / Gee / (2.*h))
Menc = Menc.reshape(orig_shape[1:])
sgn = 1.
if 'm' in self.parameters and self.parameters['m'] < 0:
sgn = -1.
return sgn * Menc * self.units['mass'] | [
"def",
"mass_enclosed",
"(",
"self",
",",
"q",
",",
"t",
"=",
"0.",
")",
":",
"q",
"=",
"self",
".",
"_remove_units_prepare_shape",
"(",
"q",
")",
"orig_shape",
",",
"q",
"=",
"self",
".",
"_get_c_valid_arr",
"(",
"q",
")",
"t",
"=",
"self",
".",
"... | Estimate the mass enclosed within the given position by assuming the potential
is spherical.
Parameters
----------
q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like
Position(s) to estimate the enclossed mass.
Returns
-------
menc : `~astropy.units.Quantity`
Mass enclosed at the given position(s). If the input position
has shape ``q.shape``, the output energy will have shape
``q.shape[1:]``. | [
"Estimate",
"the",
"mass",
"enclosed",
"within",
"the",
"given",
"position",
"by",
"assuming",
"the",
"potential",
"is",
"spherical",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/core.py#L246-L291 |
22,641 | adrn/gala | gala/potential/potential/core.py | PotentialBase.circular_velocity | def circular_velocity(self, q, t=0.):
"""
Estimate the circular velocity at the given position assuming the
potential is spherical.
Parameters
----------
q : array_like, numeric
Position(s) to estimate the circular velocity.
Returns
-------
vcirc : `~astropy.units.Quantity`
Circular velocity at the given position(s). If the input position
has shape ``q.shape``, the output energy will have shape
``q.shape[1:]``.
"""
q = self._remove_units_prepare_shape(q)
# Radius
r = np.sqrt(np.sum(q**2, axis=0)) * self.units['length']
dPhi_dxyz = self.gradient(q, t=t)
dPhi_dr = np.sum(dPhi_dxyz * q/r.value, axis=0)
return self.units.decompose(np.sqrt(r * np.abs(dPhi_dr))) | python | def circular_velocity(self, q, t=0.):
q = self._remove_units_prepare_shape(q)
# Radius
r = np.sqrt(np.sum(q**2, axis=0)) * self.units['length']
dPhi_dxyz = self.gradient(q, t=t)
dPhi_dr = np.sum(dPhi_dxyz * q/r.value, axis=0)
return self.units.decompose(np.sqrt(r * np.abs(dPhi_dr))) | [
"def",
"circular_velocity",
"(",
"self",
",",
"q",
",",
"t",
"=",
"0.",
")",
":",
"q",
"=",
"self",
".",
"_remove_units_prepare_shape",
"(",
"q",
")",
"# Radius",
"r",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"q",
"**",
"2",
",",
"axis... | Estimate the circular velocity at the given position assuming the
potential is spherical.
Parameters
----------
q : array_like, numeric
Position(s) to estimate the circular velocity.
Returns
-------
vcirc : `~astropy.units.Quantity`
Circular velocity at the given position(s). If the input position
has shape ``q.shape``, the output energy will have shape
``q.shape[1:]``. | [
"Estimate",
"the",
"circular",
"velocity",
"at",
"the",
"given",
"position",
"assuming",
"the",
"potential",
"is",
"spherical",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/core.py#L293-L318 |
22,642 | adrn/gala | gala/potential/potential/util.py | format_doc | def format_doc(*args, **kwargs):
"""
Replaces the docstring of the decorated object and then formats it.
Modeled after astropy.utils.decorators.format_doc
"""
def set_docstring(obj):
# None means: use the objects __doc__
doc = obj.__doc__
# Delete documentation in this case so we don't end up with
# awkwardly self-inserted docs.
obj.__doc__ = None
# If the original has a not-empty docstring append it to the format
# kwargs.
kwargs['__doc__'] = obj.__doc__ or ''
obj.__doc__ = doc.format(*args, **kwargs)
return obj
return set_docstring | python | def format_doc(*args, **kwargs):
def set_docstring(obj):
# None means: use the objects __doc__
doc = obj.__doc__
# Delete documentation in this case so we don't end up with
# awkwardly self-inserted docs.
obj.__doc__ = None
# If the original has a not-empty docstring append it to the format
# kwargs.
kwargs['__doc__'] = obj.__doc__ or ''
obj.__doc__ = doc.format(*args, **kwargs)
return obj
return set_docstring | [
"def",
"format_doc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"set_docstring",
"(",
"obj",
")",
":",
"# None means: use the objects __doc__",
"doc",
"=",
"obj",
".",
"__doc__",
"# Delete documentation in this case so we don't end up with",
"# awkwar... | Replaces the docstring of the decorated object and then formats it.
Modeled after astropy.utils.decorators.format_doc | [
"Replaces",
"the",
"docstring",
"of",
"the",
"decorated",
"object",
"and",
"then",
"formats",
"it",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/util.py#L165-L184 |
22,643 | adrn/gala | gala/io.py | quantity_to_hdf5 | def quantity_to_hdf5(f, key, q):
"""
Turn an Astropy Quantity object into something we can write out to
an HDF5 file.
Parameters
----------
f : :class:`h5py.File`, :class:`h5py.Group`, :class:`h5py.DataSet`
key : str
The name.
q : float, `astropy.units.Quantity`
The quantity.
"""
if hasattr(q, 'unit'):
f[key] = q.value
f[key].attrs['unit'] = str(q.unit)
else:
f[key] = q
f[key].attrs['unit'] = "" | python | def quantity_to_hdf5(f, key, q):
if hasattr(q, 'unit'):
f[key] = q.value
f[key].attrs['unit'] = str(q.unit)
else:
f[key] = q
f[key].attrs['unit'] = "" | [
"def",
"quantity_to_hdf5",
"(",
"f",
",",
"key",
",",
"q",
")",
":",
"if",
"hasattr",
"(",
"q",
",",
"'unit'",
")",
":",
"f",
"[",
"key",
"]",
"=",
"q",
".",
"value",
"f",
"[",
"key",
"]",
".",
"attrs",
"[",
"'unit'",
"]",
"=",
"str",
"(",
... | Turn an Astropy Quantity object into something we can write out to
an HDF5 file.
Parameters
----------
f : :class:`h5py.File`, :class:`h5py.Group`, :class:`h5py.DataSet`
key : str
The name.
q : float, `astropy.units.Quantity`
The quantity. | [
"Turn",
"an",
"Astropy",
"Quantity",
"object",
"into",
"something",
"we",
"can",
"write",
"out",
"to",
"an",
"HDF5",
"file",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/io.py#L27-L48 |
22,644 | adrn/gala | gala/units.py | UnitSystem.get_constant | def get_constant(self, name):
"""
Retrieve a constant with specified name in this unit system.
Parameters
----------
name : str
The name of the constant, e.g., G.
Returns
-------
const : float
The value of the constant represented in this unit system.
Examples
--------
>>> usys = UnitSystem(u.kpc, u.Myr, u.radian, u.Msun)
>>> usys.get_constant('c')
306.6013937879527
"""
try:
c = getattr(const, name)
except AttributeError:
raise ValueError("Constant name '{}' doesn't exist in astropy.constants".format(name))
return c.decompose(self._core_units).value | python | def get_constant(self, name):
try:
c = getattr(const, name)
except AttributeError:
raise ValueError("Constant name '{}' doesn't exist in astropy.constants".format(name))
return c.decompose(self._core_units).value | [
"def",
"get_constant",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"c",
"=",
"getattr",
"(",
"const",
",",
"name",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"\"Constant name '{}' doesn't exist in astropy.constants\"",
".",
"format",
"... | Retrieve a constant with specified name in this unit system.
Parameters
----------
name : str
The name of the constant, e.g., G.
Returns
-------
const : float
The value of the constant represented in this unit system.
Examples
--------
>>> usys = UnitSystem(u.kpc, u.Myr, u.radian, u.Msun)
>>> usys.get_constant('c')
306.6013937879527 | [
"Retrieve",
"a",
"constant",
"with",
"specified",
"name",
"in",
"this",
"unit",
"system",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/units.py#L160-L187 |
22,645 | adrn/gala | gala/util.py | atleast_2d | def atleast_2d(*arys, **kwargs):
"""
View inputs as arrays with at least two dimensions.
Parameters
----------
arys1, arys2, ... : array_like
One or more array-like sequences. Non-array inputs are converted
to arrays. Arrays that already have two or more dimensions are
preserved.
insert_axis : int (optional)
Where to create a new axis if input array(s) have <2 dim.
Returns
-------
res, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 2``.
Copies are avoided where possible, and views with two or more
dimensions are returned.
Examples
--------
>>> atleast_2d(3.0) # doctest: +FLOAT_CMP
array([[3.]])
>>> x = np.arange(3.0)
>>> atleast_2d(x) # doctest: +FLOAT_CMP
array([[0., 1., 2.]])
>>> atleast_2d(x, insert_axis=-1) # doctest: +FLOAT_CMP
array([[0.],
[1.],
[2.]])
>>> atleast_2d(x).base is x
True
>>> atleast_2d(1, [1, 2], [[1, 2]])
[array([[1]]), array([[1, 2]]), array([[1, 2]])]
"""
insert_axis = kwargs.pop('insert_axis', 0)
slc = [slice(None)]*2
slc[insert_axis] = None
slc = tuple(slc)
res = []
for ary in arys:
ary = np.asanyarray(ary)
if len(ary.shape) == 0:
result = ary.reshape(1, 1)
elif len(ary.shape) == 1:
result = ary[slc]
else:
result = ary
res.append(result)
if len(res) == 1:
return res[0]
else:
return res | python | def atleast_2d(*arys, **kwargs):
insert_axis = kwargs.pop('insert_axis', 0)
slc = [slice(None)]*2
slc[insert_axis] = None
slc = tuple(slc)
res = []
for ary in arys:
ary = np.asanyarray(ary)
if len(ary.shape) == 0:
result = ary.reshape(1, 1)
elif len(ary.shape) == 1:
result = ary[slc]
else:
result = ary
res.append(result)
if len(res) == 1:
return res[0]
else:
return res | [
"def",
"atleast_2d",
"(",
"*",
"arys",
",",
"*",
"*",
"kwargs",
")",
":",
"insert_axis",
"=",
"kwargs",
".",
"pop",
"(",
"'insert_axis'",
",",
"0",
")",
"slc",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"2",
"slc",
"[",
"insert_axis",
"]",
"=... | View inputs as arrays with at least two dimensions.
Parameters
----------
arys1, arys2, ... : array_like
One or more array-like sequences. Non-array inputs are converted
to arrays. Arrays that already have two or more dimensions are
preserved.
insert_axis : int (optional)
Where to create a new axis if input array(s) have <2 dim.
Returns
-------
res, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 2``.
Copies are avoided where possible, and views with two or more
dimensions are returned.
Examples
--------
>>> atleast_2d(3.0) # doctest: +FLOAT_CMP
array([[3.]])
>>> x = np.arange(3.0)
>>> atleast_2d(x) # doctest: +FLOAT_CMP
array([[0., 1., 2.]])
>>> atleast_2d(x, insert_axis=-1) # doctest: +FLOAT_CMP
array([[0.],
[1.],
[2.]])
>>> atleast_2d(x).base is x
True
>>> atleast_2d(1, [1, 2], [[1, 2]])
[array([[1]]), array([[1, 2]]), array([[1, 2]])] | [
"View",
"inputs",
"as",
"arrays",
"with",
"at",
"least",
"two",
"dimensions",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/util.py#L113-L170 |
22,646 | adrn/gala | gala/coordinates/quaternion.py | Quaternion.from_v_theta | def from_v_theta(cls, v, theta):
"""
Create a quaternion from unit vector v and rotation angle theta.
Returns
-------
q : :class:`gala.coordinates.Quaternion`
A ``Quaternion`` instance.
"""
theta = np.asarray(theta)
v = np.asarray(v)
s = np.sin(0.5 * theta)
c = np.cos(0.5 * theta)
vnrm = np.sqrt(np.sum(v * v))
q = np.concatenate([[c], s * v / vnrm])
return cls(q) | python | def from_v_theta(cls, v, theta):
theta = np.asarray(theta)
v = np.asarray(v)
s = np.sin(0.5 * theta)
c = np.cos(0.5 * theta)
vnrm = np.sqrt(np.sum(v * v))
q = np.concatenate([[c], s * v / vnrm])
return cls(q) | [
"def",
"from_v_theta",
"(",
"cls",
",",
"v",
",",
"theta",
")",
":",
"theta",
"=",
"np",
".",
"asarray",
"(",
"theta",
")",
"v",
"=",
"np",
".",
"asarray",
"(",
"v",
")",
"s",
"=",
"np",
".",
"sin",
"(",
"0.5",
"*",
"theta",
")",
"c",
"=",
... | Create a quaternion from unit vector v and rotation angle theta.
Returns
-------
q : :class:`gala.coordinates.Quaternion`
A ``Quaternion`` instance. | [
"Create",
"a",
"quaternion",
"from",
"unit",
"vector",
"v",
"and",
"rotation",
"angle",
"theta",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/quaternion.py#L27-L45 |
22,647 | adrn/gala | gala/coordinates/quaternion.py | Quaternion.random | def random(cls):
"""
Randomly sample a Quaternion from a distribution uniform in
3D rotation angles.
https://www-preview.ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf
Returns
-------
q : :class:`gala.coordinates.Quaternion`
A randomly sampled ``Quaternion`` instance.
"""
s = np.random.uniform()
s1 = np.sqrt(1 - s)
s2 = np.sqrt(s)
t1 = np.random.uniform(0, 2*np.pi)
t2 = np.random.uniform(0, 2*np.pi)
w = np.cos(t2)*s2
x = np.sin(t1)*s1
y = np.cos(t1)*s1
z = np.sin(t2)*s2
return cls([w,x,y,z]) | python | def random(cls):
s = np.random.uniform()
s1 = np.sqrt(1 - s)
s2 = np.sqrt(s)
t1 = np.random.uniform(0, 2*np.pi)
t2 = np.random.uniform(0, 2*np.pi)
w = np.cos(t2)*s2
x = np.sin(t1)*s1
y = np.cos(t1)*s1
z = np.sin(t2)*s2
return cls([w,x,y,z]) | [
"def",
"random",
"(",
"cls",
")",
":",
"s",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
")",
"s1",
"=",
"np",
".",
"sqrt",
"(",
"1",
"-",
"s",
")",
"s2",
"=",
"np",
".",
"sqrt",
"(",
"s",
")",
"t1",
"=",
"np",
".",
"random",
".",
"unif... | Randomly sample a Quaternion from a distribution uniform in
3D rotation angles.
https://www-preview.ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf
Returns
-------
q : :class:`gala.coordinates.Quaternion`
A randomly sampled ``Quaternion`` instance. | [
"Randomly",
"sample",
"a",
"Quaternion",
"from",
"a",
"distribution",
"uniform",
"in",
"3D",
"rotation",
"angles",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/quaternion.py#L112-L137 |
22,648 | adrn/gala | gala/integrate/pyintegrators/leapfrog.py | LeapfrogIntegrator.step | def step(self, t, x_im1, v_im1_2, dt):
"""
Step forward the positions and velocities by the given timestep.
Parameters
----------
dt : numeric
The timestep to move forward.
"""
x_i = x_im1 + v_im1_2 * dt
F_i = self.F(t, np.vstack((x_i, v_im1_2)), *self._func_args)
a_i = F_i[self.ndim:]
v_i = v_im1_2 + a_i * dt / 2
v_ip1_2 = v_i + a_i * dt / 2
return x_i, v_i, v_ip1_2 | python | def step(self, t, x_im1, v_im1_2, dt):
x_i = x_im1 + v_im1_2 * dt
F_i = self.F(t, np.vstack((x_i, v_im1_2)), *self._func_args)
a_i = F_i[self.ndim:]
v_i = v_im1_2 + a_i * dt / 2
v_ip1_2 = v_i + a_i * dt / 2
return x_i, v_i, v_ip1_2 | [
"def",
"step",
"(",
"self",
",",
"t",
",",
"x_im1",
",",
"v_im1_2",
",",
"dt",
")",
":",
"x_i",
"=",
"x_im1",
"+",
"v_im1_2",
"*",
"dt",
"F_i",
"=",
"self",
".",
"F",
"(",
"t",
",",
"np",
".",
"vstack",
"(",
"(",
"x_i",
",",
"v_im1_2",
")",
... | Step forward the positions and velocities by the given timestep.
Parameters
----------
dt : numeric
The timestep to move forward. | [
"Step",
"forward",
"the",
"positions",
"and",
"velocities",
"by",
"the",
"given",
"timestep",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/integrate/pyintegrators/leapfrog.py#L93-L110 |
22,649 | adrn/gala | gala/dynamics/actionangle.py | fit_isochrone | def fit_isochrone(orbit, m0=2E11, b0=1., minimize_kwargs=None):
r"""
Fit the toy Isochrone potential to the sum of the energy residuals relative
to the mean energy by minimizing the function
.. math::
f(m,b) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm iso}(x_i\,|\,m,b) - <E>)^2
TODO: This should fail if the Hamiltonian associated with the orbit has
a frame other than StaticFrame
Parameters
----------
orbit : `~gala.dynamics.Orbit`
m0 : numeric (optional)
Initial mass guess.
b0 : numeric (optional)
Initial b guess.
minimize_kwargs : dict (optional)
Keyword arguments to pass through to `scipy.optimize.minimize`.
Returns
-------
m : float
Best-fit scale mass for the Isochrone potential.
b : float
Best-fit core radius for the Isochrone potential.
"""
pot = orbit.hamiltonian.potential
if pot is None:
raise ValueError("The orbit object must have an associated potential")
w = np.squeeze(orbit.w(pot.units))
if w.ndim > 2:
raise ValueError("Input orbit object must be a single orbit.")
def f(p, w):
logm, logb = p
potential = IsochronePotential(m=np.exp(logm), b=np.exp(logb),
units=pot.units)
H = (potential.value(w[:3]).decompose(pot.units).value +
0.5*np.sum(w[3:]**2, axis=0))
return np.sum(np.squeeze(H - np.mean(H))**2)
logm0 = np.log(m0)
logb0 = np.log(b0)
if minimize_kwargs is None:
minimize_kwargs = dict()
minimize_kwargs['x0'] = np.array([logm0, logb0])
minimize_kwargs['method'] = minimize_kwargs.get('method', 'Nelder-Mead')
res = minimize(f, args=(w,), **minimize_kwargs)
if not res.success:
raise ValueError("Failed to fit toy potential to orbit.")
logm, logb = np.abs(res.x)
m = np.exp(logm)
b = np.exp(logb)
return IsochronePotential(m=m, b=b, units=pot.units) | python | def fit_isochrone(orbit, m0=2E11, b0=1., minimize_kwargs=None):
r"""
Fit the toy Isochrone potential to the sum of the energy residuals relative
to the mean energy by minimizing the function
.. math::
f(m,b) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm iso}(x_i\,|\,m,b) - <E>)^2
TODO: This should fail if the Hamiltonian associated with the orbit has
a frame other than StaticFrame
Parameters
----------
orbit : `~gala.dynamics.Orbit`
m0 : numeric (optional)
Initial mass guess.
b0 : numeric (optional)
Initial b guess.
minimize_kwargs : dict (optional)
Keyword arguments to pass through to `scipy.optimize.minimize`.
Returns
-------
m : float
Best-fit scale mass for the Isochrone potential.
b : float
Best-fit core radius for the Isochrone potential.
"""
pot = orbit.hamiltonian.potential
if pot is None:
raise ValueError("The orbit object must have an associated potential")
w = np.squeeze(orbit.w(pot.units))
if w.ndim > 2:
raise ValueError("Input orbit object must be a single orbit.")
def f(p, w):
logm, logb = p
potential = IsochronePotential(m=np.exp(logm), b=np.exp(logb),
units=pot.units)
H = (potential.value(w[:3]).decompose(pot.units).value +
0.5*np.sum(w[3:]**2, axis=0))
return np.sum(np.squeeze(H - np.mean(H))**2)
logm0 = np.log(m0)
logb0 = np.log(b0)
if minimize_kwargs is None:
minimize_kwargs = dict()
minimize_kwargs['x0'] = np.array([logm0, logb0])
minimize_kwargs['method'] = minimize_kwargs.get('method', 'Nelder-Mead')
res = minimize(f, args=(w,), **minimize_kwargs)
if not res.success:
raise ValueError("Failed to fit toy potential to orbit.")
logm, logb = np.abs(res.x)
m = np.exp(logm)
b = np.exp(logb)
return IsochronePotential(m=m, b=b, units=pot.units) | [
"def",
"fit_isochrone",
"(",
"orbit",
",",
"m0",
"=",
"2E11",
",",
"b0",
"=",
"1.",
",",
"minimize_kwargs",
"=",
"None",
")",
":",
"pot",
"=",
"orbit",
".",
"hamiltonian",
".",
"potential",
"if",
"pot",
"is",
"None",
":",
"raise",
"ValueError",
"(",
... | r"""
Fit the toy Isochrone potential to the sum of the energy residuals relative
to the mean energy by minimizing the function
.. math::
f(m,b) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm iso}(x_i\,|\,m,b) - <E>)^2
TODO: This should fail if the Hamiltonian associated with the orbit has
a frame other than StaticFrame
Parameters
----------
orbit : `~gala.dynamics.Orbit`
m0 : numeric (optional)
Initial mass guess.
b0 : numeric (optional)
Initial b guess.
minimize_kwargs : dict (optional)
Keyword arguments to pass through to `scipy.optimize.minimize`.
Returns
-------
m : float
Best-fit scale mass for the Isochrone potential.
b : float
Best-fit core radius for the Isochrone potential. | [
"r",
"Fit",
"the",
"toy",
"Isochrone",
"potential",
"to",
"the",
"sum",
"of",
"the",
"energy",
"residuals",
"relative",
"to",
"the",
"mean",
"energy",
"by",
"minimizing",
"the",
"function"
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/actionangle.py#L78-L140 |
22,650 | adrn/gala | gala/dynamics/actionangle.py | fit_harmonic_oscillator | def fit_harmonic_oscillator(orbit, omega0=[1., 1, 1], minimize_kwargs=None):
r"""
Fit the toy harmonic oscillator potential to the sum of the energy
residuals relative to the mean energy by minimizing the function
.. math::
f(\boldsymbol{\omega}) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm sho}(x_i\,|\,\boldsymbol{\omega}) - <E>)^2
TODO: This should fail if the Hamiltonian associated with the orbit has
a frame other than StaticFrame
Parameters
----------
orbit : `~gala.dynamics.Orbit`
omega0 : array_like (optional)
Initial frequency guess.
minimize_kwargs : dict (optional)
Keyword arguments to pass through to `scipy.optimize.minimize`.
Returns
-------
omegas : float
Best-fit harmonic oscillator frequencies.
"""
omega0 = np.atleast_1d(omega0)
pot = orbit.hamiltonian.potential
if pot is None:
raise ValueError("The orbit object must have an associated potential")
w = np.squeeze(orbit.w(pot.units))
if w.ndim > 2:
raise ValueError("Input orbit object must be a single orbit.")
def f(omega, w):
potential = HarmonicOscillatorPotential(omega=omega, units=pot.units)
H = (potential.value(w[:3]).decompose(pot.units).value +
0.5*np.sum(w[3:]**2, axis=0))
return np.sum(np.squeeze(H - np.mean(H))**2)
if minimize_kwargs is None:
minimize_kwargs = dict()
minimize_kwargs['x0'] = omega0
minimize_kwargs['method'] = minimize_kwargs.get('method', 'Nelder-Mead')
res = minimize(f, args=(w,), **minimize_kwargs)
if not res.success:
raise ValueError("Failed to fit toy potential to orbit.")
best_omega = np.abs(res.x)
return HarmonicOscillatorPotential(omega=best_omega, units=pot.units) | python | def fit_harmonic_oscillator(orbit, omega0=[1., 1, 1], minimize_kwargs=None):
r"""
Fit the toy harmonic oscillator potential to the sum of the energy
residuals relative to the mean energy by minimizing the function
.. math::
f(\boldsymbol{\omega}) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm sho}(x_i\,|\,\boldsymbol{\omega}) - <E>)^2
TODO: This should fail if the Hamiltonian associated with the orbit has
a frame other than StaticFrame
Parameters
----------
orbit : `~gala.dynamics.Orbit`
omega0 : array_like (optional)
Initial frequency guess.
minimize_kwargs : dict (optional)
Keyword arguments to pass through to `scipy.optimize.minimize`.
Returns
-------
omegas : float
Best-fit harmonic oscillator frequencies.
"""
omega0 = np.atleast_1d(omega0)
pot = orbit.hamiltonian.potential
if pot is None:
raise ValueError("The orbit object must have an associated potential")
w = np.squeeze(orbit.w(pot.units))
if w.ndim > 2:
raise ValueError("Input orbit object must be a single orbit.")
def f(omega, w):
potential = HarmonicOscillatorPotential(omega=omega, units=pot.units)
H = (potential.value(w[:3]).decompose(pot.units).value +
0.5*np.sum(w[3:]**2, axis=0))
return np.sum(np.squeeze(H - np.mean(H))**2)
if minimize_kwargs is None:
minimize_kwargs = dict()
minimize_kwargs['x0'] = omega0
minimize_kwargs['method'] = minimize_kwargs.get('method', 'Nelder-Mead')
res = minimize(f, args=(w,), **minimize_kwargs)
if not res.success:
raise ValueError("Failed to fit toy potential to orbit.")
best_omega = np.abs(res.x)
return HarmonicOscillatorPotential(omega=best_omega, units=pot.units) | [
"def",
"fit_harmonic_oscillator",
"(",
"orbit",
",",
"omega0",
"=",
"[",
"1.",
",",
"1",
",",
"1",
"]",
",",
"minimize_kwargs",
"=",
"None",
")",
":",
"omega0",
"=",
"np",
".",
"atleast_1d",
"(",
"omega0",
")",
"pot",
"=",
"orbit",
".",
"hamiltonian",
... | r"""
Fit the toy harmonic oscillator potential to the sum of the energy
residuals relative to the mean energy by minimizing the function
.. math::
f(\boldsymbol{\omega}) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm sho}(x_i\,|\,\boldsymbol{\omega}) - <E>)^2
TODO: This should fail if the Hamiltonian associated with the orbit has
a frame other than StaticFrame
Parameters
----------
orbit : `~gala.dynamics.Orbit`
omega0 : array_like (optional)
Initial frequency guess.
minimize_kwargs : dict (optional)
Keyword arguments to pass through to `scipy.optimize.minimize`.
Returns
-------
omegas : float
Best-fit harmonic oscillator frequencies. | [
"r",
"Fit",
"the",
"toy",
"harmonic",
"oscillator",
"potential",
"to",
"the",
"sum",
"of",
"the",
"energy",
"residuals",
"relative",
"to",
"the",
"mean",
"energy",
"by",
"minimizing",
"the",
"function"
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/actionangle.py#L142-L194 |
22,651 | adrn/gala | gala/dynamics/actionangle.py | check_angle_sampling | def check_angle_sampling(nvecs, angles):
"""
Returns a list of the index of elements of n which do not have adequate
toy angle coverage. The criterion is that we must have at least one sample
in each Nyquist box when we project the toy angles along the vector n.
Parameters
----------
nvecs : array_like
Array of integer vectors.
angles : array_like
Array of angles.
Returns
-------
failed_nvecs : :class:`numpy.ndarray`
Array of all integer vectors that failed checks. Has shape (N,3).
failures : :class:`numpy.ndarray`
Array of flags that designate whether this failed needing a longer
integration window (0) or finer sampling (1).
"""
failed_nvecs = []
failures = []
for i, vec in enumerate(nvecs):
# N = np.linalg.norm(vec)
# X = np.dot(angles,vec)
X = (angles*vec[:, None]).sum(axis=0)
diff = float(np.abs(X.max() - X.min()))
if diff < (2.*np.pi):
warnings.warn("Need a longer integration window for mode {0}"
.format(vec))
failed_nvecs.append(vec.tolist())
# P.append(2.*np.pi - diff)
failures.append(0)
elif (diff/len(X)) > np.pi:
warnings.warn("Need a finer sampling for mode {0}"
.format(str(vec)))
failed_nvecs.append(vec.tolist())
# P.append(np.pi - diff/len(X))
failures.append(1)
return np.array(failed_nvecs), np.array(failures) | python | def check_angle_sampling(nvecs, angles):
failed_nvecs = []
failures = []
for i, vec in enumerate(nvecs):
# N = np.linalg.norm(vec)
# X = np.dot(angles,vec)
X = (angles*vec[:, None]).sum(axis=0)
diff = float(np.abs(X.max() - X.min()))
if diff < (2.*np.pi):
warnings.warn("Need a longer integration window for mode {0}"
.format(vec))
failed_nvecs.append(vec.tolist())
# P.append(2.*np.pi - diff)
failures.append(0)
elif (diff/len(X)) > np.pi:
warnings.warn("Need a finer sampling for mode {0}"
.format(str(vec)))
failed_nvecs.append(vec.tolist())
# P.append(np.pi - diff/len(X))
failures.append(1)
return np.array(failed_nvecs), np.array(failures) | [
"def",
"check_angle_sampling",
"(",
"nvecs",
",",
"angles",
")",
":",
"failed_nvecs",
"=",
"[",
"]",
"failures",
"=",
"[",
"]",
"for",
"i",
",",
"vec",
"in",
"enumerate",
"(",
"nvecs",
")",
":",
"# N = np.linalg.norm(vec)",
"# X = np.dot(angles,vec)",
"X",
"... | Returns a list of the index of elements of n which do not have adequate
toy angle coverage. The criterion is that we must have at least one sample
in each Nyquist box when we project the toy angles along the vector n.
Parameters
----------
nvecs : array_like
Array of integer vectors.
angles : array_like
Array of angles.
Returns
-------
failed_nvecs : :class:`numpy.ndarray`
Array of all integer vectors that failed checks. Has shape (N,3).
failures : :class:`numpy.ndarray`
Array of flags that designate whether this failed needing a longer
integration window (0) or finer sampling (1). | [
"Returns",
"a",
"list",
"of",
"the",
"index",
"of",
"elements",
"of",
"n",
"which",
"do",
"not",
"have",
"adequate",
"toy",
"angle",
"coverage",
".",
"The",
"criterion",
"is",
"that",
"we",
"must",
"have",
"at",
"least",
"one",
"sample",
"in",
"each",
... | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/actionangle.py#L237-L283 |
22,652 | adrn/gala | gala/dynamics/actionangle.py | find_actions | def find_actions(orbit, N_max, force_harmonic_oscillator=False, toy_potential=None):
r"""
Find approximate actions and angles for samples of a phase-space orbit.
Uses toy potentials with known, analytic action-angle transformations to
approximate the true coordinates as a Fourier sum.
This code is adapted from Jason Sanders'
`genfunc <https://github.com/jlsanders/genfunc>`_
Parameters
----------
orbit : `~gala.dynamics.Orbit`
N_max : int
Maximum integer Fourier mode vector length, :math:`|\boldsymbol{n}|`.
force_harmonic_oscillator : bool (optional)
Force using the harmonic oscillator potential as the toy potential.
toy_potential : Potential (optional)
Fix the toy potential class.
Returns
-------
aaf : dict
A Python dictionary containing the actions, angles, frequencies, and
value of the generating function and derivatives for each integer
vector. Each value of the dictionary is a :class:`numpy.ndarray` or
:class:`astropy.units.Quantity`.
"""
if orbit.norbits == 1:
return _single_orbit_find_actions(
orbit, N_max,
force_harmonic_oscillator=force_harmonic_oscillator,
toy_potential=toy_potential)
else:
norbits = orbit.norbits
actions = np.zeros((3, norbits))
angles = np.zeros((3, norbits))
freqs = np.zeros((3, norbits))
for n in range(norbits):
aaf = _single_orbit_find_actions(
orbit[:, n], N_max,
force_harmonic_oscillator=force_harmonic_oscillator,
toy_potential=toy_potential)
actions[n] = aaf['actions'].value
angles[n] = aaf['angles'].value
freqs[n] = aaf['freqs'].value
return dict(actions=actions*aaf['actions'].unit,
angles=angles*aaf['angles'].unit,
freqs=freqs*aaf['freqs'].unit,
Sn=actions[3:], dSn=angles[6:], nvecs=aaf['nvecs']) | python | def find_actions(orbit, N_max, force_harmonic_oscillator=False, toy_potential=None):
r"""
Find approximate actions and angles for samples of a phase-space orbit.
Uses toy potentials with known, analytic action-angle transformations to
approximate the true coordinates as a Fourier sum.
This code is adapted from Jason Sanders'
`genfunc <https://github.com/jlsanders/genfunc>`_
Parameters
----------
orbit : `~gala.dynamics.Orbit`
N_max : int
Maximum integer Fourier mode vector length, :math:`|\boldsymbol{n}|`.
force_harmonic_oscillator : bool (optional)
Force using the harmonic oscillator potential as the toy potential.
toy_potential : Potential (optional)
Fix the toy potential class.
Returns
-------
aaf : dict
A Python dictionary containing the actions, angles, frequencies, and
value of the generating function and derivatives for each integer
vector. Each value of the dictionary is a :class:`numpy.ndarray` or
:class:`astropy.units.Quantity`.
"""
if orbit.norbits == 1:
return _single_orbit_find_actions(
orbit, N_max,
force_harmonic_oscillator=force_harmonic_oscillator,
toy_potential=toy_potential)
else:
norbits = orbit.norbits
actions = np.zeros((3, norbits))
angles = np.zeros((3, norbits))
freqs = np.zeros((3, norbits))
for n in range(norbits):
aaf = _single_orbit_find_actions(
orbit[:, n], N_max,
force_harmonic_oscillator=force_harmonic_oscillator,
toy_potential=toy_potential)
actions[n] = aaf['actions'].value
angles[n] = aaf['angles'].value
freqs[n] = aaf['freqs'].value
return dict(actions=actions*aaf['actions'].unit,
angles=angles*aaf['angles'].unit,
freqs=freqs*aaf['freqs'].unit,
Sn=actions[3:], dSn=angles[6:], nvecs=aaf['nvecs']) | [
"def",
"find_actions",
"(",
"orbit",
",",
"N_max",
",",
"force_harmonic_oscillator",
"=",
"False",
",",
"toy_potential",
"=",
"None",
")",
":",
"if",
"orbit",
".",
"norbits",
"==",
"1",
":",
"return",
"_single_orbit_find_actions",
"(",
"orbit",
",",
"N_max",
... | r"""
Find approximate actions and angles for samples of a phase-space orbit.
Uses toy potentials with known, analytic action-angle transformations to
approximate the true coordinates as a Fourier sum.
This code is adapted from Jason Sanders'
`genfunc <https://github.com/jlsanders/genfunc>`_
Parameters
----------
orbit : `~gala.dynamics.Orbit`
N_max : int
Maximum integer Fourier mode vector length, :math:`|\boldsymbol{n}|`.
force_harmonic_oscillator : bool (optional)
Force using the harmonic oscillator potential as the toy potential.
toy_potential : Potential (optional)
Fix the toy potential class.
Returns
-------
aaf : dict
A Python dictionary containing the actions, angles, frequencies, and
value of the generating function and derivatives for each integer
vector. Each value of the dictionary is a :class:`numpy.ndarray` or
:class:`astropy.units.Quantity`. | [
"r",
"Find",
"approximate",
"actions",
"and",
"angles",
"for",
"samples",
"of",
"a",
"phase",
"-",
"space",
"orbit",
".",
"Uses",
"toy",
"potentials",
"with",
"known",
"analytic",
"action",
"-",
"angle",
"transformations",
"to",
"approximate",
"the",
"true",
... | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/actionangle.py#L539-L591 |
22,653 | adrn/gala | gala/dynamics/_genfunc/toy_potentials.py | angact_ho | def angact_ho(x,omega):
""" Calculate angle and action variable in sho potential with
parameter omega """
action = (x[3:]**2+(omega*x[:3])**2)/(2.*omega)
angle = np.array([np.arctan(-x[3+i]/omega[i]/x[i]) if x[i]!=0. else -np.sign(x[3+i])*np.pi/2. for i in range(3)])
for i in range(3):
if(x[i]<0):
angle[i]+=np.pi
return np.concatenate((action,angle % (2.*np.pi))) | python | def angact_ho(x,omega):
action = (x[3:]**2+(omega*x[:3])**2)/(2.*omega)
angle = np.array([np.arctan(-x[3+i]/omega[i]/x[i]) if x[i]!=0. else -np.sign(x[3+i])*np.pi/2. for i in range(3)])
for i in range(3):
if(x[i]<0):
angle[i]+=np.pi
return np.concatenate((action,angle % (2.*np.pi))) | [
"def",
"angact_ho",
"(",
"x",
",",
"omega",
")",
":",
"action",
"=",
"(",
"x",
"[",
"3",
":",
"]",
"**",
"2",
"+",
"(",
"omega",
"*",
"x",
"[",
":",
"3",
"]",
")",
"**",
"2",
")",
"/",
"(",
"2.",
"*",
"omega",
")",
"angle",
"=",
"np",
"... | Calculate angle and action variable in sho potential with
parameter omega | [
"Calculate",
"angle",
"and",
"action",
"variable",
"in",
"sho",
"potential",
"with",
"parameter",
"omega"
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/toy_potentials.py#L18-L26 |
22,654 | adrn/gala | gala/dynamics/util.py | peak_to_peak_period | def peak_to_peak_period(t, f, amplitude_threshold=1E-2):
"""
Estimate the period of the input time series by measuring the average
peak-to-peak time.
Parameters
----------
t : array_like
Time grid aligned with the input time series.
f : array_like
A periodic time series.
amplitude_threshold : numeric (optional)
A tolerance parameter. Fails if the mean amplitude of oscillations
isn't larger than this tolerance.
Returns
-------
period : float
The mean peak-to-peak period.
"""
if hasattr(t, 'unit'):
t_unit = t.unit
t = t.value
else:
t_unit = u.dimensionless_unscaled
# find peaks
max_ix = argrelmax(f, mode='wrap')[0]
max_ix = max_ix[(max_ix != 0) & (max_ix != (len(f)-1))]
# find troughs
min_ix = argrelmin(f, mode='wrap')[0]
min_ix = min_ix[(min_ix != 0) & (min_ix != (len(f)-1))]
# neglect minor oscillations
if abs(np.mean(f[max_ix]) - np.mean(f[min_ix])) < amplitude_threshold:
return np.nan
# compute mean peak-to-peak
if len(max_ix) > 0:
T_max = np.mean(t[max_ix[1:]] - t[max_ix[:-1]])
else:
T_max = np.nan
# now compute mean trough-to-trough
if len(min_ix) > 0:
T_min = np.mean(t[min_ix[1:]] - t[min_ix[:-1]])
else:
T_min = np.nan
# then take the mean of these two
return np.mean([T_max, T_min]) * t_unit | python | def peak_to_peak_period(t, f, amplitude_threshold=1E-2):
if hasattr(t, 'unit'):
t_unit = t.unit
t = t.value
else:
t_unit = u.dimensionless_unscaled
# find peaks
max_ix = argrelmax(f, mode='wrap')[0]
max_ix = max_ix[(max_ix != 0) & (max_ix != (len(f)-1))]
# find troughs
min_ix = argrelmin(f, mode='wrap')[0]
min_ix = min_ix[(min_ix != 0) & (min_ix != (len(f)-1))]
# neglect minor oscillations
if abs(np.mean(f[max_ix]) - np.mean(f[min_ix])) < amplitude_threshold:
return np.nan
# compute mean peak-to-peak
if len(max_ix) > 0:
T_max = np.mean(t[max_ix[1:]] - t[max_ix[:-1]])
else:
T_max = np.nan
# now compute mean trough-to-trough
if len(min_ix) > 0:
T_min = np.mean(t[min_ix[1:]] - t[min_ix[:-1]])
else:
T_min = np.nan
# then take the mean of these two
return np.mean([T_max, T_min]) * t_unit | [
"def",
"peak_to_peak_period",
"(",
"t",
",",
"f",
",",
"amplitude_threshold",
"=",
"1E-2",
")",
":",
"if",
"hasattr",
"(",
"t",
",",
"'unit'",
")",
":",
"t_unit",
"=",
"t",
".",
"unit",
"t",
"=",
"t",
".",
"value",
"else",
":",
"t_unit",
"=",
"u",
... | Estimate the period of the input time series by measuring the average
peak-to-peak time.
Parameters
----------
t : array_like
Time grid aligned with the input time series.
f : array_like
A periodic time series.
amplitude_threshold : numeric (optional)
A tolerance parameter. Fails if the mean amplitude of oscillations
isn't larger than this tolerance.
Returns
-------
period : float
The mean peak-to-peak period. | [
"Estimate",
"the",
"period",
"of",
"the",
"input",
"time",
"series",
"by",
"measuring",
"the",
"average",
"peak",
"-",
"to",
"-",
"peak",
"time",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/util.py#L17-L68 |
22,655 | adrn/gala | gala/dynamics/util.py | estimate_dt_n_steps | def estimate_dt_n_steps(w0, hamiltonian, n_periods, n_steps_per_period,
dE_threshold=1E-9, func=np.nanmax,
**integrate_kwargs):
"""
Estimate the timestep and number of steps to integrate an orbit for
given its initial conditions and a potential object.
Parameters
----------
w0 : `~gala.dynamics.PhaseSpacePosition`, array_like
Initial conditions.
potential : :class:`~gala.potential.PotentialBase`
The potential to integrate the orbit in.
n_periods : int
Number of (max) orbital periods to integrate for.
n_steps_per_period : int
Number of steps to take per (max) orbital period.
dE_threshold : numeric (optional)
Maximum fractional energy difference -- used to determine initial
timestep. Set to ``None`` to ignore this.
func : callable (optional)
Determines which period to use. By default, this takes the maximum
period using :func:`~numpy.nanmax`. Other options could be
:func:`~numpy.nanmin`, :func:`~numpy.nanmean`, :func:`~numpy.nanmedian`.
Returns
-------
dt : float
The timestep.
n_steps : int
The number of timesteps to integrate for.
"""
if not isinstance(w0, PhaseSpacePosition):
w0 = np.asarray(w0)
w0 = PhaseSpacePosition.from_w(w0, units=hamiltonian.units)
# integrate orbit
dt = _autodetermine_initial_dt(w0, hamiltonian, dE_threshold=dE_threshold,
**integrate_kwargs)
n_steps = int(round(10000 / dt))
orbit = hamiltonian.integrate_orbit(w0, dt=dt, n_steps=n_steps,
**integrate_kwargs)
# if loop, align circulation with Z and take R period
circ = orbit.circulation()
if np.any(circ):
orbit = orbit.align_circulation_with_z(circulation=circ)
cyl = orbit.represent_as(coord.CylindricalRepresentation)
# convert to cylindrical coordinates
R = cyl.rho.value
phi = cyl.phi.value
z = cyl.z.value
T = np.array([peak_to_peak_period(orbit.t, f).value
for f in [R, phi, z]])*orbit.t.unit
else:
T = np.array([peak_to_peak_period(orbit.t, f).value
for f in orbit.pos])*orbit.t.unit
# timestep from number of steps per period
T = func(T)
if np.isnan(T):
raise RuntimeError("Failed to find period.")
T = T.decompose(hamiltonian.units).value
dt = T / float(n_steps_per_period)
n_steps = int(round(n_periods * T / dt))
if dt == 0. or dt < 1E-13:
raise ValueError("Timestep is zero or very small!")
return dt, n_steps | python | def estimate_dt_n_steps(w0, hamiltonian, n_periods, n_steps_per_period,
dE_threshold=1E-9, func=np.nanmax,
**integrate_kwargs):
if not isinstance(w0, PhaseSpacePosition):
w0 = np.asarray(w0)
w0 = PhaseSpacePosition.from_w(w0, units=hamiltonian.units)
# integrate orbit
dt = _autodetermine_initial_dt(w0, hamiltonian, dE_threshold=dE_threshold,
**integrate_kwargs)
n_steps = int(round(10000 / dt))
orbit = hamiltonian.integrate_orbit(w0, dt=dt, n_steps=n_steps,
**integrate_kwargs)
# if loop, align circulation with Z and take R period
circ = orbit.circulation()
if np.any(circ):
orbit = orbit.align_circulation_with_z(circulation=circ)
cyl = orbit.represent_as(coord.CylindricalRepresentation)
# convert to cylindrical coordinates
R = cyl.rho.value
phi = cyl.phi.value
z = cyl.z.value
T = np.array([peak_to_peak_period(orbit.t, f).value
for f in [R, phi, z]])*orbit.t.unit
else:
T = np.array([peak_to_peak_period(orbit.t, f).value
for f in orbit.pos])*orbit.t.unit
# timestep from number of steps per period
T = func(T)
if np.isnan(T):
raise RuntimeError("Failed to find period.")
T = T.decompose(hamiltonian.units).value
dt = T / float(n_steps_per_period)
n_steps = int(round(n_periods * T / dt))
if dt == 0. or dt < 1E-13:
raise ValueError("Timestep is zero or very small!")
return dt, n_steps | [
"def",
"estimate_dt_n_steps",
"(",
"w0",
",",
"hamiltonian",
",",
"n_periods",
",",
"n_steps_per_period",
",",
"dE_threshold",
"=",
"1E-9",
",",
"func",
"=",
"np",
".",
"nanmax",
",",
"*",
"*",
"integrate_kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
... | Estimate the timestep and number of steps to integrate an orbit for
given its initial conditions and a potential object.
Parameters
----------
w0 : `~gala.dynamics.PhaseSpacePosition`, array_like
Initial conditions.
potential : :class:`~gala.potential.PotentialBase`
The potential to integrate the orbit in.
n_periods : int
Number of (max) orbital periods to integrate for.
n_steps_per_period : int
Number of steps to take per (max) orbital period.
dE_threshold : numeric (optional)
Maximum fractional energy difference -- used to determine initial
timestep. Set to ``None`` to ignore this.
func : callable (optional)
Determines which period to use. By default, this takes the maximum
period using :func:`~numpy.nanmax`. Other options could be
:func:`~numpy.nanmin`, :func:`~numpy.nanmean`, :func:`~numpy.nanmedian`.
Returns
-------
dt : float
The timestep.
n_steps : int
The number of timesteps to integrate for. | [
"Estimate",
"the",
"timestep",
"and",
"number",
"of",
"steps",
"to",
"integrate",
"an",
"orbit",
"for",
"given",
"its",
"initial",
"conditions",
"and",
"a",
"potential",
"object",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/util.py#L94-L169 |
22,656 | adrn/gala | gala/coordinates/reflex.py | reflex_correct | def reflex_correct(coords, galactocentric_frame=None):
"""Correct the input Astropy coordinate object for solar reflex motion.
The input coordinate instance must have distance and radial velocity information. If the radial velocity is not known, fill the
Parameters
----------
coords : `~astropy.coordinates.SkyCoord`
The Astropy coordinate object with position and velocity information.
galactocentric_frame : `~astropy.coordinates.Galactocentric` (optional)
To change properties of the Galactocentric frame, like the height of the
sun above the midplane, or the velocity of the sun in a Galactocentric
intertial frame, set arguments of the
`~astropy.coordinates.Galactocentric` object and pass in to this
function with your coordinates.
Returns
-------
coords : `~astropy.coordinates.SkyCoord`
The coordinates in the same frame as input, but with solar motion
removed.
"""
c = coord.SkyCoord(coords)
# If not specified, use the Astropy default Galactocentric frame
if galactocentric_frame is None:
galactocentric_frame = coord.Galactocentric()
v_sun = galactocentric_frame.galcen_v_sun
observed = c.transform_to(galactocentric_frame)
rep = observed.cartesian.without_differentials()
rep = rep.with_differentials(observed.cartesian.differentials['s'] + v_sun)
fr = galactocentric_frame.realize_frame(rep).transform_to(c.frame)
return coord.SkyCoord(fr) | python | def reflex_correct(coords, galactocentric_frame=None):
c = coord.SkyCoord(coords)
# If not specified, use the Astropy default Galactocentric frame
if galactocentric_frame is None:
galactocentric_frame = coord.Galactocentric()
v_sun = galactocentric_frame.galcen_v_sun
observed = c.transform_to(galactocentric_frame)
rep = observed.cartesian.without_differentials()
rep = rep.with_differentials(observed.cartesian.differentials['s'] + v_sun)
fr = galactocentric_frame.realize_frame(rep).transform_to(c.frame)
return coord.SkyCoord(fr) | [
"def",
"reflex_correct",
"(",
"coords",
",",
"galactocentric_frame",
"=",
"None",
")",
":",
"c",
"=",
"coord",
".",
"SkyCoord",
"(",
"coords",
")",
"# If not specified, use the Astropy default Galactocentric frame",
"if",
"galactocentric_frame",
"is",
"None",
":",
"ga... | Correct the input Astropy coordinate object for solar reflex motion.
The input coordinate instance must have distance and radial velocity information. If the radial velocity is not known, fill the
Parameters
----------
coords : `~astropy.coordinates.SkyCoord`
The Astropy coordinate object with position and velocity information.
galactocentric_frame : `~astropy.coordinates.Galactocentric` (optional)
To change properties of the Galactocentric frame, like the height of the
sun above the midplane, or the velocity of the sun in a Galactocentric
intertial frame, set arguments of the
`~astropy.coordinates.Galactocentric` object and pass in to this
function with your coordinates.
Returns
-------
coords : `~astropy.coordinates.SkyCoord`
The coordinates in the same frame as input, but with solar motion
removed. | [
"Correct",
"the",
"input",
"Astropy",
"coordinate",
"object",
"for",
"solar",
"reflex",
"motion",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/coordinates/reflex.py#L5-L40 |
22,657 | adrn/gala | gala/dynamics/plot.py | plot_projections | def plot_projections(x, relative_to=None, autolim=True, axes=None,
subplots_kwargs=dict(), labels=None, plot_function=None,
**kwargs):
"""
Given N-dimensional quantity, ``x``, make a figure containing 2D projections
of all combinations of the axes.
Parameters
----------
x : array_like
Array of values. ``axis=0`` is assumed to be the dimensionality,
``axis=1`` is the time axis. See :ref:`shape-conventions` for more
information.
relative_to : bool (optional)
Plot the values relative to this value or values.
autolim : bool (optional)
Automatically set the plot limits to be something sensible.
axes : array_like (optional)
Array of matplotlib Axes objects.
subplots_kwargs : dict (optional)
Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`.
labels : iterable (optional)
List or iterable of axis labels as strings. They should correspond to
the dimensions of the input orbit.
plot_function : callable (optional)
The ``matplotlib`` plot function to use. By default, this is
:func:`~matplotlib.pyplot.scatter`, but can also be, e.g.,
:func:`~matplotlib.pyplot.plot`.
**kwargs
All other keyword arguments are passed to the ``plot_function``.
You can pass in any of the usual style kwargs like ``color=...``,
``marker=...``, etc.
Returns
-------
fig : `~matplotlib.Figure`
"""
# don't propagate changes back...
x = np.array(x, copy=True)
ndim = x.shape[0]
# get axes object from arguments
if axes is None:
axes = _get_axes(dim=ndim, subplots_kwargs=subplots_kwargs)
# if the quantities are relative
if relative_to is not None:
x -= relative_to
# name of the plotting function
plot_fn_name = plot_function.__name__
# automatically determine limits
if autolim:
lims = []
for i in range(ndim):
max_,min_ = np.max(x[i]), np.min(x[i])
delta = max_ - min_
if delta == 0.:
delta = 1.
lims.append([min_ - delta*0.02, max_ + delta*0.02])
k = 0
for i in range(ndim):
for j in range(ndim):
if i >= j:
continue # skip diagonal, upper triangle
plot_func = getattr(axes[k], plot_fn_name)
plot_func(x[i], x[j], **kwargs)
if labels is not None:
axes[k].set_xlabel(labels[i])
axes[k].set_ylabel(labels[j])
if autolim:
axes[k].set_xlim(lims[i])
axes[k].set_ylim(lims[j])
k += 1
axes[0].figure.tight_layout()
return axes[0].figure | python | def plot_projections(x, relative_to=None, autolim=True, axes=None,
subplots_kwargs=dict(), labels=None, plot_function=None,
**kwargs):
# don't propagate changes back...
x = np.array(x, copy=True)
ndim = x.shape[0]
# get axes object from arguments
if axes is None:
axes = _get_axes(dim=ndim, subplots_kwargs=subplots_kwargs)
# if the quantities are relative
if relative_to is not None:
x -= relative_to
# name of the plotting function
plot_fn_name = plot_function.__name__
# automatically determine limits
if autolim:
lims = []
for i in range(ndim):
max_,min_ = np.max(x[i]), np.min(x[i])
delta = max_ - min_
if delta == 0.:
delta = 1.
lims.append([min_ - delta*0.02, max_ + delta*0.02])
k = 0
for i in range(ndim):
for j in range(ndim):
if i >= j:
continue # skip diagonal, upper triangle
plot_func = getattr(axes[k], plot_fn_name)
plot_func(x[i], x[j], **kwargs)
if labels is not None:
axes[k].set_xlabel(labels[i])
axes[k].set_ylabel(labels[j])
if autolim:
axes[k].set_xlim(lims[i])
axes[k].set_ylim(lims[j])
k += 1
axes[0].figure.tight_layout()
return axes[0].figure | [
"def",
"plot_projections",
"(",
"x",
",",
"relative_to",
"=",
"None",
",",
"autolim",
"=",
"True",
",",
"axes",
"=",
"None",
",",
"subplots_kwargs",
"=",
"dict",
"(",
")",
",",
"labels",
"=",
"None",
",",
"plot_function",
"=",
"None",
",",
"*",
"*",
... | Given N-dimensional quantity, ``x``, make a figure containing 2D projections
of all combinations of the axes.
Parameters
----------
x : array_like
Array of values. ``axis=0`` is assumed to be the dimensionality,
``axis=1`` is the time axis. See :ref:`shape-conventions` for more
information.
relative_to : bool (optional)
Plot the values relative to this value or values.
autolim : bool (optional)
Automatically set the plot limits to be something sensible.
axes : array_like (optional)
Array of matplotlib Axes objects.
subplots_kwargs : dict (optional)
Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`.
labels : iterable (optional)
List or iterable of axis labels as strings. They should correspond to
the dimensions of the input orbit.
plot_function : callable (optional)
The ``matplotlib`` plot function to use. By default, this is
:func:`~matplotlib.pyplot.scatter`, but can also be, e.g.,
:func:`~matplotlib.pyplot.plot`.
**kwargs
All other keyword arguments are passed to the ``plot_function``.
You can pass in any of the usual style kwargs like ``color=...``,
``marker=...``, etc.
Returns
-------
fig : `~matplotlib.Figure` | [
"Given",
"N",
"-",
"dimensional",
"quantity",
"x",
"make",
"a",
"figure",
"containing",
"2D",
"projections",
"of",
"all",
"combinations",
"of",
"the",
"axes",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/plot.py#L34-L120 |
22,658 | adrn/gala | gala/dynamics/_genfunc/genfunc_3d.py | angmom | def angmom(x):
""" returns angular momentum vector of phase-space point x"""
return np.array([x[1]*x[5]-x[2]*x[4],x[2]*x[3]-x[0]*x[5],x[0]*x[4]-x[1]*x[3]]) | python | def angmom(x):
return np.array([x[1]*x[5]-x[2]*x[4],x[2]*x[3]-x[0]*x[5],x[0]*x[4]-x[1]*x[3]]) | [
"def",
"angmom",
"(",
"x",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"x",
"[",
"1",
"]",
"*",
"x",
"[",
"5",
"]",
"-",
"x",
"[",
"2",
"]",
"*",
"x",
"[",
"4",
"]",
",",
"x",
"[",
"2",
"]",
"*",
"x",
"[",
"3",
"]",
"-",
"x",
... | returns angular momentum vector of phase-space point x | [
"returns",
"angular",
"momentum",
"vector",
"of",
"phase",
"-",
"space",
"point",
"x"
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/genfunc_3d.py#L186-L188 |
22,659 | adrn/gala | gala/dynamics/_genfunc/genfunc_3d.py | flip_coords | def flip_coords(X,loop):
""" Align circulation with z-axis """
if(loop[0]==1):
return np.array(map(lambda i: np.array([i[2],i[1],i[0],i[5],i[4],i[3]]),X))
else:
return X | python | def flip_coords(X,loop):
if(loop[0]==1):
return np.array(map(lambda i: np.array([i[2],i[1],i[0],i[5],i[4],i[3]]),X))
else:
return X | [
"def",
"flip_coords",
"(",
"X",
",",
"loop",
")",
":",
"if",
"(",
"loop",
"[",
"0",
"]",
"==",
"1",
")",
":",
"return",
"np",
".",
"array",
"(",
"map",
"(",
"lambda",
"i",
":",
"np",
".",
"array",
"(",
"[",
"i",
"[",
"2",
"]",
",",
"i",
"... | Align circulation with z-axis | [
"Align",
"circulation",
"with",
"z",
"-",
"axis"
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/genfunc_3d.py#L213-L218 |
22,660 | adrn/gala | gala/dynamics/analyticactionangle.py | harmonic_oscillator_to_aa | def harmonic_oscillator_to_aa(w, potential):
"""
Transform the input cartesian position and velocity to action-angle
coordinates for the Harmonic Oscillator potential.
This transformation is analytic and can be used as a "toy potential"
in the Sanders & Binney (2014) formalism for computing action-angle
coordinates in any potential.
.. note::
This function is included as a method of the
:class:`~gala.potential.HarmonicOscillatorPotential`
and it is recommended to call
:meth:`~gala.potential.HarmonicOscillatorPotential.action_angle()` instead.
Parameters
----------
w : :class:`gala.dynamics.PhaseSpacePosition`, :class:`gala.dynamics.Orbit`
potential : Potential
"""
usys = potential.units
if usys is not None:
x = w.xyz.decompose(usys).value
v = w.v_xyz.decompose(usys).value
else:
x = w.xyz.value
v = w.v_xyz.value
_new_omega_shape = (3,) + tuple([1]*(len(x.shape)-1))
# compute actions -- just energy (hamiltonian) over frequency
if usys is None:
usys = []
try:
omega = potential.parameters['omega'].reshape(_new_omega_shape).decompose(usys).value
except AttributeError: # not a Quantity
omega = potential.parameters['omega'].reshape(_new_omega_shape)
action = (v**2 + (omega*x)**2)/(2.*omega)
angle = np.arctan(-v / omega / x)
angle[x == 0] = -np.sign(v[x == 0])*np.pi/2.
angle[x < 0] += np.pi
freq = potential.parameters['omega'].decompose(usys).value
if usys is not None and usys:
a_unit = (1*usys['angular momentum']/usys['mass']).decompose(usys).unit
f_unit = (1*usys['frequency']).decompose(usys).unit
return action*a_unit, (angle % (2.*np.pi))*u.radian, freq*f_unit
else:
return action*u.one, (angle % (2.*np.pi))*u.one, freq*u.one | python | def harmonic_oscillator_to_aa(w, potential):
usys = potential.units
if usys is not None:
x = w.xyz.decompose(usys).value
v = w.v_xyz.decompose(usys).value
else:
x = w.xyz.value
v = w.v_xyz.value
_new_omega_shape = (3,) + tuple([1]*(len(x.shape)-1))
# compute actions -- just energy (hamiltonian) over frequency
if usys is None:
usys = []
try:
omega = potential.parameters['omega'].reshape(_new_omega_shape).decompose(usys).value
except AttributeError: # not a Quantity
omega = potential.parameters['omega'].reshape(_new_omega_shape)
action = (v**2 + (omega*x)**2)/(2.*omega)
angle = np.arctan(-v / omega / x)
angle[x == 0] = -np.sign(v[x == 0])*np.pi/2.
angle[x < 0] += np.pi
freq = potential.parameters['omega'].decompose(usys).value
if usys is not None and usys:
a_unit = (1*usys['angular momentum']/usys['mass']).decompose(usys).unit
f_unit = (1*usys['frequency']).decompose(usys).unit
return action*a_unit, (angle % (2.*np.pi))*u.radian, freq*f_unit
else:
return action*u.one, (angle % (2.*np.pi))*u.one, freq*u.one | [
"def",
"harmonic_oscillator_to_aa",
"(",
"w",
",",
"potential",
")",
":",
"usys",
"=",
"potential",
".",
"units",
"if",
"usys",
"is",
"not",
"None",
":",
"x",
"=",
"w",
".",
"xyz",
".",
"decompose",
"(",
"usys",
")",
".",
"value",
"v",
"=",
"w",
".... | Transform the input cartesian position and velocity to action-angle
coordinates for the Harmonic Oscillator potential.
This transformation is analytic and can be used as a "toy potential"
in the Sanders & Binney (2014) formalism for computing action-angle
coordinates in any potential.
.. note::
This function is included as a method of the
:class:`~gala.potential.HarmonicOscillatorPotential`
and it is recommended to call
:meth:`~gala.potential.HarmonicOscillatorPotential.action_angle()` instead.
Parameters
----------
w : :class:`gala.dynamics.PhaseSpacePosition`, :class:`gala.dynamics.Orbit`
potential : Potential | [
"Transform",
"the",
"input",
"cartesian",
"position",
"and",
"velocity",
"to",
"action",
"-",
"angle",
"coordinates",
"for",
"the",
"Harmonic",
"Oscillator",
"potential",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/analyticactionangle.py#L299-L352 |
22,661 | adrn/gala | gala/integrate/pyintegrators/rk5.py | RK5Integrator.step | def step(self, t, w, dt):
""" Step forward the vector w by the given timestep.
Parameters
----------
dt : numeric
The timestep to move forward.
"""
# Runge-Kutta Fehlberg formulas (see: Numerical Recipes)
F = lambda t, w: self.F(t, w, *self._func_args)
K = np.zeros((6,)+w.shape)
K[0] = dt * F(t, w)
K[1] = dt * F(t + A[1]*dt, w + B[1][0]*K[0])
K[2] = dt * F(t + A[2]*dt, w + B[2][0]*K[0] + B[2][1]*K[1])
K[3] = dt * F(t + A[3]*dt, w + B[3][0]*K[0] + B[3][1]*K[1] + B[3][2]*K[2])
K[4] = dt * F(t + A[4]*dt, w + B[4][0]*K[0] + B[4][1]*K[1] + B[4][2]*K[2] + B[4][3]*K[3])
K[5] = dt * F(t + A[5]*dt, w + B[5][0]*K[0] + B[5][1]*K[1] + B[5][2]*K[2] + B[5][3]*K[3] + B[5][4]*K[4])
# shift
dw = np.zeros_like(w)
for i in range(6):
dw = dw + C[i]*K[i]
return w + dw | python | def step(self, t, w, dt):
# Runge-Kutta Fehlberg formulas (see: Numerical Recipes)
F = lambda t, w: self.F(t, w, *self._func_args)
K = np.zeros((6,)+w.shape)
K[0] = dt * F(t, w)
K[1] = dt * F(t + A[1]*dt, w + B[1][0]*K[0])
K[2] = dt * F(t + A[2]*dt, w + B[2][0]*K[0] + B[2][1]*K[1])
K[3] = dt * F(t + A[3]*dt, w + B[3][0]*K[0] + B[3][1]*K[1] + B[3][2]*K[2])
K[4] = dt * F(t + A[4]*dt, w + B[4][0]*K[0] + B[4][1]*K[1] + B[4][2]*K[2] + B[4][3]*K[3])
K[5] = dt * F(t + A[5]*dt, w + B[5][0]*K[0] + B[5][1]*K[1] + B[5][2]*K[2] + B[5][3]*K[3] + B[5][4]*K[4])
# shift
dw = np.zeros_like(w)
for i in range(6):
dw = dw + C[i]*K[i]
return w + dw | [
"def",
"step",
"(",
"self",
",",
"t",
",",
"w",
",",
"dt",
")",
":",
"# Runge-Kutta Fehlberg formulas (see: Numerical Recipes)",
"F",
"=",
"lambda",
"t",
",",
"w",
":",
"self",
".",
"F",
"(",
"t",
",",
"w",
",",
"*",
"self",
".",
"_func_args",
")",
"... | Step forward the vector w by the given timestep.
Parameters
----------
dt : numeric
The timestep to move forward. | [
"Step",
"forward",
"the",
"vector",
"w",
"by",
"the",
"given",
"timestep",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/integrate/pyintegrators/rk5.py#L52-L77 |
22,662 | adrn/gala | gala/dynamics/_genfunc/solver.py | check_each_direction | def check_each_direction(n,angs,ifprint=True):
""" returns a list of the index of elements of n which do not have adequate
toy angle coverage. The criterion is that we must have at least one sample
in each Nyquist box when we project the toy angles along the vector n """
checks = np.array([])
P = np.array([])
if(ifprint):
print("\nChecking modes:\n====")
for k,i in enumerate(n):
N_matrix = np.linalg.norm(i)
X = np.dot(angs,i)
if(np.abs(np.max(X)-np.min(X))<2.*np.pi):
if(ifprint):
print("Need a longer integration window for mode ", i)
checks=np.append(checks,i)
P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X))))
elif(np.abs(np.max(X)-np.min(X))/len(X)>np.pi):
if(ifprint):
print("Need a finer sampling for mode ", i)
checks=np.append(checks,i)
P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X))))
if(ifprint):
print("====\n")
return checks,P | python | def check_each_direction(n,angs,ifprint=True):
checks = np.array([])
P = np.array([])
if(ifprint):
print("\nChecking modes:\n====")
for k,i in enumerate(n):
N_matrix = np.linalg.norm(i)
X = np.dot(angs,i)
if(np.abs(np.max(X)-np.min(X))<2.*np.pi):
if(ifprint):
print("Need a longer integration window for mode ", i)
checks=np.append(checks,i)
P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X))))
elif(np.abs(np.max(X)-np.min(X))/len(X)>np.pi):
if(ifprint):
print("Need a finer sampling for mode ", i)
checks=np.append(checks,i)
P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X))))
if(ifprint):
print("====\n")
return checks,P | [
"def",
"check_each_direction",
"(",
"n",
",",
"angs",
",",
"ifprint",
"=",
"True",
")",
":",
"checks",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"P",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"(",
"ifprint",
")",
":",
"print",
"(",
... | returns a list of the index of elements of n which do not have adequate
toy angle coverage. The criterion is that we must have at least one sample
in each Nyquist box when we project the toy angles along the vector n | [
"returns",
"a",
"list",
"of",
"the",
"index",
"of",
"elements",
"of",
"n",
"which",
"do",
"not",
"have",
"adequate",
"toy",
"angle",
"coverage",
".",
"The",
"criterion",
"is",
"that",
"we",
"must",
"have",
"at",
"least",
"one",
"sample",
"in",
"each",
... | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/solver.py#L10-L33 |
22,663 | adrn/gala | gala/dynamics/_genfunc/solver.py | unroll_angles | def unroll_angles(A,sign):
""" Unrolls the angles, A, so they increase continuously """
n = np.array([0,0,0])
P = np.zeros(np.shape(A))
P[0]=A[0]
for i in range(1,len(A)):
n = n+((A[i]-A[i-1]+0.5*sign*np.pi)*sign<0)*np.ones(3)*2.*np.pi
P[i] = A[i]+sign*n
return P | python | def unroll_angles(A,sign):
n = np.array([0,0,0])
P = np.zeros(np.shape(A))
P[0]=A[0]
for i in range(1,len(A)):
n = n+((A[i]-A[i-1]+0.5*sign*np.pi)*sign<0)*np.ones(3)*2.*np.pi
P[i] = A[i]+sign*n
return P | [
"def",
"unroll_angles",
"(",
"A",
",",
"sign",
")",
":",
"n",
"=",
"np",
".",
"array",
"(",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
"P",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"shape",
"(",
"A",
")",
")",
"P",
"[",
"0",
"]",
"=",
"A",... | Unrolls the angles, A, so they increase continuously | [
"Unrolls",
"the",
"angles",
"A",
"so",
"they",
"increase",
"continuously"
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/_genfunc/solver.py#L81-L89 |
22,664 | adrn/gala | gala/potential/scf/core.py | compute_coeffs | def compute_coeffs(density_func, nmax, lmax, M, r_s, args=(),
skip_odd=False, skip_even=False, skip_m=False,
S_only=False, progress=False, **nquad_opts):
"""
Compute the expansion coefficients for representing the input density function using a basis
function expansion.
Computing the coefficients involves computing triple integrals which are computationally
expensive. For an example of how to parallelize the computation of the coefficients, see
``examples/parallel_compute_Anlm.py``.
Parameters
----------
density_func : function, callable
A function or callable object that evaluates the density at a given position. The call
format must be of the form: ``density_func(x, y, z, M, r_s, args)`` where ``x,y,z`` are
cartesian coordinates, ``M`` is a scale mass, ``r_s`` a scale radius, and ``args`` is an
iterable containing any other arguments needed by the density function.
nmax : int
Maximum value of ``n`` for the radial expansion.
lmax : int
Maximum value of ``l`` for the spherical harmonics.
M : numeric
Scale mass.
r_s : numeric
Scale radius.
args : iterable (optional)
A list or iterable of any other arguments needed by the density
function.
skip_odd : bool (optional)
Skip the odd terms in the angular portion of the expansion. For example, only
take :math:`l=0,2,4,...`
skip_even : bool (optional)
Skip the even terms in the angular portion of the expansion. For example, only
take :math:`l=1,3,5,...`
skip_m : bool (optional)
Ignore terms with :math:`m > 0`.
S_only : bool (optional)
Only compute the S coefficients.
progress : bool (optional)
If ``tqdm`` is installed, display a progress bar.
**nquad_opts
Any additional keyword arguments are passed through to
`~scipy.integrate.nquad` as options, `opts`.
Returns
-------
Snlm : float, `~numpy.ndarray`
The value of the cosine expansion coefficient.
Snlm_err : , `~numpy.ndarray`
An estimate of the uncertainty in the coefficient value (from `~scipy.integrate.nquad`).
Tnlm : , `~numpy.ndarray`
The value of the sine expansion coefficient.
Tnlm_err : , `~numpy.ndarray`
An estimate of the uncertainty in the coefficient value. (from `~scipy.integrate.nquad`).
"""
from gala._cconfig import GSL_ENABLED
if not GSL_ENABLED:
raise ValueError("Gala was compiled without GSL and so this function "
"will not work. See the gala documentation for more "
"information about installing and using GSL with "
"gala: http://gala.adrian.pw/en/latest/install.html")
lmin = 0
lstride = 1
if skip_odd or skip_even:
lstride = 2
if skip_even:
lmin = 1
Snlm = np.zeros((nmax+1, lmax+1, lmax+1))
Snlm_e = np.zeros((nmax+1, lmax+1, lmax+1))
Tnlm = np.zeros((nmax+1, lmax+1, lmax+1))
Tnlm_e = np.zeros((nmax+1, lmax+1, lmax+1))
nquad_opts.setdefault('limit', 256)
nquad_opts.setdefault('epsrel', 1E-10)
limits = [[0, 2*np.pi], # phi
[-1, 1.], # X (cos(theta))
[-1, 1.]] # xsi
nlms = []
for n in range(nmax+1):
for l in range(lmin, lmax+1, lstride):
for m in range(l+1):
if skip_m and m > 0:
continue
nlms.append((n, l, m))
if progress:
try:
from tqdm import tqdm
except ImportError as e:
raise ImportError('tqdm is not installed - you can install it '
'with `pip install tqdm`.\n' + str(e))
iterfunc = tqdm
else:
iterfunc = lambda x: x
for n, l, m in iterfunc(nlms):
Snlm[n, l, m], Snlm_e[n, l, m] = si.nquad(
Snlm_integrand, ranges=limits,
args=(density_func, n, l, m, M, r_s, args),
opts=nquad_opts)
if not S_only:
Tnlm[n, l, m], Tnlm_e[n, l, m] = si.nquad(
Tnlm_integrand, ranges=limits,
args=(density_func, n, l, m, M, r_s, args),
opts=nquad_opts)
return (Snlm, Snlm_e), (Tnlm, Tnlm_e) | python | def compute_coeffs(density_func, nmax, lmax, M, r_s, args=(),
skip_odd=False, skip_even=False, skip_m=False,
S_only=False, progress=False, **nquad_opts):
from gala._cconfig import GSL_ENABLED
if not GSL_ENABLED:
raise ValueError("Gala was compiled without GSL and so this function "
"will not work. See the gala documentation for more "
"information about installing and using GSL with "
"gala: http://gala.adrian.pw/en/latest/install.html")
lmin = 0
lstride = 1
if skip_odd or skip_even:
lstride = 2
if skip_even:
lmin = 1
Snlm = np.zeros((nmax+1, lmax+1, lmax+1))
Snlm_e = np.zeros((nmax+1, lmax+1, lmax+1))
Tnlm = np.zeros((nmax+1, lmax+1, lmax+1))
Tnlm_e = np.zeros((nmax+1, lmax+1, lmax+1))
nquad_opts.setdefault('limit', 256)
nquad_opts.setdefault('epsrel', 1E-10)
limits = [[0, 2*np.pi], # phi
[-1, 1.], # X (cos(theta))
[-1, 1.]] # xsi
nlms = []
for n in range(nmax+1):
for l in range(lmin, lmax+1, lstride):
for m in range(l+1):
if skip_m and m > 0:
continue
nlms.append((n, l, m))
if progress:
try:
from tqdm import tqdm
except ImportError as e:
raise ImportError('tqdm is not installed - you can install it '
'with `pip install tqdm`.\n' + str(e))
iterfunc = tqdm
else:
iterfunc = lambda x: x
for n, l, m in iterfunc(nlms):
Snlm[n, l, m], Snlm_e[n, l, m] = si.nquad(
Snlm_integrand, ranges=limits,
args=(density_func, n, l, m, M, r_s, args),
opts=nquad_opts)
if not S_only:
Tnlm[n, l, m], Tnlm_e[n, l, m] = si.nquad(
Tnlm_integrand, ranges=limits,
args=(density_func, n, l, m, M, r_s, args),
opts=nquad_opts)
return (Snlm, Snlm_e), (Tnlm, Tnlm_e) | [
"def",
"compute_coeffs",
"(",
"density_func",
",",
"nmax",
",",
"lmax",
",",
"M",
",",
"r_s",
",",
"args",
"=",
"(",
")",
",",
"skip_odd",
"=",
"False",
",",
"skip_even",
"=",
"False",
",",
"skip_m",
"=",
"False",
",",
"S_only",
"=",
"False",
",",
... | Compute the expansion coefficients for representing the input density function using a basis
function expansion.
Computing the coefficients involves computing triple integrals which are computationally
expensive. For an example of how to parallelize the computation of the coefficients, see
``examples/parallel_compute_Anlm.py``.
Parameters
----------
density_func : function, callable
A function or callable object that evaluates the density at a given position. The call
format must be of the form: ``density_func(x, y, z, M, r_s, args)`` where ``x,y,z`` are
cartesian coordinates, ``M`` is a scale mass, ``r_s`` a scale radius, and ``args`` is an
iterable containing any other arguments needed by the density function.
nmax : int
Maximum value of ``n`` for the radial expansion.
lmax : int
Maximum value of ``l`` for the spherical harmonics.
M : numeric
Scale mass.
r_s : numeric
Scale radius.
args : iterable (optional)
A list or iterable of any other arguments needed by the density
function.
skip_odd : bool (optional)
Skip the odd terms in the angular portion of the expansion. For example, only
take :math:`l=0,2,4,...`
skip_even : bool (optional)
Skip the even terms in the angular portion of the expansion. For example, only
take :math:`l=1,3,5,...`
skip_m : bool (optional)
Ignore terms with :math:`m > 0`.
S_only : bool (optional)
Only compute the S coefficients.
progress : bool (optional)
If ``tqdm`` is installed, display a progress bar.
**nquad_opts
Any additional keyword arguments are passed through to
`~scipy.integrate.nquad` as options, `opts`.
Returns
-------
Snlm : float, `~numpy.ndarray`
The value of the cosine expansion coefficient.
Snlm_err : , `~numpy.ndarray`
An estimate of the uncertainty in the coefficient value (from `~scipy.integrate.nquad`).
Tnlm : , `~numpy.ndarray`
The value of the sine expansion coefficient.
Tnlm_err : , `~numpy.ndarray`
An estimate of the uncertainty in the coefficient value. (from `~scipy.integrate.nquad`). | [
"Compute",
"the",
"expansion",
"coefficients",
"for",
"representing",
"the",
"input",
"density",
"function",
"using",
"a",
"basis",
"function",
"expansion",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/scf/core.py#L13-L129 |
22,665 | adrn/gala | gala/potential/scf/core.py | compute_coeffs_discrete | def compute_coeffs_discrete(xyz, mass, nmax, lmax, r_s,
skip_odd=False, skip_even=False, skip_m=False,
compute_var=False):
"""
Compute the expansion coefficients for representing the density distribution of input points
as a basis function expansion. The points, ``xyz``, are assumed to be samples from the
density distribution.
Computing the coefficients involves computing triple integrals which are computationally
expensive. For an example of how to parallelize the computation of the coefficients, see
``examples/parallel_compute_Anlm.py``.
Parameters
----------
xyz : array_like
Samples from the density distribution. Should have shape ``(n_samples,3)``.
mass : array_like
Mass of each sample. Should have shape ``(n_samples,)``.
nmax : int
Maximum value of ``n`` for the radial expansion.
lmax : int
Maximum value of ``l`` for the spherical harmonics.
r_s : numeric
Scale radius.
skip_odd : bool (optional)
Skip the odd terms in the angular portion of the expansion. For example, only
take :math:`l=0,2,4,...`
skip_even : bool (optional)
Skip the even terms in the angular portion of the expansion. For example, only
take :math:`l=1,3,5,...`
skip_m : bool (optional)
Ignore terms with :math:`m > 0`.
compute_var : bool (optional)
Also compute the variances of the coefficients. This does not compute the full covariance
matrix of the coefficients, just the individual variances.
TODO: separate function to compute full covariance matrix?
Returns
-------
Snlm : float
The value of the cosine expansion coefficient.
Tnlm : float
The value of the sine expansion coefficient.
"""
lmin = 0
lstride = 1
if skip_odd or skip_even:
lstride = 2
if skip_even:
lmin = 1
Snlm = np.zeros((nmax+1, lmax+1, lmax+1))
Tnlm = np.zeros((nmax+1, lmax+1, lmax+1))
if compute_var:
Snlm_var = np.zeros((nmax+1, lmax+1, lmax+1))
Tnlm_var = np.zeros((nmax+1, lmax+1, lmax+1))
# positions and masses of point masses
xyz = np.ascontiguousarray(np.atleast_2d(xyz))
mass = np.ascontiguousarray(np.atleast_1d(mass))
r = np.sqrt(np.sum(xyz**2, axis=-1))
s = r / r_s
phi = np.arctan2(xyz[:,1], xyz[:,0])
X = xyz[:,2] / r
for n in range(nmax+1):
for l in range(lmin, lmax+1, lstride):
for m in range(l+1):
if skip_m and m > 0: continue
# logger.debug("Computing coefficients (n,l,m)=({},{},{})".format(n,l,m))
Snlm[n,l,m], Tnlm[n,l,m] = STnlm_discrete(s, phi, X, mass, n, l, m)
if compute_var:
Snlm_var[n,l,m], Tnlm_var[n,l,m] = STnlm_var_discrete(s, phi, X, mass, n, l, m)
if compute_var:
return (Snlm,Snlm_var), (Tnlm,Tnlm_var)
else:
return Snlm, Tnlm | python | def compute_coeffs_discrete(xyz, mass, nmax, lmax, r_s,
skip_odd=False, skip_even=False, skip_m=False,
compute_var=False):
lmin = 0
lstride = 1
if skip_odd or skip_even:
lstride = 2
if skip_even:
lmin = 1
Snlm = np.zeros((nmax+1, lmax+1, lmax+1))
Tnlm = np.zeros((nmax+1, lmax+1, lmax+1))
if compute_var:
Snlm_var = np.zeros((nmax+1, lmax+1, lmax+1))
Tnlm_var = np.zeros((nmax+1, lmax+1, lmax+1))
# positions and masses of point masses
xyz = np.ascontiguousarray(np.atleast_2d(xyz))
mass = np.ascontiguousarray(np.atleast_1d(mass))
r = np.sqrt(np.sum(xyz**2, axis=-1))
s = r / r_s
phi = np.arctan2(xyz[:,1], xyz[:,0])
X = xyz[:,2] / r
for n in range(nmax+1):
for l in range(lmin, lmax+1, lstride):
for m in range(l+1):
if skip_m and m > 0: continue
# logger.debug("Computing coefficients (n,l,m)=({},{},{})".format(n,l,m))
Snlm[n,l,m], Tnlm[n,l,m] = STnlm_discrete(s, phi, X, mass, n, l, m)
if compute_var:
Snlm_var[n,l,m], Tnlm_var[n,l,m] = STnlm_var_discrete(s, phi, X, mass, n, l, m)
if compute_var:
return (Snlm,Snlm_var), (Tnlm,Tnlm_var)
else:
return Snlm, Tnlm | [
"def",
"compute_coeffs_discrete",
"(",
"xyz",
",",
"mass",
",",
"nmax",
",",
"lmax",
",",
"r_s",
",",
"skip_odd",
"=",
"False",
",",
"skip_even",
"=",
"False",
",",
"skip_m",
"=",
"False",
",",
"compute_var",
"=",
"False",
")",
":",
"lmin",
"=",
"0",
... | Compute the expansion coefficients for representing the density distribution of input points
as a basis function expansion. The points, ``xyz``, are assumed to be samples from the
density distribution.
Computing the coefficients involves computing triple integrals which are computationally
expensive. For an example of how to parallelize the computation of the coefficients, see
``examples/parallel_compute_Anlm.py``.
Parameters
----------
xyz : array_like
Samples from the density distribution. Should have shape ``(n_samples,3)``.
mass : array_like
Mass of each sample. Should have shape ``(n_samples,)``.
nmax : int
Maximum value of ``n`` for the radial expansion.
lmax : int
Maximum value of ``l`` for the spherical harmonics.
r_s : numeric
Scale radius.
skip_odd : bool (optional)
Skip the odd terms in the angular portion of the expansion. For example, only
take :math:`l=0,2,4,...`
skip_even : bool (optional)
Skip the even terms in the angular portion of the expansion. For example, only
take :math:`l=1,3,5,...`
skip_m : bool (optional)
Ignore terms with :math:`m > 0`.
compute_var : bool (optional)
Also compute the variances of the coefficients. This does not compute the full covariance
matrix of the coefficients, just the individual variances.
TODO: separate function to compute full covariance matrix?
Returns
-------
Snlm : float
The value of the cosine expansion coefficient.
Tnlm : float
The value of the sine expansion coefficient. | [
"Compute",
"the",
"expansion",
"coefficients",
"for",
"representing",
"the",
"density",
"distribution",
"of",
"input",
"points",
"as",
"a",
"basis",
"function",
"expansion",
".",
"The",
"points",
"xyz",
"are",
"assumed",
"to",
"be",
"samples",
"from",
"the",
"... | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/scf/core.py#L132-L216 |
22,666 | adrn/gala | gala/dynamics/nbody/core.py | DirectNBody.integrate_orbit | def integrate_orbit(self, **time_spec):
"""
Integrate the initial conditions in the combined external potential
plus N-body forces.
This integration uses the `~gala.integrate.DOPRI853Integrator`.
Parameters
----------
**time_spec
Specification of how long to integrate. See documentation
for `~gala.integrate.parse_time_specification`.
Returns
-------
orbit : `~gala.dynamics.Orbit`
The orbits of the particles.
"""
# Prepare the initial conditions
pos = self.w0.xyz.decompose(self.units).value
vel = self.w0.v_xyz.decompose(self.units).value
w0 = np.ascontiguousarray(np.vstack((pos, vel)).T)
# Prepare the time-stepping array
t = parse_time_specification(self.units, **time_spec)
ws = _direct_nbody_dop853(w0, t, self._ext_ham,
self.particle_potentials)
pos = np.rollaxis(np.array(ws[..., :3]), axis=2)
vel = np.rollaxis(np.array(ws[..., 3:]), axis=2)
orbits = Orbit(
pos=pos * self.units['length'],
vel=vel * self.units['length'] / self.units['time'],
t=t * self.units['time'])
return orbits | python | def integrate_orbit(self, **time_spec):
# Prepare the initial conditions
pos = self.w0.xyz.decompose(self.units).value
vel = self.w0.v_xyz.decompose(self.units).value
w0 = np.ascontiguousarray(np.vstack((pos, vel)).T)
# Prepare the time-stepping array
t = parse_time_specification(self.units, **time_spec)
ws = _direct_nbody_dop853(w0, t, self._ext_ham,
self.particle_potentials)
pos = np.rollaxis(np.array(ws[..., :3]), axis=2)
vel = np.rollaxis(np.array(ws[..., 3:]), axis=2)
orbits = Orbit(
pos=pos * self.units['length'],
vel=vel * self.units['length'] / self.units['time'],
t=t * self.units['time'])
return orbits | [
"def",
"integrate_orbit",
"(",
"self",
",",
"*",
"*",
"time_spec",
")",
":",
"# Prepare the initial conditions",
"pos",
"=",
"self",
".",
"w0",
".",
"xyz",
".",
"decompose",
"(",
"self",
".",
"units",
")",
".",
"value",
"vel",
"=",
"self",
".",
"w0",
"... | Integrate the initial conditions in the combined external potential
plus N-body forces.
This integration uses the `~gala.integrate.DOPRI853Integrator`.
Parameters
----------
**time_spec
Specification of how long to integrate. See documentation
for `~gala.integrate.parse_time_specification`.
Returns
-------
orbit : `~gala.dynamics.Orbit`
The orbits of the particles. | [
"Integrate",
"the",
"initial",
"conditions",
"in",
"the",
"combined",
"external",
"potential",
"plus",
"N",
"-",
"body",
"forces",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/nbody/core.py#L115-L153 |
22,667 | adrn/gala | gala/dynamics/representation_nd.py | NDMixin._apply | def _apply(self, method, *args, **kwargs):
"""Create a new representation with ``method`` applied to the arrays.
In typical usage, the method is any of the shape-changing methods for
`~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those
picking particular elements (``__getitem__``, ``take``, etc.), which
are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be
applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for
`~astropy.coordinates.CartesianRepresentation`), with the results used
to create a new instance.
Internally, it is also used to apply functions to the components
(in particular, `~numpy.broadcast_to`).
Parameters
----------
method : str or callable
If str, it is the name of a method that is applied to the internal
``components``. If callable, the function is applied.
args : tuple
Any positional arguments for ``method``.
kwargs : dict
Any keyword arguments for ``method``.
"""
if callable(method):
apply_method = lambda array: method(array, *args, **kwargs)
else:
apply_method = operator.methodcaller(method, *args, **kwargs)
return self.__class__([apply_method(getattr(self, component))
for component in self.components], copy=False) | python | def _apply(self, method, *args, **kwargs):
if callable(method):
apply_method = lambda array: method(array, *args, **kwargs)
else:
apply_method = operator.methodcaller(method, *args, **kwargs)
return self.__class__([apply_method(getattr(self, component))
for component in self.components], copy=False) | [
"def",
"_apply",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"method",
")",
":",
"apply_method",
"=",
"lambda",
"array",
":",
"method",
"(",
"array",
",",
"*",
"args",
",",
"*",
"*",
"kw... | Create a new representation with ``method`` applied to the arrays.
In typical usage, the method is any of the shape-changing methods for
`~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those
picking particular elements (``__getitem__``, ``take``, etc.), which
are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be
applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for
`~astropy.coordinates.CartesianRepresentation`), with the results used
to create a new instance.
Internally, it is also used to apply functions to the components
(in particular, `~numpy.broadcast_to`).
Parameters
----------
method : str or callable
If str, it is the name of a method that is applied to the internal
``components``. If callable, the function is applied.
args : tuple
Any positional arguments for ``method``.
kwargs : dict
Any keyword arguments for ``method``. | [
"Create",
"a",
"new",
"representation",
"with",
"method",
"applied",
"to",
"the",
"arrays",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/representation_nd.py#L14-L43 |
22,668 | adrn/gala | gala/dynamics/representation_nd.py | NDCartesianRepresentation.get_xyz | def get_xyz(self, xyz_axis=0):
"""Return a vector array of the x, y, and z coordinates.
Parameters
----------
xyz_axis : int, optional
The axis in the final array along which the x, y, z components
should be stored (default: 0).
Returns
-------
xs : `~astropy.units.Quantity`
With dimension 3 along ``xyz_axis``.
"""
# Add new axis in x, y, z so one can concatenate them around it.
# NOTE: just use np.stack once our minimum numpy version is 1.10.
result_ndim = self.ndim + 1
if not -result_ndim <= xyz_axis < result_ndim:
raise IndexError('xyz_axis {0} out of bounds [-{1}, {1})'
.format(xyz_axis, result_ndim))
if xyz_axis < 0:
xyz_axis += result_ndim
# Get components to the same units (very fast for identical units)
# since np.concatenate cannot deal with quantity.
unit = self._x1.unit
sh = self.shape
sh = sh[:xyz_axis] + (1,) + sh[xyz_axis:]
components = [getattr(self, '_'+name).reshape(sh).to(unit).value
for name in self.attr_classes]
xs_value = np.concatenate(components, axis=xyz_axis)
return u.Quantity(xs_value, unit=unit, copy=False) | python | def get_xyz(self, xyz_axis=0):
# Add new axis in x, y, z so one can concatenate them around it.
# NOTE: just use np.stack once our minimum numpy version is 1.10.
result_ndim = self.ndim + 1
if not -result_ndim <= xyz_axis < result_ndim:
raise IndexError('xyz_axis {0} out of bounds [-{1}, {1})'
.format(xyz_axis, result_ndim))
if xyz_axis < 0:
xyz_axis += result_ndim
# Get components to the same units (very fast for identical units)
# since np.concatenate cannot deal with quantity.
unit = self._x1.unit
sh = self.shape
sh = sh[:xyz_axis] + (1,) + sh[xyz_axis:]
components = [getattr(self, '_'+name).reshape(sh).to(unit).value
for name in self.attr_classes]
xs_value = np.concatenate(components, axis=xyz_axis)
return u.Quantity(xs_value, unit=unit, copy=False) | [
"def",
"get_xyz",
"(",
"self",
",",
"xyz_axis",
"=",
"0",
")",
":",
"# Add new axis in x, y, z so one can concatenate them around it.",
"# NOTE: just use np.stack once our minimum numpy version is 1.10.",
"result_ndim",
"=",
"self",
".",
"ndim",
"+",
"1",
"if",
"not",
"-",
... | Return a vector array of the x, y, and z coordinates.
Parameters
----------
xyz_axis : int, optional
The axis in the final array along which the x, y, z components
should be stored (default: 0).
Returns
-------
xs : `~astropy.units.Quantity`
With dimension 3 along ``xyz_axis``. | [
"Return",
"a",
"vector",
"array",
"of",
"the",
"x",
"y",
"and",
"z",
"coordinates",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/representation_nd.py#L100-L132 |
22,669 | adrn/gala | gala/potential/common.py | CommonBase._get_c_valid_arr | def _get_c_valid_arr(self, x):
"""
Warning! Interpretation of axes is different for C code.
"""
orig_shape = x.shape
x = np.ascontiguousarray(x.reshape(orig_shape[0], -1).T)
return orig_shape, x | python | def _get_c_valid_arr(self, x):
orig_shape = x.shape
x = np.ascontiguousarray(x.reshape(orig_shape[0], -1).T)
return orig_shape, x | [
"def",
"_get_c_valid_arr",
"(",
"self",
",",
"x",
")",
":",
"orig_shape",
"=",
"x",
".",
"shape",
"x",
"=",
"np",
".",
"ascontiguousarray",
"(",
"x",
".",
"reshape",
"(",
"orig_shape",
"[",
"0",
"]",
",",
"-",
"1",
")",
".",
"T",
")",
"return",
"... | Warning! Interpretation of axes is different for C code. | [
"Warning!",
"Interpretation",
"of",
"axes",
"is",
"different",
"for",
"C",
"code",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/common.py#L60-L66 |
22,670 | adrn/gala | gala/potential/common.py | CommonBase._validate_prepare_time | def _validate_prepare_time(self, t, pos_c):
"""
Make sure that t is a 1D array and compatible with the C position array.
"""
if hasattr(t, 'unit'):
t = t.decompose(self.units).value
if not isiterable(t):
t = np.atleast_1d(t)
t = np.ascontiguousarray(t.ravel())
if len(t) > 1:
if len(t) != pos_c.shape[0]:
raise ValueError("If passing in an array of times, it must have a shape "
"compatible with the input position(s).")
return t | python | def _validate_prepare_time(self, t, pos_c):
if hasattr(t, 'unit'):
t = t.decompose(self.units).value
if not isiterable(t):
t = np.atleast_1d(t)
t = np.ascontiguousarray(t.ravel())
if len(t) > 1:
if len(t) != pos_c.shape[0]:
raise ValueError("If passing in an array of times, it must have a shape "
"compatible with the input position(s).")
return t | [
"def",
"_validate_prepare_time",
"(",
"self",
",",
"t",
",",
"pos_c",
")",
":",
"if",
"hasattr",
"(",
"t",
",",
"'unit'",
")",
":",
"t",
"=",
"t",
".",
"decompose",
"(",
"self",
".",
"units",
")",
".",
"value",
"if",
"not",
"isiterable",
"(",
"t",
... | Make sure that t is a 1D array and compatible with the C position array. | [
"Make",
"sure",
"that",
"t",
"is",
"a",
"1D",
"array",
"and",
"compatible",
"with",
"the",
"C",
"position",
"array",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/common.py#L68-L85 |
22,671 | adrn/gala | gala/dynamics/core.py | PhaseSpacePosition.get_components | def get_components(self, which):
"""
Get the component name dictionary for the desired object.
The returned dictionary maps component names on this class to component
names on the desired object.
Parameters
----------
which : str
Can either be ``'pos'`` or ``'vel'`` to get the components for the
position or velocity object.
"""
mappings = self.representation_mappings.get(
getattr(self, which).__class__, [])
old_to_new = dict()
for name in getattr(self, which).components:
for m in mappings:
if isinstance(m, RegexRepresentationMapping):
pattr = re.match(m.repr_name, name)
old_to_new[name] = m.new_name.format(*pattr.groups())
elif m.repr_name == name:
old_to_new[name] = m.new_name
mapping = OrderedDict()
for name in getattr(self, which).components:
mapping[old_to_new.get(name, name)] = name
return mapping | python | def get_components(self, which):
mappings = self.representation_mappings.get(
getattr(self, which).__class__, [])
old_to_new = dict()
for name in getattr(self, which).components:
for m in mappings:
if isinstance(m, RegexRepresentationMapping):
pattr = re.match(m.repr_name, name)
old_to_new[name] = m.new_name.format(*pattr.groups())
elif m.repr_name == name:
old_to_new[name] = m.new_name
mapping = OrderedDict()
for name in getattr(self, which).components:
mapping[old_to_new.get(name, name)] = name
return mapping | [
"def",
"get_components",
"(",
"self",
",",
"which",
")",
":",
"mappings",
"=",
"self",
".",
"representation_mappings",
".",
"get",
"(",
"getattr",
"(",
"self",
",",
"which",
")",
".",
"__class__",
",",
"[",
"]",
")",
"old_to_new",
"=",
"dict",
"(",
")"... | Get the component name dictionary for the desired object.
The returned dictionary maps component names on this class to component
names on the desired object.
Parameters
----------
which : str
Can either be ``'pos'`` or ``'vel'`` to get the components for the
position or velocity object. | [
"Get",
"the",
"component",
"name",
"dictionary",
"for",
"the",
"desired",
"object",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/core.py#L196-L226 |
22,672 | adrn/gala | gala/dynamics/core.py | PhaseSpacePosition.to_frame | def to_frame(self, frame, current_frame=None, **kwargs):
"""
Transform to a new reference frame.
Parameters
----------
frame : `~gala.potential.FrameBase`
The frame to transform to.
current_frame : `gala.potential.CFrameBase`
The current frame the phase-space position is in.
**kwargs
Any additional arguments are passed through to the individual frame
transformation functions (see:
`~gala.potential.frame.builtin.transformations`).
Returns
-------
psp : `gala.dynamics.CartesianPhaseSpacePosition`
The phase-space position in the new reference frame.
"""
from ..potential.frame.builtin import transformations as frame_trans
if ((inspect.isclass(frame) and issubclass(frame, coord.BaseCoordinateFrame)) or
isinstance(frame, coord.BaseCoordinateFrame)):
import warnings
warnings.warn("This function now expects a "
"`gala.potential.FrameBase` instance. To transform to"
" an Astropy coordinate frame, use the "
"`.to_coord_frame()` method instead.",
DeprecationWarning)
return self.to_coord_frame(frame=frame, **kwargs)
if self.frame is None and current_frame is None:
raise ValueError("If no frame was specified when this {} was "
"initialized, you must pass the current frame in "
"via the current_frame argument to transform to a "
"new frame.")
elif self.frame is not None and current_frame is None:
current_frame = self.frame
name1 = current_frame.__class__.__name__.rstrip('Frame').lower()
name2 = frame.__class__.__name__.rstrip('Frame').lower()
func_name = "{}_to_{}".format(name1, name2)
if not hasattr(frame_trans, func_name):
raise ValueError("Unsupported frame transformation: {} to {}"
.format(current_frame, frame))
else:
trans_func = getattr(frame_trans, func_name)
pos, vel = trans_func(current_frame, frame, self, **kwargs)
return PhaseSpacePosition(pos=pos, vel=vel, frame=frame) | python | def to_frame(self, frame, current_frame=None, **kwargs):
from ..potential.frame.builtin import transformations as frame_trans
if ((inspect.isclass(frame) and issubclass(frame, coord.BaseCoordinateFrame)) or
isinstance(frame, coord.BaseCoordinateFrame)):
import warnings
warnings.warn("This function now expects a "
"`gala.potential.FrameBase` instance. To transform to"
" an Astropy coordinate frame, use the "
"`.to_coord_frame()` method instead.",
DeprecationWarning)
return self.to_coord_frame(frame=frame, **kwargs)
if self.frame is None and current_frame is None:
raise ValueError("If no frame was specified when this {} was "
"initialized, you must pass the current frame in "
"via the current_frame argument to transform to a "
"new frame.")
elif self.frame is not None and current_frame is None:
current_frame = self.frame
name1 = current_frame.__class__.__name__.rstrip('Frame').lower()
name2 = frame.__class__.__name__.rstrip('Frame').lower()
func_name = "{}_to_{}".format(name1, name2)
if not hasattr(frame_trans, func_name):
raise ValueError("Unsupported frame transformation: {} to {}"
.format(current_frame, frame))
else:
trans_func = getattr(frame_trans, func_name)
pos, vel = trans_func(current_frame, frame, self, **kwargs)
return PhaseSpacePosition(pos=pos, vel=vel, frame=frame) | [
"def",
"to_frame",
"(",
"self",
",",
"frame",
",",
"current_frame",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"potential",
".",
"frame",
".",
"builtin",
"import",
"transformations",
"as",
"frame_trans",
"if",
"(",
"(",
"inspect",
... | Transform to a new reference frame.
Parameters
----------
frame : `~gala.potential.FrameBase`
The frame to transform to.
current_frame : `gala.potential.CFrameBase`
The current frame the phase-space position is in.
**kwargs
Any additional arguments are passed through to the individual frame
transformation functions (see:
`~gala.potential.frame.builtin.transformations`).
Returns
-------
psp : `gala.dynamics.CartesianPhaseSpacePosition`
The phase-space position in the new reference frame. | [
"Transform",
"to",
"a",
"new",
"reference",
"frame",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/core.py#L348-L402 |
22,673 | adrn/gala | gala/dynamics/core.py | PhaseSpacePosition.to_coord_frame | def to_coord_frame(self, frame, galactocentric_frame=None, **kwargs):
"""
Transform the orbit from Galactocentric, cartesian coordinates to
Heliocentric coordinates in the specified Astropy coordinate frame.
Parameters
----------
frame : :class:`~astropy.coordinates.BaseCoordinateFrame`
The class or frame instance specifying the desired output frame.
For example, :class:`~astropy.coordinates.ICRS`.
galactocentric_frame : :class:`~astropy.coordinates.Galactocentric`
This is the assumed frame that the position and velocity of this
object are in. The ``Galactocentric`` instand should have parameters
specifying the position and motion of the sun in the Galactocentric
frame, but no data.
Returns
-------
c : :class:`~astropy.coordinates.BaseCoordinateFrame`
An instantiated coordinate frame containing the positions and
velocities from this object transformed to the specified coordinate
frame.
"""
if self.ndim != 3:
raise ValueError("Can only change representation for "
"ndim=3 instances.")
if galactocentric_frame is None:
galactocentric_frame = coord.Galactocentric()
if 'vcirc' in kwargs or 'vlsr' in kwargs:
import warnings
warnings.warn("Instead of passing in 'vcirc' and 'vlsr', specify "
"these parameters to the input Galactocentric frame "
"using the `galcen_v_sun` argument.",
DeprecationWarning)
pos_keys = list(self.pos_components.keys())
vel_keys = list(self.vel_components.keys())
if (getattr(self, pos_keys[0]).unit == u.one or
getattr(self, vel_keys[0]).unit == u.one):
raise u.UnitConversionError("Position and velocity must have "
"dimensioned units to convert to a "
"coordinate frame.")
# first we need to turn the position into a Galactocentric instance
gc_c = galactocentric_frame.realize_frame(
self.pos.with_differentials(self.vel))
c = gc_c.transform_to(frame)
return c | python | def to_coord_frame(self, frame, galactocentric_frame=None, **kwargs):
if self.ndim != 3:
raise ValueError("Can only change representation for "
"ndim=3 instances.")
if galactocentric_frame is None:
galactocentric_frame = coord.Galactocentric()
if 'vcirc' in kwargs or 'vlsr' in kwargs:
import warnings
warnings.warn("Instead of passing in 'vcirc' and 'vlsr', specify "
"these parameters to the input Galactocentric frame "
"using the `galcen_v_sun` argument.",
DeprecationWarning)
pos_keys = list(self.pos_components.keys())
vel_keys = list(self.vel_components.keys())
if (getattr(self, pos_keys[0]).unit == u.one or
getattr(self, vel_keys[0]).unit == u.one):
raise u.UnitConversionError("Position and velocity must have "
"dimensioned units to convert to a "
"coordinate frame.")
# first we need to turn the position into a Galactocentric instance
gc_c = galactocentric_frame.realize_frame(
self.pos.with_differentials(self.vel))
c = gc_c.transform_to(frame)
return c | [
"def",
"to_coord_frame",
"(",
"self",
",",
"frame",
",",
"galactocentric_frame",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"Can only change representation for \"",
"\"ndim=3 instances... | Transform the orbit from Galactocentric, cartesian coordinates to
Heliocentric coordinates in the specified Astropy coordinate frame.
Parameters
----------
frame : :class:`~astropy.coordinates.BaseCoordinateFrame`
The class or frame instance specifying the desired output frame.
For example, :class:`~astropy.coordinates.ICRS`.
galactocentric_frame : :class:`~astropy.coordinates.Galactocentric`
This is the assumed frame that the position and velocity of this
object are in. The ``Galactocentric`` instand should have parameters
specifying the position and motion of the sun in the Galactocentric
frame, but no data.
Returns
-------
c : :class:`~astropy.coordinates.BaseCoordinateFrame`
An instantiated coordinate frame containing the positions and
velocities from this object transformed to the specified coordinate
frame. | [
"Transform",
"the",
"orbit",
"from",
"Galactocentric",
"cartesian",
"coordinates",
"to",
"Heliocentric",
"coordinates",
"in",
"the",
"specified",
"Astropy",
"coordinate",
"frame",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/core.py#L404-L455 |
22,674 | adrn/gala | gala/dynamics/core.py | PhaseSpacePosition._plot_prepare | def _plot_prepare(self, components, units):
"""
Prepare the ``PhaseSpacePosition`` or subclass for passing to a plotting
routine to plot all projections of the object.
"""
# components to plot
if components is None:
components = self.pos.components
n_comps = len(components)
# if units not specified, get units from the components
if units is not None:
if isinstance(units, u.UnitBase):
units = [units]*n_comps # global unit
elif len(units) != n_comps:
raise ValueError('You must specify a unit for each axis, or a '
'single unit for all axes.')
labels = []
x = []
for i,name in enumerate(components):
val = getattr(self, name)
if units is not None:
val = val.to(units[i])
unit = units[i]
else:
unit = val.unit
if val.unit != u.one:
uu = unit.to_string(format='latex_inline')
unit_str = ' [{}]'.format(uu)
else:
unit_str = ''
# Figure out how to fancy display the component name
if name.startswith('d_'):
dot = True
name = name[2:]
else:
dot = False
if name in _greek_letters:
name = r"\{}".format(name)
if dot:
name = "\dot{{{}}}".format(name)
labels.append('${}$'.format(name) + unit_str)
x.append(val.value)
return x, labels | python | def _plot_prepare(self, components, units):
# components to plot
if components is None:
components = self.pos.components
n_comps = len(components)
# if units not specified, get units from the components
if units is not None:
if isinstance(units, u.UnitBase):
units = [units]*n_comps # global unit
elif len(units) != n_comps:
raise ValueError('You must specify a unit for each axis, or a '
'single unit for all axes.')
labels = []
x = []
for i,name in enumerate(components):
val = getattr(self, name)
if units is not None:
val = val.to(units[i])
unit = units[i]
else:
unit = val.unit
if val.unit != u.one:
uu = unit.to_string(format='latex_inline')
unit_str = ' [{}]'.format(uu)
else:
unit_str = ''
# Figure out how to fancy display the component name
if name.startswith('d_'):
dot = True
name = name[2:]
else:
dot = False
if name in _greek_letters:
name = r"\{}".format(name)
if dot:
name = "\dot{{{}}}".format(name)
labels.append('${}$'.format(name) + unit_str)
x.append(val.value)
return x, labels | [
"def",
"_plot_prepare",
"(",
"self",
",",
"components",
",",
"units",
")",
":",
"# components to plot",
"if",
"components",
"is",
"None",
":",
"components",
"=",
"self",
".",
"pos",
".",
"components",
"n_comps",
"=",
"len",
"(",
"components",
")",
"# if unit... | Prepare the ``PhaseSpacePosition`` or subclass for passing to a plotting
routine to plot all projections of the object. | [
"Prepare",
"the",
"PhaseSpacePosition",
"or",
"subclass",
"for",
"passing",
"to",
"a",
"plotting",
"routine",
"to",
"plot",
"all",
"projections",
"of",
"the",
"object",
"."
] | ea95575a0df1581bb4b0986aebd6eea8438ab7eb | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/dynamics/core.py#L723-L776 |
22,675 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_account_info | def get_account_info(self):
''' Get current account information
The information then will be saved in `self.account` so that you can
access the information like this:
>>> hsclient = HSClient()
>>> acct = hsclient.get_account_info()
>>> print acct.email_address
Returns:
An Account object
'''
request = self._get_request()
response = request.get(self.ACCOUNT_INFO_URL)
self.account.json_data = response["account"]
return self.account | python | def get_account_info(self):
''' Get current account information
The information then will be saved in `self.account` so that you can
access the information like this:
>>> hsclient = HSClient()
>>> acct = hsclient.get_account_info()
>>> print acct.email_address
Returns:
An Account object
'''
request = self._get_request()
response = request.get(self.ACCOUNT_INFO_URL)
self.account.json_data = response["account"]
return self.account | [
"def",
"get_account_info",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"response",
"=",
"request",
".",
"get",
"(",
"self",
".",
"ACCOUNT_INFO_URL",
")",
"self",
".",
"account",
".",
"json_data",
"=",
"response",
"[",
"\... | Get current account information
The information then will be saved in `self.account` so that you can
access the information like this:
>>> hsclient = HSClient()
>>> acct = hsclient.get_account_info()
>>> print acct.email_address
Returns:
An Account object | [
"Get",
"current",
"account",
"information"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L210-L227 |
22,676 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.update_account_info | def update_account_info(self):
''' Update current account information
At the moment you can only update your callback_url.
Returns:
An Account object
'''
request = self._get_request()
return request.post(self.ACCOUNT_UPDATE_URL, {
'callback_url': self.account.callback_url
}) | python | def update_account_info(self):
''' Update current account information
At the moment you can only update your callback_url.
Returns:
An Account object
'''
request = self._get_request()
return request.post(self.ACCOUNT_UPDATE_URL, {
'callback_url': self.account.callback_url
}) | [
"def",
"update_account_info",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"return",
"request",
".",
"post",
"(",
"self",
".",
"ACCOUNT_UPDATE_URL",
",",
"{",
"'callback_url'",
":",
"self",
".",
"account",
".",
"callback_url"... | Update current account information
At the moment you can only update your callback_url.
Returns:
An Account object | [
"Update",
"current",
"account",
"information"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L231-L243 |
22,677 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.verify_account | def verify_account(self, email_address):
''' Verify whether a HelloSign Account exists
Args:
email_address (str): Email address for the account to verify
Returns:
True or False
'''
request = self._get_request()
resp = request.post(self.ACCOUNT_VERIFY_URL, {
'email_address': email_address
})
return ('account' in resp) | python | def verify_account(self, email_address):
''' Verify whether a HelloSign Account exists
Args:
email_address (str): Email address for the account to verify
Returns:
True or False
'''
request = self._get_request()
resp = request.post(self.ACCOUNT_VERIFY_URL, {
'email_address': email_address
})
return ('account' in resp) | [
"def",
"verify_account",
"(",
"self",
",",
"email_address",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"resp",
"=",
"request",
".",
"post",
"(",
"self",
".",
"ACCOUNT_VERIFY_URL",
",",
"{",
"'email_address'",
":",
"email_address",
"}",
... | Verify whether a HelloSign Account exists
Args:
email_address (str): Email address for the account to verify
Returns:
True or False | [
"Verify",
"whether",
"a",
"HelloSign",
"Account",
"exists"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L245-L259 |
22,678 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_signature_request | def get_signature_request(self, signature_request_id, ux_version=None):
''' Get a signature request by its ID
Args:
signature_request_id (str): The id of the SignatureRequest to retrieve
ux_version (int): UX version, either 1 (default) or 2.
Returns:
A SignatureRequest object
'''
request = self._get_request()
parameters = None
if ux_version is not None:
parameters = {
'ux_version': ux_version
}
return request.get(self.SIGNATURE_REQUEST_INFO_URL + signature_request_id, parameters=parameters) | python | def get_signature_request(self, signature_request_id, ux_version=None):
''' Get a signature request by its ID
Args:
signature_request_id (str): The id of the SignatureRequest to retrieve
ux_version (int): UX version, either 1 (default) or 2.
Returns:
A SignatureRequest object
'''
request = self._get_request()
parameters = None
if ux_version is not None:
parameters = {
'ux_version': ux_version
}
return request.get(self.SIGNATURE_REQUEST_INFO_URL + signature_request_id, parameters=parameters) | [
"def",
"get_signature_request",
"(",
"self",
",",
"signature_request_id",
",",
"ux_version",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"parameters",
"=",
"None",
"if",
"ux_version",
"is",
"not",
"None",
":",
"parameters",
... | Get a signature request by its ID
Args:
signature_request_id (str): The id of the SignatureRequest to retrieve
ux_version (int): UX version, either 1 (default) or 2.
Returns:
A SignatureRequest object | [
"Get",
"a",
"signature",
"request",
"by",
"its",
"ID"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L264-L286 |
22,679 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_signature_request_list | def get_signature_request_list(self, page=1, ux_version=None):
''' Get a list of SignatureRequest that you can access
This includes SignatureRequests you have sent as well as received, but
not ones that you have been CCed on.
Args:
page (int, optional): Which page number of the SignatureRequest list to return. Defaults to 1.
ux_version (int): UX version, either 1 (default) or 2.
Returns:
A ResourceList object
'''
request = self._get_request()
parameters = {
"page": page
}
if ux_version is not None:
parameters['ux_version'] = ux_version
return request.get(self.SIGNATURE_REQUEST_LIST_URL, parameters=parameters) | python | def get_signature_request_list(self, page=1, ux_version=None):
''' Get a list of SignatureRequest that you can access
This includes SignatureRequests you have sent as well as received, but
not ones that you have been CCed on.
Args:
page (int, optional): Which page number of the SignatureRequest list to return. Defaults to 1.
ux_version (int): UX version, either 1 (default) or 2.
Returns:
A ResourceList object
'''
request = self._get_request()
parameters = {
"page": page
}
if ux_version is not None:
parameters['ux_version'] = ux_version
return request.get(self.SIGNATURE_REQUEST_LIST_URL, parameters=parameters) | [
"def",
"get_signature_request_list",
"(",
"self",
",",
"page",
"=",
"1",
",",
"ux_version",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"parameters",
"=",
"{",
"\"page\"",
":",
"page",
"}",
"if",
"ux_version",
"is",
"not... | Get a list of SignatureRequest that you can access
This includes SignatureRequests you have sent as well as received, but
not ones that you have been CCed on.
Args:
page (int, optional): Which page number of the SignatureRequest list to return. Defaults to 1.
ux_version (int): UX version, either 1 (default) or 2.
Returns:
A ResourceList object | [
"Get",
"a",
"list",
"of",
"SignatureRequest",
"that",
"you",
"can",
"access"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L289-L314 |
22,680 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_signature_request_file | def get_signature_request_file(self, signature_request_id, path_or_file=None, file_type=None, filename=None):
''' Download the PDF copy of the current documents
Args:
signature_request_id (str): Id of the signature request
path_or_file (str or file): A writable File-like object or a full path to save the PDF file to.
filename (str): [DEPRECATED] Filename to save the PDF file to. This should be a full path.
file_type (str): Type of file to return. Either "pdf" for a single merged document or "zip" for a collection of individual documents. Defaults to "pdf" if not specified.
Returns:
True if file is downloaded and successfully written, False otherwise.
'''
request = self._get_request()
url = self.SIGNATURE_REQUEST_DOWNLOAD_PDF_URL + signature_request_id
if file_type:
url += '?file_type=%s' % file_type
return request.get_file(url, path_or_file or filename) | python | def get_signature_request_file(self, signature_request_id, path_or_file=None, file_type=None, filename=None):
''' Download the PDF copy of the current documents
Args:
signature_request_id (str): Id of the signature request
path_or_file (str or file): A writable File-like object or a full path to save the PDF file to.
filename (str): [DEPRECATED] Filename to save the PDF file to. This should be a full path.
file_type (str): Type of file to return. Either "pdf" for a single merged document or "zip" for a collection of individual documents. Defaults to "pdf" if not specified.
Returns:
True if file is downloaded and successfully written, False otherwise.
'''
request = self._get_request()
url = self.SIGNATURE_REQUEST_DOWNLOAD_PDF_URL + signature_request_id
if file_type:
url += '?file_type=%s' % file_type
return request.get_file(url, path_or_file or filename) | [
"def",
"get_signature_request_file",
"(",
"self",
",",
"signature_request_id",
",",
"path_or_file",
"=",
"None",
",",
"file_type",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"url",
"=",
"self",... | Download the PDF copy of the current documents
Args:
signature_request_id (str): Id of the signature request
path_or_file (str or file): A writable File-like object or a full path to save the PDF file to.
filename (str): [DEPRECATED] Filename to save the PDF file to. This should be a full path.
file_type (str): Type of file to return. Either "pdf" for a single merged document or "zip" for a collection of individual documents. Defaults to "pdf" if not specified.
Returns:
True if file is downloaded and successfully written, False otherwise. | [
"Download",
"the",
"PDF",
"copy",
"of",
"the",
"current",
"documents"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L316-L337 |
22,681 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.send_signature_request | def send_signature_request(self, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline=False):
''' Creates and sends a new SignatureRequest with the submitted documents
Creates and sends a new SignatureRequest with the submitted documents.
If form_fields_per_document is not specified, a signature page will be
affixed where all signers will be required to add their signature,
signifying their agreement to all contained documents.
Args:
test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False.
files (list of str): The uploaded file(s) to send for signature
file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls`
title (str, optional): The title you want to assign to the SignatureRequest
subject (str, optional): The subject in the email that will be sent to the signers
message (str, optional): The custom message in the email that will be sent to the signers
signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign.
signers (list of dict): A list of signers, which each has the following attributes:
name (str): The name of the signer
email_address (str): Email address of the signer
order (str, optional): The order the signer is required to sign in
pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page
cc_email_addresses (list, optional): A list of email addresses that should be CC'd
form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest)
use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields
hide_text_tags (bool, optional): Hide text tag areas
metadata (dict, optional): Metadata to associate with the signature request
ux_version (int): UX version, either 1 (default) or 2.
allow_decline(bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0.
Returns:
A SignatureRequest object
'''
self._check_required_fields({
"signers": signers
}, [{
"files": files,
"file_urls": file_urls
}]
)
params = {
'test_mode': test_mode,
'files': files,
'file_urls': file_urls,
'title': title,
'subject': subject,
'message': message,
'signing_redirect_url': signing_redirect_url,
'signers': signers,
'cc_email_addresses': cc_email_addresses,
'form_fields_per_document': form_fields_per_document,
'use_text_tags': use_text_tags,
'hide_text_tags': hide_text_tags,
'metadata': metadata,
'allow_decline': allow_decline
}
if ux_version is not None:
params['ux_version'] = ux_version
return self._send_signature_request(**params) | python | def send_signature_request(self, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline=False):
''' Creates and sends a new SignatureRequest with the submitted documents
Creates and sends a new SignatureRequest with the submitted documents.
If form_fields_per_document is not specified, a signature page will be
affixed where all signers will be required to add their signature,
signifying their agreement to all contained documents.
Args:
test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False.
files (list of str): The uploaded file(s) to send for signature
file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls`
title (str, optional): The title you want to assign to the SignatureRequest
subject (str, optional): The subject in the email that will be sent to the signers
message (str, optional): The custom message in the email that will be sent to the signers
signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign.
signers (list of dict): A list of signers, which each has the following attributes:
name (str): The name of the signer
email_address (str): Email address of the signer
order (str, optional): The order the signer is required to sign in
pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page
cc_email_addresses (list, optional): A list of email addresses that should be CC'd
form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest)
use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields
hide_text_tags (bool, optional): Hide text tag areas
metadata (dict, optional): Metadata to associate with the signature request
ux_version (int): UX version, either 1 (default) or 2.
allow_decline(bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0.
Returns:
A SignatureRequest object
'''
self._check_required_fields({
"signers": signers
}, [{
"files": files,
"file_urls": file_urls
}]
)
params = {
'test_mode': test_mode,
'files': files,
'file_urls': file_urls,
'title': title,
'subject': subject,
'message': message,
'signing_redirect_url': signing_redirect_url,
'signers': signers,
'cc_email_addresses': cc_email_addresses,
'form_fields_per_document': form_fields_per_document,
'use_text_tags': use_text_tags,
'hide_text_tags': hide_text_tags,
'metadata': metadata,
'allow_decline': allow_decline
}
if ux_version is not None:
params['ux_version'] = ux_version
return self._send_signature_request(**params) | [
"def",
"send_signature_request",
"(",
"self",
",",
"test_mode",
"=",
"False",
",",
"files",
"=",
"None",
",",
"file_urls",
"=",
"None",
",",
"title",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"message",
"=",
"None",
",",
"signing_redirect_url",
"=",
... | Creates and sends a new SignatureRequest with the submitted documents
Creates and sends a new SignatureRequest with the submitted documents.
If form_fields_per_document is not specified, a signature page will be
affixed where all signers will be required to add their signature,
signifying their agreement to all contained documents.
Args:
test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False.
files (list of str): The uploaded file(s) to send for signature
file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls`
title (str, optional): The title you want to assign to the SignatureRequest
subject (str, optional): The subject in the email that will be sent to the signers
message (str, optional): The custom message in the email that will be sent to the signers
signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign.
signers (list of dict): A list of signers, which each has the following attributes:
name (str): The name of the signer
email_address (str): Email address of the signer
order (str, optional): The order the signer is required to sign in
pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page
cc_email_addresses (list, optional): A list of email addresses that should be CC'd
form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest)
use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields
hide_text_tags (bool, optional): Hide text tag areas
metadata (dict, optional): Metadata to associate with the signature request
ux_version (int): UX version, either 1 (default) or 2.
allow_decline(bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0.
Returns:
A SignatureRequest object | [
"Creates",
"and",
"sends",
"a",
"new",
"SignatureRequest",
"with",
"the",
"submitted",
"documents"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L339-L417 |
22,682 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.send_signature_request_with_template | def send_signature_request_with_template(self, test_mode=False, template_id=None, template_ids=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, ccs=None, custom_fields=None, metadata=None, ux_version=None, allow_decline=False):
''' Creates and sends a new SignatureRequest based off of a Template
Creates and sends a new SignatureRequest based off of the Template
specified with the template_id parameter.
Args:
test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False.
template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids.
template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id.
title (str, optional): The title you want to assign to the SignatureRequest
subject (str, optional): The subject in the email that will be sent to the signers
message (str, optional): The custom message in the email that will be sent to the signers
signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign.
signers (list of dict): A list of signers, which each has the following attributes:
role_name (str): Signer role
name (str): The name of the signer
email_address (str): Email address of the signer
pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page
ccs (list of str, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes:
role_name (str): CC role name
email_address (str): CC email address
custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}`
metadata (dict, optional): Metadata to associate with the signature request
ux_version (int): UX version, either 1 (default) or 2.
allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0.
Returns:
A SignatureRequest object
'''
self._check_required_fields({
"signers": signers
}, [{
"template_id": template_id,
"template_ids": template_ids
}]
)
params = {
'test_mode': test_mode,
'template_id': template_id,
'template_ids': template_ids,
'title': title,
'subject': subject,
'message': message,
'signing_redirect_url': signing_redirect_url,
'signers': signers,
'ccs': ccs,
'custom_fields': custom_fields,
'metadata': metadata,
'allow_decline': allow_decline
}
if ux_version is not None:
params['ux_version'] = ux_version
return self._send_signature_request_with_template(**params) | python | def send_signature_request_with_template(self, test_mode=False, template_id=None, template_ids=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, ccs=None, custom_fields=None, metadata=None, ux_version=None, allow_decline=False):
''' Creates and sends a new SignatureRequest based off of a Template
Creates and sends a new SignatureRequest based off of the Template
specified with the template_id parameter.
Args:
test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False.
template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids.
template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id.
title (str, optional): The title you want to assign to the SignatureRequest
subject (str, optional): The subject in the email that will be sent to the signers
message (str, optional): The custom message in the email that will be sent to the signers
signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign.
signers (list of dict): A list of signers, which each has the following attributes:
role_name (str): Signer role
name (str): The name of the signer
email_address (str): Email address of the signer
pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page
ccs (list of str, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes:
role_name (str): CC role name
email_address (str): CC email address
custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}`
metadata (dict, optional): Metadata to associate with the signature request
ux_version (int): UX version, either 1 (default) or 2.
allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0.
Returns:
A SignatureRequest object
'''
self._check_required_fields({
"signers": signers
}, [{
"template_id": template_id,
"template_ids": template_ids
}]
)
params = {
'test_mode': test_mode,
'template_id': template_id,
'template_ids': template_ids,
'title': title,
'subject': subject,
'message': message,
'signing_redirect_url': signing_redirect_url,
'signers': signers,
'ccs': ccs,
'custom_fields': custom_fields,
'metadata': metadata,
'allow_decline': allow_decline
}
if ux_version is not None:
params['ux_version'] = ux_version
return self._send_signature_request_with_template(**params) | [
"def",
"send_signature_request_with_template",
"(",
"self",
",",
"test_mode",
"=",
"False",
",",
"template_id",
"=",
"None",
",",
"template_ids",
"=",
"None",
",",
"title",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"message",
"=",
"None",
",",
"signing_... | Creates and sends a new SignatureRequest based off of a Template
Creates and sends a new SignatureRequest based off of the Template
specified with the template_id parameter.
Args:
test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False.
template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids.
template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id.
title (str, optional): The title you want to assign to the SignatureRequest
subject (str, optional): The subject in the email that will be sent to the signers
message (str, optional): The custom message in the email that will be sent to the signers
signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign.
signers (list of dict): A list of signers, which each has the following attributes:
role_name (str): Signer role
name (str): The name of the signer
email_address (str): Email address of the signer
pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page
ccs (list of str, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes:
role_name (str): CC role name
email_address (str): CC email address
custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}`
metadata (dict, optional): Metadata to associate with the signature request
ux_version (int): UX version, either 1 (default) or 2.
allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0.
Returns:
A SignatureRequest object | [
"Creates",
"and",
"sends",
"a",
"new",
"SignatureRequest",
"based",
"off",
"of",
"a",
"Template"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L419-L492 |
22,683 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.remind_signature_request | def remind_signature_request(self, signature_request_id, email_address):
''' Sends an email to the signer reminding them to sign the signature request
Sends an email to the signer reminding them to sign the signature
request. You cannot send a reminder within 1 hours of the last reminder
that was sent. This includes manual AND automatic reminders.
Args:
signature_request_id (str): The id of the SignatureRequest to send a reminder for
email_address (str): The email address of the signer to send a reminder to
Returns:
A SignatureRequest object
'''
request = self._get_request()
return request.post(self.SIGNATURE_REQUEST_REMIND_URL + signature_request_id, data={
"email_address": email_address
}) | python | def remind_signature_request(self, signature_request_id, email_address):
''' Sends an email to the signer reminding them to sign the signature request
Sends an email to the signer reminding them to sign the signature
request. You cannot send a reminder within 1 hours of the last reminder
that was sent. This includes manual AND automatic reminders.
Args:
signature_request_id (str): The id of the SignatureRequest to send a reminder for
email_address (str): The email address of the signer to send a reminder to
Returns:
A SignatureRequest object
'''
request = self._get_request()
return request.post(self.SIGNATURE_REQUEST_REMIND_URL + signature_request_id, data={
"email_address": email_address
}) | [
"def",
"remind_signature_request",
"(",
"self",
",",
"signature_request_id",
",",
"email_address",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"return",
"request",
".",
"post",
"(",
"self",
".",
"SIGNATURE_REQUEST_REMIND_URL",
"+",
"signature_... | Sends an email to the signer reminding them to sign the signature request
Sends an email to the signer reminding them to sign the signature
request. You cannot send a reminder within 1 hours of the last reminder
that was sent. This includes manual AND automatic reminders.
Args:
signature_request_id (str): The id of the SignatureRequest to send a reminder for
email_address (str): The email address of the signer to send a reminder to
Returns:
A SignatureRequest object | [
"Sends",
"an",
"email",
"to",
"the",
"signer",
"reminding",
"them",
"to",
"sign",
"the",
"signature",
"request"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L495-L515 |
22,684 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.cancel_signature_request | def cancel_signature_request(self, signature_request_id):
''' Cancels a SignatureRequest
Cancels a SignatureRequest. After canceling, no one will be able to sign
or access the SignatureRequest or its documents. Only the requester can
cancel and only before everyone has signed.
Args:
signing_request_id (str): The id of the signature request to cancel
Returns:
None
'''
request = self._get_request()
request.post(url=self.SIGNATURE_REQUEST_CANCEL_URL + signature_request_id, get_json=False) | python | def cancel_signature_request(self, signature_request_id):
''' Cancels a SignatureRequest
Cancels a SignatureRequest. After canceling, no one will be able to sign
or access the SignatureRequest or its documents. Only the requester can
cancel and only before everyone has signed.
Args:
signing_request_id (str): The id of the signature request to cancel
Returns:
None
'''
request = self._get_request()
request.post(url=self.SIGNATURE_REQUEST_CANCEL_URL + signature_request_id, get_json=False) | [
"def",
"cancel_signature_request",
"(",
"self",
",",
"signature_request_id",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"request",
".",
"post",
"(",
"url",
"=",
"self",
".",
"SIGNATURE_REQUEST_CANCEL_URL",
"+",
"signature_request_id",
",",
... | Cancels a SignatureRequest
Cancels a SignatureRequest. After canceling, no one will be able to sign
or access the SignatureRequest or its documents. Only the requester can
cancel and only before everyone has signed.
Args:
signing_request_id (str): The id of the signature request to cancel
Returns:
None | [
"Cancels",
"a",
"SignatureRequest"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L517-L533 |
22,685 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_template | def get_template(self, template_id):
''' Gets a Template which includes a list of Accounts that can access it
Args:
template_id (str): The id of the template to retrieve
Returns:
A Template object
'''
request = self._get_request()
return request.get(self.TEMPLATE_GET_URL + template_id) | python | def get_template(self, template_id):
''' Gets a Template which includes a list of Accounts that can access it
Args:
template_id (str): The id of the template to retrieve
Returns:
A Template object
'''
request = self._get_request()
return request.get(self.TEMPLATE_GET_URL + template_id) | [
"def",
"get_template",
"(",
"self",
",",
"template_id",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"return",
"request",
".",
"get",
"(",
"self",
".",
"TEMPLATE_GET_URL",
"+",
"template_id",
")"
] | Gets a Template which includes a list of Accounts that can access it
Args:
template_id (str): The id of the template to retrieve
Returns:
A Template object | [
"Gets",
"a",
"Template",
"which",
"includes",
"a",
"list",
"of",
"Accounts",
"that",
"can",
"access",
"it"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L705-L717 |
22,686 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_template_list | def get_template_list(self, page=1, page_size=None, account_id=None, query=None):
''' Lists your Templates
Args:
page (int, optional): Page number of the template List to return. Defaults to 1.
page_size (int, optional): Number of objects to be returned per page, must be between 1 and 100, default is 20.
account_id (str, optional): Which account to return Templates for. Must be a team member. Use "all" to indicate all team members. Defaults to your account.
query (str, optional): String that includes search terms and/or fields to be used to filter the Template objects.
Returns:
A ResourceList object
'''
request = self._get_request()
parameters = {
'page': page,
'page_size': page_size,
'account_id': account_id,
'query': query
}
return request.get(self.TEMPLATE_GET_LIST_URL, parameters=parameters) | python | def get_template_list(self, page=1, page_size=None, account_id=None, query=None):
''' Lists your Templates
Args:
page (int, optional): Page number of the template List to return. Defaults to 1.
page_size (int, optional): Number of objects to be returned per page, must be between 1 and 100, default is 20.
account_id (str, optional): Which account to return Templates for. Must be a team member. Use "all" to indicate all team members. Defaults to your account.
query (str, optional): String that includes search terms and/or fields to be used to filter the Template objects.
Returns:
A ResourceList object
'''
request = self._get_request()
parameters = {
'page': page,
'page_size': page_size,
'account_id': account_id,
'query': query
}
return request.get(self.TEMPLATE_GET_LIST_URL, parameters=parameters) | [
"def",
"get_template_list",
"(",
"self",
",",
"page",
"=",
"1",
",",
"page_size",
"=",
"None",
",",
"account_id",
"=",
"None",
",",
"query",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"parameters",
"=",
"{",
"'page'",... | Lists your Templates
Args:
page (int, optional): Page number of the template List to return. Defaults to 1.
page_size (int, optional): Number of objects to be returned per page, must be between 1 and 100, default is 20.
account_id (str, optional): Which account to return Templates for. Must be a team member. Use "all" to indicate all team members. Defaults to your account.
query (str, optional): String that includes search terms and/or fields to be used to filter the Template objects.
Returns:
A ResourceList object | [
"Lists",
"your",
"Templates"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L720-L741 |
22,687 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.add_user_to_template | def add_user_to_template(self, template_id, account_id=None, email_address=None):
''' Gives the specified Account access to the specified Template
Args:
template_id (str): The id of the template to give the account access to
account_id (str): The id of the account to give access to the template. The account id prevails if both account_id and email_address are provided.
email_address (str): The email address of the account to give access to.
Returns:
A Template object
'''
return self._add_remove_user_template(self.TEMPLATE_ADD_USER_URL, template_id, account_id, email_address) | python | def add_user_to_template(self, template_id, account_id=None, email_address=None):
''' Gives the specified Account access to the specified Template
Args:
template_id (str): The id of the template to give the account access to
account_id (str): The id of the account to give access to the template. The account id prevails if both account_id and email_address are provided.
email_address (str): The email address of the account to give access to.
Returns:
A Template object
'''
return self._add_remove_user_template(self.TEMPLATE_ADD_USER_URL, template_id, account_id, email_address) | [
"def",
"add_user_to_template",
"(",
"self",
",",
"template_id",
",",
"account_id",
"=",
"None",
",",
"email_address",
"=",
"None",
")",
":",
"return",
"self",
".",
"_add_remove_user_template",
"(",
"self",
".",
"TEMPLATE_ADD_USER_URL",
",",
"template_id",
",",
"... | Gives the specified Account access to the specified Template
Args:
template_id (str): The id of the template to give the account access to
account_id (str): The id of the account to give access to the template. The account id prevails if both account_id and email_address are provided.
email_address (str): The email address of the account to give access to.
Returns:
A Template object | [
"Gives",
"the",
"specified",
"Account",
"access",
"to",
"the",
"specified",
"Template"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L744-L759 |
22,688 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.remove_user_from_template | def remove_user_from_template(self, template_id, account_id=None, email_address=None):
''' Removes the specified Account's access to the specified Template
Args:
template_id (str): The id of the template to remove the account's access from.
account_id (str): The id of the account to remove access from the template. The account id prevails if both account_id and email_address are provided.
email_address (str): The email address of the account to remove access from.
Returns:
An Template object
'''
return self._add_remove_user_template(self.TEMPLATE_REMOVE_USER_URL, template_id, account_id, email_address) | python | def remove_user_from_template(self, template_id, account_id=None, email_address=None):
''' Removes the specified Account's access to the specified Template
Args:
template_id (str): The id of the template to remove the account's access from.
account_id (str): The id of the account to remove access from the template. The account id prevails if both account_id and email_address are provided.
email_address (str): The email address of the account to remove access from.
Returns:
An Template object
'''
return self._add_remove_user_template(self.TEMPLATE_REMOVE_USER_URL, template_id, account_id, email_address) | [
"def",
"remove_user_from_template",
"(",
"self",
",",
"template_id",
",",
"account_id",
"=",
"None",
",",
"email_address",
"=",
"None",
")",
":",
"return",
"self",
".",
"_add_remove_user_template",
"(",
"self",
".",
"TEMPLATE_REMOVE_USER_URL",
",",
"template_id",
... | Removes the specified Account's access to the specified Template
Args:
template_id (str): The id of the template to remove the account's access from.
account_id (str): The id of the account to remove access from the template. The account id prevails if both account_id and email_address are provided.
email_address (str): The email address of the account to remove access from.
Returns:
An Template object | [
"Removes",
"the",
"specified",
"Account",
"s",
"access",
"to",
"the",
"specified",
"Template"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L761-L776 |
22,689 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.delete_template | def delete_template(self, template_id):
''' Deletes the specified template
Args:
template_id (str): The id of the template to delete
Returns:
A status code
'''
url = self.TEMPLATE_DELETE_URL
request = self._get_request()
response = request.post(url + template_id, get_json=False)
return response | python | def delete_template(self, template_id):
''' Deletes the specified template
Args:
template_id (str): The id of the template to delete
Returns:
A status code
'''
url = self.TEMPLATE_DELETE_URL
request = self._get_request()
response = request.post(url + template_id, get_json=False)
return response | [
"def",
"delete_template",
"(",
"self",
",",
"template_id",
")",
":",
"url",
"=",
"self",
".",
"TEMPLATE_DELETE_URL",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"response",
"=",
"request",
".",
"post",
"(",
"url",
"+",
"template_id",
",",
"get_j... | Deletes the specified template
Args:
template_id (str): The id of the template to delete
Returns:
A status code | [
"Deletes",
"the",
"specified",
"template"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L778-L795 |
22,690 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_template_files | def get_template_files(self, template_id, filename):
''' Download a PDF copy of a template's original files
Args:
template_id (str): The id of the template to retrieve.
filename (str): Filename to save the PDF file to. This should be a full path.
Returns:
Returns a PDF file
'''
url = self.TEMPLATE_GET_FILES_URL + template_id
request = self._get_request()
return request.get_file(url, filename) | python | def get_template_files(self, template_id, filename):
''' Download a PDF copy of a template's original files
Args:
template_id (str): The id of the template to retrieve.
filename (str): Filename to save the PDF file to. This should be a full path.
Returns:
Returns a PDF file
'''
url = self.TEMPLATE_GET_FILES_URL + template_id
request = self._get_request()
return request.get_file(url, filename) | [
"def",
"get_template_files",
"(",
"self",
",",
"template_id",
",",
"filename",
")",
":",
"url",
"=",
"self",
".",
"TEMPLATE_GET_FILES_URL",
"+",
"template_id",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"return",
"request",
".",
"get_file",
"(",
... | Download a PDF copy of a template's original files
Args:
template_id (str): The id of the template to retrieve.
filename (str): Filename to save the PDF file to. This should be a full path.
Returns:
Returns a PDF file | [
"Download",
"a",
"PDF",
"copy",
"of",
"a",
"template",
"s",
"original",
"files"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L798-L815 |
22,691 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.create_embedded_template_draft | def create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False):
''' Creates an embedded Template draft for further editing.
Args:
test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to 1. Defaults to 0.
client_id (str): Client id of the app you're using to create this draft.
files (list of str): The file(s) to use for the template.
file_urls (list of str): URLs of the file for HelloSign to use for the template. Use either `files` or `file_urls`, but not both.
title (str, optional): The template title
subject (str, optional): The default template email subject
message (str, optional): The default template email message
signer_roles (list of dict): A list of signer roles, each of which has the following attributes:
name (str): The role name of the signer that will be displayed when the template is used to create a signature request.
order (str, optional): The order in which this signer role is required to sign.
cc_roles (list of str, optional): The CC roles that must be assigned when using the template to send a signature request
merge_fields (list of dict, optional): The merge fields that can be placed on the template's document(s) by the user claiming the template draft. Each must have the following two parameters:
name (str): The name of the merge field. Must be unique.
type (str): Can only be "text" or "checkbox".
use_preexisting_fields (bool): Whether to use preexisting PDF fields
Returns:
A Template object specifying the Id of the draft
'''
params = {
'test_mode': test_mode,
'client_id': client_id,
'files': files,
'file_urls': file_urls,
'title': title,
'subject': subject,
'message': message,
'signer_roles': signer_roles,
'cc_roles': cc_roles,
'merge_fields': merge_fields,
'use_preexisting_fields': use_preexisting_fields
}
return self._create_embedded_template_draft(**params) | python | def create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False):
''' Creates an embedded Template draft for further editing.
Args:
test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to 1. Defaults to 0.
client_id (str): Client id of the app you're using to create this draft.
files (list of str): The file(s) to use for the template.
file_urls (list of str): URLs of the file for HelloSign to use for the template. Use either `files` or `file_urls`, but not both.
title (str, optional): The template title
subject (str, optional): The default template email subject
message (str, optional): The default template email message
signer_roles (list of dict): A list of signer roles, each of which has the following attributes:
name (str): The role name of the signer that will be displayed when the template is used to create a signature request.
order (str, optional): The order in which this signer role is required to sign.
cc_roles (list of str, optional): The CC roles that must be assigned when using the template to send a signature request
merge_fields (list of dict, optional): The merge fields that can be placed on the template's document(s) by the user claiming the template draft. Each must have the following two parameters:
name (str): The name of the merge field. Must be unique.
type (str): Can only be "text" or "checkbox".
use_preexisting_fields (bool): Whether to use preexisting PDF fields
Returns:
A Template object specifying the Id of the draft
'''
params = {
'test_mode': test_mode,
'client_id': client_id,
'files': files,
'file_urls': file_urls,
'title': title,
'subject': subject,
'message': message,
'signer_roles': signer_roles,
'cc_roles': cc_roles,
'merge_fields': merge_fields,
'use_preexisting_fields': use_preexisting_fields
}
return self._create_embedded_template_draft(**params) | [
"def",
"create_embedded_template_draft",
"(",
"self",
",",
"client_id",
",",
"signer_roles",
",",
"test_mode",
"=",
"False",
",",
"files",
"=",
"None",
",",
"file_urls",
"=",
"None",
",",
"title",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"message",
"... | Creates an embedded Template draft for further editing.
Args:
test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to 1. Defaults to 0.
client_id (str): Client id of the app you're using to create this draft.
files (list of str): The file(s) to use for the template.
file_urls (list of str): URLs of the file for HelloSign to use for the template. Use either `files` or `file_urls`, but not both.
title (str, optional): The template title
subject (str, optional): The default template email subject
message (str, optional): The default template email message
signer_roles (list of dict): A list of signer roles, each of which has the following attributes:
name (str): The role name of the signer that will be displayed when the template is used to create a signature request.
order (str, optional): The order in which this signer role is required to sign.
cc_roles (list of str, optional): The CC roles that must be assigned when using the template to send a signature request
merge_fields (list of dict, optional): The merge fields that can be placed on the template's document(s) by the user claiming the template draft. Each must have the following two parameters:
name (str): The name of the merge field. Must be unique.
type (str): Can only be "text" or "checkbox".
use_preexisting_fields (bool): Whether to use preexisting PDF fields
Returns:
A Template object specifying the Id of the draft | [
"Creates",
"an",
"embedded",
"Template",
"draft",
"for",
"further",
"editing",
"."
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L817-L868 |
22,692 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.create_team | def create_team(self, name):
''' Creates a new Team
Creates a new Team and makes you a member. You must not currently belong to a team to invoke.
Args:
name (str): The name of your team
Returns:
A Team object
'''
request = self._get_request()
return request.post(self.TEAM_CREATE_URL, {"name": name}) | python | def create_team(self, name):
''' Creates a new Team
Creates a new Team and makes you a member. You must not currently belong to a team to invoke.
Args:
name (str): The name of your team
Returns:
A Team object
'''
request = self._get_request()
return request.post(self.TEAM_CREATE_URL, {"name": name}) | [
"def",
"create_team",
"(",
"self",
",",
"name",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"return",
"request",
".",
"post",
"(",
"self",
".",
"TEAM_CREATE_URL",
",",
"{",
"\"name\"",
":",
"name",
"}",
")"
] | Creates a new Team
Creates a new Team and makes you a member. You must not currently belong to a team to invoke.
Args:
name (str): The name of your team
Returns:
A Team object | [
"Creates",
"a",
"new",
"Team"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L888-L902 |
22,693 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.update_team_name | def update_team_name(self, name):
''' Updates a Team's name
Args:
name (str): The new name of your team
Returns:
A Team object
'''
request = self._get_request()
return request.post(self.TEAM_UPDATE_URL, {"name": name}) | python | def update_team_name(self, name):
''' Updates a Team's name
Args:
name (str): The new name of your team
Returns:
A Team object
'''
request = self._get_request()
return request.post(self.TEAM_UPDATE_URL, {"name": name}) | [
"def",
"update_team_name",
"(",
"self",
",",
"name",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"return",
"request",
".",
"post",
"(",
"self",
".",
"TEAM_UPDATE_URL",
",",
"{",
"\"name\"",
":",
"name",
"}",
")"
] | Updates a Team's name
Args:
name (str): The new name of your team
Returns:
A Team object | [
"Updates",
"a",
"Team",
"s",
"name"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L906-L918 |
22,694 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.destroy_team | def destroy_team(self):
''' Delete your Team
Deletes your Team. Can only be invoked when you have a team with only one member left (yourself).
Returns:
None
'''
request = self._get_request()
request.post(url=self.TEAM_DESTROY_URL, get_json=False) | python | def destroy_team(self):
''' Delete your Team
Deletes your Team. Can only be invoked when you have a team with only one member left (yourself).
Returns:
None
'''
request = self._get_request()
request.post(url=self.TEAM_DESTROY_URL, get_json=False) | [
"def",
"destroy_team",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"request",
".",
"post",
"(",
"url",
"=",
"self",
".",
"TEAM_DESTROY_URL",
",",
"get_json",
"=",
"False",
")"
] | Delete your Team
Deletes your Team. Can only be invoked when you have a team with only one member left (yourself).
Returns:
None | [
"Delete",
"your",
"Team"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L920-L930 |
22,695 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.add_team_member | def add_team_member(self, account_id=None, email_address=None):
''' Add or invite a user to your Team
Args:
account_id (str): The id of the account of the user to invite to your team.
email_address (str): The email address of the account to invite to your team. The account id prevails if both account_id and email_address are provided.
Returns:
A Team object
'''
return self._add_remove_team_member(self.TEAM_ADD_MEMBER_URL, email_address, account_id) | python | def add_team_member(self, account_id=None, email_address=None):
''' Add or invite a user to your Team
Args:
account_id (str): The id of the account of the user to invite to your team.
email_address (str): The email address of the account to invite to your team. The account id prevails if both account_id and email_address are provided.
Returns:
A Team object
'''
return self._add_remove_team_member(self.TEAM_ADD_MEMBER_URL, email_address, account_id) | [
"def",
"add_team_member",
"(",
"self",
",",
"account_id",
"=",
"None",
",",
"email_address",
"=",
"None",
")",
":",
"return",
"self",
".",
"_add_remove_team_member",
"(",
"self",
".",
"TEAM_ADD_MEMBER_URL",
",",
"email_address",
",",
"account_id",
")"
] | Add or invite a user to your Team
Args:
account_id (str): The id of the account of the user to invite to your team.
email_address (str): The email address of the account to invite to your team. The account id prevails if both account_id and email_address are provided.
Returns:
A Team object | [
"Add",
"or",
"invite",
"a",
"user",
"to",
"your",
"Team"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L932-L945 |
22,696 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.remove_team_member | def remove_team_member(self, account_id=None, email_address=None):
''' Remove a user from your Team
Args:
account_id (str): The id of the account of the user to remove from your team.
email_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided.
Returns:
A Team object
'''
return self._add_remove_team_member(self.TEAM_REMOVE_MEMBER_URL, email_address, account_id) | python | def remove_team_member(self, account_id=None, email_address=None):
''' Remove a user from your Team
Args:
account_id (str): The id of the account of the user to remove from your team.
email_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided.
Returns:
A Team object
'''
return self._add_remove_team_member(self.TEAM_REMOVE_MEMBER_URL, email_address, account_id) | [
"def",
"remove_team_member",
"(",
"self",
",",
"account_id",
"=",
"None",
",",
"email_address",
"=",
"None",
")",
":",
"return",
"self",
".",
"_add_remove_team_member",
"(",
"self",
".",
"TEAM_REMOVE_MEMBER_URL",
",",
"email_address",
",",
"account_id",
")"
] | Remove a user from your Team
Args:
account_id (str): The id of the account of the user to remove from your team.
email_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided.
Returns:
A Team object | [
"Remove",
"a",
"user",
"from",
"your",
"Team"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L948-L961 |
22,697 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_embedded_object | def get_embedded_object(self, signature_id):
''' Retrieves a embedded signing object
Retrieves an embedded object containing a signature url that can be opened in an iFrame.
Args:
signature_id (str): The id of the signature to get a signature url for
Returns:
An Embedded object
'''
request = self._get_request()
return request.get(self.EMBEDDED_OBJECT_GET_URL + signature_id) | python | def get_embedded_object(self, signature_id):
''' Retrieves a embedded signing object
Retrieves an embedded object containing a signature url that can be opened in an iFrame.
Args:
signature_id (str): The id of the signature to get a signature url for
Returns:
An Embedded object
'''
request = self._get_request()
return request.get(self.EMBEDDED_OBJECT_GET_URL + signature_id) | [
"def",
"get_embedded_object",
"(",
"self",
",",
"signature_id",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"return",
"request",
".",
"get",
"(",
"self",
".",
"EMBEDDED_OBJECT_GET_URL",
"+",
"signature_id",
")"
] | Retrieves a embedded signing object
Retrieves an embedded object containing a signature url that can be opened in an iFrame.
Args:
signature_id (str): The id of the signature to get a signature url for
Returns:
An Embedded object | [
"Retrieves",
"a",
"embedded",
"signing",
"object"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L966-L980 |
22,698 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_template_edit_url | def get_template_edit_url(self, template_id):
''' Retrieves a embedded template for editing
Retrieves an embedded object containing a template url that can be opened in an iFrame.
Args:
template_id (str): The id of the template to get a signature url for
Returns:
An Embedded object
'''
request = self._get_request()
return request.get(self.EMBEDDED_TEMPLATE_EDIT_URL + template_id) | python | def get_template_edit_url(self, template_id):
''' Retrieves a embedded template for editing
Retrieves an embedded object containing a template url that can be opened in an iFrame.
Args:
template_id (str): The id of the template to get a signature url for
Returns:
An Embedded object
'''
request = self._get_request()
return request.get(self.EMBEDDED_TEMPLATE_EDIT_URL + template_id) | [
"def",
"get_template_edit_url",
"(",
"self",
",",
"template_id",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"return",
"request",
".",
"get",
"(",
"self",
".",
"EMBEDDED_TEMPLATE_EDIT_URL",
"+",
"template_id",
")"
] | Retrieves a embedded template for editing
Retrieves an embedded object containing a template url that can be opened in an iFrame.
Args:
template_id (str): The id of the template to get a signature url for
Returns:
An Embedded object | [
"Retrieves",
"a",
"embedded",
"template",
"for",
"editing"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L983-L997 |
22,699 | hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | HSClient.get_oauth_data | def get_oauth_data(self, code, client_id, client_secret, state):
''' Get Oauth data from HelloSign
Args:
code (str): Code returned by HelloSign for our callback url
client_id (str): Client id of the associated app
client_secret (str): Secret token of the associated app
Returns:
A HSAccessTokenAuth object
'''
request = self._get_request()
response = request.post(self.OAUTH_TOKEN_URL, {
"state": state,
"code": code,
"grant_type": "authorization_code",
"client_id": client_id,
"client_secret": client_secret
})
return HSAccessTokenAuth.from_response(response) | python | def get_oauth_data(self, code, client_id, client_secret, state):
''' Get Oauth data from HelloSign
Args:
code (str): Code returned by HelloSign for our callback url
client_id (str): Client id of the associated app
client_secret (str): Secret token of the associated app
Returns:
A HSAccessTokenAuth object
'''
request = self._get_request()
response = request.post(self.OAUTH_TOKEN_URL, {
"state": state,
"code": code,
"grant_type": "authorization_code",
"client_id": client_id,
"client_secret": client_secret
})
return HSAccessTokenAuth.from_response(response) | [
"def",
"get_oauth_data",
"(",
"self",
",",
"code",
",",
"client_id",
",",
"client_secret",
",",
"state",
")",
":",
"request",
"=",
"self",
".",
"_get_request",
"(",
")",
"response",
"=",
"request",
".",
"post",
"(",
"self",
".",
"OAUTH_TOKEN_URL",
",",
"... | Get Oauth data from HelloSign
Args:
code (str): Code returned by HelloSign for our callback url
client_id (str): Client id of the associated app
client_secret (str): Secret token of the associated app
Returns:
A HSAccessTokenAuth object | [
"Get",
"Oauth",
"data",
"from",
"HelloSign"
] | 4325a29ad5766380a214eac3914511f62f7ecba4 | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1230-L1253 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.